This article first appeared in Xing personal website liuxing.io
Introduction
In JavaScript, besides Object, Array should be the most commonly used type. An array is a group of ordered data, using square brackets to indicate [1, 2, 3]
, and each element can be accessed by index (the index starts from 0). The length and element types of arrays in JavaScript are not fixed.
Array creation
First, let’s take a look at several ways to create arrays: literal way, Array constructor, spread operator ( ...
), ES6’s new static methods for creating arrays from()
and of()
Array literal
Array literal (array literal) should be the most commonly used creation method in JavaScript, and it is quite convenient when initializing arrays. An array literal is a comma-separated list of elements enclosed in square brackets.
const users = ['LiuXing', 'liuixng.io'];
console.log(users.length); // 2
In the above example, an array containing two strings is created.
Constructor
You can also use the Array constructor to create an array. You can Array()
constructor to create an array with the length of the incoming value; you can also pass the elements to be saved to the Array constructor to create an array containing the incoming value.
// 传入要保存的元素
const users = Array('LiuXing', 'liuxing.io'); ['LiuXing', 'liuxing.io']
console.log(users.length); // 2
const arr1 = new Array(); []
// 传入数字 直接创建一个长度为3的数组
const arr2 = Array(3); [,,]
console.log(users.length); // 3
When using the Array constructor, with or without the new operator, the result is the same.
Spread operator
You can use the spread operator ...
to include elements of another array in an array literal. The spread operator can easily create a shallow copy of the array. The spread operator can also be used for any iterable object.
const original = [1, 2, 3];
const copy = [...original]
copy[0] = 0 // 修改copy不会法改变原数组
original[0] // 1
Array static method
ES6 Array adds two new static methods for creating arrays: from()
and of()
. from()
used to convert a class array to an array, and of()
used to convert a set of parameters to an array.
Array.form()
Create a new array instance from an array-like object or an iterable object.
Array.form()
can receive 3 parameters:
- The first required parameter is the pseudo-array object or iterable object that you want to convert into an array: such as Map and Set, Arguments object
- The second is an optional mapping function parameter, which can directly enhance the value of the new array, similar to the array map method
- The third optional parameter is used to specify the value of this in the mapping function, but this rewritten this value is not applicable in arrow functions
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]
const a1 = [1, 2, 3, 4];
const a2 = Array.from(a1, function(x) {return x**this.exponent}, {exponent: 2});
console.log(a2); // [1, 4, 9, 16]
Array.of()
Create a new array instance based on a set of parameters, supporting any number and types of parameters. Will be the elements in the returned array in order.
Array.of(7); // [7]
Array.of(1, 2, 3); // [1, 2, 3]
Array detection
In essence, arrays belong to a special kind of object. typeof
operator will return the type of the array is object
. A classic problem is to judge whether an object is an array, usually by instanceof
, constructor
Object.prototype.toString
, but the first two may be inaccurate, and the latter is more troublesome. To solve this small problem, JavaScript provides the Array.isArray()
method, which returns a boolean value indicating whether the parameter is an array. It can make up for the deficiencies of the typeof
operator.
Array.isArray([1, 2, 3]);
// true
Array.isArray({foo: 123});
// false
Array.isArray("foobar");
// false
Array.isArray(undefined);
// false
But in an environment that does not support this method, we can provide the following Polyfill, that is, use Object.prototype.toString
to judge
if (!Array.isArray) {
Array.isArray = function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
}
Array method
There are many methods for arrays. This article will divide these methods into operation methods, sorting methods, stack and queue methods, iteration methods, search methods, and array conversion methods. In the array operation method, only concat()
and slice()
will not change the original array, and other methods will change the original array. All sorting methods will change the original array. All stack and queue methods also change the original array.
Array operation method
For the elements in the array, we have many operation methods, such as: concat()
used to connect two arrays. slice()
used for slicing, splice()
deletes or inserts elements in the middle of the array...
contact()
concat
method is used to merge multiple arrays. It adds the elements of the new array to the back of the original array elements, and then returns a new result array without the original array.
['liu', 'xing'].concat(['love', 'dev'])
// ["liu", "xing", "love", 'dev']
If one or more arrays are concat()
, 0608c379a76426 will add each item of these arrays to the result array. If the parameters are not arrays, add them directly to the end of the result array
[1, 2, 3].concat(4, 5, 6)
// [1, 2, 3, 4, 5, 6]
At the same time, the concat
method can also easily create a shallow copy of the current array.
slice()
slice()
method is used for slicing, that is, intercepting some of the elements in the array, and then returning a new array, leaving the original array unchanged.
slice()
method can receive one or two parameters: the start index and end index of the returned element. slice()
includes the start index but not the end index.
arr.slice(start, end);
If there are two parameters, slice()
returns all elements corresponding to the start index to the end index, which does not include the elements corresponding to the end index.
arr.slice(start, end);
If there is only one parameter, slice() will return all elements from that index to the end of the array.
arr.slice(start, end);
If you don't slice()
, it will intercept all elements from beginning to end, which is equivalent to returning a copy of the original array.
arr.slice(start, end);
If slice()
method is negative, it indicates the position of the reciprocal calculation
arr.slice(start, end);
splice()
Perhaps the most powerful array method is splice()
, which is the "universal method" for modifying the array. It can delete several elements from the specified index, and then add several elements from that position. The return value is the deleted element, this method will change the original array.
arr.splice(start, count, addElement1, addElement2, ...);
splice
is to specify the starting position of the modification (counting from 0), and the second parameter is the number of deleted elements. If there are more parameters behind, it means that these are the new elements to be inserted into the array.
There are three main ways to use:
- delete . Need to
splice()
: the position of the first element to be deleted and the number of elements to be deleted. Can be from
Delete any number of elements from the array, for example,splice(0, 2)
will delete the first two elements. - insert . You need to
splice()
: start insertion position index, 0 (delete 0 elements) and the element to be inserted.
Insert the element at the specified position in the array. After the third parameter, you can pass the fourth, fifth, or as many as you like
Elements to be inserted. - replace .
splice()
can insert a new element at the specified position while deleting the element, so that we can easily replace the element. For example,splice(2, 1, "liuxing")
will delete an element at position 2, and then insert "liuxing" into the array from that position.
copyWithin()
copyWithin()
method can shallowly copy a part of the array to another position in the same array and return it without changing the length of the original array.
[1, 2, 3, 4, 5].copyWithin(0, 3)
// [4, 5, 3, 4, 5]
fill()
fill()
method can fill all elements in an array from the start index to the end index with a fixed value. Does not include the termination index.
['a', 'b', 'c'].fill(7)
// [7, 7, 7]
new Array(3).fill(7)
// [7, 7, 7]
Sorting method
sort()
sort
method can sort the array members, and the original array will be changed after sorting. The default sort order is constructed when the elements are converted (by calling the String()
conversion function) into strings, and then their UTF-16 code unit value sequences are compared. Such as:
let values = [0, 3, 1, 2, 10];
values.sort();
console.log(values); // [0, 1, 10, 2, 3]
As can be seen from the above example, the default sorting method is problematic in the sorting of numbers. For this reason, the sort() method can receive a comparison function as the second parameter to determine which value should be ranked first. The comparison function can receive two parameters, which represent the two array members to be compared.
- If the first parameter should be ranked before the second parameter, return a negative value;
- If the two parameters are equal, it returns 0;
- If the first parameter should come after the second parameter, it returns a positive value.
The format is as follows
function compare(a, b) {
if (a < b ) { // 按某种排序标准进行比较, a 小于 b
return -1;
}
if (a > b ) {
return 1;
}
// a must be equal to b
return 0;
}
The sorting of the previous instance array can be written like this
let values = [0, 3, 1, 2, 10];
values.sort((a, b) => a - b);
console.log(values); // [0, 1, 2, 3, 10]
reverse()
As the name suggests, the reverse()
method is to reverse the array elements. This method will change the original array.
let values = [1, 2, 3, 4, 5];
values.reverse();
console.log(values); // 5,4,3,2,1
Stacks and queues
JavaScript arrays and native methods can simulate two other commonly used data structures: stacks and queues
stack is a last-in-first-out (LIFO, Last-In-First-Out) structure , that is, the most recently added item is deleted first. The insertion (called push) and deletion (called pop) of data items only occur in one place on the stack, that is, the top of the stack. JavaScript arrays provide push() and pop() methods to achieve stack-like behavior.
push()
push()
method is used to add elements (any number of elements) to the end of the array and return the latest length of the array. This method will change the original array.
let arr = [];
arr.push(1) // 1
arr.push('liuxing') // 2
arr // [1, 'liuxing', true, {}]
pop()
pop()
method is used to delete the last element of the array and return that element. This method will change the original array.
let arr = ['a', 'b', 'c'];
arr.pop() // 'c'
arr // ['a', 'b']
form of First-In-First-Out (FIFO, First-In-First-Out). The queue adds data to the end of the list, but gets data from the beginning of the list. Because there is a push() method to add data to the end of the data, there is a way to get the data from the beginning of the array to simulate the queue. This array method is called shift(), it deletes the first item of the array and returns it, and then the length of the array is reduced by 1. Using shift() and push(), you can use the array as a queue
shift()
shift()
method is used to delete the first element of the array and return that element. This method will change the original array.
let arr = ['a', 'b', 'c'];
arr.shift() // 'a'
arr // ['b', 'c']
unshift()
unshift()
method is used to add an element to the first position of the array and returns the length of the array after adding the new element. This method will change the original array.
let arr = ['a', 'b', 'c'];
arr.unshift('liuixng'); // 4
arr // ['liuxing', 'a', 'b', 'c']
Array iteration method
ES6 arrays provide three new methods for retrieving the contents of arrays: entries()
, keys()
and values()
. They all return an iterator object. keys()
returns an iterator of array indexes, values()
returns an iterator of array elements, and entries()
returns an iterator of key/value pairs. You can use the for...of
loop to traverse.
keys()
Returns an iterator object containing the indices of all array elements.
for (let index of ['a', 'b'].keys()) {
console.log(index);
}
// 0
// 1
values()
Returns an iterator object containing all the array elements.
for (let elem of ['a', 'b'].values()) {
console.log(elem);
}
// 'a'
// 'b'
entries()
Returns a key-value pair iterator object containing all array elements.
for (let [index, elem] of ['a', 'b'].entries()) {
console.log(index, elem);
}
// 0 "a"
// 1 "b"
forEach()
forEach
method iterates each element of the array and calls the callback function we specify once for each element. It does not return a value and is only used to manipulate data. forEach()
method is equivalent to using for
loop through the array.
let numbers = [1, 2, 3, 4, 5];
numbers.forEach((item, index, array) => {
// 执行某些操作
console.log(item)
});
map()
map()
will pass each element of the array into the callback function in order, and then return a new array composed of the results of each function call. Note: The callback function will only be called on indexes that have a value.
let numbers = [1, 2, 3, 4, 5];
let mapResult = numbers.map((item, index, array) => item * 2);
console.log(mapResult); // [2,4,6,8,10]
flat()
flat()
used to tie the array. That is, convert from a multi-dimensional array to a one-bit array. This method receives a parameter (default is 1) for the specified depth traversal, and then merges all the elements with the elements in the traversed sub-array into a new array and returns.
[1, 2, [3, 4]].flat()
// [1, 2, 3, 4]
If you want to flatten the array regardless of how many layers, you can pass in Infinity
as a parameter
[1, [2, [3]]].flat(Infinity)
// [1, 2, 3]
flatMap()
flatMap()
is similar to map()
Only the returned array will be automatically flattened. Calling flatMap()
equivalent to calling map()
, but flatMap()
is more efficient.
[2, 3, 4].flatMap((x) => [x, x * 2])
// [2, 4, 3, 6, 4, 8]
filter()
filter()
method is used to filter array elements. It will run the passed function on each item of the array, and true
will be returned as a new array. This method will not change the original array.
let numbers = [1, 2, 3, 4, 5];
let filterResult = numbers.filter((item, index, array) => item > 2);
console.log(filterResult); // [3, 4, 5]
some()
is every()
, and both are used to determine whether the elements in the array meet a certain condition (assertion function).
- For
every()
, the passed-in function must returntrue
for each item before it will returntrue
; - For
some()
, as long as there is an item that makes the passed function returntrue
, it will returntrue
.
some()
If at least one element in the array satisfies the test function, true
is returned, otherwise false
is returned.
let numbers = [1, 2, 3, 4, 5];
let everyResult = numbers.every((item, index, array) => item > 2);
console.log(everyResult); // false
every()
If each element in the array satisfies the test function, it returns true
, otherwise it returns false。
let numbers = [1, 2, 3, 4, 5];
let someResult = numbers.some((item, index, array) => item > 2);
console.log(everyResult); // true
reduce()
and reduceRight()
these two methods will iterate all the items in the array, and build a final return value on this basis. reduce()
method traverses from the first item of the array to the last item. And reduceRight()
starts from the last item and traverses to the first item.
reduce()
Execute the callback function once for each array element from left to right, and put the return value of the last callback function in a scratchpad and pass it to the next callback function, and return the return value of the last callback function.
let values = [1, 2, 3, 4, 5];
let sum = values.reduce(function(prev, cur, index, array){
console.log(prev, cur)
return prev + cur;
});
// 1 2
// 3 3
// 6 4
// 10 5
console.log(sum) // 15
reduceRught()
Execute the callback function once for each array element from right to left, and put the return value of the last callback function in a scratchpad and pass it to the next callback function, and return the return value of the last callback function.
let values = [1, 2, 3, 4, 5];
let sum = values.reduceRight(function(prev, cur, index, array){
console.log(prev, cur)
return prev + cur;
});
// 5 4
// 9 3
// 12 2
// 14 1
console.log(sum) // 15
Search in the array
JavaScript provides two methods for searching arrays: searching by strict equality and searching by assertion function.
indexOf()
,lastIndexOf()
andincludes()
are search methods that are strictly equal. They all accept two parameters: the element to be searched and an optional starting search position.find()
andfindIndex()
methods use an assertion function. They receive 3 parameters: element, index and the array itself
indexOf()
indexOf
method returns the position of the first occurrence of the given element in the array. If it does not appear, it returns -1
. It can also accept a second parameter, which indicates the starting position of the search.
let arr = Array.from('liuxing');
arr.indexOf('i') // 1
arr.indexOf('i', 2) // 4
lastIndexOf()
lastIndexOf
method returns the position of the last occurrence of the given element in the array (find from back to -1
), if it does not appear, it returns 0608c379a868a5.
let arr = Array.from('liuxing');
arr.lastIndexOf('i') // 4
arr.lastIndexOf('i',3) // 1
includes()
includes()
method is used to determine whether an array contains a specified value and returns a Boolean value. It returns true if it contains, otherwise it returns false.
let arr = Array.from('liuxing');
arr.includes('i') // true
arr.includes('io') // false
find()
find()
method returns the value of the first element in the array that satisfies the assertion function. Otherwise, it returns undefined.
const people = [
{
name: "LiuXing",
age: 99
},
{
name: "XingLiu",
age: 9
}
];
people.find(element => element.name === 'LiuXing') // {name: "LiuXing", age: 99}
findIndex()
findIndex()
method returns the position of the first element in the array that satisfies the assertion function. Otherwise, it returns -1.
const people = [
{
name: "LiuXing",
age: 99
},
{
name: "XingLiu",
age: 9
}
];
people.findIndex(element => element.name === 'LiuXing') // 0
Array conversion method
All objects have toLocaleString()
, toString()
and valueOf()
methods. Among them, valueOf()
of the array returns the array itself. And toString()
returns a comma-separated string formed by concatenating the equivalent string of each value in the array. toString()
method is called for each value of the array to get the final string.
valueOf()
valueOf
method is a method owned by all objects, which means that the object is evaluated. The valueOf
method of the array returns the array itself.
let arr = [1, 2, 3];
arr.valueOf() // [1, 2, 3]
toString() and toLocaleString()
toString
method is also a general method for objects. The difference between toLocaleString()
and toString()
toLocaleString()
corresponds to the region of the execution environment, such as a date object. The toString
and toLocaleString()
methods of the array return the string form of the array.
let arr = [10000, 20000, 3000];
arr.toString() // 10000,20000,3000
arr.toLocaleString() // "10,000,20,000,3,000"
join()
join()
method receives a parameter as a string separator, concatenates all array members into a string and returns. If no parameters are provided, they are separated by commas by default.
let a = [1, 2, 3, 4, 5];
a.join(' ') // '1 2 3 4 5'
a.join() // "1,2,3,4,5"
to sum up
This article talks about the creation of the array to the detection of the array, and finally talks about the various methods of the array, such as the array traversal method and the search method. This is a partial document-style article that requires frequent review.
Reference link
End of this article
Welcome to follow my official account and play together. There are technical dry goods and nonsense
Left-handed code, right-handed bricks, throw bricks to attract jade
Document informationCopyright notice: Attribution-Non-commercial use-No interpretation 4.0 International (CC BY-NC-ND 4.0)
Original link: https://www.liuxing.io/blog/javascript-array-methods-tutorial/
Date of Publication: April 17, 2021
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。