操作方法
数组基本操作可以归纳为 增、删、改、查,需要留意的是哪些方法会对原数组产生影响,哪些方法不会。
下面对数组常用的操作方法做一个归纳。
增
下面前三种是对原数组产生影响的增添方法,第四种则不会对原数组产生影响
-
.push() 接收
任意数量的参数,并将它们添加到数组未尾,返回数组的最新长度 -
.unshift() 在数组的
开头添加任意数量的参数,返回数组的最新长度 -
·splice(start, deleteCount, ...items) 返回
删除元素组成的数组,从start开始删除deleteCount个元素,并在当前位置插入items -
.concat() 数组
合并,返回新数组,不会影响原始数组
| 方法 | 参数 | 返回值 | 是否影响原数组 |
|---|---|---|---|
| .push() | 任意数量的参数 | 数组最新长度 | 是 |
| .unshift() | 任意数量的参数 | 数组最新长度 | 是 |
| ·splice((start, deleteCount, ...items) | start: 起始位置;deleteCoun:删除的数量; items: 插入的参数 | 删除元素组成的数组 | 是 |
| .concat() | 任意数量的参数 | 新数组 | 否 |
代码如下:
const arr = ['1']
const count = arr.push("red", "green")
console.log(count) // 3
const count1 = arr.unshift('0')
console.log(count1, arr) // 4 ['0', '1', 'red', 'green']
const removed = arr.splice(1, 0, 'pick', 'blue')
console.log(removed, arr) // [] ['0','pick', 'blue', '1', 'red', 'green']
const arr1 = [0]
const newArr = arr1.concat('1', [2, 3])
console.log(arr1, newArr) // [0] [0, '1', 2, 3]
删
下面三种都会影响原数组,最后一项不影响原数组
- pop() 删除数组最后一项,返回被删除的项
- shift() 删除数组第一项,返回被删除的项
- splice(start, deleteCount)
- slice(start, end) 用于创建一个包含原有数组中一个或多个元素的新数组,不会影响原始数组
| 方法 | 参数 | 返回值 | 是否改变原数组 |
|---|---|---|---|
| pop() | 返回被删除的数组最后一项 | 是 | |
| shift() | 返回被删除的数组第一项 | 是 | |
| splice(start, deleteCount) | start:起始位置;deleteCount: 删除的数量 | 删除元素组成的数组 | 是 |
| slice(start, end) | start: 开始截取的位置; end: 结束位置 | 截取元素组成的新数组 | 否 |
const arr = [0, 1, 2]
const deLaItem = arr.pop()
console.log(arr, deLaItem) // [0, 1] 2
const deFiItem = arr.shift();
console.log(arr, deFiItem); // 0 [1]
const arr1 = [0, 1, 2, 3, 4];
const delArr = arr1.splice(1, 2);
console.log(delArr, arr1); // [1, 2] [0, 3, 4]
const arr2 = [0, 1, 2, 3, 4];
const delArr2 = arr2.splice(1)
console.log(delArr2, arr2); // [1, 2, 3, 4] [0]
const arr3 = [0, 1, 2, 3, 4];
const newArr = arr3.slice(1, 3);
console.log(newArr, arr3); // [1, 2] [0, 1, 2, 3, 4]
改
splice()
查
即查找元素,返回元素坐标或者元素值
- indexOf() 返回要查找的元素在数组中的位置
下标,如果没找到则返回-1 - lastIndexOf 从最后一个值
向前查找的 找到了就会返回当前下标,没找到返回-1 - includes() 返回
布尔值 - find() 接收一个
回调函数,返回第一个匹配的元素 - findIndex() 接收一个
回调函数,返回符合条件的第一个下标,没有返回-1
const arr = [1, 2, 3, 4, 5, 4, 3, 2, 1];
console.log(arr.indexOf(4)); // 3
console.log(arr.lastIndexOf(4)); // 5
console.log(arr.includes(4)); // true
const people = [
{
name: "Matt",
age: 27
},
{
name: "Nicholas",
age: 29
}
];
console.log(people.find((element, index, array) => element.age < 28));
// {name: "Matt", age: 27}
console.log(people.findIndex((element, index, array) => element.age < 28));
// 0
排序方法
数组有两个方法可以用来对元素重新排序
- reverse() 原数组
倒序排序,改变原数组, 返回排序后的数组 - sort() 接受一个比较函数 ,
改变原数组,返回排序后的数组
function compare(value1, value2) {
if (value1 < value2) {
return -1;
} else if (value1 > value2) {
return 1;
} else {
return 0;
}
}
const arr = [0, 1, 5, 10, 15];
console.log(arr.sort(compare));
// [0, 1, 5, 10, 15]
转换方法
- join() 方法接收一个参数,即
字符串分隔符,返回包含所有项的字符串 - toString() 数组转字符串
- toLocaleString()
const arr = ['hello', 'world'];
console.log(arr.join(',')) // 'hello,world'
console.log(arr.toString()) // 'hello,world'
迭代方法
常用来迭代数组的方法(都不改变原数组)有如下:
- some() 一项满足就返回true
- every() 所有项都满足才返回true
- forEach() 遍历,没有返回值
- filter() 返回
满足筛选条件的元素组成的数组 - map() 不写return即遍历,写return即返回处理后的元素组成的数组。
some
对数组每一项都运行传入的测试函数,如果至少有1个元素返回 true ,则这个方法返回 true
const numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
const someResult = numbers.some((item, index, array) => item > 2);
console.log(someResult) // true
every()
对数组每一项都运行传入的测试函数,如果所有元素都返回 true ,则这个方法返回 true
const numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
const everyResult = numbers.every((item, index, array) => item > 2);
console.log(everyResult) // false
forEach()
对数组每一项都运行传入的函数,没有返回值
arr.forEach((item, index, arr) => {
//do something
});
map
没有return时,对数组的遍历。有return时,返回一个新数组,该新数组的元素是经过过滤(逻辑处理)过的函数。
注意:
- map()不会对
空数组进行检测。 - map()不会改变原始数组。
- map() 函数的作用是对数组中的每一个元素进行处理,返回新的元素
for、forEach、map性能差异和选择:
- 如果只是
简单的遍历数组并执行操作,可以使用forEach - 如果需要返回一个
新的数组,则可以使用map - 如果需要更
灵活的控制循环条件和循环体,则可以使用for循环 - 在
性能要求较高的情况下,可以考虑使用for循环来提高执行效率。 - 性能方面
for > map > forEach
const numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
const mapResult = numbers.map((item, index, array) => item * 2);
console.log(mapResult) // [2,4,6,8,10,8,6,4,2]
filter()
对数组中的每一运行给定的函数,会返回满足该函数的项组成的数组。
const numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
const filterResult = numbers.filter((item, index, array) => item > 2);
console.log(filterResult); // [3,4,5,4,3]
其他方法
reduce()
reduce 它可以通过迭代数组中的每一个元素,将其与累加器进行操作,并最终返回一个汇总的结果。reduce 允许你将数组“压缩”为一个单一的输出值,这个值可以是数字、字符串、对象等。
array.reduce((accumulator, currentValue, currentIndex, array) => {
// 操作
}, initialValue);
回调函数的参数:
- accumulator:累加器,保存上一次回调函数的返回值。
- currentValue:数组当前处理的元素。
- currentIndex:数组当前元素的索引。
- array:正在被遍历的数组。
- initialValue:初始值,可选参数。如果提供该参数,则 accumulator 在第一次迭代时会等于该值,否则 accumulator 会等于数组的第一个元素。
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // 输出 15
const items = [
{ name: '手机', price: 3000 },
{ name: '电脑', price: 8000 },
{ name: '耳机', price: 500 }
];
const totalPrice = items.reduce((total, item) => total + item.price, 0);
console.log(totalPrice); // 输出 11500
数组去重:
const numbers = [1, 2, 3, 4, 4, 3, 2, 1];
const uniqueNumbers = numbers.reduce((acc, num) => {
if (!acc.includes(num)) {
acc.push(num);
}
return acc;
}, []);
console.log(uniqueNumbers); // 输出 [1, 2, 3, 4]