JavaScript tutorial quick start

Posted by cmattoon on Sun, 02 Jan 2022 22:47:03 +0100

JavaScript quick start

Basic grammar

grammar

The syntax of JavaScript is similar to that of the Java language. Each statement is written in; End the statement block with {...}. However, JavaScript does not force you to add;, at the end of each statement;, The engine responsible for executing JavaScript code in the browser will automatically add; at the end of each statement;.

For example, the following line of code is a complete assignment statement:

var x = 1;

The following line of code is a string, but it can still be regarded as a complete statement:

'Hello, world';

The following line of code contains two statements, each with; Indicates the end of the statement:

var x = 1; var y = 2; // It is not recommended to write multiple statements on one line!

A statement block is a set of statements. For example, the following code makes a judgment first. If the judgment is true, it will execute {...} All statements in:

if (2 > 1) {
    x = 1;
    y = 2;
    z = 3;
}

Note the curly braces {...} Statements within have indents, usually 4 spaces. Indentation is not required by JavaScript syntax, but indentation helps us understand the level of code, so we should follow the indentation rules when writing code. Many text editors have the function of "automatic indentation" to help organize the code.

{...} You can also nest to form a hierarchy:

if (2 > 1) {
    x = 1;
    y = 2;
    z = 3;
    if (x < y) {
        z = 4;
    }
    if (x > y) {
        z = 5;
    }
}

JavaScript itself has no limit on the level of nesting, but too much nesting will undoubtedly greatly increase the difficulty of understanding the code. In this case, you need to extract part of the code and call it as a function, which can reduce the complexity of the code.

notes

Comments are the same as java comments

Characters starting with / / and ending at the end of the line are regarded as line comments. Comments are presented to developers and will be automatically ignored by the JavaScript engine:

// This is a line of comments
alert('hello'); // This is also a comment

Another block annotation is / **/ Wrap multiple lines of characters and treat a large "block" as a comment:

/* Starting here is the block annotation
 Still comments
 Still comments
 End of comment */

Case

Please note that JavaScript is strictly case sensitive. If the case is wrong, the program will report an error or run abnormally.

Data types and variables

Basic data type

As the name suggests, a computer is a machine that can do mathematical calculations. Therefore, computer programs can naturally deal with all kinds of numerical values. However, the computer can process not only numerical values, but also text, graphics, audio, video, web pages and other data. Different data needs to define different data types. The following data types are defined in JavaScript:

Number

JavaScript does not distinguish between integers and floating-point numbers. It is uniformly represented by Number. The following are legal Number types:

123; // Integer 123
0.456; // Floating point number 0.456
1.2345e3; // Scientific counting means 1.2345x1000, which is equivalent to 1234.5
-99; // negative
NaN; // NaN means Not a Number. When the result cannot be calculated, NaN means Not a Number
Infinity; // Infinity means infinity. When the value exceeds the maximum value that JavaScript Number can represent, it means infinity

Because computers use binary, it is sometimes convenient to use hexadecimal to represent integers. Hexadecimal is represented by 0x prefix and 0-9, a-f, such as 0xff00, 0xa5b4c3d2, etc., which are exactly the same as the values represented by decimal.

Number can directly perform four operations, and the rules are consistent with mathematics:

1 + 2; // 3
(1 + 2) * 5 / 2; // 7.5
2 / 0; // Infinity
0 / 0; // NaN
10 % 3; // 1
10.5 % 3; // 1.5

Note that% is a remainder operation.

character string

String is any text enclosed in single quotation marks or double quotation marks, such as' abc ',' xyz ', etc. Please note that' 'or "" itself is only a representation, not a part of the string. Therefore, the string' abc 'has only three characters: A, b and c.

Boolean value

Boolean values are completely consistent with Boolean algebra. A Boolean value has only two values: true and false, either true or false. You can directly use true and false to represent Boolean values or calculate them through Boolean operations:

true; // This is a true value
false; // This is a false value
2 > 1; // This is a true value
2 >= 3; // This is a false value

&&The operation is an and operation, and the & & operation result is true only if all are true:

true && true; // This & & statement evaluates to true
true && false; // This & & statement evaluates to false
false && true && false; // This & & statement evaluates to false

||The operation is an or operation. As long as one of them is true, the operation result is true:

false || false; // This | statement evaluates to false
true || false; // This | statement evaluates to true
false || true || false; // This | statement evaluates to true

! The operation is a non operation. It is a unary operator, changing true to false and false to true:

! true; // The result is false
! false; // The result is true
! (2 > 5); // The result is true

Boolean values are often used in condition judgment, such as:

var age = 15;
if (age >= 18) {
    alert('adult');
} else {
    alert('teenager');
}

Comparison operator

When we compare numbers, we can get a Boolean value through the comparison operator:

2 > 5; // false
5 >= 2; // true
7 == 7; // true

In fact, JavaScript allows you to compare any data type:

false == 0; // true
false === 0; // false

Pay special attention to the equality operator = =. JavaScript is designed with two comparison operators:

The first is = = comparison, which will automatically convert the data type for comparison. In many cases, very strange results will be obtained;

The second is = = = comparison, which does not automatically convert data types. If the data types are inconsistent, false is returned. If they are consistent, compare again.

Due to the design defect of JavaScript, do not use = = = comparison. Always use = = = comparison.

Another exception is that the special Number NaN is not equal to all other values, including itself:

NaN === NaN; // false

The only way to judge NaN is through the isNaN() function:

isNaN(NaN); // true

Finally, pay attention to the equality comparison of floating-point numbers:

1 / 3 === (1 - 2 / 3); // false

This is not a design flaw in JavaScript. Floating point numbers will produce errors in the operation process, because the computer cannot accurately represent infinite circular decimals. To compare whether two floating-point numbers are equal, you can only calculate the absolute value of their difference to see if it is less than a threshold:

Math.abs(1 / 3 - (1 - 2 / 3)) < 0.0000001; // true

null and undefined

Null represents an "empty" value, which is different from 0 and the empty string ''. 0 is a numeric value, '' represents a string of length 0, and null represents "empty".

In other languages, there are also null expressions similar to JavaScript. For example, Java also uses null, Swift uses nil, and Python uses None. However, in JavaScript, there is also an undefined similar to null, which means "undefined".

JavaScript designers want to use null to represent an empty value, while undefined means that the value is undefined. Facts have proved that this is of little use, and it is of little significance to distinguish between the two. In most cases, we should use null. Undefined is only useful when judging whether a function parameter is passed.

array

An array is a set of sequentially arranged collections, each value of which is called an element. Arrays of JavaScript can include any data type. For example:

[1, 2, 3.14, 'Hello', null, true];

The above array contains 6 elements. Arrays are represented by [] and elements are separated by.

Another way to create an array is through the Array() function:

new Array(1, 2, 3); // Created array [1, 2, 3]

However, for the sake of code readability, it is strongly recommended to use [].

The elements of the array can be accessed by index. Note that the starting value of the index is 0:

var arr = [1, 2, 3.14, 'Hello', null, true];
arr[0]; // Returns the element with index 0, i.e. 1
arr[5]; // Returns the element with index 5, that is, true
arr[6]; // Index out of range, return undefined

object

JavaScript objects are a set of unordered collections composed of key values, such as:

var person = {
    name: 'Bob',
    age: 20,
    tags: ['js', 'web', 'mobile'],
    city: 'Beijing',
    hasCar: true,
    zipcode: null
};

The keys of JavaScript objects are all string types, and the values can be any data type. The above person object defines a total of 6 key value pairs, and each key is also called the attribute of the object. For example, the name attribute of person is' Bob ', and the zipcode attribute is null.

To get the properties of an object, we use object variables How attribute names are:

person.name; // 'Bob'
person.zipcode; // null

character string

JavaScript strings are represented by characters enclosed by '' or ''.

If 'itself is also a character, it can be enclosed by "". For example, "I'm OK" contains six characters: I,', m, space, O and K.

What if the string contains both 'and'? It can be identified by the escape character \, such as:

'I\'m \"OK\"!';

The content of the string is: I'm "OK"!

Escape character \ can escape many characters, such as \ n for line feed, \ t for tab, and the character \ itself needs to be escaped, so the character represented by \ \ is \.

ASCII characters can be represented in hexadecimal in the \ x## form, for example:

'\x41'; // Exactly equivalent to 'A'

You can also use \ u##### to represent a Unicode character:

'\u4e2d\u6587'; // Exactly equivalent to 'Chinese'

Multiline string

Because multi line strings are cumbersome to write in \ n, the latest ES6 standard adds a representation method of multi line strings, using backquotes express:

`This is a
 Multiline
 character string`;

Note: the back quote is below ESC on the keyboard and to the left of number key 1:

┌─────┐ ┌─────┬─────┬─────┬─────┐
│ ESC │ │ F1  │ F2  │ F3  │ F4  │
│     │ │     │     │     │     │
└─────┘ └─────┴─────┴─────┴─────┘
┌─────┬─────┬─────┬─────┬─────┐
│  ~  │  !  │  @  │  #  │  $  │
│  `  │  1  │  2  │  3  │  4  │
├─────┴──┬──┴──┬──┴──┬──┴──┬──┘
│        │     │     │     │
│  tab   │  Q  │  W  │  E  │
├────────┴──┬──┴──┬──┴──┬──┘
│           │     │     │
│ caps lock │  A  │  S  │
└───────────┴─────┴─────┘

Template string

To connect multiple strings, use the + sign:

var name = 'Xiao Ming';
var age = 20;
var message = 'Hello, ' + name + ', You this year' + age + 'Years old!';
alert(message);

If many variables need to be connected, it is troublesome to use the + sign. ES6 adds a new template string. The representation method is the same as the above multi line string, but it will automatically replace the variables in the string:

var name = 'Xiao Ming';
var age = 20;
var message = `Hello, ${name}, You this year ${age}Years old!`;
alert(message);

Exercise: test whether your browser supports ES6 template string. If not, please change the template string to + connected ordinary string:

'use strict';

// If the browser supports the template string, the variables inside the string will be replaced:
var name = 'Xiao Ming';
var age = 20;

Operation string

Common operations of string are as follows:

var s = 'Hello, world!';
s.length; // 13

To get the character at a specified position in the string, use an Array like subscript operation, and the index number starts from 0:

var s = 'Hello, world!';

s[0]; // 'H'
s[6]; // ' '
s[7]; // 'w'
s[12]; // '!'
s[13]; // Undefined indexes that exceed the range will not report an error, but will always return undefined

It should be noted that the string is immutable. If an index of the string is assigned, there will be no error, but there will be no effect:

var s = 'Test';
s[0] = 'X';
alert(s); // s is still 'Test'

JavaScript provides some common methods for strings. Note that calling these methods will not change the content of the original string, but return a new string:

toUpperCase

toUpperCase() capitalizes a string:

var s = 'Hello';
s.toUpperCase(); // Return to 'HELLO'

toLowerCase

toLowerCase() changes all strings to lowercase:

var s = 'Hello';
var lower = s.toLowerCase(); // Return 'hello' and assign it to the variable lower
lower; // 'hello'

indexOf

indexOf() searches where the specified string appears:

var s = 'hello, world';
s.indexOf('world'); // Return 7
s.indexOf('World'); // If the specified substring is not found, - 1 is returned

substring

substring() returns the substring of the specified index interval:

var s = 'hello, world'
s.substring(0, 5); // From index 0 to 5 (excluding 5), return 'hello'
s.substring(7); // From index 7 to the end, return 'world'

array

JavaScript's Array can contain any data type and access each element through an index.

To obtain the length of the Array, directly access the length attribute:

var arr = [1, 2, 3.14, 'Hello', null, true];
arr.length; // 6

Please note that directly assigning a new value to the length of the Array will change the size of the Array:

var arr = [1, 2, 3];
arr.length; // 3
arr.length = 6;
arr; // arr becomes [1, 2, 3, undefined, undefined, undefined]
arr.length = 2;
arr; // arr becomes [1, 2]

Array can modify the corresponding element to a new value through the index. Therefore, assigning a value to the index of array will directly modify the array:

var arr = ['A', 'B', 'C'];
arr[1] = 99;
arr; // arr now becomes ['a ', 99,' C ']

Please note that if the index exceeds the range during index assignment, the Array size will also change:

var arr = [1, 2, 3];
arr[5] = 'x';
arr; // arr becomes [1, 2, 3, undefined, undefined, 'x']

Most other programming languages do not allow you to directly change the size of the Array. If you access the index beyond the bounds, you will report an error. However, the JavaScript Array does not have any errors. When writing code, it is not recommended to directly modify the size of the Array. When accessing the index, ensure that the index does not cross the boundary.

indexOf

Similar to String, Array can also search the location of a specified element through indexOf():

var arr = [10, 20, '30', 'xyz'];
arr.indexOf(10); // The index of element 10 is 0
arr.indexOf(20); // The index of element 20 is 1
arr.indexOf(30); // Element 30 is not found, return - 1
arr.indexOf('30'); // The index of element '30' is 2

Note that the number 30 and the string '30' are different elements.

slice

slice() is the substring() version of the corresponding String. It intercepts some elements of the Array and returns a new Array:

var arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
arr.slice(0, 3); // From index 0 to index 3, but excluding index 3: ['A', 'B', 'C']
arr.slice(3); // From index 3 to end: ['d ',' e ',' f ',' g ']

Note that the start and end parameters of slice() include the start index and not the end index.

If slice() is not passed any parameters, it intercepts all elements from beginning to end. Using this, we can easily copy an Array:

var arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
var aCopy = arr.slice();
aCopy; // ['A', 'B', 'C', 'D', 'E', 'F', 'G']
aCopy === arr; // false

push and pop

push() adds several elements to the end of the Array, and pop() deletes the last element of the Array:

var arr = [1, 2];
arr.push('A', 'B'); // Return the new length of Array: 4
arr; // [1, 2, 'A', 'B']
arr.pop(); // pop() returns' B '
arr; // [1, 2, 'A']
arr.pop(); arr.pop(); arr.pop(); // pop 3 times continuously
arr; // []
arr.pop(); // If the empty array continues, pop will not report an error, but return undefined
arr; // []

unshift and shift

If you want to add several elements to the head of the Array, use the unshift() method. The shift() method deletes the first element of the Array:

var arr = [1, 2];
arr.unshift('A', 'B'); // Return the new length of Array: 4
arr; // ['A', 'B', 1, 2]
arr.shift(); // 'A'
arr; // ['B', 1, 2]
arr.shift(); arr.shift(); arr.shift(); // 3 consecutive shifts
arr; // []
arr.shift(); // If the empty array continues to shift, no error will be reported, but undefined will be returned
arr; // []

sort

sort() can sort the current Array. It will directly modify the element position of the current Array. When called directly, it will be sorted according to the default order:

var arr = ['B', 'C', 'A'];
arr.sort();
arr; // ['A', 'B', 'C']

Can we sort according to the order we specify? Absolutely. We'll talk about it later in the function.

reverse

reverse() calls the elements of the entire Array, that is, reverse:

var arr = ['one', 'two', 'three'];
arr.reverse(); 
arr; // ['three', 'two', 'one']

splice

The splice() method is a "universal method" to modify the Array. It can delete several elements from the specified index, and then add several elements from this position:

var arr = ['Microsoft', 'Apple', 'Yahoo', 'AOL', 'Excite', 'Oracle'];
// Delete three elements from index 2, and then add two more elements:
arr.splice(2, 3, 'Google', 'Facebook'); // Return deleted elements ['yahoo ',' AOL ',' excite ']
arr; // ['Microsoft', 'Apple', 'Google', 'Facebook', 'Oracle']
// Delete only, do not add:
arr.splice(2, 2); // ['Google', 'Facebook']
arr; // ['Microsoft', 'Apple', 'Oracle']
// Add only, not delete:
arr.splice(2, 0, 'Google', 'Facebook'); // Returned [], because no element was deleted
arr; // ['Microsoft', 'Apple', 'Google', 'Facebook', 'Oracle']

concat

The concat() method connects the current Array with another Array and returns a new Array:

var arr = ['A', 'B', 'C'];
var added = arr.concat([1, 2, 3]);
added; // ['A', 'B', 'C', 1, 2, 3]
arr; // ['A', 'B', 'C']

Note that the concat() method does not modify the current Array, but returns a new Array.

In fact, the concat() method can receive any element and Array, automatically disassemble the Array, and then add them all to the new Array:

var arr = ['A', 'B', 'C'];
arr.concat(1, 2, [3, 4]); // ['A', 'B', 'C', 1, 2, 3, 4]

join

The join() method is a very practical method. It connects each element of the current Array with the specified string, and then returns the connected string:

var arr = ['A', 'B', 'C', 1, 2, 3];
arr.join('-'); // 'A-B-C-1-2-3'

If the element of Array is not a string, it will be automatically converted to a string and then connected.

Multidimensional array

If an element of the Array is an Array, a multidimensional Array can be formed, for example:

var arr = [[1, 2, 3], [400, 500, 600], '-'];

The above Array contains three elements, and the first two elements themselves are Array.

object

The object of JavaScript is an unordered collection data type, which is composed of several key value pairs.

JavaScript objects are used to describe an object in the real world. For example, in order to describe the naughty child "Xiao Ming", we can use several key value pairs to describe him:

var xiaoming = {
    name: 'Xiao Ming',
    birth: 1990,
    school: 'No.1 Middle School',
    height: 1.70,
    weight: 65,
    score: null
};

JavaScript uses a {...} Represents an object. Key value pairs are declared in the form of xxx: xxx, separated by. Note that the last key value pair does not need to be added at the end. If it is added, some browsers (such as lower versions of IE) will report an error.

The above object declares a name attribute with a value of 'xiaoming', a birth attribute with a value of 1990, and some other attributes. Finally, after assigning this object to the variable xiaoming, you can obtain xiaoming's attributes through the variable xiaoming:

xiaoming.name; // 'Xiao Ming'
xiaoming.birth; // 1990

Access to properties is through Operator, but this requires that the property name must be a valid variable name. If the property name contains special characters, it must be enclosed with '':

var xiaohong = {
    name: 'Xiao Hong',
    'middle-school': 'No.1 Middle School'
};

xiaohong's property name middle school is not a valid variable, so it needs to be enclosed with ''. Access to this property is also unavailable Operator, which must be accessed with ['xxx ']:

xiaohong['middle-school']; // 'No.1 Middle School'
xiaohong['name']; // 'little red'
xiaohong.name; // 'little red'

You can also use xiaohong['name '] to access xiaohong's name attribute, but xiaohong Name is more concise. When we write JavaScript code, we try to use standard variable names for attribute names, so that we can directly use object Access a property in the form of prop.

In fact, all properties of JavaScript objects are strings, but the value corresponding to the property can be any data type.

What will be returned if you access a non-existent property? JavaScript stipulates that accessing nonexistent attributes does not report an error, but returns undefined:

'use strict';

var xiaoming = {
    name: 'Xiao Ming'
};

Run

Because JavaScript objects are dynamically typed, you can freely add or delete attributes to an object:

var xiaoming = {
    name: 'Xiao Ming'
};
xiaoming.age; // undefined
xiaoming.age = 18; // Add an age attribute
xiaoming.age; // 18
delete xiaoming.age; // Delete age attribute
xiaoming.age; // undefined
delete xiaoming['name']; // Delete name attribute
xiaoming.name; // undefined
delete xiaoming.school; // Deleting a nonexistent school attribute will not report an error

If we want to check whether xiaoming has a certain attribute, we can use the in operator:

var xiaoming = {
    name: 'Xiao Ming',
    birth: 1990,
    school: 'No.1 Middle School',
    height: 1.70,
    weight: 65,
    score: null
};
'name' in xiaoming; // true
'grade' in xiaoming; // false

However, be careful. If in judges that an attribute exists, it may not be xiaoming's attribute, but it may be inherited by xiaoming:

'toString' in xiaoming; // true

Because toString is defined in the object object, and all objects will eventually point to the object on the prototype chain, xiaoming also has the toString attribute.

To determine whether a property is owned by xiaoming rather than inherited, you can use the hasOwnProperty() method:

var xiaoming = {
    name: 'Xiao Ming'
};
xiaoming.hasOwnProperty('name'); // true
xiaoming.hasOwnProperty('toString'); // false

Conditional judgment

JavaScript uses if () {...} else { ... } To make conditional judgment. For example, different contents can be displayed according to age, which can be realized with if statement as follows:

var age = 20;
if (age >= 18) { // If age > = 18 is true, the if statement block is executed
    alert('adult');
} else { // Otherwise, execute else statement block
    alert('teenager');
}

The else statement is optional. If the statement block contains only one statement, you can omit {}:

var age = 20;
if (age >= 18)
    alert('adult');
else
    alert('teenager');

The danger of omitting {} is that if you want to add some statements later, but forget to write {}, you will change if else... Semantics of, for example:

var age = 20;
if (age >= 18)
    alert('adult');
else
    console.log('age < 18'); // Add a line of log
    alert('teenager'); // < - this line is no longer under the control of else

The else clause of the above code is actually only responsible for executing console log('age < 18');, The original alert('teenager '); No longer belongs to if else... The control range of the is. It will be executed every time.

On the contrary, if there is {}, there will be no error:

var age = 20;
if (age >= 18) {
    alert('adult');
} else {
    console.log('age < 18');
    alert('teenager');
}

That's why we suggest that you always write {}.

Multi line conditional judgment

If you want to judge the conditions more carefully, you can use multiple if else... Combination of:

var age = 3;
if (age >= 18) {
    alert('adult');
} else if (age >= 6) {
    alert('teenager');
} else {
    alert('kid');
}

The above multiple if else... The combination of is actually equivalent to two layers of if else...:

var age = 3;
if (age >= 18) {
    alert('adult');
} else {
    if (age >= 6) {
        alert('teenager');
    } else {
        alert('kid');
    }
}

But we usually write else and if together to increase readability. There is no problem with omitting {} in else here, because it contains only one if statement. Note that the last separate else should not be omitted {}.

Note that if else... The execution feature of the statement is one of two, in multiple if else... In the statement, if a condition is true, the subsequent judgment will not be continued.

What if the conditional judgment statement result of if is not true or false? For example:

var s = '123';
if (s.length) { // The condition calculation result is 3
    //
}

JavaScript regards null, undefined, 0, NaN and empty string '' as false, and all other values are regarded as true. Therefore, the judgment result of the above code condition is true.

loop

To calculate 1 + 2 + 3, we can write the expression directly:

1 + 2 + 3; // 6

To calculate 1 + 2 + 3 +... + 10, you can barely write it.

However, to calculate 1 + 2 + 3 +... + 10000, it is impossible to write an expression directly.

In order for the computer to calculate thousands of repetitions, we need circular statements.

There are two types of JavaScript loops. One is the for loop, which circulates the execution of statement blocks through initial conditions, end conditions and incremental conditions:

var x = 0;
var i;
for (i=1; i<=10000; i++) {
    x = x + i;
}
x; // 50005000

Let's analyze the control conditions of the for loop:

  • i=1, which is the initial condition. Set the variable i to 1;
  • I < = 10000, which is the judgment condition. If it is satisfied, continue the cycle, and if it is not satisfied, exit the cycle;
  • i + + this is the increment condition after each cycle. Since the variable i will add 1 after each cycle, it will eventually exit the cycle after several cycles without meeting the judgment condition i < = 10000.

The most common place for the for loop is to use the index to traverse the array:

var arr = ['Apple', 'Google', 'Microsoft'];
var i, x;
for (i=0; i<arr.length; i++) {
    x = arr[i];
    console.log(x);
}

The three conditions of the for loop can be omitted. If there is no judgment condition to exit the loop, you must use the break statement to exit the loop, otherwise it is an endless loop:

var x = 0;
for (;;) { // Loop on indefinitely
    if (x > 100) {
        break; // Exit the loop by if judgment
    }
    x ++;
}

for ... in

A variant of the for loop is for In loop, which can loop out all attributes of an object in turn:

var o = {
    name: 'Jack',
    age: 20,
    city: 'Beijing'
};
for (var key in o) {
    console.log(key); // 'name', 'age', 'city'
}

To filter out the inherited properties of the object, use hasOwnProperty():

var o = {
    name: 'Jack',
    age: 20,
    city: 'Beijing'
};
for (var key in o) {
    if (o.hasOwnProperty(key)) {
        console.log(key); // 'name', 'age', 'city'
    }
}

Since Array is also an object, and the index of each element of it is regarded as an attribute of the object, for In loop can directly loop out the index of Array:

var a = ['A', 'B', 'C'];
for (var i in a) {
    console.log(i); // '0', '1', '2'
    console.log(a[i]); // 'A', 'B', 'C'
}

Note that for The loop of in to Array gets String instead of Number.

while

The for loop is useful when the initial and end conditions of the loop are known. The for loop that ignores the conditions above is easy to make people unable to see the logic of the loop. At this time, it is better to use the while loop.

The while loop has only one judgment condition. If the condition is met, the loop will continue. If the condition is not met, the loop will exit. For example, if we want to calculate the sum of all odd numbers within 100, we can use the while loop:

var x = 0;
var n = 99;
while (n > 0) {
    x = x + n;
    n = n - 2;
}
x; // 2500

In the loop, the variable n decreases continuously until it becomes - 1. When the while condition is no longer satisfied, the loop exits.

do ... while

The last loop is do {...} The only difference between the while () loop and the while loop is that the condition is not judged at the beginning of each loop, but at the completion of each loop:

var n = 0;
do {
    n = n + 1;
} while (n < 100);
n; // 100

Use do {...} Be careful with the while () loop. The loop will execute at least once, while the for and while loops may not execute at all.

Summary

Loop is an effective way to let the computer do repetitive tasks. Sometimes, if the code is written incorrectly, the program will fall into "dead loop", that is, loop forever. The dead loop of JavaScript will make the browser unable to display or execute the logic of the current page normally. Some browsers will hang up directly, and some browsers will prompt you to forcibly terminate the execution of JavaScript after a period of time. Therefore, pay special attention to the problem of dead loop.

When writing loop code, be careful to write initial and judgment conditions, especially boundary values. In particular, note that I < 100 and I < = 100 are different judgment logic.

Map and Set

The default object representation {} of JavaScript can be regarded as the data structure of Map or Dictionary in other languages, that is, a set of key value pairs.

But there is a small problem with JavaScript objects, that is, the key must be a string. But in fact, Number or other data types are also very reasonable as keys.

Map

Map is the structure of a group of key value pairs, which has extremely fast search speed.

For example, suppose you want to find the corresponding grades according to the students' names. If you use Array, you need two arrays:

var names = ['Michael', 'Bob', 'Tracy'];
var scores = [95, 75, 85];

Given a name, to find the corresponding score, first find the corresponding position in the names, and then take the corresponding score from the scores. The longer the Array, the longer the time.

If you use Map, you only need a cross reference table of "name" - "score" to find the score directly according to the name. No matter how large the table is, the search speed will not slow down. Write a Map in JavaScript as follows:

var m = new Map([['Michael', 95], ['Bob', 75], ['Tracy', 85]]);
m.get('Michael'); // 95

Initializing a map requires a two-dimensional array, or directly initializing an empty map. Map has the following methods:

var m = new Map(); // Empty Map
m.set('Adam', 67); // Add new key value
m.set('Bob', 59);
m.has('Adam'); // Whether key 'Adam' exists: true
m.get('Adam'); // 67
m.delete('Adam'); // Delete key 'Adam'
m.get('Adam'); // undefined

Since a key can only correspond to one value, if you put value into a key multiple times, the following value will flush out the previous value:

var m = new Map();
m.set('Adam', 67);
m.set('Adam', 88);
m.get('Adam'); // 88

Set

Like Map, Set is also a Set of keys, but does not store value. Since keys cannot be repeated, there are no duplicate keys in the Set.

To create a Set, you need to provide an Array as input, or directly create an empty Set:

var s1 = new Set(); // Empty Set
var s2 = new Set([1, 2, 3]); // Including 1, 2 and 3

Duplicate elements are automatically filtered in the Set:

var s = new Set([1, 2, 3, 3, '3']);
s; // Set {1, 2, 3, "3"}

Note that the number 3 and the string '3' are different elements.

You can add elements to the Set by using the add(key) method. You can add elements repeatedly, but it will not have any effect:

s.add(4);
s; // Set {1, 2, 3, 4}
s.add(4);
s; // Still Set {1, 2, 3, 4}

Elements can be deleted through the delete(key) method:

var s = new Set([1, 2, 3]);
s; // Set {1, 2, 3}
s.delete(3);
s; // Set {1, 2}

iterable

Subscript loops can be used to traverse array, and subscripts cannot be used to traverse Map and Set. In order to unify collection types, the ES6 standard introduces new iterable types. Array, Map and Set all belong to iterable types.

Collections with iterable types can be accessed through the new for Of loop.

Use for Of loop traverses the collection. The usage is as follows:

var a = ['A', 'B', 'C'];
var s = new Set(['A', 'B', 'C']);
var m = new Map([[1, 'x'], [2, 'y'], [3, 'z']]);
for (var x of a) { // Traverse Array
    console.log(x);
}
for (var x of s) { // Traversal Set
    console.log(x);
}
for (var x of m) { // Traverse Map
    console.log(x[0] + '=' + x[1]);
}

You may have questions, for Of loop and for What is the difference between in cycles?

for ... The in loop actually traverses the attribute name of the object due to historical problems. An Array is actually an object, and the index of each element of it is regarded as an attribute.

When we manually add additional properties to the Array object, for The in loop will have unexpected effects:

var a = ['A', 'B', 'C'];
a.name = 'Hello';
for (var x in a) {
    console.log(x); // '0', '1', '2', 'name'
}

for ... The in loop will include name, but not the length attribute of Array.

for ... The of loop completely fixes these problems. It only loops the elements of the collection itself:

var a = ['A', 'B', 'C'];
a.name = 'Hello';
for (var x of a) {
    console.log(x); // 'A', 'B', 'C'
}

That's why the new for Of loop.

Note that the forEach() method is Es5 1 standard, you need to test whether the browser supports it.

Set is similar to Array, but set has no index, so the first two parameters of the callback function are the element itself:

var s = new Set(['A', 'B', 'C']);
s.forEach(function (element, sameElement, set) {
    console.log(element);
});

The callback function parameters of map are value, key and map itself:

var m = new Map([[1, 'x'], [2, 'y'], [3, 'z']]);
m.forEach(function (value, key, map) {
    console.log(value);
});

If you are not interested in some parameters, you can ignore them because JavaScript function calls do not require that the parameters must be consistent. For example, you only need to obtain the element of the Array:

var a = ['A', 'B', 'C'];
a.forEach(function (element) {
    console.log(element);
});

Topics: Javascript ECMAScript