📜  过滤 mutate 数组 - Javascript (1)

📅  最后修改于: 2023-12-03 14:57:54.453000             🧑  作者: Mango

过滤、改变和创建新数组 - Javascript

在Javascript中,我们经常会需要对数组进行过滤、改变、或者创建新的数组。这时候,会用到JavaScript中的很多数组API,如filtermap、和reduce等。本文将会介绍如何运用filtermap方法来过滤和改变数组。另外,我们还会介绍如何使用concatslice方法创建新的数组。

过滤数组 - filter方法

filter方法可以过滤数组中不符合要求的元素,同时返回符合要求的元素组成的新数组。

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

const smallerNumbers = numbers.filter(number => number < 4);

console.log(smallerNumbers); // [1, 2, 3]

上述代码中,我们定义了一个常量numbers,它包含一些数字。接着,我们调用filter方法来过滤出所有小于4的数字,这样得到了一个新的数组smallerNumbers

当回调函数返回值为真(true),filter方法将保留元素。否则,该元素将从新数组中删除。

改变数组 - map方法

map方法可以基于数组中的元素,产生一个新的数组。

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

const biggerNumbers = numbers.map(number => number * 2);

console.log(biggerNumbers); // [2, 4, 6, 8, 10]

上面的代码中,我们使用map方法来将所有数字乘以2,从而得到一个新数组biggerNumbers

创建新数组

使用concatslice方法可以从原有数组中创建新数组。

使用concat方法

concat方法可以将多个数组合并至一个新数组中:

const numbers = [1, 2, 3];
const animals = ["cat", "dog", "bird"];

const newArray = numbers.concat(animals);

console.log(newArray); // [1, 2, 3, "cat", "dog", "bird"]

在上面的代码中,我们定义了两个数组:numbersanimals。接着,我们使用concat方法将这两个数组组合成一个新数组。

使用slice方法

slice方法可以从原有数组中提取出指定部分,并返回一个新的数组。它接受两个参数,startendstart表示开始位置(包含当前位置),end表示结束位置(不包含当前位置)。

const fruits = ["apple", "banana", "orange", "grape", "plum"];

const citrusFruits = fruits.slice(2, 4);

console.log(citrusFruits); // ["orange", "grape"]

在上面的代码中,我们定义了一个数组fruits,包含了若干水果。接着,我们使用slice方法提取出介于第二个和第四个元素之间的所有水果,得到一个新数组citrusFruits

总结

在Javascript中,我们可以使用filtermap方法来过滤、改变数组中的元素,使用concatslice方法来创建新的数组。这些方法是非常有用和强大的,它们能够让我们更加高效的处理数组数据,从而提高我们的工作效率。