JavaScript 开发者必须了解的数组方法

2025-06-10

JavaScript 开发者必须了解的数组方法

这篇文章是我的对象方法文章的后续

数组是 JavaScript 的重要组成部分。它允许我们将多个元素存储在一个变量中。假设你有 100 个联系人,为每个联系人创建一个变量会非常困难。使用数组,你可以将联系人存储在一个变量中。

数组带有内置方法,使我们能够根据需要改变和转换数据。

在本文中,我们将了解 10 种数组方法及其用例。

1. Filter()

你听说过高阶函数吗?简单来说,高阶函数是一种像 filter 方法一样,接受一个函数作为参数或返回一个函数作为输出的方法。filter 方法实际上是对一个数组进行过滤,并根据其作为参数的条件(函数)返回一个输出。

const employees = [
  {
    id: '001',
    name: 'Siradji',
    isPermanent: true,
  },
  {
    id: '002',
    name: 'Lydia',
    isPermanent: false,
  },
];

// Filters through employees array and return permanent employees.

const permEmployees = employees.filter(
  (employee) => employee.isPermanent === true
);
console.log(permEmployees);
//  [{
//     id: '001',
//     name: 'Siradji',
//     isPermanent: true,
//   }]
Enter fullscreen mode Exit fullscreen mode

2. Push()

这也许是最常用的数组方法之一。push 方法将其作为参数的元素插入到现有数组的末尾。

const fruits = ['banana', 'mango', 'apple', 'kiwi'];

fruits.push('orange');

console.log(fruits);

// [ "bananan", "mango", "apple", "kiwi", "orange"]
Enter fullscreen mode Exit fullscreen mode

3. 加入()

此方法通过连接数组内以逗号或字符串分隔的所有元素来创建并返回一个字符串。

const names = ['Ola', 'james', 'jackie', 'nina'];
const joinAll = names.join('');

console.log(joinAll);
// Olajamesjackienina

const dashSeperator = names.join('-');

console.log(dashSeperator);
// Ola-james-jackie-nina
Enter fullscreen mode Exit fullscreen mode

4. Map()

还记得高阶函数吗?它也接收一个函数作为参数。它根据参数的结果创建一个新数组。

const news = [
  {
    title: 'finally, tom has managed to eat jerry mouse',
    publishedAt: 10,
    isAHit: true,
  },
  {
    title: 'UFO spotted in califionia',
    publishedAt: 11,
    isAHit: true,
  },
]
const newsTitle = news.map( news => news.title)

console.log(newsTitle)
// ["finally, tom has managed to eat jerry mouse",
// "UFO spotted in califionia"]

];
Enter fullscreen mode Exit fullscreen mode

5. Splice()

此方法删除或替换现有数组的元素。请注意,此方法会改变原始数组。

//  replace an element
const cars = ['audi', 'volvo', 'benz', 'honda'];

//  @params start index, delete count, new dara
cars.splice(1, 0, 'BMW');

console.log(cars);
// ["audi", "volvo", "BMW", "benze", "honda"]
Enter fullscreen mode Exit fullscreen mode

6. Concat()

我想 JavaScript 社区里的每个人都知道什么是连接。这个方法的含义不言而喻。顾名思义,它将两个数组连接成一个。该方法在第一个数组上调用,并将第二个数组作为参数。

const africa = ['nigeria', 'niger', 'ghana', 'kenya'];
const asia = ['korea', 'japan', 'vietnam', 'china'];

const countries = africa.concat(asia);

console.log(countries);

// ["nigeria", "niger", "ghana", "kenya", "korea", "japan", "vietnam", "china"]
Enter fullscreen mode Exit fullscreen mode

7. Some()

啊!我最喜欢的数组方法来了。这个方法将每个元素与其接收的函数进行匹配,并返回一个布尔值。
我已经多次使用过这个方法,下面是最近的一个用例。

const postcodes = ['45220', '46689', '56322', '44520', '23252', '6422'];

const { postcode } = { name: 'james', paid: true, postcode: 45220 };

const isValidPostCode = postcodes.some((code) => code === postcode);

console.log(isValidPostCode);

// true
Enter fullscreen mode Exit fullscreen mode

这里发生了什么?假设我们正在构建一个订单表单。我们指定了配送到特定邮编的地区,并且我们不希望客户将订单发送到我们不配送的地区。因此,我们提取客户在订单表单中输入的邮编(第 2 行),并使用 some 方法进行验证。在上面的代码块中,isValidPostCode 将为 true,因为该邮编与我们在 postcodes 数组中保存的值匹配。

8. 排序()

如果数组中的元素无法排序,那就没什么意思了。好在有个方法可以帮我们实现这一点。JavaScript 中的 sort 方法会根据传入的函数返回一个已排序的元素数组。默认情况下,它会按升序排序,但我们可以更改。

const fruits = ['banana', 'mango', 'apple', 'kiwi'];

fruit.sort();

console.log(fruits);

// ["apple", "banana", "kiwi", "mango"]

const numbers = [9, 5, 7, 3, 2];

//  descending
numbers.sort((a, b) => b - a);

console.log(numbers);
// [9, 7, 5, 3, 2]

// ascending
numbers.sort((a, b) => a - b);
console.log(numbers);
// [2, 3, 5, 7, 9]
Enter fullscreen mode Exit fullscreen mode

9. FindIndex()

在数组中查找元素的索引可能非常困难,尤其是在数组很大的情况下。幸好,有了 findIndex 方法,我们可以轻松做到这一点。findIndex 方法接受一个函数作为参数,返回第一个元素的索引;如果元素不存在,则返回 -1。

const cars = ['audi', 'volvo', 'benz', 'honda'];

//  returns true
const carIndex = cars.findIndex((car) => car === 'honda');

console.log(carIndex);
// 3

//  returns false
const carIndex = cars.findIndex((car) => car === 'toyota');
console.log(carIndex);
//  -1
Enter fullscreen mode Exit fullscreen mode

10. Slice()

此方法对数组进行切片,并根据起始索引和切片计数返回切片后的部分。它接受两个参数。第一个参数是起始索引,第二个参数是从起始索引开始的切片计数。

const asia = ['korea', 'japan', 'vietnam', 'china'];

// @params starting index, slice count
const sliced = asia.slice(1, 3)

console.log(sliced)
// ['japan', 'vietnam']
Enter fullscreen mode Exit fullscreen mode

你可以在这里查看 GitHub 仓库。别忘了点个星。

感谢您的阅读,希望您能从本文中有所收获。

鏂囩珷鏉ユ簮锛�https://dev.to/siradji/array-methods-that-you-must-know-as-a-javascript-developer-31g8
PREV
测试 SpringBoot 应用程序
NEXT
学习 NodeJS 第一部分:了解基本知识