Foreword: I recently read some methods in JS array. Today I'll share them with you. (some methods may be biased) for details, please refer to mdn
ps:
( ⭐) Unusual methods
( ⭐⭐) Common methods
( ⭐⭐⭐) Very common and used many times
Array.prototype.join()(⭐⭐⭐)
**The join() * * method concatenates all elements of an array (or an array like object) into a string and returns the string. If the array has only one item, the item will be returned without the separator
example:
const elements = ['Fire', 'Air', 'Water']; console.log(elements.join());// "Fire,Air,Water" console.log(elements.join(''));// "FireAirWater" console.log(elements.join('-'));// "Fire-Air-Water"
Array.prototype.pop()(⭐⭐⭐)
The pop() method deletes the last element from the array and returns the value of that element. This method changes the length of the array.
example:
const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato']; console.log(plants.pop());//"tomato" console.log(plants);// ["broccoli", "cauliflower", "cabbage", "kale"] plants.pop(); console.log(plants);// ["broccoli", "cauliflower", "cabbage"]
Array.prototype.push()(⭐⭐⭐)
The push() method adds one or more elements to the end of the array and returns the new length of the array.
example:
const animals = ['pigs', 'goats', 'sheep']; const count = animals.push('cows'); console.log(count);//4 console.log(animals);// ["pigs", "goats", "sheep", "cows"] animals.push('chickens', 'cats', 'dogs'); console.log(animals);//["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]
Array.prototype.reverse()(⭐⭐⭐)
The reverse() method reverses the position of the elements in the array and returns the array. The first element of the array becomes the last, and the last element of the array becomes the first. This method changes the original array.
example:
const array1 = ['one', 'two', 'three']; console.log(array1);//["one", "two", "three"] const reversed = array1.reverse(); console.log( reversed);// ["three", "two", "one"] console.log( array1);// ["three", "two", "one"]
Array.prototype.shift()(⭐⭐⭐)
**The shift() * * method deletes the first element from the array and returns the value of the element. This method changes the length of the array.
example:
const array1 = [1, 2, 3]; const firstElement = array1.shift(); console.log(array1);// [2, 3] console.log(firstElement);// 1
Array.prototype.slice()(⭐⭐⭐)
slice() method returns a new array object, which is a shallow copy of the original array (including begin and excluding end) determined by begin and end. The original array will not be changed.
Explanation:
-
slice does not modify the original array, but only returns a new array that shallow copies the elements in the original array.
-
Syntax: arr.slice(begin, end)
-
Parameters:
-
begin optional. Extract the index at the beginning (starting from 0), and extract the original array elements from this index.
-
End optional. Extract the index at the end (starting from 0) and end extracting the elements of the original array at this index. slice will extract all elements in the original array whose index is from begin to end (including begin but not end)
-
example:
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant']; console.log(animals.slice(2));//["camel", "duck", "elephant"] console.log(animals.slice(2, 4));// ["camel", "duck"] console.log(animals.slice(1, 5));// ["bison", "camel", "duck", "elephant"] console.log(animals.slice(-2));//["duck", "elephant"] console.log(animals.slice(2, -1));// ["camel", "duck"]
Array.prototype.some()(⭐⭐⭐)
The some() method tests whether at least one element in the array has passed the provided function test. It returns a Boolean value.
example:
const array = [1, 2, 3, 4, 5]; const even = (element) => element % 2 === 0; console.log(array.some(even));// true
Array.prototype.sort()(⭐⭐⭐)
**The sort() * * method sorts the elements of the array using an in place algorithm and returns the array. The default sort order is built when the elements are converted to strings and then their UTF-16 code unit value sequences are compared
example:
const months = ['March', 'Jan', 'Feb', 'Dec']; months.sort(); console.log(months);//["Dec", "Feb", "Jan", "March"] const array1 = [1, 30, 4, 21, 100000]; array1.sort(); console.log(array1);// [1, 100000, 21, 30, 4]
Array.prototype.splice()(⭐⭐⭐)
The splice() method modifies the array by deleting or replacing existing elements or adding new elements in place, and returns the modified contents in the form of an array. This method will change the original array.
Explanation:
- If the number of elements added to the array is not equal to the number of elements deleted, the length of the array will change accordingly
- Syntax: array.splice(start, deleteCount, item1, item2 [,...)
- Parameters:
- Start. Specifies the start position of the modification (counted from 0). If the length of the array is exceeded, the content is added from the end of the array; if it is a negative value, it indicates the number of bits from the end of the array
- deleteCount optional integer indicating the number of array elements to be removed.
- item1, item2,... Optional. The elements to be added to the array start at the start position. If not specified, splice() will delete only the array elements.
example:
const months = ['Jan', 'March', 'April', 'June']; months.splice(1, 0, 'Feb'); console.log(months);//["Jan", "Feb", "March", "April", "June"] months.splice(4, 1, 'May'); console.log(months);// ["Jan", "Feb", "March", "April", "May"]
Array.prototype.toString()(⭐⭐⭐)
toString() returns a string representing the specified array and its elements.
example:
const array1 = [1, 2, 'a', '1a']; console.log(array1.toString());//"1,2,a,1a"
Array.prototype.unshift()(⭐⭐⭐)
The unshift() method adds one or more elements to the beginning of the array and returns the new length of the array (this method modifies the original array).
example:
const array1 = [1, 2, 3]; console.log(array1.unshift(4, 5));// 5 console.log(array1);//[4, 5, 1, 2, 3]
Array.prototype.concat()(⭐⭐)
Simply put, the concat method is used to merge arrays without changing the point of this. It is a shallow copy
Explanation:
- The concat() method is used to merge two or more arrays =. This method does not change the existing array, but returns a new array.
- Syntax: value1.concat(value2,value3,...)
- Parameters: value1, Value2 and value3 are the arrays to be merged.
- The concat method does not change this or any array provided as a parameter, but returns a shallow copy containing copies of the same elements combined with the original array
example:
Example 1:
<script> var arr1 = ['a', 'b', 'c']; var arr2 = [1, 2, 3]; var arr=arr1.concat(arr2); console.log(arr);//['a', 'b', 'c', 1, 2, 3] </script>
result:
Example 2:
<script> var num1 = [[1]]; var num2 = [2, [3]]; var num3 = [5, [6]]; var nums = num1.concat(num2); console.log(nums);// [[1], 2, [3]] var nums2 = num1.concat(4, num3); console.log(nums2)// [[1], 4, 5,[6]] </script>
result:
Array.prototype.filter()(⭐⭐)
Simply put, the * * filter() * * method creates a new array containing all the elements of the test implemented by the provided function.
The return value is a new array of elements that pass the test. If no array elements pass the test, an empty array is returned.
Explanation:
-
The filter calls the callback function once for each element in the array, and creates a new array with all the elements that make the callback return true or the value equivalent to true.
-
Syntax:
var newArray = arr.filter(callback(element, index, array), thisArg)
-
Parameters:
-
callback is a function used to test each element of the array. Returning true means that the element passes the test, and the element is retained; false means that it is not retained.
-
thisArg optional
The value used for this when callback is executed.
-
-
The filter does not change the original array, it returns the filtered new array.
example:
<script> var arry=[12, 5, 8, 130, 44] var arry1=arry.filter(item=>item>10); console.log(arry1);//[12, 130, 44] </script>
Array.prototype.find()(⭐⭐)
Simply put, the find() method returns the value of the first element in the array that satisfies the provided test function. Otherwise, it returns undefined.
Explanation:
-
The find method executes the callback function once for each element in the array until one callback returns true
-
Syntax:
arr.find(callback, thisArg)
-
Parameters:
- callback is a function executed on each item of the array and receives three parameters.
- thisArg optional. The object used as this when the callback is executed.
example:
<script> var inventory = [ { name: 'apples', quantity: 2 }, { name: 'bananas', quantity: 0 }, { name: 'cherries', quantity: 5 } ]; function findCherries(fruit) { return fruit.name === 'cherries'; } console.log(inventory.find(findCherries)); // { name: 'cherries', quantity: 5 } </script>
Array.prototype.forEach()
Simply put, the * * forEach() * * method executes the given function once for each element of the array.
The return value is undefined
Explanation:
-
The forEach() method executes the callback function once for each item in the array that contains valid values in ascending order, and those deleted or uninitialized items will be skipped
-
Syntax: array. Foreach (callback (currentvalue, index, array) [, thisarg)
-
Parameters:
- callback is a function executed for each element in the array, which receives one to three parameters
- thisArg optional parameter. Used as the value of this when the callback function callback is executed.
example:
const array1 = ['a', 'b', 'c']; array1.forEach(element => console.log(element)); // expected output: "a" // expected output: "b" // expected output: "c"
Array.from()( ⭐⭐) (it's complicated. It's recommended to see MDN)
Simply put, the Array.from() method creates a new array or object from a similar array or iteratable object. The return value is a new array instance.
Explanation:
- Array.from() can create array objects in the following ways:
- Pseudo array object (any object with one length attribute and several index attributes)
- Iteratable object (you can get the elements in the object, such as Map and Set)
- Syntax: Array.from(arrayLike, mapFn, thisArg)
- Parameters:
- arrayLike. A pseudo array object or iteratable object that you want to convert to an array.
- mapFn optional. If this parameter is specified, each element in the new array will execute the callback function.
- thisArg optional parameter, this object when the callback function mapFn is executed.
example:
console.log(Array.from('foo')); // expected output: Array ["f", "o", "o"] console.log(Array.from([1, 2, 3], x => x + x)); // expected output: Array [2, 4, 6]
Array.prototype.includes()(⭐⭐)
Simply put, the includes() method is used to determine whether an array contains a specified value. If it does, it returns true, otherwise it returns false.
Explanation:
- Syntax: arr.includes(valueToFind, fromIndex)
- Parameters:
- valueToFind the element value to find.
- fromIndex is optional. Find valueToFind starting at the fromIndex index. If it is a negative value, the search starts from the index of array.length + fromIndex in ascending order (even if the absolute value of fromIndex jumps forward by one index from the end, and then searches backward). The default is 0.
example:
<script> [1, 2, 3].includes(2); // true [1, 2, 3].includes(4); // false [1, 2, 3].includes(3, 3); // false [1, 2, 3].includes(3, -1); // true [1, 2, NaN].includes(NaN); // true </script>
Array.isArray()(⭐⭐)
Array.isArray() is used to determine whether the value passed is an array
example:
Array.isArray([1, 2, 3]); // true Array.isArray({foo: 123}); // false Array.isArray("foobar"); // false Array.isArray(undefined); // false
Array.prototype.every()(⭐)
Simply put, the every() method tests whether all elements in an array can pass the test of a specified function. It returns a Boolean value.
Note: if you receive an empty array, this method will return true in all cases.
explain
-
The every method executes the callback function once for each element in the array until it finds one that will cause the callback to return falsy If such an element is found, the every method will immediately return false. Otherwise, if callback returns true for each element, every will return true.
-
Syntax:
arr.every(callback(element, index, array), thisArg)
-
Parameter: callback function is used to test the function of each element (if you don't know the callback function, search it yourself). thisArg is optional. It is used for the value of this when callback is executed.
example
Example 1
<script> const isBelowThreshold = (currentValue) => currentValue < 40; const array1 = [1, 30, 39, 29, 10, 13]; console.log(array1.every(isBelowThreshold));// true </script>
Example 2
function isBigEnough(element) {//Detects whether all elements in the array are greater than 10 return element >= 10; } [12, 5, 8, 130, 44].every(isBigEnough); // false [12, 54, 18, 130, 44].every(isBigEnough); // true
promote
The function () above can be optimized into an arrow function.
[12, 5, 8, 130, 44].every(x => x >= 10); // false [12, 54, 18, 130, 44].every(x => x >= 10); // true
Array.prototype.fill()(⭐)
Simply put, the * * fill() * * method fills all elements in an array from the start index to the end index with a fixed value. The end index is not included. (half closed and half open) the return value is the modified array.
Explanation:
-
The fill method accepts three parameters, value, start and end. The start and end parameters are optional,
-
Syntax:
arr.fill(value, start, end)
-
Parameters:
- value is used to fill in the values of array elements.
- Start (optional). The start index is 0 by default
- end (optional). Terminates the index. The default value is this.length.
-
This method does not require this to be an array object.
example:
Example 1:
<script> const array1 = [1, 2, 3, 4]; console.log(array1.fill(0, 2, 4));// [1, 2, 0, 0] console.log(array1.fill(5, 1));//[1, 5, 5, 5] console.log(array1.fill(6));//[6, 6, 6, 6] </script>
Array.prototype.copyWithin()(⭐)
The simple understanding is to copy the array elements from the start position to the end position to the target position of the array.
Explanation:
- The copyWithin() method copies a part of the array to another location in the same array and returns it without changing the length of the original array. It can change the this object itself and return it, not just its copy. It returns the changed array.
- Syntax: arr.copyWithin(target, start, end)
- Parameters:
- Target: copy to target. If target is greater than or equal to arr.length, no copy will occur. If target is after start, the copied sequence will be modified to conform to arr.length.
- Start: the starting position of replication. If start is negative, the specified index position is equal to length+start
- End: the end position of the copy. If start is negative, the specified index position is equal to length+start
- The copyWithin function is designed to be generic and does not require that its this value must be an array object.
example:
Example 1:
Let's start with a simple warm-up
<script> const array1 = ['a', 'b', 'c', 'd', 'e']; console.log(array1.copyWithin(0, 3, 4));// ["d", "b", "c", "d", "e"] console.log(array1.copyWithin(1, 3));// ["d", "d", "e", "d", "e"] </script>
result:
Upgrade:
// Copy position 3 to position 0 [1, 2, 3, 4, 5].copyWithin(0, 3, 4) // [4, 2, 3, 4, 5] // -2 is equivalent to position 3 and - 1 is equivalent to position 4 [1, 2, 3, 4, 5].copyWithin(0, -2, -1) // [4, 2, 3, 4, 5] // Copy position 3 to position 0 [].copyWithin.call({length: 5, 3: 1}, 0, 3) // {0: 1, 3: 1, length: 5} // Copy bit 2 to the end of the array and to bit 0 var i32a = new Int32Array([1, 2, 3, 4, 5]); i32a.copyWithin(0, 2); // Int32Array [3, 4, 5, 4, 5] // For platforms that do not deploy the copyWithin method of TypedArray // The following wording is required [].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4); // Int32Array [4, 2, 3, 4, 5]
3.Array.prototype.entries()( ⭐ (just understand)
Simply put, the entries() method returns a new Array Iterator object
Explanation:
- The entries() method returns a new Array Iterator object that contains key / value pairs for each index in the array.
- A new Array Iterator object. Array Iterator is an object. Its prototype (proto:Array Iterator) has a next method that can be used to traverse the iterator to obtain [key,value] of the original array.
example:
const array1 = ['a', 'b', 'c']; const iterator1 = array1.entries(); console.log(iterator1.next().value);// [0, "a"] console.log(iterator1.next().value);//Array [1, "b"]
4.Array.prototype.every()(⭐)
Explanation:
- The every() method tests whether all elements in an array can pass the test of a specified function. It returns a Boolean value.
- Parameter: callback
example:
<script> const isBelowThreshold = (currentValue) => currentValue < 40; const array1 = [1, 30, 39, 29, 10, 13]; console.log(array1.every(isBelowThreshold));// true </script>