The latest front-end interview question in 2021 (operation method of array in Js)
preface
Tip: how to count arrays in JS
This paper aims at the problems of operating array related methods in the process of front-end interview
I don't know if there are any friends who often confuse the methods of operating arrays like me, or are not very proficient in some methods
Today, we will make a classification and summary of the description and use methods of most methods for your convenience.
Don't talk much, just do it 💪
1, Array creation
Define array, array assignment
The code is as follows (example):
var arrayObj = new Array0; //Create an array var arrayObj = new Array([size]); //Create an array and specify the length. Note that it is not the upper limit, but the length var arrayObj = new Array([elementO[, element1[ .. element]]]); //Create an array and assign values
It should be noted that although the second method specifies the length of the array, in fact, the array becomes longer in all cases, that is, even if the length is specified as 5, the elements can still be stored outside the specified account. Note: the length will change accordingly.
2, Access to array elements
Find array elements by subscript index value
The code is as follows (example):
var arrayObj = [1,2,3] console.log(arrayObj[0]) //1 console.log(arrayObj[0]) //2 console.log(arrayObj[0]) //3
The index value of the first array element is 0, the second index value is 1, and so on
3, Array properties
constructor
- Description: returns the prototype function that creates an array object.
- Syntax: array constructor
- The code is as follows (example):
arrayObj.constructor; //Return the function created by arrayObj array object prototype: console.log(arrayObj.constructor) //Output: function array() {[native code]}
length
- Description: sets or returns the number of array elements.
- Syntax: array length
- The code is as follows (example):
var arrayObj = [1,2,3];; //Return the function created by arrayObj array object prototype: console.log(arrayObj.length) //Output: 3
prototype
- Description: allows you to add properties or methods to an array object.
- Syntax: array prototype. name=value
- The code is as follows (example):
>The above briefly introduces the basic concepts for Xiaobai's understandingvar arrayObj = [1,2,3]; arrayObj.prototype.sum=function(){ //You can add properties or methods to an array var sum = 0 for (i=0;i<this.length;i++){ sum+=this[i] } return sum } arrayObj.sum //6
4, Addition of array elements
Mainly push, unshift and splice
push
- Syntax: arrayobj push([item1 [item2 [. . . [itemN ]]]]);
- push() method: you can add one or more parameters to the end of the array; Returns the length of the added array. The original array is changed.
- The code is as follows (example):
var arr=[1,2,3,4]; var a=arr.push(9,8,7); console.log(a,arr);//1,2,3,4,9,8,7;
unshift
- Syntax: arrayobj unshift([item1 [item2 [. . . [itemN ]]]]);
- unshift() method: you can add one or more parameters to the head of the array; Returns the length of the added array. The original array is changed.
- The code is as follows (example):
var arr=[1,2,3,4]; var a=arr.unshift(9,8,7); console.log(a,arr);//7; 9,8,7,1,2,3,4;
splice
- Syntax: arrayobj splice(insertPos,0,[item1[, item2[, . . . [,itemN]]]]);
- splice() method: without parameters, it returns an empty array, and the original array remains unchanged;
A parameter that intercepts from the index bit represented by the parameter until the end of the array, returns the intercepted array, and the original array is changed;
Two parameters. The first parameter represents the index bit to be intercepted, and the second parameter represents the intercepted length. The intercepted array is returned, and the original array is changed;
Three or more parameters. The third and subsequent parameters represent the value to be inserted from the intercept bit. - The code is as follows (example):
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.splice(0,0,"a"); console.log(fruits )//"a","Banana", "Orange", "Apple", "Mango"
5, Deletion of array elements
Mainly pop, shift
pop
- Syntax: arrayobj pop();
- pop() method: delete an element from the end of the array and return the deleted element. The original array is changed.
- The code is as follows (example):
var arr=[1,2,3,4]; var a=arr.pop(); console.log(a,arr)//4;1,2,3,
shift
- Syntax: arrayobj shift();
- shift() method: delete an element from the head of the array and return the deleted element. The original array is changed.
- The code is as follows (example):
var arr = [1,2,3,4]; var a = arr.shift(); console.log(a,arr)//1;2,3,4,
splice
This method has been introduced above and will not be repeated here
6, Interception and merging of arrays
Mainly concat and slice
slice
- Syntax: arrayobj slice(start, [end]);
- slice() method: if no parameter is passed, the original array will be returned; If a parameter is intercepted from the index represented by the parameter to the end of the array, the intercepted array is returned, and the original array remains unchanged;
Two parameters, intercepted from the index corresponding to the first parameter to the index corresponding to the second parameter, but including the value on the index corresponding to the second parameter, the original array does not change & at most two parameters are accepted - The code is as follows (example):
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; var citrus = fruits.slice(1,3); console.log(citrus )//Orange,Lemon
concat
- Syntax: arrayobj concat([item1[, item2[, . . . [,itemN]]]]);
- concat() method: it belongs to the string method, and the array can also be used. It accepts one or more parameters, puts the values in the parameters behind the array of the operation, and returns the spliced array. The original array remains unchanged. If the parameter is an array, extract the value before operation.
- The code is as follows (example):
var arr = [1,2,3,4]; arr.concat([5,6,7])//[1,2,3,4,5,6,7]
7, Copy of array
The slice and concat methods can also be used to copy the array,
You can also use the extension operator in es6
arrayObj.slice(0); // Returns the copy array of the array. Note that it is a new array, not pointing to
arrayObj.concat(); // Returns the copy array of the array. Note that it is a new array, not pointing to
- ... extension operator
- The code is as follows (example):
let arr = [1, 2], arr1 = [...arr]; console.log(arr1); // [1, 2] // Array contains empty bits let arr2 = [1, , 3], arr3 = [...arr2]; console.log(arr3); [1, undefined, 3] //Merge array console.log([...[1, 2],...[3, 4]]); // [1, 2, 3, 4]
8, Sorting of array elements
Mainly reverse, short
reverse
- Syntax: arrayobj reverse();
- reverse() method: used to reverse the order of elements in the array.
- The code is as follows (example):
ar fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.reverse(); console.log(fruits)//Mango,Apple,Orange,Banana
sort
- Syntax: arrayobj sort();
- sort() method: used to sort the elements of the array.
- The code is as follows (example):
var Array = [1,2,3,4,5]; var fruits = Array.sort(function(a,b){ //return a - b; // from small to large return b-a; //From big to small })
9, Stringing of array elements
join
- Syntax: arrayobj join(separator);
- join() method: it is used to convert all elements in the array into a string. The elements are separated by the specified separator.
- The code is as follows (example):
var arr = [1,2,3,4] var bbc = arr.join() console.log(bbc)//1,2,3,4
toLocaleString, toString, valueOf: can be regarded as the special usage of join, not commonly used
10, ES5 and ES6 add array methods
indexOf()
- Syntax: string indexOf(searchvalue,start)
- indexOf() method: string method. Array can also be applied. This method can return the position where a specified string value appears for the first time in the string; If a parameter, return the index value of the parameter in the array. If the parameter is not in the array of operations, return - 1.
- The code is as follows (example):
var arr = [1,2,3,4]; arr.indexOf(1) // 0 arr.indexOf(5) // -1
forEach()
- Syntax: Syntax: array forEach(function(currentValue, index, arr), thisValue)
- forEach() method: the array is traversed, and only the array can be traversed. It does not accept the return value or the return value is undefined.
- The code is as follows (example):
var arr = [1,2,3,4,5]; arr.forEach((item,index,arr)=>{ //item is the current array element // Index is the current index // arr is the array name })
map()
- Syntax: array map(function(currentValue,index,arr), thisValue)
- map() method: traversal of the array. It is used to receive a return value and create a new array without changing the original array.
- The code is as follows (example):
var arr = [1,2,3,4,5,6]; arr.map(function(item,index,arr){ return item * 2 }) //Output [2,4,6,8,10,12]
filter()
- Syntax: array filter(function(currentValue,index,arr), thisValue)
- filter() method: filter out some qualified elements and return a new array.
- The code is as follows (example):
var ages = [32, 33, 16, 40]; function checkAdult(age) { return age >= 18; //Returns the elements in the array ages where all elements are greater than 18: } function myFunction() { document.getElementById("demo").innerHTML = ages.filter(checkAdult); } //The output results are: 32,33,40
some()
- Syntax: array some(function(currentValue,index,arr),thisValue)
- some() method: check whether the array contains a value and return a Boolean value. If any element in the array meets the given conditions, the result is true, otherwise it is false.
- The code is as follows (example):
var ages = [3, 10, 18, 20]; function checkAdult(age) { return age >= 18; } function myFunction() { document.getElementById("demo").innerHTML = ages.some(checkAdult); } //The output result is: true
every()
- Syntax: array every(function(currentValue,index,arr), thisValue)
- every() method: this method is used to detect whether all elements of the array meet the specified conditions (provided by the function), and return a Boolean value. The result is true or false.
- The code is as follows (example):
var ages = [32, 33, 16, 40]; function checkAdult(age) { return age >= 18; //Check whether all elements of the array ages are greater than or equal to 18 } function myFunction() { document.getElementById("demo").innerHTML = ages.every(checkAdult); } //The output result is: false
reduce()
- Syntax: array reduce(function(total, currentValue, currentIndex, arr), initialValue)
- reduce() method: call the specified callback function for all elements in the array, and the return value of the callback function is the cumulative result. And the return value is provided as a parameter in the next callback function.
- The code is as follows (example):
var numbers = [65, 44, 12, 4]; function getSum(total, num) { return total + num; //Calculates the sum of array additions } function myFunction(item) { document.getElementById("demo").innerHTML = numbers.reduce(getSum); } //Output result: 125
Array.from( )
- Syntax: array from(arrayLike[, mapFn[, thisArg]])
- Array.from() method: convert the class array object or iteratable object into an array, such as arguments, js selector, and find the dom collection and the array simulated by the object.
- The code is as follows (example):
// The parameter is an array and returns the same array as the original array console.log(Array.from([1, 2])); // [1, 2] // Parameter contains empty bits console.log(Array.from([1, , 3])); // [1, undefined, 3]
Array.of( )
- Syntax: array of(item1,item2, …)
- Array.of() method: create an array, take all values in the parameter as elements to form an array, and return an empty array if the parameter is empty.
- The code is as follows (example):
console.log(Array.of(1, 2, 3, 4)); // [1, 2, 3, 4] // Parameter values can be of different types console.log(Array.of(1, '2', true)); // [1, '2', true] // Returns an empty array when the parameter is null console.log(Array.of()); // []
find( )
- Syntax: array find(function(currentValue, index, arr),thisValue)
- The find() method returns the value of the first element of the array that passes the test (judgment in the function).
- The find() method calls the function once for each element in the array:
When the elements in the array return true when testing the condition, find() returns the qualified elements, and the subsequent values will not call the execution function.
undefined if there are no qualified elements - The code is as follows (example):
let arr = Array.of(1, 2, 3, 4); console.log(arr.find(item => item > 2)); // 3 // Array empty bits are processed as undefined console.log([, 1].find(n => true)); // undefined
Note: the find() function does not execute for empty arrays.
Note: find() does not change the original value of the array.
findIndex( )
- Syntax: array findIndex(function(currentValue, index, arr), thisValue)
- The findIndex() method returns the position of the first element of the array passing in a test condition (function) that meets the condition.
- The findIndex() method calls the function once for each element in the array:
When the element in the array returns true when testing the condition, findIndex() returns the index position of the qualified element, and the subsequent value will not call the execution function.
If there are no qualified elements, - 1 is returned - The code is as follows (example):
let arr = Array.of(1, 2, 1, 3); // Parameter 1: callback function // Parameter 2 (optional): Specifies the value of this in the callback function console.log(arr.findIndex(item => item == 1)); // 0 // Array empty bits are processed as undefined console.log([, 1].findIndex(n => true)); //0
Note: the findIndex() function does not execute for empty arrays.
Note: findIndex() does not change the original value of the array.
includes( )
- Syntax: arr.includes(searchElement)
arr.includes(searchElement, fromIndex) - The includes() method is used to determine whether an array contains a specified value. If yes, it returns true; otherwise, it returns false.
- The code is as follows (example):
// Parameter 1: contains the specified value [1, 2, 3].includes(1); // true // Parameter 2: optional. The starting index of the search is 0 by default [1, 2, 3].includes(1, 2); // false // Inclusion judgment of NaN [1, NaN, 3].includes(NaN); // true
Note: it is different from the has method of Set and Map; The has method of Set is used to find the value; The has method of Map is used to find the key name.
fill( )
- Syntax: array fill(value, start, end)
- The fill() method is used to replace the elements of the array with a fixed value.
- The code is as follows (example):
let arr = Array.of(1, 2, 3, 4); // Parameter 1: value used to populate // Parameter 2: start index to be filled // Parameter 3 (optional): the end index to be filled. It defaults to the end of the array console.log(arr.fill(0,1,2)); // [1, 0, 3, 4]
entries( )
- Syntax: array entries()
- The entries() method returns an array iteration object that contains the key / value pairs of the array.
The index value of the array in the iteration object is used as the key, and the array element is used as the value. - The code is as follows (example):
for(let [key, value] of ['a', 'b'].entries()){ console.log(key, value); } // 0 "a" // 1 "b" // Do not use for Of cycle let entries = ['a', 'b'].entries(); console.log(entries.next().value); // [0, "a"] console.log(entries.next().value); // [1, "b"] // Array contains empty bits console.log([...[,'a'].entries()]); // [[0, undefined], [1, "a"]]
keys( )
- Syntax: array fill(value, start, end)
- The fill() method is used to replace the elements of the array with a fixed value.
- The code is as follows (example):
let arr = Array.of(1, 2, 3, 4); // Parameter 1: value used to populate // Parameter 2: start index to be filled // Parameter 3 (optional): the end index to be filled. It defaults to the end of the array console.log(arr.fill(0,1,2)); // [1, 0, 3, 4]
keys( )
- Syntax: array keys()
- The keys() method is used to create an iteratable object from the array that contains the array keys.
Returns true if the object is an array, false otherwise. - The code is as follows (example):
for(let key of ['a', 'b'].keys()){ console.log(key); } // 0 // 1 // Array contains empty bits console.log([...[,'a'].keys()]); // [0, 1]
values( )
- Syntax: array values( )
- values() method: iterate over key values.
- The code is as follows (example):
for(let value of ['a', 'b'].values()){ console.log(value); } // "a" // "b" // Array contains empty bits console.log([...[,'a'].values()]); // [undefined, "a"]
flat( )
- Syntax: array flat( )
- The fill() method is used to convert a nested array to a one-dimensional array
- The code is as follows (example):
console.log([1 ,[2, 3]].flat()); // [1, 2, 3] // Specifies the number of nesting levels for the transformation console.log([1, [2, [3, [4, 5]]]].flat(2)); // [1, 2, 3, [4, 5]] // No matter how many layers are nested console.log([1, [2, [3, [4, 5]]]].flat(Infinity)); // [1, 2, 3, 4, 5] // Auto skip empty space console.log([1, [2, , 3]].flat());<p> // [1, 2, 3]
It's over here
summary
Tip: most of the methods are here, but Xiaobian is tired 🐶,
If you have any mistakes or suggestions, you can leave a message in the comment area. The editor will reply and modify it as soon as he sees it.