Arrays in JavaScript are a very useful data structure that can store a series of elements and provide many convenient operation methods. Here are some commonly used array methods:
- push(): Add one or more elements to the end of the array
let arr = [1, 2, 3];
arr.push(4);
console.log(arr); // [1, 2, 3, 4]
- pop(): removes the last element from the end of the array
let arr = [1, 2, 3];
let last = arr.pop();
console.log(arr); // [1, 2]
console.log(last); // 3
- unshift(): Add one or more elements to the beginning of the array
let arr = [1, 2, 3];
arr.unshift(0);
console.log(arr); // [0, 1, 2, 3]
- shift(): delete the first element from the beginning of the array
let arr = [1, 2, 3];
let first = arr.shift();
console.log(arr); // [2, 3]
console.log(first); // 1
- splice(): Insert, delete, or replace elements at specified positions
let arr = [1, 2, 3, 4, 5];
arr.splice(2, 1); // 删除下标为2的元素
console.log(arr); // [1, 2, 4, 5]
arr.splice(2, 0, 3); // 在下标为2处插入元素3
console.log(arr); // [1, 2, 3, 4, 5]
arr.splice(2, 1, 'three'); // 替换下标为2的元素
console.log(arr); // [1, 2, 'three', 4, 5]
- slice(): returns the subarray at the specified position
let arr = [1, 2, 3, 4, 5];
let subArr = arr.slice(2, 4); // 返回下标为2和3的元素组成的数组
console.log(subArr); // [3, 4]
- concat(): Merge multiple arrays
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let arr3 = arr1.concat(arr2);
console.log(arr3); // [1, 2, 3, 4, 5, 6]
- forEach(): Perform the specified operation on each element of the array
let arr = [1, 2, 3];
arr.forEach(function(item, index, array) {
console.log(item, index, array);
});
// 输出:
// 1 0 [1, 2, 3]
// 2 1 [1, 2, 3]
// 3 2 [1, 2, 3]
- map(): Perform the specified operation on each element of the array and return a new array
let arr = [1, 2, 3];
let newArr = arr.map(function(item) {
return item * 2;
});
console.log(newArr); // [2, 4, 6]
- filter(): Filter the unqualified elements in the array and return a new array
let arr = [1, 2, 3, 4, 5];
let newArr = arr.filter(function(item) {
return item % 2 === 0;
});
console.log(newArr); // [2, 4]
- reduce(): Perform the specified operation on each element of the array and return a cumulative value
let arr = [1, 2, 3, 4, 5];
let sum = arr.reduce(function(prev, curr) {
return prev + curr;
});
console.log(sum); // 15
These methods are very commonly used, and mastering them can allow you to process arrays more efficiently.