05_JavaScript basic syntax

1 variable

1.1 Identifier

In program development, it is often necessary to customize some symbols to mark some names and give them specific uses, such as variable names, function names, etc. These symbols are called identifiers.

Define rules

  • It consists of uppercase and lowercase letters (AZ,az), numbers (0-9), underscore (_) and dollar sign ($).
  • Cannot start with a number.
  • Strictly case sensitive.
  • Keyword naming in JavaScript cannot be used. For example: var, for, while.
  • We should try our best to "know its meaning when we see its name".
  • Although the identifier is expressed in Unicode encoding and can use all contents of UTF-8, only English is recommended.

Notice

  • When multiple words are required to be represented in an identifier, common representation methods include underscore (Hungarian nomenclature) (such as user_name), camel case (small camel case nomenclature) (such as userName) and Pascal method (big camel case nomenclature) (such as UserName).
  • The underline method is usually used in naming variables, and the camel case method is usually used in naming function names.

Class exercises:

Determine whether the following identifiers are legal

it、It、t-o、t o、age66、_age、789lu、$name

1.2 Reserved keywords

  • Reserved keywords: refers to words that have been defined in advance and given special meanings in the JavaScript language.
break case catch class const continue
debugger default delete do else export
extends false finally for function if
import in instanceof new null return
super switch this throw try true
typeof was void while with yield

Note: Keywords cannot be used as variable names and function names, otherwise syntax errors will occur during JavaScript loading.

  • Future reserved keywords: refers to words that are reserved and may become reserved keywords in the future.
abstract arguments await byte boolean char
double enum eval final float goto
implements int interface let long native
package private protected public short static
synchronized throws transient volatile

Note: When defining identifiers, it is recommended not to use future reserved keywords to avoid errors when converting to keywords in the future.

1.3 The role of variables

Variables can be thought of as containers for storing data. (The cup holding water, the cup refers to the variable, and the water in the cup refers to the data stored in the variable.)

grammar

  • Variables in JavaScript are usually declared using the var keyword, and the naming rules for variable names are the same as identifiers.
  • Legal variable names (such as number, _it123), illegal variable names (such as 88shout, &num).
var sales;
var hits, hot, NEWS;
var room_101, room102;
var $name, $age;
  • For variables that are not assigned an initial value, the default value will be set to undefined.
  • A semicolon at the end of a line indicates the end of a statement.
  • The comma (,) operator between variables can realize the declaration of multiple variables at the same time in one statement.

1.4 Variable assignment

// 声明变量、为变量赋值
var unit, room;
unit = 3;
room = 1001;

// 声明变量的同时为变量赋值
var fname = 'Tom', age = 12;

// 省略var关键字,直接为变量赋值
flag = false;
a = 1, b = 2;

Although variables in JavaScript can be assigned without declaring them in advance, the var keyword can be omitted directly to assign a value to the variable. However, since JavaScript uses dynamic compilation, it is not easy to find errors in the code when the program is running. Therefore, it is recommended to develop a good habit of declaring variables before using them.

1.5 Define constants

It can be understood as a quantity whose value remains unchanged while the script is running. Pi in mathematics is a constant whose value is fixed and cannot be changed.

Features: Once defined, it cannot be modified or redefined.

Syntax: The const keyword is added in ES6 to implement the definition of constants.

Constant naming rules: Follow the identifier naming rules. It is customary to always use uppercase letters for constant names.

The value of a constant: A constant can be specific data when assigned, or it can be the value of an expression or a variable.

var r = 6;
const PI = 3.14;
const P = 2 * PI * r;
// 输出结果:P=37.68
console.log('P=' + P);
  • Once a constant is assigned a value, it cannot be changed.
  • A constant must be assigned a value when it is declared.

2 data types

When using or assigning a value, determine the corresponding type according to the specific content of the setting. But every computer language has its own supported data types, and JavaScript is no exception.

2.1 Data type classification

  • Basic data types (value types)
    • Boolean
    • Number (numeric type)
    • String (character type)
    • Null (empty type)
    • Undefined (undefined type)
  • Reference data type: Object

Reference data types will be introduced in detail in later chapters.

Note: In JavaScript, any value that is not a numeric value, a string, a Boolean value, a symbol, null, and undefined is an object.

2.2 Basic data types

2.2.1 Boolean type

Boolean is one of the more commonly used data types in JavaScript and is usually used for logical judgments.

  • true
  • false

Represents the "true" and "false" of things, strictly following case, so the true and false values ​​only represent Boolean types when they are all lowercase.

2.2.2 Numeric type

Numeric types in JavaScript do not distinguish between integers and floating point numbers. All numbers are numeric types.

  • Add the "-" sign to indicate negative numbers.
  • Add the "+" sign to represent positive numbers (normally omit the "+").
  • Set to NaN to indicate a non-numeric value.
// 八进制数字序列范围:0~7
// 十六进制数字序列范围:0~9以及A~F
// 在JS中八进制前面加 0,十六进制前面加 0x
var oct = 032;		  // 八进制数表示的26
var dec = 26;		  // 十进制数26
var hex = 0x1a;		  // 十六进制数表示的26
var fnum1 = 7.26;	  // 标准格式
var fnum2 = -6.24;	  // 标准格式
var fnum3 = 3.14E6;	  // 科学计数法格式3.14*106
var fnum4 = 8.96E-3;  // 科学计数法格式8.96*10-3

As long as the given value does not exceed the range allowed for numeric specification in JavaScript.

special value

  • Infinity, represents infinity, greater than any value
  • -Infinity, represents infinitesimal, smaller than any value
  • NaN, Not a Number, represents a non-numeric value

NaN not a numeric value

  • NaN is a property of the global object, and its initial value is NaN.
  • Like the special value NaN in numeric types, they both represent Not a Number.
  • Can be used to indicate whether a certain data is of numeric type.
  • NaN does not have an exact value, but only represents a range of non-numeric types.
  • For example, when NaN is compared with NaN, the result may not be true (true) because the data being operated on may be any type of Boolean, character, null, undefined, and object.
2.2.3 Character type

Character type (String) is a character sequence composed of Unicode characters, numbers, etc. We generally call this character sequence a string.

Function: Represents the data type of text.

Syntax: Character data in the program is enclosed in single quotes (') or double quotes (").

var slogan = 'Knowledge';		// 单引号,存放一个单词
var str = "the sky is blue."; 	// 双引号,存放一个句子
var color = '"red"blue'; 		// 单引号中包含双引号
var food = "'pizza'bread";		// 双引号中包含单引号
var num = '', total = "";		// 定义空字符串
  • A string delimited by single quotes can contain double quotes.
  • Single quotes can also be included in a string delimited by double quotes.

**How ​​to use single quotes within single quotes, or double quotes within double quotes? **Use the escape character "\" to escape.

var say1 = 'I\'m is ...';  	 // 在控制台的输出结果:I'm is ...
var say2 = "\"Tom\"";        // 在控制台的输出结果:"Tom"

When using special symbols such as newline and Tab in a string, you also need to use the escape character "\".

Special characters meaning Special characters meaning
\' apostrophe \" Double quotes
\n Carriage return and line feed \v Tab (Tab, horizontal)
\t Tab symbol \r newline
\f Page change \\ backslash(\)
\b backspace \0 Nullbyte
\xhh ISO-8859-1 character represented by two hexadecimal digits hh. For example, "\x61" means "a" \uhhhh Unicode character represented by four hexadecimal digits hhhh. For example, "\u597d" means "good"
2.2.4 Empty type
  • The null type (Null) has only one special null value.
  • The empty type is used to represent a non-existent or invalid object and address.
  • JavaScript is case-sensitive, so the variable value only represents null when it is lowercase null.
2.2.5 Undefined type
  • Undefined type (Undefined) also has only one special undefined value.
  • The undefined type is used when the declared variable has not been initialized, and the default value of the variable is undefined.
  • Unlike null, undefined means that no value is set for the variable, while null means that the variable (object or address) does not exist or is invalid.
  • Note: null and undefined are not equal to the empty string ('') or 0.

2.3 Data type detection

Why data type detection is needed? Let’s first look at the following example.

var num1 = 12, num2 = '34', sum = 0;	// 声明变量并赋值
sum = num1 + num2;			            // 变量进行相加运算
console.log(sum); 			            // 输出结果:1234

Please analyze and tell the data type of variable sum and why?

  • The variable sum is of character type.
  • As long as one of the operands of the operator "+" is a character type, it represents character concatenation.
  • Of the two variables involved in the operation, num1 is of numeric type and num2 is of character type, so the final output variable sum is the string concatenated between num1 and num2.

Therefore, when there are requirements for the data types involved in the operation, data type detection is required.

JavaScript provides the following two methods for detecting data types:

typeof operator

The typeof operator returns the unevaluated type of the operand as a string.

onsole.log(typeof num1);       	// 输出结果:number
console.log(typeof num2);       // 输出结果:string
console.log(typeof sum);       	// 输出结果:string

When using typeof to detect the type of null, object is returned instead of null.

Object.prototype.toString.call()

Since everything in JavaScript is an object, you can use the Object.prototype.toString.call() extension function of the object prototype to distinguish data types more accurately.

var data = null;	// 待判断的数据
var type = 'Null';	// 数据类型,开始字母要大写,如Boolean等
// 检测数据类型的表达式,若是指定的type型,则返回true,否则返回false
Object.prototype.toString.call(data) == '[object ' + type + ']';

The return value of Object.prototype.toString.call(data) is a character result in the form of "[object data type]". (The return value can be observed through console.log().)

2.4 Data type conversion

2.4.1 Convert to Boolean type

Often used in expressions and flow control statements, such as data comparison and conditional judgment.

Syntax: Boolean() function.

Note: The Boolean() function converts any non-empty string and non-zero value to true, and converts empty strings (''), 0, NaN, undefined and null to false.

// 判断用户是否有内容输入。
var con = prompt(); 
if (Boolean(con)) {
    
    
  document.write('已输入内容');
} else {
    
    
  document.write('无输入内容');
}

Analysis of Boolean(con):

  • When the user clicks the "Cancel" button, the result is false
  • If the user does not enter anything and clicks the "OK" button, the result will be false.
  • The user enters "haha" and clicks the "OK" button, and the result is true.
2.4.2 Convert to numeric type

In actual development, when receiving data passed by users for calculation, in order to ensure that all data involved in the calculation are numerical, it is often necessary to convert it.

Syntax: Number() function, parseInt() function, or parseFloat() function.

// 根据用户的输入完成自动求和。
// 获取用户的输入,完成自动求和
var num1 = prompt('请输入求和的第1个数据:');   // 123
var num2 = prompt('请输入求和的第2个数据:');   // 456abc
console.log(num1 + num2);  // 123456abc
console.log(parseInt(num1) + parseInt(num2));  // 579

There are certain differences in the use of functions that convert numeric types.

Data to be transferred Number() parseInt() pressFloat()
Pure numeric string Convert to corresponding number Convert to corresponding number Convert to corresponding number
empty string 0 NaN NaN
A string starting with a number NaN Convert to starting number Convert to starting number
Character string starting with non-number NaN NaN NaN
null 0 NaN NaN
undefined NaN NaN NaN
false 0 NaN NaN
true 1 NaN NaN
  • All functions will ignore leading zeros when converting pure numbers. For example, the string "0123" will be converted to 123.

  • The parseFloat() function converts data to floating point numbers (can be understood as decimals).

  • The parseInt() function will directly omit the decimal part, return the integer part of the data, and set the conversion base number through the second parameter.

Note: In actual development, it is also necessary to judge whether the converted result is NaN. The operation can only be performed when it is not NaN. At this time, you can use the isNaN() function to determine, when the given value is undefined, NaN and {} (object), it returns true, otherwise it returns false.

2.4.3 Convert character type

Syntax: String() function and toString() method.

Difference: The String() function can convert any type into a character type; except for null and undefined, which do not have a toString() method, all other data types can complete character conversion.

// 根据用户的输入完成自动求和。
var num1 = num2 = num3 = 4, num4 = 26;
console.log(String(12));
console.log(num1 + num2 + num3.toString());
console.log(num4.toString(2));

Note: When the toString() method performs data type conversion, you can convert the value into a string in the specified base through parameter settings, such as num4.toString(2), which means first convert decimal 26 to binary 11010, and then convert It is character data.

3 expressions

An expression can be a collection of various types of data, variables, and operators.

The simplest expression can be a variable.

var x, y, z;         // 声明变量
x = 1;		         // 将表达式“1”的值赋给变量x
y = 2 + 3;	         // 将表达式“2 + 3”的值赋给变量y
z = y = x;	         // 将表达式“y = x”的值赋给变量z
console.log(z);	     // 将表达式“z”的值作为参数传给console.log()方法
console.log(x + y);  // 将表达式“x + y”的值作为参数传给console.log()方法

4 operators

The so-called operators are symbols specifically used to tell the program to perform specific calculations or logical operations.

4.1 Arithmetic operators

  • Perform arithmetic operations on numeric type variables and constants.
  • It is also the simplest and most commonly used arithmetic symbol.
operator Operation example result
+ add 5+5 10
- reduce 6-4 2
* take 3*4 12
/ remove 3/2 1.5
% Ask for surplus 5%7 5
** Exponentiation 3**4 81
++ Autoincrement (prefix) a=2, b=++a; a=3;b=3;
++ Auto-increment (post-increment) a=2, b=a++; a=3;b=2;
Decrement (front) a=2, b=–a; a=1;b=1;
Self-decrementing (post-position) a=2, b=a–; a=1;b=2;
  • The four mixed operations follow the principle of "first multiplication and division, then addition and subtraction".
  • The sign of the result of the modulo operation depends on the sign of the modulus (the number to the left of %).
  • Try to avoid using decimals for calculations. Sometimes the precision of JavaScript may cause deviations in the results.
  • "+" and "-" can also represent positive or negative numbers in arithmetic operations.
  • The operator (++ or –) is placed in front of the operand, and the increment or decrement operation is performed first, and then other operations are performed. If the operator is placed after the operand, other operations are performed first, and then the increment or decrement operation is performed.
  • If the operator (++ or –) comes first, the formula is: increment first, then return the value; if the operator (++ or –) comes last, the original value is returned first, and then the value is incremented.
  • The increment and decrement operators only operate on numeric and Boolean data, and treat Boolean values ​​true as 1 and false as 0.
  • Except for addition operations, other operators perform corresponding mathematical operations and when encountering non-number values, they will all be converted into number values ​​before performing operations. This feature can be used for implicit number type conversion.
  • 正号和负号,两者能够进行相应的数学运算同时在遇到非number的值时会将其强制转换成number值再进行运算,此特性可用于隐式number类型转换

4.2 字符串运算符

JavaScript中,“+”操作的两个数据中只要有一个是字符型,则“+”就表示字符串运算符,用于返回两个数据拼接后的字符串。

口诀:数值相加,字符相连

var color = 'blue';
var str = 'The sky is '+color;
var tel = 110 + '120';
console.log(str);                   	// 输出结果为:The sky is blue
console.log(tel);                   	// 输出结果为:110120
console.log(typeof str, typeof tel);	// 输出结果:string string

注意:利用字符串运算符“+”的特性,可以将布尔型、整型、浮点型或为 null 的数据,与空字符串进行拼接,就会完成字符型的自动转换。

4.3 赋值运算符

赋值运算符是一个二元运算符,即它有两个操作数。它将运算符右边的值赋给左边的变量。

运算符 运算 范例 结果
= 赋值 a=3, b=2; a=3;b=2;
+= 加并赋值 a=3, b=2; a+=b; a=5;b=2;
-= 减并赋值 a=3, b=2;a-=b; a=1;b=2;
*= 乘并赋值 a=3, b=2;a*=b; a=6;b=2;
/= 除并赋值 a=3, b=2;a/=b; a=1.5;b=2;
%= 模并赋值 a=3, b=2;a%=b; a=1;b=2;
+= 连接并赋值 a=‘abc’;a+=‘def’; a=‘abcdef’;
**= 幂运算并赋值 a=2; a**= 5; a=32;
<<= 左移位赋值 a=9,b=2;a <<= b; a=36;b=2;
>>= 右移位赋值 a=-9,b=2;a >>= b; a=-3;b=2;
>>>= 无符号右移位赋值 a=-9,b=2;a >>>= b; a= 1073741821;b=2;
&= 按位与赋值 a=3,b=9;a &= b; a=1;b=9;
^= 按位异或赋值 a=3,b=9;a ^= b; a=10;b=9;
|= 按位或赋值 a=3,b=9;a |= b; a=11;b=9;

注意:

  • “=”是赋值运算符,而非数学意义上的相等的关系。
  • 一条赋值语句可以对多个变量进行赋值。
  • 赋值运算符的结合性为“从右向左”。
var a = b = c = 8;	
// 将5赋值给变量c
// 再把变量c的值赋值给变量b
// 把变量b的值赋值变量a,表达式赋值完成

var num1 = 2;
num1 += 3;	
// 等价于:
num1 = num1 + 3;

var num2 = '2';
num2 += 3;	
// 等价于:
num2 = num2 + 3;

4.4 比较运算符

用来对两个数值或变量进行比较。其结果是布尔类型的 true 或 false。

运算符 运算 范例 结果
== 等于 x == 4 false
!= 不等于 x != 4 true
=== 全等 x === 5 true
!== 不全等 x !== ‘5’ true
> 大于 x > 5 false
>= 大于或等于 x >= 5 true
< 小于 x < 5 false
<= 小于或等于 x <= 5 true

注意:

  • 不相同类型的数据进行比较时,首先会自动将其转换成相同类型的数据后再进行比较。
  • 运算符“==”和“!=”运算符在比较时,只比较值是否相等。
  • 运算符“=”与“!”要比较数值和其数据类型是否相等。

不同类型数据比较,规律如下:

类型 类型 比较方式 说明
对象型 对象型 比较是不是同一内存地址
对象型 字符型 对象先转化为字符型,再进行比较。
对象型 布尔型 两边都要先转为数值型,布尔类型false为0,true为1。对象类型先隐式调用toString方法,然后再调用Number() alert([]==false);
alert([]==0);
alert([1]==1);
alert([1]==true);
alert([2]==true);
对象型 数值型 对象类型先转为数值型,再进行比较。对象类型先隐式调用toString方法,然后再调用Number()
数值型 布尔型 布尔型先转化为数值型,布尔类型false为0,true为1,再进行比较。
数值型 字符型 字符型先转化为数值型,再进行比较。
布尔型 布尔型 两边都要先转化为数值型,再进行比较。
null undefined true
null,undefined 其他类型 false alert(nullfalse);
alert(null
0);
alert(null==‘’);

4.5 逻辑运算符

是在程序开发中用于逻辑判断的符号。其返回值类型是布尔类型。

运算符 运算 范例 结果
&& a && b a和b都为true,结果为true,否则为false
|| a || b a和b中至少有一个为true,则结果为true,否则为false
! ! a 若a为false,结果为true,否则相反
  • 逻辑运算符的结合性是从左到右。
  • 当使用“&&”连接两个表达式时,如果左边表达式的值为 false,则右边的表达式不会执行,逻辑运算结果为false。(短路)
  • 当使用“||”连接两个表达式时,如果左边表达式的值为 true,则右边的表达式不会执行,逻辑运算结果为true。(短路)
  • 逻辑运算符可针对结果为布尔值的表达式进行运算。
  • 非运算:两次取非会得到原值的布尔值,此特性可用于隐式布尔类型转换。

4.6 三元运算符

三元运算符是一种需要三个操作数的运算符,运算的结果根据给定条件决定。

语法:条件表达式 ? 表达式1 : 表达式2

  • 先求条件表达式的值。
  • 如果为true,则返回表达式1的执行结果。
  • 如果条件表达式的值为false,则返回表达式2的执行结果。

4.7 位运算符(了解)

是针对二进制数的每一位进行运算的符号。它专门针对数字0和1进行操作。

运算符 运算 范例 结果
& 按位与 a & b a和b每一位进行“与”操作后的结果
| 按位或 a | b a和b每一位进行“或”操作后的结果
~ 按位非 ~ a a的每一位进行“非”操作后的结果
^ 按位异或 a ^ b a和b每一位进行“异或”操作后的结果
<< 左移 a << b 将a左移b位,右边用0填充
>> 右移 a >> b 将a右移b位,丢弃被移出位,左边最高位用0或1填充
>>> 无符号右移 a >>>b 将a右移b位,丢弃被移出位,左边最高位用0填充

JavaScript 中位运算符仅能对数值型的数据进行运算。在对数字进行位运算之前,程序会将所有的操作数转换成二进制数,然后再逐位运算。

JavaScript 中的数都是以4字节32位表示,一个字节8位。

有符号整数使用 31 位表示整数的数值,用第 32 位表示整数的符号,0 表示正数,1 表示负数。数值范围从 -2147483648 到 2147483647。

// 按位与
//   00000000 00000000 00000000 00001111 2^3+2^2+2^1+1=8+4+2+1=15
// & 00000000 00000000 00000000 00001001 2^3+1=9
// —————————————————————————------------
//   00000000 00000000 00000000 00001001 2^3+1=9

// 按位或
//   00000000 00000000 00000000 00001111
// | 00000000 00000000 00000000 00001001
// —————————————————————————------------
//   00000000 00000000 00000000 00001111

// 按位非
// 把运算数转换成 32 位数字
// 把二进制数转换成它的二进制反码
// 把二进制数转换成浮点数
// 实质上是对数字求负,然后减 1
// ~ 00000000 00000000 00000000 00001111
// —————————————————————————------------
//   11111111 11111111 11111111 11110000 -16

// 按位异或
// 不同为 1,相同为 0
//   00000000 00000000 00000000 00001111
// ^ 00000000 00000000 00000000 00001001
// —————————————————————————------------
//   00000000 00000000 00000000 00000110 2^2+2^1=6

// 左移
//   00000000 00000000 00000000 00001001 <<2
// —————————————————————————------------
//   00000000 00000000 00000000 00100100

// 右移
//   00000000 00000000 00000000 00001001 >>2
// —————————————————————————------------
//   00000000 00000000 00000000 00000010

// 无符号右移
//   00000000 00000000 00000000 00010011 >>>2
// —————————————————————————------------
//   00000000 00000000 00000000 00000100

4.8 运算符优先级

指的是在表达式中各个运算符参与运算的先后顺序(比如:先乘除,后加减)。

表中运算符的优先级由上至下递减。

结合方向 运算符
()
. [] new(有参数,无结合性)
new(无参数)
++(后置) --(后置)
! ~ -(负数) +(正数) ++(前置) --(前置) typeof void delete
**
* / %
+ -
<< >> >>>
< <= > >= in instanceof
== != === !==
&
^
|
&&
||
?:
= += = *= /= %= <<= >>= >>>= &= ^= |=
,
  • 同一单元格的运算符具有相同的优先级。
  • 左结合方向表示同级运算符的执行顺序为从左到右。
  • 右结合方向则表示执行顺序为从右到左。
  • 补充:圆括号()优先级别最高。例如, 4 + 3 * 2的 输出结果为10,(4 + 3) * 2的输出结果为14。
console.log( 4 >= 6 || '人' != '阿凡达' && !(12 * 2 == 144) && true)	// true

var a = 3 > 5 && 2 < 7 && 3 == 4; 
console.log(a); 	//false 

var b = 3 <= 4 || 3 > 1 || 3 != 2; 
console.log(b); 	//true

var c = 2 === "2"; 
console.log(c);  	//false

var d = !c || b && a ;
console.log(d);		//true

5 流程控制

5.1 选择结构

选择结构语句需要根据给出的条件进行判断来决定执行对应的代码。

5.1.1 if 单分支语句

if 条件判断语句也被称为单分支语句,当满足某种条件时,就进行某种处理。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

// 只有年龄大于等于18周岁,才输出已成年,否则无输出。
// if ( 判断条件 ) {
    
    
//    代码段
// }

if(age >= 18){
    
    
    console.log('已成年');
}
5.1.2 if…else 双分支语句

if…else 语句也称为双分支语句,当满足某种条件时,就进行某种处理,否则进行另一种处理。

// 判断一个学生的年龄,大于等于18岁则是成年人,否则是未成年人。
// if ( 判断条件 ) {
    
    
//     代码段1;
// } else {
    
    
//     代码段2;
// }

if (age >= 18) {
    
    
    console.log('已成年');
} else {
    
    
    console.log('未成年');
}
5.1.3 if…else if…else 多分支语句

if…else if…else 语句也称为多分支语句,可针对不同情况进行不同的处理。

// 对一个学生的考试成绩进行等级的划分,分数在90~100分为优秀,分数在80~90分为优秀为良好,分数在70~80分为中等,分数在60~70分为及格,分数小于60则为不及格。
// if (条件1)  {
    
    
// 	代码段1;
// } else if(条件2)  {
    
    
// 	    代码段2;
// }
// ...
// else if(条件n)  {
    
    
// 	    代码段n; 	
// } else {	
// 	    代码段n+1;
// }

if (score >= 90) {
    
    
    console.log('优秀');
} else if (score >= 80) {
    
    
    console.log('良好');
} else if (score >= 70) {
    
    
    console.log('中等');
} else if (score >= 60) {
    
    
    console.log('及格');
} else {
    
    
    console.log('不及格');
}

注意:“if…else if…else”语句在使用时,“else if”中间要有空格,否则程序会报语法错误。

5.1.4 switch 多分支语句

switch 语句也是多分支语句,功能与 if 系列条件语句相同,不同的是它只能针对某个表达式的值作出判断,从而决定执行哪一段代码。

特点:代码更加清晰简洁、便于阅读。

// 根据学生成绩 score 进行评比(满分为100分)。
// switch (表达式) {
    
    
//     case 值1:代码段1; break;
//     case 值2:代码段2; break;
//         ...
//     default: 代码段n;
// }

switch (parseInt(score / 10)) {
    
    
    case 10:
    case 9:
        console.log('优');
        break;
    case 8:
        console.log('良');
        break;
    case 7:
        console.log('中');
        break;
    case 6:
        console.log('及格');
        break;
    case 5:
    case 4:
    case 3:
    case 2:
    case 1:
    default:
        console.log('差');
}

5.2 循环结构

所谓循环语句就是可以实现一段代码的重复执行。

5.2.1 while 循环

while 循环语句是根据循环条件来判断是否重复执行一段代码。

// 连续输出1~100之间的数字
// while ( 循环条件 ) {
    
    
//     循环体
//     ……
// }

var num = 1;
while (num <= 100) {
    
    
    console.log(num);
    num++;
}

注意:需要注意的是,若循环条件永远为 true 时,则会出现死循环,因此在开发中应根据实际需要,在循环体中设置循环出口,即循环结束的条件。

5.2.2 do…while 循环

do…while 循环语句的功能与 while 循环语句类似,唯一的区别在于,while 是先判断条件后执行循环体,而do…while 会无条件执行一次循环体后再判断条件。

// do {
    
    
//     循环体
//     ……
// } while (循环条件);

var num = 100;
do {
    
    
    console.log(num);
    num--;
} while (num >= 1)
5.2.3 for 循环

for 循环语句是最常用的循环语句,它适合循环次数已知的情况。

var num = 1;           // 初始化表达式
while (num <= 100) {
    
       // 循环条件
    console.log(num);  // 循环体
    num++;             // 操作表达式
}

// for (初始化表达式;循环条件;操作表达式)
for (var num = 1; num <= 100; num++) {
    
    
    console.log(num);
}

for 关键字后面小括号“()”中包括了三部分内容:

  • 初始化表达式
  • 循环条件
  • 操作表达式

它们之间用“;”分隔,{}中的执行语句为循环体。

注意:for 循环语句小括号“()”内的每个表达式都可以为空,但是必须保留分号分割符。当每个表达式都为空时,表示该for 循环语句的循环条件永远满足,会进入无限循环的状态,此时如果要结束无限循环,可在 for 语句循环体中用跳转语句进行控制。

let 关键字

  • 在 ES6 中,可以通过 let 关键字声明一个块级作用域(可以理解为 {} 之间的代码)的本地变量。
  • 它与 var 关键字的区别是,let 关键字在块级作用域内不能重复定义同名的变量,且该变量仅在块级作用范围内有效。
// let关键字
for (let i = 0; i < 3; ++i) {
    
    
}
// 输出结果:i is not defined
console.log(i); 

// var关键字
for (var i = 0; i < 3; ++i) {
    
    
}
// 输出结果为:3
console.log(i);

通过 let 定义的变量相比 var 来说,有一个更加清晰的作用范围,方便了变量的维护与控制。

5.3 跳转语句

跳转语句用于实现程序执行过程中的流程跳转。

常用的跳转语句:有 break 和 continue 语句。

break 与 continue 的区别

  • break 语句可应用在 switch 和循环语句中,其作用是终止当前语句的执行,跳出 switch 选择结构或循环语句,执行后面的代码。
  • continue 语句用于结束本次循环的执行,开始下一轮循环的执行操作。

break 和 continue 语句还可跳转到指定的标签语句处,实现嵌套语句的多层次跳转。

// 定义标签
label:statement
// 使用标签
break/continue  label;

outerloop:
for (var i = 0; i < 10; i++)
{
    
    
    innerloop:
    for (var j = 0; j < 10; j++)
    {
    
    
        if (j > 3)
        {
    
    
            break;
        }
        if (i == 2)
        {
    
    
            break innerloop;
        }
        if (i == 4)
        {
    
    
            break outerloop;
        }
        document.write("i=" + i + " j=" + j + "");
    }
}
  • label 表示标签的名称,如 start、end 等任意合法的标识符。
  • statement 表示具体执行的语句,如 if、while、变量的声明等。
  • 标签语句必须在使用之前定义,否则会出现找不到标签的情况。

6 练习作业

  • 根据平均分来划分等级

    • 得到小明同学的各科平均成绩,如果大于等于90为优秀,小于90大于等于80为良好,小于80大于等于70为一般,小于70大于等于60为较差,小于60为很差
  • 加油优惠价格计算

    • 加油站实行多加多优惠政策,鼓励车主多加油
    • 已知92号汽油,每升7.15元;如果大于等于20升,那么每升7.1
    • 已知95号汽油,每升7.63元;如果大于等于40升,那么每升7.6
    • 编写JS程序,用户输入自己的汽油编号,然后输入自己加多少升,弹出价格。
  • 输出100以内的所有质数

  • 判断一个数是否是素数(素数也叫作质数)

  • 输入圆的半径计算面积和周长

  • 三元运算符比较最大值

  • while实现1-100相加求和

  • while do…while验证用户名和密码

  • 打印菱形、三角形

  • 输出【100-999】中的水仙花数

    • 水仙花数是指一个3位数,它的每个位上的数字的3次幂之和等于它本身,例如:13+53+3^3=153。
  • 打印金字塔

  • 九九乘法表

    image-20220103232309923
  • 一百个和尚分一百个馒头,大和尚一人分三个,小和尚三人分一个,正好分完。问大、小和尚各几人?

  • 公鸡一个五块钱,母鸡一个三块钱,小鸡三个一块钱,现在要用一百块钱买一百只鸡,问公鸡、母鸡、小鸡各多少只?

          break outerloop;
      }
      document.write("i=" + i + " j=" + j + "");
    

    }
    }


- label 表示标签的名称,如 start、end 等任意合法的标识符。
- statement 表示具体执行的语句,如 if、while、变量的声明等。
- 标签语句必须在使用之前定义,否则会出现找不到标签的情况。



## 6 练习作业

- 根据平均分来划分等级
	- 得到小明同学的各科平均成绩,如果大于等于90为优秀,小于90大于等于80为良好,小于80大于等于70为一般,小于70大于等于60为较差,小于60为很差
- 加油优惠价格计算
	- 加油站实行多加多优惠政策,鼓励车主多加油
	- 已知92号汽油,每升7.15元;如果大于等于20升,那么每升7.1
	- 已知95号汽油,每升7.63元;如果大于等于40升,那么每升7.6
	- 编写JS程序,用户输入自己的汽油编号,然后输入自己加多少升,弹出价格。
- 输出100以内的所有质数
- 判断一个数是否是素数(素数也叫作质数)
- 输入圆的半径计算面积和周长
- 三元运算符比较最大值
- while实现1-100相加求和
- while do...while验证用户名和密码
- 打印菱形、三角形

- 输出【100-999】中的水仙花数
	- 水仙花数是指一个3位数,它的每个位上的数字的3次幂之和等于它本身,例如:1^3+5^3+3^3=153。

- 打印金字塔

[外链图片转存中...(img-TiSa8RbT-1695633510590)]

- 九九乘法表

  <img src="https://img-home.csdnimg.cn/images/20230724024159.png?origin_url=https%3A%2F%2Fgitee.com%2Frawait%2Frwpicgo%2Fraw%2Fmaster%2Fteaching%2F2022-01-03%2F202201032323026.png&pos_id=img-rQ8QhapN-1695633577683)" alt="image-20220103232309923" />

- 一百个和尚分一百个馒头,大和尚一人分三个,小和尚三人分一个,正好分完。问大、小和尚各几人?

- 公鸡一个五块钱,母鸡一个三块钱,小鸡三个一块钱,现在要用一百块钱买一百只鸡,问公鸡、母鸡、小鸡各多少只?

- 红白球共25个,白黑球共31个,红黑球共28个,求三种球各有多少?求红白黑球的个数

Guess you like

Origin blog.csdn.net/zhangchen124/article/details/133277087