Chapter 7 data processing

achievements

chapter Code quantity (line)
7.1

7.1 array

An array is a collection of ordered elements. In JavaScript, the length of an array is variable. As long as you add elements to the end of the array, the length of the array will increase automatically. At the same time, each element in the array can be rewritten freely. In fact, this is not surprising, but it should be, because in JavaScript, array is also an object. Arrays are just some properties of objects that inherit JavaScript.

7.1.1 array of JavaScript

In JavaScript, arrays can be generated by literal and new expressions. The generation of new expression will be explained in the next section. Here is an example of array literal.

// Examples of array literals

var hzh1 = [3, 4, 5];
console.log("hzh1 The data types are:");
console.log(typeof hzh1);   // After the typeof operation on the array is object
[Running] node "e:\HMV\JavaScript\JavaScript.js"
hzh1 The data types are:
object

[Done] exited with code=0 in 2.555 seconds

Array literals are written by listing the array elements in brackets ([]) and separating them by commas. The length of an array without elements is zero.

var hzh2 = [];
console.log("hzh2 The length of the is:" + hzh2.length);
[Running] node "e:\HMV\JavaScript\JavaScript.js"
hzh2 The length of is: 0

[Done] exited with code=0 in 0.926 seconds

In JavaScript, we usually form an array with a length of zero, and then add elements to it.

var hzh4 = [];
hzh4[0] = "Huang Zihan";
hzh4[1] = "It's a handsome man!"
console.log("hzh[0] = " + hzh4[0]);
console.log("hzh[1] = " + hzh4[1]);
console.log("hzh[0] + hzh[0] = " + (hzh4[0] + hzh4[1]));
[Running] node "e:\HMV\JavaScript\JavaScript.js"
hzh[0] = Huang Zihan
hzh[1] = It's a handsome man!
hzh[0] + hzh[0] = Huang Zihan is a handsome man!

[Done] exited with code=0 in 8.728 seconds

In JavaScript, we can specify any value or object reference as an element, and there is no need to ensure the consistency of element types in the array. You may not be surprised by this feature because you already know that you can assign any type of value to a variable, but it is really different from Java sequence. In Java, in principle, the elements in the same array must be of the same type. On the one hand, the high degree of freedom of JavaScript is really convenient, but on the other hand, it may also cause element assignment errors caused by unexpected data type conversion, so please pay more attention to this.

// There is no need to ensure that the types of elements are consistent.
var hzh5 = 'Huang Zihan';
var hzh6 = [1, 'Huang Zihan', hzh5, true, null, undefined, 
            {hzh7: 3, hzh8: 4}, [2, 'hzh9'], 
            function(hzh10, hzh11) {
                return Number(hzh10) + Number(hzh11);
            }
];
console.log("hzh6 = " + hzh6);
[Running] node "e:\HMV\JavaScript\JavaScript.js"
hzh6 = 1,Huang Zihan,Huang Zihan,true,,,[object Object],2,hzh9,function(hzh10, hzh11) {
                return Number(hzh10) + Number(hzh11);
            }

[Done] exited with code=0 in 0.795 seconds

When writing array literals, you can also omit some intermediate elements. The value of the omitted element will be considered an undefined value.

// An array in which intermediate elements are omitted,. The value of the omitted element will be considered an undefined value.
var hzh12 = [3, ,5];
console.log("hzh12[0] = " + hzh12[0]);
console.log("hzh12[1] = " + hzh12[1]);
console.log("hzh12[2] = " + hzh12[2]);
[Running] node "e:\HMV\JavaScript\JavaScript.js"
hzh12[0] = 3
hzh12[1] = undefined
hzh12[2] = 5

[Done] exited with code=0 in 0.196 seconds

In ECMAScript, if the array literal is written with a comma as follows, the comma will be ignored. However, in the old version of Internet Explorer, the cause of this error is well known. Therefore, you should avoid using commas at the end of arrays.

var hzh13 = [3, 4, ];
console.log("hzh13[0] = " + hzh13[0]);
console.log("hzh13[1] = " + hzh13[1]);
console.log("hzh13[2] = " + hzh13[2]);
console.log("hzh13 Length of: " + hzh13.length);
[Running] node "e:\HMV\JavaScript\JavaScript.js"
hzh13[0] = 3
hzh13[1] = 4
hzh13[2] = undefined
hzh13 Length of: 2

[Done] exited with code=0 in 0.285 seconds

7.1.2 access to array elements

You can access the elements of the array through the bracket operator ([] operator). What is written in [] is the value of the subscript. Subscripts start with 0. If the subscript does not have a corresponding element, an undefined value is obtained.

// Examples of using arrays

var hzh1 = [3, 4, 5];
console.log("Output separately hzh Array elements:");
console.log("hzh1[0] = " + hzh1[0]);
console.log("hzh1[1] = " + hzh1[1]);
console.log("hzh1[2] = " + hzh1[2]);
console.log("hzh1[3] = " + hzh1[3]);
[Running] node "e:\HMV\JavaScript\JavaScript.js"
Output separately hzh Array elements:
hzh1[0] = 3
hzh1[1] = 4
hzh1[2] = 5
hzh1[3] = undefined

[Done] exited with code=0 in 1.122 seconds

Any expression that results in a numeric value can be used as a subscript. Internally, the expression as a subscript will be evaluated as a string and then used numerically. Therefore, it is OK to use strings that can be interpreted as numeric values as subscripts as follows. However, this will make the code less readable, so it is not recommended.

// Examples of using arrays

var huangzihan = [3, 4, 5];
var hzh0 = '0';
var hzh1 = '1';
var hzh2 = '2';
var hzh3 = '3';
console.log("Output separately huangzihan Array elements:");
console.log("huangzihan[0] = " + huangzihan[hzh0]);
console.log("huangzihan[1] = " + huangzihan[hzh1]);
console.log("huangzihan[2] = " + huangzihan[hzh2]);
console.log("huangzihan[3] = " + huangzihan[hzh3]);
console.log("");
console.log("output huangzihan The 11th element of the array:");
console.log("huangzihan[11] = " + huangzihan[hzh1 + 1]);
console.log("output huangzihan The 22nd element of the array:");
console.log("huangzihan[22] = " + huangzihan[hzh2 + 2]);
console.log("output huangzihan The 33rd element of the array:");
console.log("huangzihan[33] = " + huangzihan[hzh3 + 3]);
console.log("");
var zero = { toString:function() { return '0'} };
var one = { toString:function() { return '1'} };
var two = { toString:function() { return '2'} };
var three = { toString:function() { return '3'} };
console.log("Output separately huangzihan Array elements:");
console.log("huangzihan[0] = " + huangzihan[zero]);
console.log("huangzihan[1] = " + huangzihan[one]);
console.log("huangzihan[2] = " + huangzihan[two]);
console.log("huangzihan[3] = " + huangzihan[three]);
[Running] node "e:\HMV\JavaScript\JavaScript.js"
Output separately huangzihan Array elements:
huangzihan[0] = 3
huangzihan[1] = 4
huangzihan[2] = 5
huangzihan[3] = undefined

output huangzihan The 11th element of the array:
huangzihan[11] = undefined
 output huangzihan The 22nd element of the array:
huangzihan[22] = undefined
 output huangzihan The 33rd element of the array:
huangzihan[33] = undefined

Output separately huangzihan Array elements:
huangzihan[0] = 3
huangzihan[1] = 4
huangzihan[2] = 5
huangzihan[3] = undefined

[Done] exited with code=0 in 0.169 seconds

If the bracket operator is written to the left of the assignment expression, the corresponding element can be overwritten.

// Overwrite elements of array

var huangzihan = [3, 4, 5];
huangzihan[2] = huangzihan[2] * 2; // Overwrite the value of the element with subscript 2
console.log("output huangzihan Array:");
console.log(huangzihan);
[Running] node "e:\HMV\JavaScript\JavaScript.js"
output huangzihan Array:
[ 3, 4, 10 ]

[Done] exited with code=0 in 0.174 seconds

If the subscript written on the left side of the assignment expression exceeds the number of elements, a new element will be added to the array. The subscript value of the new element does not have to be immediately followed by the number of existing elements. If you access the element skipped in the middle, the undefined value is returned.

// Overwrite elements of array

var huangzihan = [3, 4, 5];
huangzihan[3] = 20;

// When the number of elements is 3, if it is assigned to the element with subscript 3 (the fourth element), an element will be added.
console.log("array huangzihan: ");
console.log(huangzihan);
console.log("");
// If you assign a value with a subscript of 10 (the 11th element), the number of elements becomes 11
huangzihan[10] = 100;
console.log("array huangzihan: ");
console.log(huangzihan);
console.log("array huangzihan Length of:");
console.log(huangzihan.length);
console.log("");
//If the skipped element is accessed, the undefined value is returned
console.log("huangzihan[4] = " + huangzihan[4]);
[Running] node "e:\HMV\JavaScript\JavaScript.js"
array huangzihan: 
[ 3, 4, 5, 20 ]

array huangzihan: 
[ 3, 4, 5, 20, <6 empty items>, 100 ]
array huangzihan Length of:
11

huangzihan[4] = undefined

[Done] exited with code=0 in 0.18 seconds

Length of array 7.3

Write the dot operator and length after an array to get the length of the array. The length value of the array is the subscript value of the last element in the array plus 1. The reason why this slightly complex expression is used is that if an array with gaps between elements is generated, the number of elements is different from the length of the array. Please see the specific example below.

var hzh1 = [2,,,,,3]; 
// Unlike the number of elements, the length of the array is
console.log("array hzh1 Length of:" + hzh1.length); 
[Running] node "e:\HMV\JavaScript\JavaScript.js"
array hzh1 Length of: 6

[Done] exited with code=0 in 0.367 seconds

After adding the element to the end, the value of length will increase automatically (code listing 7.1). If some intermediate elements are skipped when adding elements, the value of length is the subscript value of the last element minus 1.

Code listing 7.1 automatic calculation of the length value of the array
var hzh2 = ['zero', 'one', 'two'];
console.log("array hzh2 First time length:" + hzh2.length);
// With the help of hzh2 Length adding an element to the end of an array is a idiom
hzh2[hzh2.length] = 'three';
console.log("array hzh2 Second length:" + hzh2.length);
hzh2[100] = 'Huang Zihan';
console.log("array hzh2 Second length:" + hzh2.length);
[Running] node "e:\HMV\JavaScript\JavaScript.js"
array hzh2 First time length: 3
 array hzh2 Second length: 4
 array hzh2 Second length: 101

[Done] exited with code=0 in 0.186 seconds

You can also explicitly change the value of length (listing 7.2). After rewriting, the length of the array will change accordingly. If the value becomes smaller, the elements in excess will be rounded off. If the value becomes larger, the element of the new part will be undefined.

Code listing 7.2 changing the length of an array
var hzh3 = ['zero', 'one', 'two'];
hzh3.length = 2;     // Shorten the length of the array
console.log("Shortened array:");
console.log(hzh3);   // The last element will be lost
console.log("");
hzh3.length = 3;     // Restore (lengthen) the array to its original length
console.log("Lengthened array:");
console.log(hzh3);   // The new part is the undefined value
console.log("");
console.log("View the data type of the new part:");
console.log(typeof hzh3[2]);
[Running] node "e:\HMV\JavaScript\JavaScript.js"
Shortened array:
[ 'zero', 'one' ]

Lengthened array:
[ 'zero', 'one', <1 empty item> ]

View the data type of the new part:
undefined

[Done] exited with code=0 in 0.165 seconds

Internally, the array length is the length attribute, so it can also be accessed through the bracket operator as follows. However, this has no benefit other than increasing the length of the code, so it is generally not used in this way.

var hzh3 = ['zero', 'one', 'two'];
console.log("Check array length with brackets:");
console.log(hzh3['length']);
console.log("");
console.log("use length Property check array length:");
console.log(hzh3.length);
console.log("");
console.log("The above two judgments are equal:");
console.log(hzh3['length'] == hzh3.length);
[Running] node "e:\HMV\JavaScript\JavaScript.js"
Check array length with brackets:
3

use length Property check array length:
3

The above two judgments are equal:
true

[Done] exited with code=0 in 0.162 seconds

7.1.4 enumeration of array elements

The for statement is the most commonly used way to enumerate array elements. Here is an example.

var hzh1 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log("Enumeration array hzh1 Elements of:");
for(var i = 0, len = hzh1.length; i < len; i++) {
    console.log(hzh1[i]);
}
[Running] node "e:\HMV\JavaScript\JavaScript.js"
Enumeration array hzh1 Elements of:
1
2
3
4
5
6
7
8
9

[Done] exited with code=0 in 0.194 seconds

Although array elements can also be enumerated through the for in statement or for each in statement, they cannot guarantee the order of enumeration. If you want to ensure that the enumeration is in the desired order, use the for statement.

In addition to loop statements such as for statements, there are some methods that can call each element in the array in order. The enumeration of array elements can be realized in this way. Because its internal mechanism is still a circular statement, it is also called internal loop.

special column

Upper limit of array length

In ECMAScript, the upper limit of the array length of JavaScript is the 32nd power of 2. This is different from the upper limit of the value in JavaScript. Please pay attention to it. Values above the 32nd power of 2 will only be recognized as attribute names, not values. Therefore, although it seems that it is possible to add elements with a number greater than 2 to the power of 32, this is not an element of the array, so the value of length will not increase automatically. If the boundary value is exceeded, serious errors may be caused.

var hzh1 = [];
hzh1[Math.pow(2, 32) - 2] = '';
console.log("Length of output array:");
console.log(hzh1.length);        // Array length is 2 ^ 32 - 1
console.log("");
hzh1[Math.pow(2, 32) - 1] = ''; // Although it seems that success has added elements
console.log("See if there are additional elements:");
console.log(hzh1.length);
console.log("");
console.log("2^32-1 Exists as an attribute and is not recognized as a subscript of an array element:")
console.log(Object.keys(hzh1));
[Running] node "e:\HMV\JavaScript\JavaScript.js"
Length of output array:
4294967295

See if there are additional elements:
4294967295

2^32-1 Exists as an attribute and is not recognized as a subscript of an array element:
[ '4294967294', '4294967295' ]

[Done] exited with code=0 in 0.191 seconds

ECMAScript version 5 has several internal loop methods of this type. The most representative forEach method will be introduced below. The parameter of the forEach method should be a function (callback function) that can be called by each element in the array.

The following code can enumerate all elements in the array

Array.forEAch(function(e) {console.log(e);})

Three parameters are passed to the callback function: element, subscript value and array object. Here is a specific example.

var hzh1 = [
    'Huang Zihan is a handsome man!',
    'Huang Zihan is a pretty boy!',
    'Huang Zihan is so powerful!',
    'Huang Zihan is so clever!'
];

// Parameters of callback function
// Parameter e: element value
// Parameter i: subscript value
// Parameter a: array object

hzh1.forEach(function(e, i, a) {
    console.log(i, e);
})
[Running] node "e:\HMV\JavaScript\JavaScript.js"
0 Huang Zihan is a handsome man!
1 Huang Zihan is a pretty boy!
2 Huang Zihan is so powerful!
3 Huang Zihan is so clever!

[Done] exited with code=0 in 0.262 seconds

You can also specify the object pointed to by the this reference in the callback function as the second parameter of forEach.

7.1.5 multidimensional array

Since any content can be specified as an element of an array, the array itself can naturally become an element of another array. If a value is specified as an element of an array, you can access the element by using multiple [] operators in succession, as shown below. An array can even use itself as an element of the array.

var hzh1 = [1, ['hzh2', 'hzh3', 'hzh4', 'hzh5']];
console.log("Output separately hzh1 Elements of the array:");
console.log("hzh1[0] = " + hzh1[0]);
console.log("hzh1[1][0] = " + hzh1[1][0]);
console.log("hzh1[1][1] = " + hzh1[1][1]);
console.log("hzh1[1][2] = " + hzh1[1][2]);
console.log("hzh1[1][3] = " + hzh1[1][3]);
[Running] node "e:\HMV\JavaScript\JavaScript.js"
Output separately hzh1 Elements of the array:
hzh1[0] = 1
hzh1[1][0] = hzh2
hzh1[1][1] = hzh3
hzh1[1][2] = hzh4
hzh1[1][3] = hzh5

[Done] exited with code=0 in 0.164 seconds

7.1.6 an array is an object

In JavaScript, an Array is an object. Internally, it is an object instance of an Array object (Array class). Therefore, you can also call the constructor of Array through the new expression to generate an Array.

Depending on the situation, the parameters passed to the Array constructor can be interpreted in different ways. If the number of parameters is 1 and is a numeric value, it means the length of the Array (number of elements); If the number of parameters is greater than or equal to 2, these parameters represent the elements of the Array. See code listing 7.3 for a specific example.

Listing 7.3 is an example of calling the Array constructor
// If there is only one parameter, the parameter will become the length of the array
var hzh1 = new Array(5);    
console.log("array hzh1: ");
console.log(hzh1);
console.log("");
// Parameters will become elements of the array
var hzh2 = new Array(3, 4, 'huangzihan');
console.log("array hzh2: ");
console.log(hzh2);
console.log("");
// Since implicit data type conversion does not occur, the parameter is converted to a numeric type,
// Therefore, this parameter will be considered as the element with subscript 0 in the array
var hzh3 = new Array('5');
console.log("array hzh3: ");
console.log(hzh3);
[Running] node "e:\HMV\JavaScript\JavaScript.js"
array hzh1: 
[ <5 empty items> ]

array hzh2: 
[ 3, 4, 'huangzihan' ]

array hzh3: 
[ '5' ]

[Done] exited with code=0 in 0.172 seconds

Although the method of generating arrays through new expressions was introduced earlier, if there is no special reason, it is better to use literal expressions to generate arrays, because it is simpler to express through literal expressions. The Array generated by the Array literal expression is also an instance object of Array, which can be confirmed as follows.

var arr = [];    // Generate array objects by array literals
arr.constructor; // In fact, this is no different from the object generated by new Array()
function Array() {
    [native code]
}

When generating an array through a new expression, the meaning of the parameters will change according to the number of parameters, which often leads to errors. In order to avoid unexpected errors, it is recommended not to use this method. However, in some specific cases, it is better to use the new expression. For example, the new expression is more convenient when specifying the length of the array while generating the array.

For example, it is not impossible to generate an array with the number of elements of 100 and the value of each element is uncertain through the literal quantity of the array (you need to write 100 in []), but it will be very troublesome. At this time, it is best to use the new expression. In addition, since the length of the array will increase automatically when adding elements, it is not necessary to specify the length of the array while generating the array. The reason why it is required to specify the length of the array at the same time is to improve the execution efficiency and make the meaning of the array more clear, so as to improve the readability of the code.

The following is an example of calling a method of an array object.

// An example of calling a method of an array object
var hzh4 = ['zero', 'one', 'two'];
// Call the join method
console.log("hzh4.join('_') = " + (hzh4.join('_')));   
console.log("");  
// You can also make method calls to array literals directly        
console.log("[3, 4, 5].join('_') = " + ([3, 4, 5].join('_')));  
[Running] node "e:\HMV\JavaScript\JavaScript.js"
hzh4.join('_') = zero_one_two

[3, 4, 5].join('_') = 3_4_5

[Done] exited with code=0 in 0.161 seconds

The bracket operator here is used to access the elements of the array. In fact, it is used to access the attributes of the object. That is, internally, values such as subscript value 0 or 1 are actually the attribute names of array objects. It can be confirmed by a variety of means, as in code listing 7.4.

As you can see in listing 7.4, length is also one of the attribute names. However, the for statement does not enumerate them. This is because the enumerable attribute of the length attribute is false.

Code listing 7.4 attributes of array
var hzh5 = ['zero', 'one', 'two'];
console.log("Enumeration array hzh5 Attribute value of:");
for (var n in hzh5) {
    console.log(n);               // Enumeration of subscript values, that is, the enumeration of attribute names
}
console.log("Enumeration of property names:" + (Object.keys(hzh5))); 
console.log("Enumeration of property names (ignored) enumerable Properties:" + 
             (Object.getOwnPropertyNames(hzh5)));
// Check whether the subscript 0 exists
console.log("Whether subscript 0 exists:" + ('0' in hzh5));
// The value 0 will be converted to string type '0' for verification
console.log("Verification of value 0:" + (0 in hzh5));
// Check whether the length attribute exists
console.log("yes length Properties to verify:" + ('length' in hzh5));
[Running] node "e:\HMV\JavaScript\tempCodeRunnerFile.js"
Enumeration array hzh5 Attribute value of:
0
1
2
 Enumeration of property names: 0,1,2
 Enumeration of property names (ignored) enumerable Properties): 0,1,2,length
 Whether subscript 0 exists: true
 Verification of value 0: true
 yes length Properties to verify: true

[Done] exited with code=0 in 0.208 seconds

Section 5.9 has explained the use of objects as associative arrays in JavaScript. If interpreted in this way, arrays in JavaScript can be regarded as associative arrays whose key values happen to be continuous values. In addition, it should be noted that if there is no [] operation on an array object with a positive integer, the value will be interpreted as an attribute name for attribute access. Look at the example below.

var hzh6 = ['zero', 'one', 'two'];
hzh6.x = 'X';  // Add attribute x to array object
console.log("Enumeration array hzh6 Attribute value of:");
for(var p in hzh6) {
    console.log(p);
}
[Running] node "e:\HMV\JavaScript\JavaScript.js"
Enumeration array hzh6 Attribute value of:
0
1
2
x

[Done] exited with code=0 in 0.174 seconds

7.1.7 Array class

Table 7.1 functions and constructor calls of array class

Table 7.2 attributes of array class

Table 7.3 array Properties of the prototype object

Table 7.4 instance properties of Array class

7.1.8 significance of array objects

An array is an object, and the subscript value used for element access is its corresponding attribute name.

So, like the following, is the object generated by the object literal equivalent to the array?

var hzh1 = { 
    0: "Huang Zihan is a handsome man!", 
    1: "Huang Zihan is a pretty boy!", 
    2: "Huang Zihan is so clever!",
    3: "Huang Zihan is so powerful!",
}
// Is it with hzh1 = ["Huang Zihan is a handsome guy!", "Huang Zihan is a pretty boy!", 
// "Huang Zihan is so clever!", "Huang Zihan is really awesome!"] Are they the same?
console.log("Check whether they are the same:");
console.log(hzh1[1]); // In this statement, the two seem to be the same
[Running] node "e:\HMV\JavaScript\JavaScript.js"
Check whether they are the same:
Huang Zihan is a pretty boy!

[Done] exited with code=0 in 0.325 seconds

The conclusion is that the above object (associative array) is not an array.

The first difference is the enumerable attribute of the length attribute.

Another difference is that the value of the length attribute of the array will increase automatically. For arrays, the length attribute will be added automatically when new elements are added. Adding elements through the push method or the unshift method can also make the hzh1 objects mentioned above produce the same result, but the effect of increasing the value of the length attribute cannot be achieved only by assigning values to the elements.

[comment] the above words can also be tested.

7.1.9 idioms of arrays

sort

You can sort the element values of the array through the sort method. If the sort method is called without parameters, it is sorted as a string. When sorting in the form of string, sorting is realized by comparing the size of Unicode encoded values. Here is a concrete example.

var hzh1 = ['1', '9', '2', '5', '3', '6', '7', '4', '8'];
console.log("Pair array hzh Sort:");
console.log(hzh1.sort());
console.log("");
var hzh2 = ['Huang Zihan', 'You Yuxi', 'Peng Yuyan', 'Wu Yanzu', 'Jay Chou'];
console.log("Pair array hzh2 Sort:");
console.log(hzh2.sort());
console.log("");
var hzh3 = ['h', 'Z', 'H', 'y', 'X', 'p', 'Y', 'w', 'J', 'l'];
console.log("Pair array hzh3 Sort:");
console.log(hzh3.sort());
[Running] node "e:\HMV\JavaScript\JavaScript.js"
Pair array hzh Sort:
[
  '1', '2', '3',
  '4', '5', '6',
  '7', '8', '9'
]

Pair array hzh2 Sort:
[ 'Wu Yanzu', 'Jay Chou', 'You Yuxi', 'Peng Yuyan', 'Huang Zihan' ]

Pair array hzh3 Sort:
[
  'H', 'J', 'X', 'Y',
  'Z', 'h', 'l', 'p',
  'w', 'y'
]

[Done] exited with code=0 in 0.165 seconds

After sorting, the array will change.

If you want to sort the array in a way other than a string, you need to pass the comparison function as an argument to the sort method. If it is an array of numeric values, you can use the following comparison function. When sorting values using the default string sorting method, although the expected results can be obtained for single digit values. However, it will also produce such a result that 10 is smaller than 2 (please confirm the result of '10' > '2'). Therefore, it should be noted that just because the sorting in string form can get the correct result in the case of single digits, it should not be mistaken that it is also applicable to all numerical sorting.

// Sorting of arrays of values
var hzh = [1, 0, 20, 100, 55];
console.log("Array before output sorting:");
console.log(hzh);
console.log("");
console.log("Output sorted array:");
console.log(hzh.sort(function(a,b) { return a - b; }));
[Running] node "e:\HMV\JavaScript\JavaScript.js"
Array before output sorting:
[ 1, 0, 20, 100, 55 ]

Output sorted array:
[ 0, 1, 20, 55, 100 ]

[Done] exited with code=0 in 0.169 seconds

Each element in the array will call the comparison function of the parameters passed to the sort method when sorting. After accepting the values of the two elements, the function will return the result of the comparison. Take X and y for example. If x is larger than y, it will return a positive value. That is, if x appears after y when sorting, a positive value of 1 will be returned. Otherwise, a negative value will be returned. If the values are in the same order, 0 is returned.

The above description may not be easy to understand. In short, for numerical cases, if you return the subtraction results like the above, you can get the consistent results.

The sort method changes this array when exchanging elements. The method of rewriting the target object is called destructive method. In JavaScript, arrays contain many destructive methods. These are destructive methods.

  • pop,push,reverse,shift,sort,splice,unshift

If you only know JavaScript, you may take it for granted that the order of array elements should be changed. However, there is also a non-destructive implementation of sorting without changing the target array and returning a new array. Generally speaking, destructive methods are easy to cause errors, so they should be avoided as much as possible. In addition, you can use the free method to prevent unexpected changes to the array.

If you use the sort method to sort the free array, an error will be raised as follows.

var hzh1 = ['1', '9', '2', '5', '3', '6', '7', '4', '8'];
Object.freeze(hzh1);
console.log(hzh1.sort());
[Running] node "e:\HMV\JavaScript\JavaScript.js"
e:\HMV\JavaScript\JavaScript.js:3
console.log(hzh1.sort());
                 ^

TypeError: Cannot assign to read only property '0' of object '[object Array]'
    at Array.sort (<anonymous>)
    at Object.<anonymous> (e:\HMV\JavaScript\JavaScript.js:3:18)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
    at internal/main/run_main_module.js:17:47

[Done] exited with code=1 in 0.166 seconds
Generate strings from arrays

Next, we will introduce a common method to generate strings through the combination of push and join. The string can be spliced part by part through the array to generate a new string. After all the strings of each part are pushed to the array, they are spliced into a string through join. It is generally believed that this method is faster than string splicing (+ operation or + = operation).

However, the running speed will vary with the specific implementation, so we can't blindly think that this method has better performance. If necessary, it is better to measure the speed yourself. However, because the mainstream view now thinks that this method has better performance, many existing codes adopt this method. Therefore, even if it is not necessary to use this method, it is necessary to understand its meaning. Here is a concrete example.

var hzh = [];
hzh.push('<div>');
hzh.push('yellow');
hzh.push('son');
hzh.push('culvert');
hzh.push(Date());
hzh.push('</div>');
console.log("Splice the above strings:");
console.log(hzh.join(''));
[Running] node "e:\HMV\JavaScript\JavaScript.js"
Splice the above strings:
<div>Huang Zihan Sat May 07 2022 13:45:16 GMT+0800 (GMT+08:00)</div>

[Done] exited with code=0 in 0.169 seconds

The parameter of join is the character used to separate each part when splicing strings. In the above example, a null character is passed, so the split character is not actually used. If not passed to the join parameter, the default split character is a comma character.

The inverse transformation corresponding to join is the split method of String class. It divides the String according to the split character, then adds each part of the String as an element to the array, and returns the array. The first parameter of split is the String value used to represent the split character. Regular expressions can also be used.

The following is a specific example of using a space as a split character to generate an array.

var hzh1 = "Huang Zihan is a handsome man!"
console.log("Use spaces to split strings hzh1: ");
console.log(hzh1.split(''));   // The string is split by spaces
console.log("");
var hzh2 = 'Huang Zihan is a pretty boy!'
console.log("Regular expressions that use spaces to split strings hzh2: ");
console.log(hzh2.split(/\s/)); // The string is segmented by spaces (in the form of regular expressions)
[Running] node "e:\HMV\JavaScript\JavaScript.js"
Use spaces to split strings hzh1: 
[
  'yellow', ' ', 'son', ' ',
  'culvert', ' ', 'yes', ' ',
  'Handsome', ' ', 'brother', ' ',
  '!'
]

Regular expressions that use spaces to split strings hzh2: 
[
  'yellow', 'son',
  'culvert', 'yes',
  'Pretty', 'Son',
  '!'
]

[Done] exited with code=0 in 0.189 seconds
Copy of array

Now let's consider array replication. In many cases, errors related to replication and destructive methods are very common, and many people must have encountered them. Arrays are no exception.

Since only its reference is entered in the era of array assignment, the elements of the array are not copied. Just point a variable to the same array entity. Because array is an object, this result is inevitable. Here is a specific example.

var hzh1 = [3, 5, 4];
var hzh2 = hzh1;              // From the perspective of the variable hzh2, it contains the same elements as hzh1
console.log("Output variable hzh2 Value of:");
console.log(hzh2);
console.log("");
hzh2[0] = 123;                // Modify the elements of the array through the variable hzh2
console.log("output hzh1 Array:"); // This change can also be reflected in the variable hzh1
console.log(hzh1);
[Running] node "e:\HMV\JavaScript\JavaScript.js"
Output variable hzh2 Value of:
[ 3, 5, 4 ]

output hzh1 Array:
[ 123, 5, 4 ]

[Done] exited with code=0 in 0.712 seconds

If you want to copy the elements of the array, you can use the concat method or slice method.

Next, I will introduce the examples of using concat method and slice method respectively (code listing 7.5 and code listing 7.6).

Listing 7.5 copies the array through the concat method
var hzh1 = [3, 5, 4];
var hzh2 = [].concat(hzh1);
console.log("Output array hzh2: ");
console.log(hzh2); // From the perspective of the variable hzh2, it contains the same elements as hzh1
console.log("");
hzh2[0] = 123; // Modify the elements of the array through the variable hzh2
console.log("Output array hzh1: ");
console.log(hzh1); // There is no change at variable hzh1 (because the element is copied)
[Running] node "e:\HMV\JavaScript\JavaScript.js"
Output array hzh2: 
[ 3, 5, 4 ]

Output array hzh1: 
[ 3, 5, 4 ]

[Done] exited with code=0 in 0.193 seconds
Code listing 7.6 copies the array through the slice method
var hzh1 = [3, 5, 4];
var hzh2 = hzh1.slice(0, hzh1.length);
console.log("Output array hzh2: ");
console.log(hzh2); // From the perspective of the variable hzh2, it contains the same elements as hzh1
console.log("");
hzh2[0] = 123;     // Modify the elements of the array through the variable hzh2
console.log("Output array hzh1: ");
console.log(hzh1); // There is no change at variable hzh1 (because the element is copied)
[Running] node "e:\HMV\JavaScript\JavaScript.js"
Output array hzh2: 
[ 3, 5, 4 ]

Output array hzh1: 
[ 3, 5, 4 ]

[Done] exited with code=0 in 0.303 seconds

Generally, there are two ways to copy objects or array entities: deep copy and shallow copy.

Deep replication is a complete replication. If the object's properties also reference other objects, those objects are copied together.

Shallow copy only copies attribute values and element values, and does not copy related reference objects. The replication through concat and slice is shallow replication. It can be confirmed in the following way.

var hzh1 = [ {x:2} ];       // The element of the array is a reference to an object
var hzh2 = [].concat(hzh1); // Copy elements through concat
hzh2[0].x = 123;            // Modify the object referenced by the element at variable hzh2
console.log("output hzh1 Modified element:");
console.log(hzh1[0].x);     // This change can also be reflected in the variable hzh1 (this is a shallow copy)
[Running] node "e:\HMV\JavaScript\JavaScript.js"
output hzh1 Modified element:
123

[Done] exited with code=0 in 0.161 seconds

If you need to use deep replication, you need to implement it yourself. However, in practical use, there is almost no case where deep replication must be used.

Element deletion

If you want to delete the elements in the array, you can use the delete operation. However, after deleting an element through delete, the deleted place will leave the so-called spare element. If you want to eliminate the gap in the sequence after element deletion, you can use the splice method. See the example in listing 7.7.

Code listing 7.7 deletion of element (splice method)
var huangzihan = ['hzh0', 'hzh1', 'xxx', 'hzh2', 'hzh3'];
delete huangzihan[2];    // If you delete only through delete
console.log("Output array huangzihan: ");
console.log(huangzihan); // There will be an empty subscript of 2
console.log("");
huangzihan.splice(2, 1); // Delete 1 element from the position with subscript 2
console.log("Re output huangzihan: ");
console.log(huangzihan); // The space left after deleting the elements of the previous sequence is deleted
[Running] node "e:\HMV\JavaScript\JavaScript.js"
Output array huangzihan: 
[ 'hzh0', 'hzh1', <1 empty item>, 'hzh2', 'hzh3' ]

Re output huangzihan: 
[ 'hzh0', 'hzh1', 'hzh2', 'hzh3' ]

[Done] exited with code=0 in 0.187 seconds
Screening processing

For the forEach method, we should not pay attention to the process of enumerating elements, but treat the array as a single object that collects various members and enumeration as an operation on the object.

If the original set is regarded as input and the later generated set is regarded as output, this operation can also be regarded as a function. In a sense, there are only formal differences between it and function. However, the difference in this form of expression is also very important. If we look at the problem from another angle and regard it as a transformation process, we will find that there are not only for loop operations that can be used to enumerate array elements, but also related operations that can be used for filtering and pipeline processing.

For screening processing or pipeline processing, it will be more convenient if it is divided into multiple levels. The multi-level processing of array methods can be realized through chain syntax. The following is a randomly designed use example, which does not provide any actual functions.

var hzh = ['zero', 'one', 'two', 'three', 'four'];
// map: this operation takes the length of the element string as a new element and converts it into an array
// Filter: this operation will filter out the part with even value in the element
var huangzihan = hzh.map(
    function(e) {
        return e.length;
    }
).filter(
    function(e) {
        return e % 2 == 0;
    }
);
console.log("Output variable huangzihan: ");
console.log(huangzihan);
[Running] node "e:\HMV\JavaScript\JavaScript.js"
Output variable huangzihan: 
[ 4, 4 ]

[Done] exited with code=0 in 0.165 seconds

Split the above code into two parts:

var hzh = ['zero', 'one', 'two', 'three', 'four'];
var huangzihan = hzh.map(
        function(e) {
            return e.length;
        }
    )
console.log("Output variable huangzihan: ");
console.log(huangzihan);
[Running] node "e:\HMV\JavaScript\JavaScript.js"
Output variable huangzihan: 
[ 4, 3, 3, 5, 4 ]

[Done] exited with code=0 in 0.19 seconds

You can see that the map function converts the length of the string of the array into a number. Next, look at the following code:

var hzh = ['zero', 'one', 'two', 'three', 'four'];
var hzh1 = hzh.map(
    function (e) {
        return e.length;
    }
)
console.log("Output call map Variable after method hzh1: ");
console.log(hzh1);
console.log("");
var hzh2 = hzh1.filter(
    function (e) {
        return e % 2 == 0;
    }
);
console.log("Output call filter After method hzh2 Variable:");
console.log(hzh2);
[Running] node "e:\HMV\JavaScript\JavaScript.js"
Output call map Variable after method hzh1: 
[ 4, 3, 3, 5, 4 ]

Output call filter After method hzh2 Variable:
[ 4, 4 ]

[Done] exited with code=0 in 0.162 seconds

You can see that the filter method deletes all odd values. I followed the above method:

var huangzihan = [
    'Huang Zihan',
    '',
    'Huang Zihan is a handsome man!',
    'huangzihan',
    '1921323493',
    '19124896017',
]
var hzh = huangzihan.map(
    function (e) {
        return e.length;
    }).filter(
        function (e) {
            return e % 2 == 0;
        }
    )
console.log("Convert the converted hzh Variable output:");
console.log(hzh);
[Running] node "e:\HMV\JavaScript\JavaScript.js"
Convert the converted hzh Variable output:
[ 0, 10, 10 ]

[Done] exited with code=0 in 0.195 seconds

As can be seen from table 7.3, there are many methods that can be used for such screening. Some people call these methods iterator class methods. If you don't want to enumerate array elements through loops, you can also consider whether this type of method can be used.

One of the advantages of this approach is that the code will become more concise. Another advantage is that this method can make developers more sensitive to destructive methods and more cautious in use. This is because if you want to use chain syntax in filtering processing, you should avoid destructive methods.

7.1.10 internal implementation of array

In many languages other than JavaScript, arrays will implicitly occupy a contiguous memory space. This implicit internal implementation makes efficient memory use and high-speed element method possible. However, in JavaScript, the entity of an array is an object, so its usual implementation does not occupy a continuous memory space.

If you have development experience in other programming languages, you may worry about whether the execution efficiency of arrays in JavaScript is relatively low. In fact, whether arrays in JavaScript will use continuous memory space depends on the specific implementation method. Compared with other programming languages that do use continuous memory space, the array efficiency of JavaScript is indeed a little worrying, but in fact, all JavaScript implementations have spent a lot of effort to improve their own performance.

By comparing code listing 7.1 with code listing 7.2, we can speculate on the internal implementation of arrays in different implementation methods to a certain extent. By the way, 1e7 in the code here represents the 7th power of 10. The numerical literal quantity in exponential form (see table 3.6) is very useful in the code of performance test class. It will be much easier to remember its use.

Listing 7.1 accesses a large number of array elements
var huangzihan = [];
for (var hzh1 = 0; hzh1 < 1e7; hzh1++) {
    huangzihan[hzh1] = '';
}

console.log(huangzihan[hzh1]);

I don't know if the value is too large and there is no control

Code listing 7.2 object form of code listing 7.1
var huangzihan = {}; // object
for (var hzh1 = 0; hzh1 < 1e7; hzh1++) {
    huangzihan[hzh1] = '';
}

console.log(huangzihan[hzh1]);

Depending on the implementation, the execution speed of code listing 7.1 and code listing 7.2 will be different. This is actually a reflection of whether the array uses continuous memory space. However, if the array always uses contiguous memory space internally, the following code should occupy up to GB of contiguous memory. However, in the general implementation, this situation will not happen.

var hzh = {};
hzh[1e9] =''; // If the array does occupy continuous memory space, it should consume a lot of memory

In popular JavaScript implementations, small arrays (parts with smaller subscript values) will occupy continuous memory space, while parts with larger subscript values will generally be processed in a way similar to the properties of objects.

However, in the final analysis, it still depends on the specific implementation method. In addition, in JavaScript, someone also proposed the need to add Int32Array
Or Int8Array (see the link below).

7.1.11 array style objects

7.1.12 iterators

Generator 13.7.1

7.1.14 inner package of array

7.2 JSON

7.2.1 JSON string

7.2.2 JSON object

7.3 date processing

7.4 regular expressions

7.4.1 definition of regular expression

7.4.2 terms related to regular expressions

7.4.3 regular expression syntax

7.4.4 regular expressions in JavaScript

7.4.5 regular expression programming

7.4.6 string objects and regular expression objects

Posted by BITRU on Fri, 13 May 2022 12:24:07 +0300