You don't know about JavaScript-advanced full grasp of Item30 Array
In programming languages, the importance of arrays is self-evident. arrays in JavaScript are also one of the most commonly used objects. arrays are ordered sets of values. Due to the weak type, arrays in JavaScript are flexible and powerful. arrays of high-level languages such as Java can only store the same type or its sub-type elements. JavaScript can store multiple types of elements in the same array, the length can also be dynamically adjusted. The array length can be automatically changed as the data increases or decreases.
1. Create an array
Create arrays in multiple JavaScript methods
1. Constructor
1. No parameter constructor creates an empty array
var a1 = new Array ();
2. A numeric parameter constructor, specify the length of the array (since the length of the array can be adjusted dynamically, the effect is not large), create an array of the specified length
var a2 = new Array (5);
3. Constructor with initialized data, create array and initialize parameter data
var a3 = new Array (4, 'hello', new Date ());
2. Literal
1. Use square brackets to create an empty array, which is equivalent to calling a parameterless constructor
var a4 = [];
2. Use square brackets and pass in initialization data, which is equivalent to calling the constructor with initialization data
var a5 = [10];
be careful
1. If you use a constructor to create an array, if you pass in a numeric parameter, an array of length will be created. If more than one is passed, an array will be created, and the parameters will be added to the array as initialization data.
var a1 = new Array (5);
console.log (a1.length); // 5
console.log (a1); // [], the array is empty
var a2 = new Array (5,6);
console.log (a2.length); // 2
console.log (a2); // [5,6]
But using the literal method, no matter how many parameters are passed in, the parameters will be used as initialization content
var a1 = [5];
console.log (a1.length); // 1
console.log (a1); // [5]
var a2 = [5,6];
console.log (a2.length); // 2
console.log (a2); // [5,6]
2. When using arrays with initialization parameters to create arrays, it is best not to bring extra "," at the end, which is different in different browsers.
var a1 = [1,2,3,];
console.log (a1.length);
console.log (a1);
The result of this script running on a modern browser is the same as we thought, the length is 3, but in the low version of IE, it is indeed an array of length 4, the last data is undefined
2. The index and length of the array
The value of the array can be read and written through natural number index access, and the subscript can also be a variable or expression that results in a non-negative integer
var a1 = [1,2,3,4];
console.log (a1 [0]); // 1
var i = 1;
console.log (a1 [i]); // 2
console.log (a1 [++ i]); // 3
Arrays are also objects. The secret of indexing is that the array will convert the index value to the corresponding string (1 => ”1”) as the object property name
console.log (1 in a1); // true, is indeed an attribute
The particularity of the index is that the array will automatically update the length property. Of course, because JavaScript syntax stipulates that numbers cannot be used as variable names, we cannot display the format using array.1. This shows that in fact, negative numbers, even non-numeric "indexes" are allowed, but these will become the attributes of the array, not the index
var a = new Array (1,2,3);
a [-10] = a [-10];
a [sss] = sss;
In this way, we can see that all indexes are attribute names, but only natural numbers (with the largest value) are indexes. Generally, when we use arrays, there will be no array out-of-bounds errors. Because of this, the array indexes may not be continuous. , Return undefined when accessing elements where index does not exist
var a = new Array (1,2,3);
a [100] = 100;
console.log (a.length); // 101
console.log (a [3]); // undefined
console.log (a [99]); // undefined
console.log (a [100]); 100
In the above example, although assigning a [100] directly does not affect a [4] or a [99], the length of the array is affected. The length property of the array is equal to the largest index + 1 in the array. We know that the array ’s The length property is also a writable property. When the value of the length property of the array is forced to be less than or equal to the maximum index value, the array will automatically delete the data with indexd greater than or equal to length. Add a few sentences to the code just now
a.length = 2
console.log (a); // [1,2]
At this time, you will find that a [2] and a [100] are automatically deleted. Similarly, if you set length to a value greater than the maximum index + 1, the array will automatically expand, but no new elements will be added to the array. , Just add empty space at the end
a.length = 5;
console.log (a); // [1,2] // There are no 3 undefined behind
3. Element addition / deletion
1. Basic method
The above example has been used to add elements to the array, just use the index directly (index does not need to be continuous)
var a = new Array (1,2,3);
a [3] = 4;
console.log (a); // [1, 2, 3, 4]
As mentioned earlier, the array is also an object, and the index is only a special property, so we can use the method of deleting the object property and delete the array element
delete a [2];
console.log (a [2]); // undefined
This is similar to directly assigning a [2] to undefined, it will not change the length of the array, nor will it change the correspondence between the index and value of other data.
2. Stack method
Some of the students in the above example have always discovered that the deletion method is not the form we want. Many times we want to delete the index of the middle element, the index of the latter element is automatically reduced by one, and the array length is also reduced by one, just like The one taken in a stack, the array has helped us do this kind of operation, pop and push can let us use the stack to use the array first in and then out
var a = new Array (1,2,3);
a.push (4);
console.log (a); // [1, 2, 3, 4]
console.log (a.length); // 4
console.log (a.pop (a)); // 4
console.log (a); // [1, 2, 3]
console.log (a.length); // 3
3. Queue method
Since the stack method is implemented, how can the first-in-first-out queue be less, the shift method can delete the smallest element of the array index, and reduce the index of all subsequent elements by one, and the length is also reduced by one, so that shift / push can be used to simulate the queue.
Using the shift () and push () methods together, you can use arrays like queues:
var colors = new Array ();
var count = colors.push (red, green); // Push two items
alert (count); // 2
count = colors.push (black); // add items from the end of the array, the order of the array is: red, green, black
alert (count); // 3
var item = colors.shift (); // Get the first item
alert (item); // red
alert (colors.length); // 2
// It can be seen from the example: the shift () and push () methods can add items from the end of the array, can remove the first item in the array and return the item.
// If you want to achieve the opposite operation, you can use the unshift () and pop () methods, that is, add items at the front of the array and remove items from the end of the array.
var colors = new Array ();
var count = colors.unshift (red, green); // Push two items
alert (count); // 2
count = colors.unshift (black); // Add items from the front of the array, the order of the array is: black, red, green
alert (count); // 3
var item = colors.pop ();
alert (item); // The last item removed and returned is green
From the above two sets of examples, you can clearly see the usage of these two sets of methods.
4. The ultimate artifact
JavaScript provides a splice method for solving array addition and deletion at a time (the replacement effect can be achieved by combining these two methods). The method has three parameters
1. Start indexing
2. Delete the displacement of the element
3. New elements inserted, of course, you can write multiple
The splice method returns a new array consisting of deleted elements, or an empty array if there is no deletion
var a = new Array (1,2,3,4,5);
delete
Specify the first two parameters, you can use splice to delete the array elements, will also bring index adjustment and length adjustment
var a = new Array (1,2,3,4,5);
console.log (a.splice (1,3)); // [2, 3, 4]
console.log (a.length); // 2
console.log (a); // [1,5]
If the array index does not start from 0, then the result will be very interesting, there is such an array
var a = new Array ();
a [2] = 2;
a [3] = 3;
a [7] = 4;
a [8] = 5;
console.log (a.splice (3,4)); // [3]
console.log (a.length); // 5
console.log (a); // [2: 2, 3: 4, 4: 5]
As you can see in the above example, the first parameter of splice is the absolute index value, not relative to the array index. The second parameter is not the number of deleted elements, but how many times the delete action is performed, not the actual index of the array. Move, but move continuously. At the same time adjust the index of the back element, the front index ignores
Insert and replace
As long as the second parameter of the method, that is, the number of times the delete action is performed is set to 0, the third parameter and later fill in the content to be inserted and splice can perform the insert operation, and if the second parameter is not 0, it becomes the first Delete and insert at this position, which is the replacement effect
var a = new Array (1,2,3,4,5);
a.splice (1,0,9,99,999);
console.log (a.length); // 8
console.log (a); // [1, 9, 99, 999, 2, 3, 4, 5]
a.splice (1,3,8,88,888);
console.log (a.length); // 8
console.log (a); // [1, 8, 88, 888, 2, 3, 4, 5]
4. Common methods
join (char)
This method is also available in C # and other languages. Its function is to connect array elements (the object calls its toString () method) using parameters as connectors to form a string.
var a = new Array (1,2,3,4,5);
console.log (a.join (',')); // 1,2,3,4,5
console.log (a.join ('')); // 1 2 3 4 5
slice (start, end)
Not to be confused with the splice method, slice
var a = new Array (1,2,3,4,5);
console.log (a); // [1, 2, 3, 4, 5]
console.log (a.slice (1,2)); // 2
console.log (a.slice (1, -1)); // [2, 3, 4]
console.log (a.slice (3,2)); /// []
console.log (a); // [1, 2, 3, 4, 5]
The method is used to return a fragment or sub-array in the array. If only one parameter is returned, the parameter is returned to the end of the array. If the parameter has a negative number, it is counted from the end of the array (-3 means that the array is the third, and most people will not do this) , But it is useful when you do n’t know the length of the array and want to discard the last n, but the length of the array is well known ..., a tangled usage), if start is greater than end returns an empty array, it is worth noting that slice does not Will change the original array, but return a new array.
concat (array)
Looks like Cut, but this is really not a phonetic word. The concat method is used to splice arrays. A.concat (b) returns a new array composed of a and b. It will not modify any original array, nor will it recursively connect the inside of the array. Array
var a = new Array (1,2,3,4,5);
var b = new Array (6,7,8,9);
console.log (a.concat (b)); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log (a); // [1, 2, 3, 4, 5]
console.log (b); // [6, 7, 8, 9]
reverse ()
The method is used to reverse the array, the difference is that it will modify the original array
var a = new Array (1,2,3,4,5);
a.reverse ();
console.log (a); // [5, 4, 3, 2, 1]
Similarly, when the array index is not continuous or starts with 0, the result needs attention
var a = new Array ();
a [2] = 2;
a [3] = 3;
a [7] = 4;
a [8] = 5;
a.reverse ();
sort
The sort method is used to sort the array. When there is no parameter, it will be sorted in ascending alphabetical order. If it contains undefined, it will be sorted to the end, and the object element will call its toString method. If you want to sort according to your own definition, you can pass A sorting method goes in, a very typical strategy pattern, the same sort will change the original array.
var a = new Array (5,4,3,2,1);
a.sort ();
console.log (a); // [1, 2, 3, 4, 5]
but. . .
var a = new Array (7,8,9,10,11);
a.sort ();
console.log (a); // [10, 11, 7, 8, 9]
Because sorting by alphabet, 7 is bigger than 10, at this time we need to pass in a custom sorting function
var a = new Array (7,8,9,10,11);
a.sort (function (v1, v2) {
return v1-v2;
});
console.log (a); // [7, 8, 9, 10, 11]
The principle is similar to sort in C # (the design pattern in the .NET Framework-the application strategy pattern is List sorting), but you can directly pass the method in. The following is purely speculation
Sort uses quick sort internally. If there are no parameters when comparing the size of two elements, the alphabet is directly judged. If there are parameters, the two parameters being compared are passed into the custom method and called (the two being compared) The number will be passed to v1, v2 of the custom method), if the return value is greater than 0, it means v1> v2, if it is equal to 0, it means v1 = v2, if it is less than 0, it means v1
At last
After understanding these, it is really amazing to look at arrays, that is, powerful and flexible, but there are certain inconveniences in traversing elements and obtaining element positions. These have been solved in ECMAScript. Proficient use can make our JavaScript elegant and Efficient.
6. New methods of ECMAScript5
The importance of arrays in various programming languages is self-evident, but in the previous JavaScript, arrays (detailed explanation of JavaScript arrays) have been very powerful, but the operation method is not perfect, and they have been properly supplemented in ECMAScript5.
Array.isArray (element)
This is a static function of the Array object, used to determine whether an object is an array
var a = new Array (123);
var b = new Date ();
console.log (Array.isArray (a)); // true
console.log (Array.isArray (b)); // false
.indexOf (element) / .lastIndexOf (element)
As the name implies, these two methods are used to find the position of the specified element in the array. When the first one is found, the index is returned. If no one is found, -1 is returned. IndexOf searches from beginning to end, and lastIndexOf searches backward.
var a = new Array (1,2,3,3,2,1);
console.log (a.indexOf (2)); // 1
console.log (a.lastIndexOf (2)); // 4
.forEach (element, index, array)
Traverse the array, the parameter is a callback function, the callback function has three parameters: the current element, the element index, the entire array
var a = new Array (1,2,3,4,5,6);
a.forEach (function (e, i, array) {
array [i] = e + 1;
});
console.log (a); // [2, 3, 4, 5, 6, 7]
.every (function (element, index, array)) / .some (function (element, index, array))
These two functions are similar to the logical decision in discrete mathematics. The callback function returns a Boolean value. Every is the return of true when each callback function of the "all" function returns true, and terminates execution when it encounters false. It returns false; some function is "exist". When a callback function returns true, it terminates execution and returns true, otherwise it returns false. Calling every on an empty array returns true, some returns false.
var a = new Array (1,2,3,4,5,6);
/ * 0: 1
1: 2
twenty three
3: 4
4: 5
false * /
console.log (a.every (function (e, i, arr) {
console.log (i + ':' + e);
return e <5;
}));
var a = new Array (1,2,3,4,5,6);
/ * 0: 1
1: 2
twenty three
3: 4
4: 5
true * /
console.log (a.some (function (e, i, arr) {
console.log (i + ':' + e);
return e> 4;
}));
.map (function (element))
Similar to forEach, traverse the array, the return value of the callback function forms a new array to return, the index structure of the new array is consistent with the original array, the original array remains unchanged
var a = new Array (1,2,3,4,5,6);
console.log (a.map (function (e) {
return e * e;
})); // [1, 4, 9, 16, 25, 36]
console.log (a); // [1, 2, 3, 4, 5, 6]
.filter (function (element))
Return a subset of the array. The callback function is used to logically determine whether to return. If true is returned, the current element is added to the returned array, false is not added, the new array only contains the value that returns true, and the missing index does not include the original array constant
var a = new Array (1,2,3,4,5,6);
console.log (a.filter (function (e) {
return e% 2 == 0;
})); // [2, 4, 6]
console.log (a); // [1, 2, 3, 4, 5, 6]
.reduce (function (v1, v2), value) / .reduceRight (function (v1, v2), value)
Traverse the array, call the callback function, combine the array elements into a value, reduce starts from the index minimum, reduceRight reverses, the method has two parameters
1. Callback function: combine two values into one and return the result
2.value, an initial value, optional
var a = new Array (1,2,3,4,5,6);
console.log (a.reduce (function (v1, v2) {
return v1 + v2;
})); // twenty one
console.log (a.reduceRight (function (v1, v2) {
return v1-v2;
}, 100)); // 79