快来看看JS数组中常用的方法吧! 原创
简介
数组对我们前端来说非常重要,作为一种特殊的数据结构,数组在开发中太常见了,它允许在单个变量名下存储多个项的集合,因此,熟练掌握一些常见的 api 是很有必要的。
一、常用的增删改查
1. 增
- push()
- unshift()
- splice()
- concat()
其中前 3 种可以改变原数组,第 4 种则不会
push()
push()
方法接收一个或多个参数,并将它们添加到数组末尾,返回数组的最新长度
const arr = [];
const length = arr.push("pink", "cyan");
console.log(length) // 2
console.log('arr: ', arr); // [ 'pink', 'cyan' ]
unshift()
unshift()
在数组开头添加任意多个值,然后返回新的数组长度
const arr = [ 'red' ];
const length = arr.unshift("pink", "cyan");
console.log(length) // 3
console.log('arr: ', arr); // [ 'pink', 'cyan', 'red' ]
splice()
splice()
传入 3 个参数,分别是开始位置、要删除的元素数量、插入的元素,返回空数组
const arr = [ "pink", "cyan", 'red' ];
const emptyArr = arr.splice(1, 0, 'white', 'black'); // 从下标为 1 的元素开始,删除 0 个,添加 2 个
console.log(emptyArr) // [ ]
console.log('arr: ', arr); // [ 'pink', 'white', 'black', 'cyan', 'red' ]
concat()
concat()
用于拼接两个数组,不会改变原数组,返回新数组
const arr1 = [ "pink", "cyan" ];
const arr2 = [ 'white', 'black' ];
const newArr = arr1.concat(arr2);
console.log('newArr: ', newArr); // [ 'pink', 'cyan', 'white', 'black' ]
使用扩展运算符(…)会更优雅:
const newArr = [...arr1, ...arr2]
console.log('newArr: ', newArr); // [ 'pink', 'cyan', 'white', 'black' ]
2. 删
- pop()
- shift()
- splice()
- slice()
其中前 3 种会影响原数组,第 4 种则不会
pop()
pop()
方法用于删除数组的最后一项,同时减少数组的length
值,返回被删除的项
const arr = ["pink", "cyan"];
const deleteItem = arr.pop();
console.log(deleteItem) // cyan
console.log('arr: ', arr); // [ 'pink' ]
shift()
shift()
方法用于删除数组的第一项,同时减少数组的length
值,返回被删除的项
const arr = ["pink", "cyan"];
const deleteItem = arr.shift();
console.log(deleteItem) // pink
console.log('arr: ', arr); // [ 'cyan' ]
splice()
可参考第 1 点中的 splice()
slice()
slice()
用于创建一个包含原有数组中一个或多个元素的新数组,不会影响原始数组
const colors1 = ["red", "green", "blue", "yellow", "purple"];
const colors2 = colors1.slice(1); // 从下标为 1 开始截取到最后一个
const colors3 = colors1.slice(1, 4); // 从下标为 1 开始到截取到下标为 4 (不包含 4)的元素
console.log(colors1) // [ 'red', 'green', 'blue', 'yellow', 'purple' ]
console.log(colors2); // [ 'green', 'blue', 'yellow', 'purple' ]
console.log(colors3); // [ 'green', 'blue', 'yellow' ]
3. 改
可参考第 1 点中的 splice()
, splice()
很强!增删改都能做
4. 查
即查找元素,返回元素坐标或者元素值
- indexOf()
- includes()
- find()
indexOf()
indexOf()
返回要查找的元素在数组中的位置,如果没找到则返回 -1
const numbers = [1, 2, 3];
numbers.indexOf(3) // 2
numbers.indexOf(4) // -1
includes()
includes()
返回要查找的元素在数组中的位置,找到返回true
,否则false
const numbers = [1, 2, 3, 4, 5];
numbers.includes(4) // true
find()
find()
返回第一个匹配的元素
const people = [
{
name: "Matt",
age: 18
},
{
name: "Nicholas",
age: 19
},
{
name: "Michael",
age: 20
}
];
people.find((element, index, array) => element.age < 20) // { name: "Matt", age: 18 }
二、排序方法
数组有两个方法可以用来对元素重新排序:
- reverse()
- sort()
reverse()
顾名思义,将数组元素方向反转
const values = [1, 2, 3, 4, 5];
values.reverse();
console.log(values); // 5,4,3,2,1
sort()
sort()
方法接受一个比较函数,用于判断哪个值应该排在前面
function compare(value1, value2) {
if (value1 < value2) {
return -1;
} else if (value1 > value2) {
return 1;
} else {
return 0;
}
}
const values = [0, 1, 5, 10, 15];
values.sort(compare);
console.log(values); // [0,1,5,10,15]
使用箭头函数更优雅:
const numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a - b); // a - b 为升序,b - a 为降序
console.log(numbers);// [1, 2, 3, 4, 5]
三、转换方法
join()
join()
方法接收一个参数,即字符串分隔符,返回包含所有项的字符串
const colors = ["red", "green", "blue"];
console.log(colors.join(",")); // red,green,blue
console.log(colors.join("||")); // red||green||blue
四、迭代方法
重点!工作中常用,合理使用能加快开发效率
常用来迭代数组的方法(都不改变原数组):
- some()
- every()
- forEach()
- filter()
- map()
some()
some()
对数组每一项都执行传入的测试函数,如果至少有1个元素返回 true ,则这个方法返回 true
const array = [1, 2, 3, 4, 5];
// 检查元素是否是偶数
const even = (element) => element % 2 === 0;
console.log(array.some(even)); // true
every()
every()
对数组每一项都执行传入的测试函数,如果所有元素都返回 true ,则这个方法返回 true
const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold)); // true
forEach()
forEach()
对数组每一项都执行传入的函数,没有返回值
const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));
// "a"
// "b"
// "c"
如果某一项为空,则跳过该项继续遍历
const logArrayElements = (element, index, array) => {
console.log('a[' + index + '] = ' + element);
};
// 注意:下标为 2 的元素会被跳过,因为该项为空
[2, 5,, 9].forEach(logArrayElements);
// a[0] = 2
// a[1] = 5
// a[3] = 9
filter()
filter()
对数组每一项都执行传入的函数,函数返回 true
的项会组成数组之后返回
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// ["exuberant", "destruction", "present"]
如果想过滤掉 falsy 值,可以直接使用 filter(Boolean),如:
const fruits = [undefined, 'apple', false, 'banana', 0, 'orange', null, ''];
const result = fruits.filter(Boolean);
console.log(result); // [ 'apple', 'banana', 'orange' ]
map()
map()
对数组每一项都执行传入的函数,返回由每次函数调用的结果构成的数组
const array1 = [1, 4, 9, 16];
const map1 = array1.map(x => x * 2);
console.log(map1);
// [2, 8, 18, 32]
map()
的使用场景非常多,作为前端,有时候后端返回的数据可能不是我们想要的,这时我们就可以用 map()
进行调整:
const icArray = [
{ id: 1, count: 10 },
{ id: 2, count: 20 },
{ id: 3, count: 30 }
];
// 假设现在有个需求,需要将 icArray 中每个对象的 id 的值作为新数组中每个对象的 key, 将每个对象的 count 的值作为新数组中每个对象的 value,则可以这样做:
const reformattedArray = icArray.map(({ id, count}) => ({ [id]: count }));
console.log('reformattedArray: ', reformattedArray); // [{1: 10}, {2: 20}, {3: 30}]
console.log('icArray', icArray); // icArray 还是原来的值: [{ id: 1, count: 10 },{ id: 2, count: 20 },{ id: 3, count: 30 }];
很强,到时候有些忘记了就来复习下
数组增删改查拿捏住了
学到了