WEB程序员笔记

一个前端开发工程师的个人博客

作为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,
//   }]

2. Push()

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

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

fruits.push('orange');

console.log(fruits);

// [ "bananan", "mango", "apple", "kiwi", "orange"]

3. Join()

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

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

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"]

];

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"]

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"]

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

这里发生了什么?假设我们正在构建订单。我们有一些邮递区号,我们希望将这些邮递区号交付给我们,而我们不希望客户将订单下达到我们未交付的地点。因此,我们提取了他们在订单表格(第2行)中输入的邮政编码,并使用some方法对其进行了验证。在上面的代码块中,isValidPostCode将为true,因为邮政编码与我们的邮政编码数组中的内容匹配。

8. Sort()

如果我们不能对数组中的元素进行排序,那将不会很有趣。幸运的是,有一种方法可以让我们做到这一点。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]

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

10. Slice()

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

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

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

console.log(sliced)
// ['japan', 'vietnam']

您可以在此处查看github仓库。别忘了留下星星。

感谢您的阅读,希望您能从本文中学到一些东西。

点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注