【个人记录】JS中一些不熟悉的数组方法

57 阅读1分钟

array.findIndex

array.findIndex(callback(element, index, array), thisArg);

array.findIndex 方法返回数组中第一个满足提供的测试函数的元素的索引。如果没有找到符合条件的元素,则返回 -1

const numbers = [5, 12, 8, 130, 44];

const index = numbers.findIndex(element => element > 10);
console.log(index); // 1,找到第一个大于 10 的元素,索引为 1

array.find

array.find(callback(element, index, array), thisArg);

find() 方法用于查找数组中满足条件的第一个元素,并返回该元素。如果没有满足条件的元素,则返回 undefined

const numbers = [1, 2, 3, 4, 5];
const result = numbers.find(num => num > 3);
console.log(result);  // 4

array.splice

array.splice(start, deleteCount, item1, item2, ..., itemN);

splice() 方法用于改变数组,删除现有元素并/或添加新元素,直接修改原数组。

  • start:数组中开始操作的位置。
  • deleteCount(可选):要删除的元素个数。如果不指定此参数,则从 start 位置开始删除所有元素。
  • item1, item2, ..., itemN(可选):要添加到数组中的新元素。
const fruits = ['apple', 'banana', 'cherry', 'date'];

// 删除 1 个元素,从索引 1 开始
const removed = fruits.splice(1, 1);
console.log(fruits);  // ['apple', 'cherry', 'date']
console.log(removed); // ['banana']

// 从索引 2 开始,删除 1 个元素,并添加新元素
fruits.splice(2, 1, 'grape');
console.log(fruits); // ['apple', 'cherry', 'grape']