JavaScript基础,数组的常用方法有那些,如何简单使用?

5.1k 词

数组是 JavaScript 中用于存储有序集合的特殊对象 。它能够包含不同数据类型的值,并且是可调整大小的 。

  • 末尾增增加删除操作

**push()**在数组末尾添加一个或多个元素,并返回新数组的长度 。

<strong>pop()</strong>在数组末尾删除 并返回数组的最后一个元素 。

这两个方法都会修改原素组。

1
2
3
4
5
const fruits = ["apple", "banana"];
fruits.push("orange"); // 返回 3
console.log(fruits); // ["apple", "banana", "orange"]
const lastFruit = fruits.pop(); // 返回 "orange"
console.log(fruits); // ["apple", "banana"]

  • 数组开头的增加删除操作

**unshift()**在数组开头添加一个或多个元素,并返回新数组的长度 。

**shift()**在数组开头删除并返回数组的第一个元素 。

这两个方法都会修改原数组 。

1
2
3
4
5
const colors = ["blue", "green"];
colors.unshift("red"); // 返回 3
console.log(colors); // ["red", "blue", "green"]
const firstColor = colors.shift(); // 返回 "red"
console.log(colors); // ["blue", "green"]

  • 在任意位置删除、插入数组操作

**splice()**方法通过删除、替换或添加元素来修改原始数组 。它返回一个包含被删除元素的新数组 。它常用于在任意位置插入、删除或替换元素。

1
2
3
4
5
6
const months = ["Jan", "Feb", "Mar", "Apr"];
months.splice(1, 0, "Feb-new"); // 在索引1处插入"Feb-new",不删除
console.log(months); // ["Jan", "Feb-new", "Feb", "Mar", "Apr"]

months.splice(2, 1); // 从索引2开始删除1个元素 ("Feb")
console.log(months); // ["Jan", "Feb-new", "Mar", "Apr"]

  • 生成新数组的删除

**slice()**方法从现有数组中复制指定部分元素,创建一个新的数组对象,而不修改原始数组 。它返回一个包含提取元素的新数组 。

1
2
3
4
const originalArray = [1, 2, 3, 4, 5];
const newArray = originalArray.slice(1, 4); // 从索引1到4(不含4)
console.log(newArray); // [2, 3, 4]
console.log(originalArray); // [1, 2, 3, 4, 5] (原数组未变)

  • 数组的合并操作

**concat()**方法用于合并两个或多个数组,并返回一个新数组 。它不修改原始数组 。

1
2
3
4
5
const arr1 = [1, 2];
const arr2 = [3, 4];
const arr3 = arr1.concat(arr2, [5, 6]);
console.log(arr3); // [1, 2, 3, 4, 5, 6]
console.log(arr1); // [1, 2] (原数组未变)

  • 索引访问元素

**at()**方法接受一个整数值,返回该索引处的数组元素 。它支持正数和负数索引,负数索引从数组末尾开始计数 。

1
2
3
const arr = [7, 8, 9, 10, 11];
console.log(arr.at(0)); // 10 (第一个元素)
console.log(arr.at(-1)); // 50 (最后一个元素)

  • 查找元素位置

**indexOf()**返回在数组中可以找到给定元素的第一个索引 。

**lastIndexOf()**则返回最后一个索引 。如果未找到,返回 -1。

1
2
3
const numbers = [1, 2, 3, 2, 4];
console.log(numbers.indexOf(2)); // 1
console.log(numbers.lastIndexOf(2)); // 3

  • 检查元素是否存在

**includes()**方法判断数组是否包含某个值,返回 truefalse

1
2
3
const fruits = ["apple", "banana", "orange"];
console.log(fruits.includes("banana")); // true
console.log(fruits.includes("grape")); // false

  • 遍历执行

** forEach(callbackFn, thisArg)**方法对数组的每个元素执行一次提供的 callbackFn 函数 。它总是返回 undefined,且不能链式调用 。

回调会接收 elementindexarray 作为参数 。它不会为稀疏数组中的空槽调用回调函数 。

1
2
3
4
5
6
7
const numbers = [1, 2, 3];
let sum = 0;
numbers.forEach(num => {
sum += num;
console.log(num * 2); // 2, 4, 6
});
console.log(sum); // 6

  • 数组转换生成新数组

**map()**方法为数组中的每个元素调用一次提供的回调函数,并用结果构建一个新数组 。它不修改原始数组 。新数组的长度与原始数组相同 。

1
2
3
4
5
6
7
const officers = [{ id: 20, name: 'Captain Piett' }, { id: 24, name: 'General Veers' }];
const officerIds = officers.map(officer => officer.id);
console.log(officerIds); // [8, 12]

const prices = ;
const discountedPrices = prices.map(price => price * 0.9);
console.log(discountedPrices); // [26]

  • 条件筛选生成新数组

**filter()**方法创建一个给定数组一部分的浅拷贝,其中包含通过所提供函数测试的所有元素 。它返回一个新数组。

1
2
3
4
5
6
7
8
9
10
11
12
const numbers = [5, 12, 8, 130, 44];
const bigEnough = numbers.filter(value => value >= 10);
console.log(bigEnough); // [12, 130, 44]

const pilots = [
{ id: 2, name: "Wedge Antilles", faction: "Rebels" },
{ id: 8, name: "Ciena Ree", faction: "Empire" },
{ id: 40, name: "Iden Versio", faction: "Empire" },
{ id: 66, name: "Thane Kyrell", faction: "Rebels" }
];
const rebels = pilots.filter(pilot => pilot.faction === "Rebels");
console.log(rebels); // [{ id: 2, name: "Wedge Antilles", faction: "Rebels" }, { id: 66, name: "Thane Kyrell", faction: "Rebels" }]

  • 用于计算操作

reduce(callback, currentValue**)**方法将数组中的所有元素缩减为单个值,返回的这个值可以是任何类型 。它对数组的每个元素执行一次

callback,并将回调结果(累加器)从一个元素传递到下一个元素 。

currentValue 是可选的,如果提供,它将作为 accumulator 的初始值 。

1
2
3
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // 15

  • 查找第一个/最后一个匹配元素

**find()**方法返回数组中满足提供的测试函数的第一个元素的值 。如果未找到,则返回 undefined

**findLast()**则反向迭代数组,返回满足测试函数的最后一个元素的值 。

1
2
3
4
5
6
7
8
9
10
const inventory = [
{ name: "apples", quantity: 2 },
{ name: "bananas", quantity: 0 },
{ name: "cherries", quantity: 5 },
];
const cherries = inventory.find(fruit => fruit.name === "cherries");
console.log(cherries); // { name: 'cherries', quantity: 5 }
const numbers = [1, 2, 3, 4, 5, 6];
const lastEven = numbers.findLast(num => num % 2 === 0);
console.log(lastEven); // 6

  • 查找匹配元素的索引

** findIndex()**方法返回数组中满足提供的测试函数的第一个元素的索引 。如果未找到,则返回 -1

**findLastIndex()**则返回最后一个匹配元素的索引 。

1
2
3
4
5
6
const numbers = [10, 20, 30, 20, 40];
const firstIndex = numbers.findIndex(num => num === 20);
console.log(firstIndex); // 1

const lastIndex = numbers.findLastIndex(num => num === 20);
console.log(lastIndex); // 3

  • 将数组元素连接成字符串

**join(separator)**方法将数组中的所有元素连接成一个字符串并返回 。

separator 是可选的,用于指定分隔符,默认是逗号 (,) 。如果数组为空,则返回空字符串 。

1
2
3
4
const fruits =;
console.log(fruits.join()); // "Apple,Banana,Orange" [36]
console.log(fruits.join(" | ")); // "Apple | Banana | Orange" [34]
console.log(fruits.join("")); // "AppleBananaOrange" [36]