Interview questions that often appear in the written test. Arrays in JavaScript are somewhat different from those in other languages. In order to facilitate the learning of array methods, the editor has compiled the operation methods for arrays for you below. Let’s take a look.
Array creation
There are two ways to create arrays in JavaScript. The first is to use the Array constructor:
var arr1 = new Array(); //Create an empty array var arr2 = new Array(20); //Create an array with 20 items var arr3 = new Array("lily","lucy","Tom"); //Create an array with 3 stringsThe second basic way to create an array is to use array literal notation:
var arr4 = []; //Create an empty array var arr5 = [20]; //Create an array containing 1 item var arr6 = ["lily","lucy","Tom"]; //Create an array containing 3 strings
When reading and setting the values of an array, use square brackets and provide a 0-based numeric index of the corresponding value:
var arr6 = ["lily","lucy","Tom"]; // Create an array alert(arr6[0]); //lilyarr6[1] = "mary"; //Modify the second item to maryarr6[3] = "sean"; //Add the fourth item to sean
The length property of an array in JavaScript can be modified, see the following example:
var arr = ["lily","lucy","Tom"]; // Create an array containing 3 strings arr[arr.length] = "sean"; //Add a "sean" arr.length = arr.length-1 at the subscript of 3 (that is, the end of the array).
If you need to determine whether an object is an array object, before ECMAScript 5, we can use instanceof Array to judge, but the problem with the instanceof operator is that it assumes that there is only one global execution environment. If the web page contains multiple frameworks, there are actually more than two different global execution environments, thus there are more than two different versions of the Array constructor. If you pass an array from one framework to another, the passed array has different constructors from the array created natively in the second framework.
ECMAScript 5 has added the Array.isArray() method. The purpose of this method is to determine whether a value is an array, regardless of which global execution environment it was created.
Array method
Let’s start by introducing the array method. The array methods include array prototype methods and methods inherited from object objects. Here we will only introduce the array prototype methods. The array prototype methods mainly include the following:
join()
push() and pop()
shift() and unshift()
sort()
reverse()
concat()
slice()
splice()
indexOf() and lastIndexOf() (newly added to ES5)
forEach() (Newly added in ES5)
map() (newly added to ES5)
filter() (newly added to ES5)
Every() (Newly added to ES5)
some() (newly added to ES5)
reduce() and reduceRight() (newly added to ES5)
New browser support for ES5:
Opera 11+
Firefox 3.6+
Safari 5+
Chrome 8+
Internet Explorer 9+
For supported browser versions, it can be implemented through the Array prototype extension. The following is a detailed introduction to the basic functions of each method.
1. Join()
join(separator): Group elements of the array into a string, with separator as the separator. If omitted, use commas as the separator by default. This method only receives one parameter: that is, separator.
var arr = [1,2,3];console.log(arr.join()); // 1,2,3console.log(arr.join("-")); // 1-2-3console.log(arr); // [1, 2, 3] (the original array remains unchanged)The join() method can be used to repeat the string. Just pass in the string and the number of repetitions to return the repeated string. The function is as follows:
function repeatString(str, n) {return new Array(n + 1).join(str);}console.log(repeatString("abc", 3)); // abcabcabcconsole.log(repeatString("Hi", 5)); // HiHiHiHiHi2. Push() and pop()
push(): You can receive any number of parameters, add them one by one to the end of the array, and return the length of the modified array.
pop(): Remove the last item at the end of the array, reduce the length value of the array, and then return the removed item.
var arr = ["Lily","lucy","Tom"];var count = arr.push("Jack","Sean");console.log(count); // 5console.log(arr); // ["Lily", "lucy", "Tom", "Jack", "Sean"]var item = arr.pop();console.log(item); // Seanconsole.log(arr); // ["Lily", "lucy", "Tom", "Jack"]3. shift() and unshift()
shift(): Delete the first item of the original array and return the value of the deleted element; if the array is empty, return undefined.
unshift: Add the argument to the beginning of the original array and return the length of the array.
This set of methods corresponds exactly to the push() and pop() methods above. One is the beginning of the operand array and the other is the end of the operand array.
var arr = ["Lily","lucy","Tom"];var count = arr.unshift("Jack","Sean");console.log(count); // 5console.log(arr); //["Jack", "Sean", "Lily", "lucy", "Tom"]var item = arr.shift();console.log(item); // Jackconsole.log(arr); // ["Sean", "Lily", "lucy", "Tom"]4. sort()
sort(): Arrange array items in ascending order - that is, the smallest value is at the front and the largest value is at the last.
When sorting, the sort() method calls the toString() transformation method for each array item, and then compares the resulting string to determine how to sort. Even if each item in the array is a numeric value, the sort() method compares a string, so the following situation occurs:
var arr1 = ["a", "d", "c", "b"];console.log(arr1.sort()); // ["a", "b", "c", "d"]arr2 = [13, 24, 51, 3];console.log(arr2.sort()); // [13, 24, 3, 51](meta array is changed)
To solve the above problem, the sort() method can receive a comparison function as a parameter so that we specify which value is ahead of which value. The comparison function receives two parameters, returns a negative number if the first parameter should be before the second, returns 0 if the two parameters are equal, and returns a positive number if the first parameter should be after the second. Here is a simple comparison function:
function compare(value1, value2) {if (value1 < value2) {return -1;} else if (value1 > value2) {return 1;} else {return 0;}}arr2 = [13, 24, 51, 3];console.log(arr2.sort(compare)); // [3, 13, 24, 51]If you need to generate descending sorting results through the comparison function, just exchange the values returned by the comparison function:
function compare(value1, value2) {if (value1 < value2) {return 1;} else if (value1 > value2) {return -1;} else {return 0;}}arr2 = [13, 24, 51, 3];console.log(arr2.sort(compare)); // [51, 24, 13, 3]5. reverse()
reverse(): Invert the order of array items.
var arr = [13, 24, 51, 3];console.log(arr.reverse()); //[3, 51, 24, 13]console.log(arr); //[3, 51, 24, 13](original array change)
6. concat()
concat() : Add the argument to the original array. This method will first create a copy of the current array, then add the received parameters to the end of the copy, and finally return the newly built array. Without passing parameters to the concat() method, it simply copies the current array and returns a copy.
var arr = [1,3,5,7];var arrCopy = arr.concat(9,[11,13]);console.log(arrCopy); //[1, 3, 5, 7, 9, 11, 13]console.log(arr); // [1, 3, 5, 7](The original array has not been modified)
From the above test results, we can find that: if what is passed in is not an array, then the parameters are added directly to the array. If what is passed in is an array, then the items in the array are added to the array. But what if the one passed in is a two-dimensional array?
var arrCopy2 = arr.concat([9,[11,13]]);console.log(arrCopy2); //[1, 3, 5, 7, 9, Array[2]]console.log(arrCopy2[5]); //[11, 13]
In the above code, the fifth item of the arrCopy2 array is an array containing two items. That is to say, the concat method can only add each item passed into the array to the array. If some items passed into the array are arrays, this array item will also be added to arrCopy2 as an item.
7. slice()
slice(): Returns a new array composed of items from the specified start subscript to the end subscript in the original array. The slice() method can accept one or two parameters, that is, the start and end positions of the item to be returned. In the case of only one parameter, the slice() method returns all items starting from the specified position of the parameter to the end of the current array. If there are two parameters, the method returns the item between the start and end positions - but does not include the item at the end position.
var arr = [1,3,5,7,9,11];var arrCopy = arr.slice(1);var arrCopy2 = arr.slice(1,4);var arrCopy3 = arr.slice(1,-2);var arrCopy4 = arr.slice(-4,-1);console.log(arr); //[1, 3, 5, 7, 9, 11](the original array has not changed)console.log(arrCopy); //[3, 5, 7, 9, 11]console.log(arrCopy2); //[3, 5, 7]console.log(arrCopy3); //[3, 5, 7, 11]console.log(arrCopy2); //[3, 5, 7]console.log(arrCopy3); //[3, 5, 7]console.log(arrCopy4); //[5, 7, 9]
arrCopy only sets one parameter, that is, the starting subscript is 1, so the returned array is subscript 1 (including subscript 1) and starts to the end of the array.
arrCopy2 sets two parameters, returning a subarray of the start subscript (including 1) and the start to the end subscript (excluding 4).
arrCopy3 sets two parameters, terminates the subscript as a negative number. When a negative number occurs, add the negative number to the value of the array length (6) to replace the number at that position, so it is a subarray starting from 1 to 4 (excluding).
Both parameters in arrCopy4 are negative numbers, so they are added to the array length 6 and converted to positive numbers, so they are equivalent to slice(2,5).
8. splice()
splice(): A very powerful array method, it has many uses, which can implement deletion, insertion and replacement.
Delete: You can delete any number of items, just specify 2 parameters: the location of the first item to be deleted and the number of items to be deleted. For example, splice(0,2) will delete the first two items in the array.
Insert: You can insert any number of items into the specified position, just provide 3 parameters: start position, 0 (number of items to be deleted), and the items to be inserted. For example, splice(2,0,4,6) will insert 4 and 6 from position 2 of the current array.
Replace: You can insert any number of items into the specified position and delete any number of items at the same time. You only need to specify 3 parameters: the starting position, the number of items to be deleted, and any number of items to be inserted. The number of inserted items does not have to be equal to the number of deleted items. For example, splice (2,1,4,6) deletes the item at the current array position 2, and then inserts 4 and 6 from position 2.
The splice() method always returns an array containing items removed from the original array, and if no items are deleted, an empty array is returned.
var arr = [1,3,5,7,9,11];var arrRemoved = arr.splice(0,2);console.log(arr); //[5, 7, 9, 11]console.log(arrRemoved); //[1, 3]var arrRemoved2 = arr.splice(2,0,4,6);console.log(arr); // [5, 7, 4, 6, 9, 11]console.log(arrRemoved2); // []var arrRemoved3 = arr.splice(1,1,2,4);console.log(arr); // [5, 2, 4, 4, 6, 9, 11]console.log(arrRemoved3); //[7]
9. indexOf() and lastIndexOf()
indexOf(): receives two parameters: the item to be found and (optional) index indicating the location of the search starting point. Where, look up backward from the beginning of the array (position 0).
lastIndexOf: receives two parameters: the item to be found and (optional) index indicating the location of the search starting point. Where, start looking forward from the end of the array.
Both methods return the position of the item to be found in the array, or return 1 if not found. When comparing the first parameter to each item in the array, the convergence operator is used.
var arr = [1,3,5,7,7,5,3,1];console.log(arr.indexOf(5)); //2console.log(arr.lastIndexOf(5)); //5console.log(arr.indexOf(5,2)); //2console.log(arr.lastIndexOf(5,4)); //2console.log(arr.indexOf("5")); //-110. forEach()
forEach(): traverses the array and runs the given function on each item in the array. This method has no return value. The parameters are all function types, and there are parameters passed by default. The parameters are: the traversed array content; the corresponding array index, the array itself.
var arr = [1, 2, 3, 4, 5];arr.forEach(function(x, index, a){console.log(x + '|' + index + '|' + (a === arr));});// The output is: // 1|0|true// 2|1|true// 3|2|true// 4|3|true// 5|4|true11. map()
map(): refers to "map", which runs a given function on each item in the array, and returns the array composed of the result of each function call.
The following code uses the map method to square each number in the array.
var arr = [1, 2, 3, 4, 5];var arr2 = arr.map(function(item){return item*item;});console.log(arr2); //[1, 4, 9, 16, 25]12. filter()
filter(): "Filter" function, each item in the array runs a given function and returns an array that meets the filtering conditions.
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];var arr2 = arr.filter(function(x, index) {return index % 3 === 0 || x >= 8;}); console.log(arr2); //[1, 4, 7, 8, 9, 10]13.every()
every(): determines whether each item in the array meets the condition. Only when all items meet the condition will true be returned.
var arr = [1, 2, 3, 4, 5];var arr2 = arr.every(function(x) {return x < 10;}); console.log(arr2); //truevar arr3 = arr.every(function(x) {return x < 3;}); console.log(arr3); // false14. Some()
some(): determines whether there are items in the array that meet the conditions. As long as one of them meets the conditions, it will return true.
var arr = [1, 2, 3, 4, 5];var arr2 = arr.some(function(x) {return x < 3;}); console.log(arr2); //truevar arr3 = arr.some(function(x) {return x < 1;}); console.log(arr3); // false15. reduce() and reduceRight()
Both methods implement iterating over all items of the array and then building a final returned value. The reduce() method starts from the first item of the array and goes through it one by one to the end. reduceRight() starts from the last item of the array and traverses forward to the first item.
Both methods receive two parameters: a function called on each item and (optional) as the initial value of the merge base.
The function passed to reduce() and reduceRight() receives 4 parameters: the previous value, the current value, the index of the item, and the array object. Any value returned by this function will be automatically passed to the next item as the first parameter. The first iteration occurs on the second term of the array, so the first parameter is the first term of the array, and the second parameter is the second term of the array.
The following code uses reduce() to implement the sum of the array, and the initial value of 10 is added to the array at the beginning.
var values = [1,2,3,4,5];var sum = values.reduceRight(function(prev, cur, index, array){return prev + cur;},10);console.log(sum); //25The above is a complete collection of JavaScript array methods introduced by the editor (recommended). I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!