JavaScript Day02 Operators and Type Conversion and Flow Control Statements

Article directory

1. Operator

1.1. Arithmetic operators

operator describe example result
+ addition var num = 1 + 2; 3
- subtraction var num = 4 - 3; 1
* multiplication var num = 4 * 3; 12
/ division var num = 6 / 3; 2
% Take the remainder var num = 7 3%; 1
  • 1.1.1 - Normal Data Operations

var num1 = 8;
var num2 = 4;

console.log(num1 + num2); //12
console.log(num1 - num2); //4
console.log(num1 / num2); //2
console.log(num1 * num2); //32
console.log(num1 % num2); //0
  • 1.1.2 - When performing data operations, except for '+', other operators can automatically convert string numbers into numbers

var num1 = '8';
var num2 = '4';

console.log(num1 - num2); //4
console.log(num1 / num2); //2
console.log(num1 * num2); //32
console.log(num1 % num2); //0

1.2. Unary operators

1.2.1 - There are 8 commonly used unary operators in JavaScript

operator describe
+ Convert operands to numbers, string concatenation
- converts the operand to a number, and at the same time becomes a negative number
! logical negation operator
++ increment
decrease
delete Delete a value at a specific index in an array or object
typeof When the operand is placed after typeof, the type of the current operand will be returned. For numeric types, it can be returned accurately. For reference types, Function will return 'function', and others will only return 'object'
void The void operator returns undefined for any value.

1.2.2 + (plus sign)

1. The first usage of '+': adding data
var num1 = 3;
var num2 = 5;
var sum = num1 + num2; //8
2. '+' is placed in front of the data, which is to take a positive number
var num = 6;
console.log(+num); // 6
3. When '+' is operated with a string, it is a string connector
var a = 'hello';
var b = 'world';
console.log(a + b); // helloworld
4. '+' can implicitly convert numeric strings or Boolean types to number types
var a = '123';
var b = true;
console.log(+a, +b); // 123  1

1.2.3 - (minus sign)

1. Positive and negative signs can be used to take positive or negative numbers, and other operators cannot be converted
var num1 = 6;
var num2 = -6;
console.log(-num1); //-6
console.log(+num1); //6
console.log(-num2); //6
console.log(+num2); //-6
2. Positive and negative signs can implicitly convert string numbers into numbers
var num1 = '20';
var num2 = '-20';
console.log(-num1); //-20
console.log(+num1, typeof +num1); //20 number
console.log(-num2); //20
console.log(+num2, typeof +num2); //-20 number

1.2.4 !

1. It is often used as the negation operation in conditional judgment, type judgment, etc. You can also use '!' to convert variables to Boolean type
var a;
if (!a) {
    
    }
console.log(!null);  //true
console.log(!undefined);  //true
console.log(!''); //true
console.log(!100);  //false
console.log(!'abc');  //false

1.2.5++ (incremental)

Usually used for loop statements, animation operations, etc.

1. ++ is placed in front and assigned: accumulate first, then assign
var num = 0;
var a = ++num;
console.log(a); // 1
console.log(num); // 1
//num先自加1,再赋值给a
2. ++ is placed at the back and assigned: first assign, then accumulate
var num = 0;
var a = num++;
console.log(a); // 0
console.log(num); // 1
//先把num的值赋值给a,num再自加1

1.2.6 --(decrease)

Usually used for loop statements, animation operations, etc. The method of use is similar to ++.

1.2.7 delete

1. Delete the value of a specific index in an array or object
var obj = {
    
    
  name:'zhangsan',
  age: 17
};
delete obj.name;
console.log(obj); // {age: 17}

var arr = [1,2,3,4,5];
delete arr[2];
console.log(arr); //[ 1, 2, <1 empty item>, 4, 5 ]

1.2.8 typeof

When the operand is placed after typeof, the type of the current operand will be returned. For numeric types, it can be returned accurately. For reference types, Function will return 'function', and others will only return 'object'

var obj = {
    
    
  name:'zhangsan',
  age: 17
};
var arr = [1,2,3,4,5];
console.log(typeof obj, typeof arr); //object object

1.3 Extension: JavaScript Implicit Conversion

There are two types of data types in JavaScript: primitive types and object types:

1.3.1 Primitive type (basic type):

Undefined, Null, String, Number, Boolean, Symbol (newly introduced by es6, not considered yet)

1.3.2 Object types

object

  • -Since implicit conversion is required, there should be a set of conversion rules to track what is finally converted

There are three main types of conversions involved in implicit conversions:

1. Convert the value to the original value, ToPrimitive().

2. Convert the value to a number, ToNumber().

3. Convert the value to a string, ToString().

  • - convert the value to primitive by ToPrimitive

The abstract operation ToPrimitive inside the js engine has such a signature:

ToPrimitive(input, PreferredType?)

input is the value to be converted, and PreferredType is an optional parameter, which can only be of type Number or String.
It is just a conversion flag. The converted result is not necessarily the type of the parameter value, but the converted result must be an original value (or an error is reported).

It is special to find the original value of Date, PreferredType is String, and other Object objects are Number.

  • Conversion of primitive types
- Addition, subtraction, multiplication and division:

1. Add a number to a string, and the number will be converted into a string. Number-by-number or string-by-string requires no conversion.

In the process of addition, first perform the original value ToPrimitive() operation on the left and right sides of the plus sign, and then if there are two or more primitive values, as long as one of them is of String type, perform two or more primitive values. Convert the string toString() operation to perform string splicing; otherwise, convert two or more original values ​​to number toNumber() operation to perform digital addition.

var a = 1 + 2 + '3';
console.log(a, typeof a); // '33' string
var b = 1 + 2 + 3;
console.log(b, typeof b); // 6 number

2. Number minus string, string into number. If the string is not a pure number, it will be converted to NaN. The same goes for subtracting numbers from strings. The subtraction of two strings is also converted into a number first.

// -
10 - '20'    //-10
10 - 'one'   //NaN
10 - '100a'  //NaN

3. The conversion of multiplication, division, greater than, less than and subtraction is the same.

// *
10*'20'      //200
'10'*'20'    //200
// /
20/'10'      //2
'20'/'10'    //2
'20'/'one'  //NaN
  • - Implicit conversions about ==

1. undefined is equal to null

2. When comparing strings and numbers, convert strings to numbers

3. When comparing numbers and Booleans, convert Booleans to numbers

4. When comparing strings and Booleans, both are converted to numbers

// ==
undefined == null;    //true
'0' == 0;            //true,字符串转数字
0 == false;           //true,布尔转数字
'0' == false;       //true,两者转数字
  • - Conversion of reference types

    Comparisons between primitive types are relatively straightforward. The comparison between the reference type and the basic type is relatively complicated. First, the reference type must be converted into a basic type, and then compared according to the above method.

1.3.3 - PreferredType conversion strategy

  • - If the PreferredType is marked as Number, the following operation process will be performed to convert the input value.

1. If the input value is already an original value, return it directly
2. Otherwise, if the input value is an object, call the valueOf() method of the object,
if the return value of the valueOf() method is an original value , the original value is returned.
3. Otherwise, call the toString() method of this object. If the toString() method returns an original value, return the original value.
4. Otherwise, a TypeError exception is thrown.

  • - If the PreferredType is marked as String, the following operation process will be performed to convert the input value.

1. If the input value is already an original value, return it directly.
2. Otherwise, call the toString() method of this object. If the toString() method returns an original value, return the original value.
3. Otherwise, if the input value is an object, call the valueOf() method of the object, and
if the return value of the valueOf() method is an original value, return the original value.
4. Otherwise, a TypeError exception is thrown.

-Notice:

​ The value of PreferredType will be automatically set according to the following rules:

​ 1. If the object is of Date type, PreferredType is set to String

2. Otherwise, PreferredType is set to Number

1.3.4 - Case

[] + [] // ""

ToPrimitive, both are Array objects, not Date objects, so Number is used as the conversion standard, so first call valueOf(), the result is still [ ], not the original value, so continue to call toString(), the result is "" (empty String) primitive value, will return "". The second [ ] procedure is the same, returning "". The results on both sides of the plus sign are of String type, so string concatenation is performed, and the result is "".

[] + {
    
    }	// "[object Object]"

For ToPrimitive, Number is still used as the conversion standard.
The result of [ ] is "".
{ } call valueOf() first, the result is { }, not the original value, so continue to call toString(), the result is "[object Object]", which is the original value, and return "[object Object]".
The results on both sides of the plus sign are of String type, so string concatenation is performed, and the result is "[object Object]".

+ [] // 0

+[ ] becomes a unary operation. The original value of [ ] is "", and the result of converting "" into Number is 0.

{
    
    } + {
    
    } // "[object Object][object Object]"

In canary versions of chrome and node the results are as expected.
The result is "object Object".
In normal version of chrome browser the result is NaN.
Why is this? The reason is that in node, the statement starting with "{" and ending with "}" will be wrapped with ( ), and it becomes ({ } + { }), and the result is as expected. The normal version of chrome will still parse it into {};+{}, and the result becomes NaN

1.4. Assignment operator

operator example Equivalent to
= x = y x = y
+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y
The = assignment operator assigns a value to a variable.
var x = 7;
The += assignment operator adds a value to a variable.
var x = 7;
x += 8; 
The -= assignment operator subtracts a value from a variable.
var x = 7;
x -= 8; 
The *= assignment operator multiplies variables.
var x = 7;
x *= 8; 
The /= assignment operator divides variables.
var x = 7;
x /= 8; 
The %= assignment operator assigns the remainder to a variable.
var x = 7;
x %= 8; 

1.5. Comparison operators

Comparison operators are used in logical statements to determine whether variables or values ​​are equal. Usually used in conditional judgment statements.

The priority of comparison operators is lower than that of arithmetic operators, and higher than that of assignment operators. The result of the operation is generally boolean

operator describe Compare return
== equal x == 8 false
x == 5 true
x == “5” true
=== equal in value and equal in type x === 5 true
x === “5” false
!= not equal x != 8 true
!== unequal values ​​or unequal types x !== 5 false
x !== “5” true
x !== 8 true
> more than the x > 8 false
< less than x < 8 true
>= greater than or equal to x >= 8 false
<= less than or equal to x <= 8 true
==

Equivalence means that when the types of the values ​​on both sides are different, it is necessary to perform type conversion to the same type first, and then compare whether the values ​​are equal.

// 常用于相同类型的值的比较
console.log(123 == 345);  //false
console.log('123' == '345');  //false
// 如果两个值类型不同,也有可能相等,需根据以下规则进行类型转换在比较
// 如果一个是null,一个是undefined,那么相等
console.log(null == undefined); //true
// 如果一个是字符串,一个是数值,把字符串转换成数值之后再进行比较
console.log(123 == '123');  //true
//如果是整数类型和boolean类型的数值进行比较,1和true使用==比较结果为true,0和false使用==比较结果也为true,其它都为false;可以理解记忆为使用==比较整数时将1等同true,将0等同false。
console.log(1 == true); //true
console.log(0 == false);  //true
===

Identity means that no type conversion is performed, and the results of different types must be unequal.

// 如果类型不同,就一定不相等
console.log(123 === '123'); //false
// 如果两个都是数值,并且是同一个值,那么相等;如果其中至少一个是NaN,那么不相等。(判断一个值是否是NaN,只能使用isNaN() 来判断)
console.log(123 === 123); //true
console.log(123 === 10 / 'a');  //false
// 如果两个都是字符串,每个位置的字符都一样,那么相等,否则不相等。
console.log('hello' === 'hello'); //true
// 如果两个值都是true,或是false,那么相等
console.log(true === true); //true
console.log(1 === true);  //false
// 如果两个值都是null,或是undefined,那么相等
console.log(null === null); //true
console.log(null === undefined);  //false
The difference between double and triple

Double-equality means that it is true as long as the values ​​are equal, while triple-equality requires that not only the values ​​are equal, but also the types be the same.
Suggestion: try to use strict operator third etc. Because "==" is imprecise, it may have some counterintuitive consequences.

Notice:

1. For basic types such as string and number, there is a difference between double and third classes

1) Comparison between different types, double equality comparison "converted into the same type of value" to see if the "value" is equal, === if the types are different, the result is unequal

2) Comparison of the same type, direct "value" comparison, the result of the two is the same

2. For advanced types such as Array and Object, there is no difference between double-class and third-class

Perform "pointer address" comparison

3. There is a difference between basic type and advanced type, double class and third class

1) For ==, convert the advanced type to the basic type for "value" comparison

2) Because the types are different, the === result is false

!=

!= and == are used similarly. If the types of comparison are different, first try to convert the type, then compare the values, and finally return the result of the value comparison.

!==

!== and === are used similarly, only when they are of the same type, their values ​​will be compared.

'>' and '<' greater than and less than
var a = 10;
var b = 20;
console.log(a > b); //false
console.log(a < b); //true
'>=' and '<=' greater than or equal to and less than or equal to
var a = 10;
var b = 20;
console.log(a >= b); //false
console.log(a <= b); //true
Use '>''<''>=''<=' for non-numeric values

##### When comparing non-numeric values, they will be converted to numeric values ​​first, and then compared.

// true转换为数值是1 false转换为数值是0
console.log(1 > true); // 结果为false
console.log(1 >= true); // 结果为true
console.log(1 > '0'); // 结果为true
console.log(1 > null); // 结果为true
//任何值和NaN作比较结果都是false
console.log(1 > 'hello'); // 结果为false 任何值和NaN作比较结果都是false

If both sides of the symbol are character strings, they will not be converted to numeric values ​​for comparison, but the Unicode encodings of the characters in the character strings will be compared separately.
Note: Therefore, when comparing two string-type numbers, it must be converted first.

console.log('134545353' > '5'); // 不转型则返回false
console.log('134545353' > +'5');// 这样结果才返回true

而在比较字符编码时,是一位一位进行比较的,如果符号两侧第一位一样,则比较下一位,所以借此可以用来对英文进行排序,而比较中文是没有意义的。

console.log('1' < '5'); // 结果为true
console.log('11' < '5'); // 结果也为true
console.log('be' > 'b'); // 结果为true 先比较第一位b的字符编码是一样的,再比较第二位,由于be有e,而b只有一位,所以be>b
console.log('be' < 'b'); // 结果为false

1.6.逻辑运算符

运算符 描述 例子
&& and (x < 10 && y > 1) 为 true
|| or ````(x==5
! not !(x==y) 为 true

1.6.1 && 与(同真才真,有假则假)

可应用于任意数值。如果有一个操作数不是布尔类型,逻辑与就不一定返回boolean类型

如果第一个操作数是null,NaN,undefined,false,0,""可被转换为false的值的时候返回该值

console.log(null && 'world'); //null

当第一个表达式为真,整个表达式的结果取决于第二个表达式,返回第二个表达式

console.log('hello' && 'world'); //world

当第一个表达式为假,整个表达式的结果就可以确定,返回第一个表达式

console.log(false && 'world'); //false

[null,NaN,undefined,false,0,“”]直接返回该操作数

console.log(''&&123);  //''  空字符串
console.log(0&&null);  //0
console.log(123&&345); //345
console.log(123&&undefined); //undefined

1.6.2 ||(有真才真,同假则假)

如果两个或多个操作数都是null,NaN,undefined,false,0,""可被转换为false的值的时候返回该值。

console.log(null || false); //false

如果第一个操作数是null,NaN,undefined,false,0,“” 则返回第二个操作数。

console.log(null || 'hello'); //'hello'

如果第一个操作数是真,直接返回第一个操作数。

console.log(123||345);   //123

当第一个表达式为真,整个表达式的结果就可以确定,返回第一个表达式

当第一个表达式为假,整个表达式的结果取决于第二个表达式,返回第二个表达式

有一个为true结果就为true

同时为false结果才为false

1.6.3 !(NOT)

经常被用作条件判断时的取反操作,类型判断等,还可以用’!'将变量转换为Boolean类型

var a;
if (!a) {
    
    }
console.log(!null);  //true
console.log(!undefined);  //true
console.log(!''); //true
console.log(!100);  //false
console.log(!'abc');  //false

1.7.三目运算符

·JavaScript中的三目运算符用作判断时

基本语法为: expression ? sentence1 : sentence2

当expression的值为真时执行sentence1,否则执行 sentence2

var age = 19;
var result = age > 16 ? "成年人":"未成年人";
// 当age大于16岁时,条件为真,执行sentence1,其次反之

2.类型转换

2.1.* => 字符串类型

2.1.1 其他类型转换为String

toString()函数

​ 除了null,undefined,其他三种基本数据类型的变量均有一个toString()函数,该函数可以获取该变量指定值的字符串表示。

var a = true;
var b = 123;
console.log(a.toString(), b.toString());// 'true'  '123'
console.log(typeof a.toString(), typeof b.toString());//string string

​ 如果变量为number类型,默认情况下toString()是以十进制格式返回数值的字符串表示,通过传递参数,可以输入以二进制,八进制,十六进制乃至任意有效进制格式的字符串值

var num = 10;
console.log(num.toString());  //"10"
console.log(num.toString(2))	//"1010"
console.log(num.toString(8))	//"12"
console.log(num.toString(16))	//"a"

​ 任意其他数据与字符串相加都会转化为字符串

console.log(typeof (true + ''));  //string

2.2.* => 布尔类型

-其他数据类型转换为Boolean

Boolean()包装器

Boolean('hello') //true

使用!!转换任意其他数据类型都可以转换为布尔类型。

!!'hello' //true

2.3.* => 数字类型

其他数据类型转换为Number
Number()包装器

如果转换的值是null,undefined,boolean,number

Number(true); //1
Number(false); //0
Number(null); //0
Number(undefined); //NaN
Number(10); //10 如果是数字值,原样输出

如果转换的值是string

Number("123"); //123  如果仅包含数值,转换为对应的数值
Number("234.1"); //234.1 解析为对应的小数 
Number("+12.1"); //12.1 首位为符号位,其余为为数值,转换为对应的数值 
Number("1+2.3"); // NaN 符号位出现在其他位置,解析为NaN 
Number("0xa"); //10 如果仅包含十六进制格式,转为为对应的十进制的值
Number("010"); //10【注意】不会当做八进制被解析,结果为10。 
Number(""); // 0 空字符串被转换为0 
Number("123ac"); // NaN 包含其他字符: NaN 
Number(12); //12
parseInt()函数

如果转换的值是null,undefined,boolean,均转换为NaN

如果转换的值是Number

parseInt(10); //10 如果是整数值,原样输出 parseInt(10.3); //10 如果是小数,舍去小数点一级后面的内容

如果转换的值是string

parseInt("123"); //123;如果仅包含数值,转换为对应的数值
parseInt("234.1"); //234;小数点后面的数值省略 
parseInt("+12.1"); //12; 首位为符号位,其余为为数值,转换为整数 
parseInt("1+2.7"); //1; 符号位出现在其他位置,保留符号位前面的数值 
parseInt("0xa"); //10; 如果仅包含十六进制格式,转为为对应的十进制的值
parseInt("010"); //10; 【注意】不会当做八进制被解析,结果为10
parseInt(""); //NaN;空字符串被转换为NaN
parseInt("1+2.3"); //1;如果首位为数值,依次向后解析,找到连续的数值,直到遇到第一个非数值的,将之前获取的数值转换为Number返回 parseInt("123ac"); //123;
parseFloat()函数

如果转换的值是null,undefined,boolean,均转换为NaN

如果转换的值是Number

parseFloat(10); //10 如果是整数值,原样输出 parseFloat(10.1); //10.1 如果是小数,保留小数点,但是如果是10.0结果为10

如果转换的值是string

parseFloat("123"); //123;如果仅包含数值,转换为对应的数值
parseFloat("234.1"); //234.1;保留小数点后面的数值 
parseFloat("+12.1"); //12.1; 首位为符号位,其余为为数值,转换为整数 
parseFloat("1+2.6"); //1;符号位出现在其他位置,保留符号位前的数值 
parseFloat("0xa"); //0; 【注意】不会当做十六进制来解析。
parseFloat("010"); //10; 【注意】不会当做八进制被解析,结果为10
parseFloat(""); //NaN;空字符串被转换为NaN
parseFloat("1+2.3"); //1;如果首位为数值,依次向后解析,找到连续的数值,直到遇到第一个非数值的,将之前获取的数值转换为Number返回 parseFloat("123.3ac");//123.3;
+
+"23"                    //23
+null                    //0
+undefined               //NaN

3.流程控制语句

3.1. if…Else 语句


条件语句用于基于不同的条件来执行不同的动作。


条件语句

通常在写代码时,总是需要为不同的决定来执行不同的动作。可以在代码中使用条件语句来完成该任务。

在 JavaScript 中,我们可使用以下条件语句:

  • if 语句 - 只有当指定条件为 true 时,使用该语句来执行代码
  • if…else 语句 - 当条件为 true 时执行代码,当条件为 false 时执行其他代码
  • if…else if…else 语句- 使用该语句来选择多个代码块之一来执行
  • switch 语句 - 使用该语句来选择多个代码块之一来执行

if 语句

只有当指定条件为 true 时,该语句才会执行代码。

if (condition)
{
    
    
    当条件为 true 时执行的代码
}

condition表示任意表达式,该表达式求值的结果不一定是布尔类型,如果不是布尔类型,ECMAScript会调用Boolean() 转换函数将这个表达式结果转换为一个布尔类型 ,当该值为true时,执行if代码块中的内容。

if…else 语句

使用 if…else 语句在条件为 true 时执行代码,在条件为 false 时执行其他代码。

if (condition)
{
    
    
    当条件为 true 时执行的代码
}
else
{
    
    
    当条件不为 true 时执行的代码
}

当condition为true时,执行if代码块中的内容,否则,执行else代码块中的内容,一般情况下,如果代码块中代码只有一行,可以省略大括号。

if…else if…else 语句

使用 if…else if…else 语句来选择多个代码块之一来执行。

if (condition1)
{
    
    
		statement1
    当条件 1true 时执行的代码
}
else if (condition2)
{
    
    
		statement2
    当条件 2true 时执行的代码
}
else
{
    
    
		statement3
  	当条件 1 和 条件 2 都不为 true 时执行的代码
}

多条件分支,当condition1为true时,执行statement1,否则当condition2为true时执行statement2,当condition1,condition2都为false的时候执行statement3。

综合案列:

function exchange(num) {
    
    
  if (num && typeof num == 'number') {
    
    
    //typeof num=='number' && 0<num and num<=10
    if (num > 0 && num <= 10) {
    
    
      if (num == 1) {
    
    
        result = "壹";
      } else if (num == 2) {
    
    
        result = "贰";
      } else if (num == 3) {
    
    
        result = "叁";
      } else if (num == 4) {
    
    
        result = "肆";
      } else if (num == 5) {
    
    
        result = "伍";
      } else if (num == 6) {
    
    
        result = "陆";
      } else if (num == 7) {
    
    
        result = "柒";
      } else if (num == 8) {
    
    
        result = "捌";
      } else if (num == 9) {
    
    
        result = "玖";
      } else {
    
    
        result = "拾";
      }
    } else if(num > 10) {
    
    
      result = "请输入不大于10的数字";
    } else{
    
    
      result = "请输入不小于0的数字";
    }
  } else if (num == 0) {
    
    
    result = "零";
  } else {
    
    
    result = "请输入数字";
  }
  console.log(result);
}
exchange(0);
exchange(-120);
exchange(100);
exchange('as');
exchange();

3.2.switch 语句


switch 语句用于基于不同的条件来执行不同的动作。


使用 switch 语句来选择要执行的多个代码块之一。

switch(n)
{
    
    
    case 1:
        执行代码块 1
        break;
    case 2:
        执行代码块 2
        break;
    default:case 1case 2 不同时执行的代码
}

工作原理:首先设置表达式 n(通常是一个变量)。随后表达式的值会与结构中的每个 case 的值做比较。如果存在匹配,则与该 case 关联的代码块会被执行。请使用 break 来阻止代码自动地向下一个 case 运行。

3.2.1 -案例:

var d=new Date().getDay(); 
switch (d) 
{
    
     
  case 0:
    console.log('周日');
  break; 
  case 1:
    console.log('周一');
  break; 
  case 2:
    console.log('周二'); 
  break; 
  case 3:
    console.log('周三'); 
  break; 
  case 4:
    console.log('周四'); 
  break; 
  case 5:
    console.log('周五');
        
        
  break; 
  case 6:
    console.log('周六'); 
  break; 
}

3.2.2 -default 关键词

请使用 default 关键词来规定匹配不存在时做的事情:

var d = new Date().getDay();
switch (d) {
    
    
  case 4:
    console.log('周四');
    break;
  case 5:
    console.log('周五');
    break;
  default:
    console.log('期待周末');
}

3.2.3-注意:

  1. case代码块中break不能省略

  2. default可以放到代码任意位置,break不能省略,最后位置可以省略break;

  3. 变量与常量对比使用”===“

建议:

做等值比较的分支控制建议使用switch,非等值的判断建议使用If

3.3 循环语句


循环可以将代码块执行指定的次数。


如果希望一遍又一遍地运行相同的代码,并且每次的值都不同,那么使用循环是很方便的。

我们可以这样输出数组的值:

var arr = [1,2,3,4,5]
for (var i=0;i<arr.length;i++)
{
    
     
    console.log(i)
}

不同类型的循环

JavaScript 支持不同类型的循环:

  • for - 循环代码块一定的次数
  • for/in - 循环遍历对象的属性
  • while - 当指定的条件为 true 时循环指定的代码块
  • do/while - 同样当指定的条件为 true 时循环指定的代码块

3.3.1.For 循环

for 循环是您在希望创建循环时常会用到的工具。

下面是 for 循环的语法:

for (*语句 1*; *语句 2*; *语句 3*)
{
    
    
  *被执行的代码块*
}
for (var i=0; i<5; i++)
{
    
    
    console.log(i);
}

从上面的例子中,您可以看到:

Statement 1 在循环开始之前设置变量 (var i=0)。

Statement 2 定义循环运行的条件(i 必须小于 5)。

Statement 3 在每次代码块已被执行后增加一个值 (i++)。

语句 1 (代码块)开始前执行

通常我们会使用语句 1 初始化循环中所用的变量 (var i=0)。

语句 1 是可选的,也就是说不使用语句 1 也可以。

您可以在语句 1 中初始化任意(或者多个)值。

语句 2 定义运行循环(代码块)的条件

通常语句 2 用于评估初始变量的条件。

语句 2 同样是可选的。

如果语句 2 返回 true,则循环再次开始,如果返回 false,则循环将结束。

语句 3 在循环(代码块)已被执行之后执行

通常语句 3 会增加初始变量的值。

语句 3 也是可选的。

语句 3 有多种用法。增量可以是负数 (i–),或者更大 (i=i+15)。

语句 3 也可以省略(比如当循环内部有相应的代码时)。

// 1-100偶数和
var result = 0;
for(var i=0;i<=100;i++){
    
    
  if(i%2==0){
    
    
  	result += i;
  }
} 
console.log(result);
// 冒泡排序
//1、比较相邻的两个元素,如果前一个比后一个大,则交换位置。
//2、比较完第一轮的时候,最后一个元素是最大的元素。
//3、这时候最后一个元素是最大的,所以最后一个元素就不需要参与比较大小。
function bubbleSort(arr) {
    
    
  var len = arr.length;
  //外层控制循环多少趟
  for (var i = 0; i < len-1; i++) {
    
    
    //内层控制每一趟的循环次数
    for (var j = 0; j < len - 1 - i; j++) {
    
    
         // 相邻元素两两对比,元素交换,大的元素交换到后面
        if (arr[j] > arr[j + 1]) {
    
    
            var temp = arr[j];
            arr[j] = arr[j+1];
            arr[j+1] = temp;
        }
    }
  }
  return arr;
}
//举个数组
var arr = [20,18,27,19,35];
//使用函数
bubbleSort(arr)

3.3.2 关键字 break

如果想在所有迭代前退出,即可使用break。当执行break后,会立即跳出循环体。

关键字 continue与break不同的是,continue不会跳出循环。而是立即结束当前循环,进入下一次循环。

for(var i=0;;i++){
    
    
  console.log(i);
  if(i==5){
    
    
    break;
  }
}

3.3.3 增强版for循环

for…in用于遍历数组或者对象的属性

for(自定义变量名 in 数组/对象){

​ 执行代码

}

“自定义变量名”用来指定是数组的元素索引,也可以是对象的属性

//循环数组
var arr=[10,'aa',20,30,40];
for(var i=0;i<arr.length;i++){
    
    
  console.log(i+"--"+arr[i]);
}
for(var key in arr){
    
    
  console.log(key+"--"+arr[key]);
}
//循环对象属性:
var obj = {
    
    
  name:"briup",
  age:12,
  salary:10000
};
/*
两种方式访问属性:
objectName.propertyName
或者
objectName["propertyName"]
*/
console.log(obj.name);
console.log(obj["age"]);
console.log(obj.salary);
for(var key in obj){
    
    
  console.log(key+"--"+obj[key]);
}

3.4.while 循环


只要指定条件为 true,循环就可以一直执行代码块。


while 循环会在指定条件为真时循环执行代码块。

语法

while (*条件*)
{
    
    
  *需要执行的代码*
}
while (i<5)
{
    
    
    console.log(i);
    i++;
}
// 求1-100的和
var result = 0;
var i = 1;
while(i<=100){
    
    
	result += i;
	i++;
}
console.log(result);

3.5.do/while 循环

do/while 循环是 while 循环的变体。该循环会在检查条件是否为真之前执行一次代码块,然后如果条件为真的话,就会重复这个循环。

do
{
    
    
    需要执行的代码
}
while (条件);

下面的例子使用 do/while 循环。该循环至少会执行一次,即使条件为 false 它也会执行一次,因为代码块会在条件被测试前执行:

do
{
    
    
    console.log(i);
    i++;
}
while (i<5);
// 求1-100的和
var result = 0;
var i = 1;
do{
    
    
	result += i;
	i++;
} while(i<=100);
console.log(result);

3.6.递归

一个过程或函数在其定义或说明中有直接或间接调用自身的一种方法,它通常把一个大型复杂的问题层层转化为一个与原问题相似的规模较小的问题来求解,递归策略只需少量的程序就可描述出解题过程所需要的多次重复计算,大大地减少了程序的代码量。

使用递归实现阶乘

// 递归 通俗理解
// 函数自己调用自己 停不下来
// 需要有 跳出的条件
/*
    使用递归 求n的阶乘
    假设 写好了一个函数 factorial
    1 => 1
    2 => 1*2 ->factorial(1)*2
    3 => 1*2*3 ->factorial(2)*3
    4 => 1*2*3*4 ->factorial(3)*4
    ...
    n => 1*2*3...*n ->factorial(n-1)*n
*/
function factorial(n) {
    
    
  // 跳出条件
  if (n == 1) {
    
    
    return 1;
  }
  return factorial(n - 1) * n;
}
var result = factorial(4);
console.log(result);

Guess you like

Origin blog.csdn.net/qq_63299825/article/details/131303445