JavaScript中的数组提供了丰富的方法,可以用于对数组进行各种操作。比如迭代方法、查找方法、添加、删除和替换元素、数组合并和拆分、排序和反转等方法。

js的数组方法详解

数组查找方法

1、filter(callback)

创建一个新数组,包含所有使回调函数返回 true 的元素。

1
2
3
4
5
6
7
const numbers = [1, 2, 3, 4, 5, 6];

const evenNumbers = numbers.filter(function (num) {
return num % 2 === 0;
});

console.log(evenNumbers); // 输出: [2, 4, 6]

2、find(callback)

返回数组中第一个满足条件的元素。

1
2
3
4
5
6
7
const numbers = [1, 2, 3, 4, 5, 6];

const firstEven = numbers.find(function (num) {
return num % 2 === 0;
});

console.log(firstEven); // 输出: 2

3、findIndex(callback)

返回数组中第一个满足条件的元素的索引。

1
2
3
4
5
6
7
const numbers = [1, 2, 3, 4, 5, 6];

const firstEvenIndex = numbers.findIndex(function (num) {
return num % 2 === 0;
});

console.log(firstEvenIndex); // 输出: 1

4、every(callback)

检查数组中的所有元素是否满足指定的条件,如果是则返回 true,否则返回 false。

1
2
3
4
5
6
7
const numbers = [2, 4, 6, 8, 10];

const allEven = numbers.every(function (num) {
return num % 2 === 0;
});

console.log(allEven); // 输出: true

5、some(callback)

检查数组中是否至少有一个元素满足指定的条件,如果是则返回 true,否则返回 false。

1
2
3
4
5
6
7
const numbers = [1, 3, 5, 7, 8];

const hasEven = numbers.some(function (num) {
return num % 2 === 0;
});

console.log(hasEven); // 输出: true

其他方法

1、splice()方法

用法:对数组进行插入、删除和替换等操作。它的语法如下:

1
array.splice(start, deleteCount, item1, item2, ...)
  • start: 指定开始修改的位置,是一个索引值。
  • deleteCount: 可选参数,指定要删除的元素个数,如果为 0 则不删除元素。
  • item1, item2, ...: 可选参数,指定要插入到数组中的元素。

splice 方法的主要作用是在指定的位置对数组进行修改。下面是一些具体的用法示例:

1、删除元素

1
2
3
4
5
6
7
let myArray = [1, 2, 3, 4, 5];

// 从索引为 2 的位置开始删除 2 个元素
let removedElements = myArray.splice(2, 2);
// 返回被删除的元素
console.log(myArray); // 输出: [1, 2,5]
console.log(removedElements); // 输出: [3, 4]

2、插入元素

1
2
3
4
5
6
let myArray = [1, 2, 3, 4, 5];

// 从索引为 2 的位置开始删除 0 个元素,并插入元素 6 和 7
myArray.splice(2, 0, 6, 7);

console.log(myArray); // 输出: [1, 2, 6, 7, 3, 4, 5]

3、替换元素

1
2
3
4
5
6
let myArray = [1, 2, 3, 4, 5];

// 从索引为 2 的位置开始删除 2 个元素,并插入元素 6 和 7
myArray.splice(2, 2, 6, 7);

console.log(myArray); // 输出: [1, 2, 6, 7, 5]

2、sort()方法

sort 方法是 JavaScript 数组对象的一个排序方法,用于对数组元素进行排序。默认情况下,sort 方法将元素转换为字符串,然后按照字符串的 Unicode 代码单元排序。这可能不符合预期,因此通常需要传递一个比较函数来指定排序规则。下面是 sort 方法的详细解释:

使用比较函数:

1
2
3
4
5
6
7
8
9
let myArray = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];

// 使用比较函数进行数值排序(升序)
myArray.sort(function(a, b) {
return a - b;
});

console.log(myArray);
// 输出: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

比较函数接受两个参数 ab,如果 a 应该排在 b 之前,返回负值;如果 ab 相等,返回 0;如果 a 应该排在 b 之后,返回正值。上述示例中,使用比较函数实现了升序排序。

降序排序:

1
2
3
4
5
6
7
8
9
let myArray = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];

// 使用比较函数进行数值排序(降序)
myArray.sort(function(a, b) {
return b - a;
});

console.log(myArray);
// 输出: [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]