数组Array

截取拼接

1.slice 截取数组的一部分,不修改原数组。

let myArray = [1,2,3,4,5];
// 使用 slice 创建一个新的数组,包含索引 1 到索引 3 的元素(不包括索引 3)
let newArray = myArray.slice(1, 3);
console.log(newArray); // 输出新的数组,这里是 [2,3]
console.log(myArray); // 输出原始数组,这里是 [1,2,3,4,5]

2.splice 对数组进行修改,可以删除、插入和替换元素,会直接修改原数组。

删除元素
let myArray = [1,2,3,4,5];
//删除从索引 2 开始的两个元素
let removedElements = myArray.splice(2,2);
console.log(removedElements); // 输出被删除的元素,这里是 [3,4]
console.log(myArray); // 输出原始数组,这里是 [1,2,5]

插入元素
let myArray = [1,2,3,4,5];
//在索引2的位置插入元素 10 和 11
let removedElements = myArray.splice(2,0,10,11);
console.log(removedElements); // 输出被删除的元素,这里是 []
console.log(myArray); //输出原始数组,这里是 [1,2,10,11,3,4,5]

替换元素
let myArray = [1, 2, 3, 4, 5];
//替换从索引 2 开始的两个元素为新的元素
let removedElements = myArray.splice(2, 2,'a','b');
console.log(removedElements); // 输出被删除的元素,这里是 [3,4]
console.log(myArray); //输出原始数组,这里[1,2,'a','b',5]

在上面的例子中,splice 方法的第一个参数是操作的起始索引,第二个参数是要删除的元素个数。如果第二个参数为 0,则表示插入元素而不删除。

之后的参数是要插入到数组中的元素,可以插入一个或多个元素。如果只是插入元素而不删除,第二个参数可以为 0。

遍历数组

1.forEach

会改变原始数组

let myArray = [1, 2, 3, 4, 5];
myArray.forEach((element, index, arr) => {
  arr[index] = element * 2;
});
console.log(myArray); // 输出修改后的原始数组,每个元素乘以 2

2.map

不会改变原始数组,返回一个新数组
let myArray = [1, 2, 3, 4, 5];
let newArray = myArray.map((element) => {
  return element * 2;
});
console.log(newArray); // 输出新的数组,这里是 [2, 4, 6, 8, 10]
console.log(myArray); // 输出原始数组,这里是 [1, 2, 3, 4, 5]

3.filter

用于筛选数组,不会改变原始数组,返回一个新数组
let myArray = [1, 2, 3, 4, 5];
let newArray = myArray.filter((element) => {
  return element > 2;
});
console.log(newArray); // 输出新的数组,这里是 [3, 4, 5]
console.log(myArray); // 输出原始数组,这里是 [1, 2, 3, 4, 5]

4.reduce

它用于将数组的所有元素累积到一个单一的结果中。
reduce 方法接受一个回调函数和一个可选的初始值。
这个回调函数会接受四个参数:累积器(accumulator)、当前元素(current element)、当前索引(current index)、数组本身。

求和:
let myArray = [1, 2, 3, 4, 5];
// 使用 reduce 方法计算数组元素的和
let sum = myArray.reduce((accumulator, currentElement) => {
  return accumulator + currentElement;
}, 0); // 初始值为 0
console.log(sum); // 输出数组元素的和,这里是 15

将数组转成对象:
let names = ['Alice', 'Bob', 'Charlie'];
let nameObject = names.reduce((obj, name, index) => {
  obj[index + 1] = name;
  return obj;
}, {});
console.log(nameObject);
// 输出对象,这里是 {1: 'Alice', 2: 'Bob', 3: 'Charlie'}

posted @ 2024-01-16 16:31  Hishine  阅读(50)  评论(0)    收藏  举报