每个JavaScript开发人员都必须知道的8个重要的数组函数

Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. Neither the length of a JavaScript array nor the types of its elements are fixed. Since an array’s length can change at any time, and data can be stored at non-contiguous locations in the array, JavaScript arrays are not guaranteed to be dense; this depends on how the programmer chooses to use them.

数组是类列表对象,其原型具有执行遍历和变异操作的方法。 JavaScript数组的长度及其元素的类型均未固定。 由于数组的长度可以随时更改,并且数据可以存储在数组中的非连续位置,因此不能保证JavaScript数组密集。 这取决于程序员如何选择使用它们。

Following are the important JavaScript Array Functions

以下是重要JavaScript数组函数

1. Array.prototype.map() (1. Array.prototype.map())

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

map()方法创建一个新数组,其中填充了在调用数组中每个元素上调用提供的函数的结果。

const array1 = [1, 4, 9, 16];// pass a function to map
const map1 = array1.map(x => x * 2);console.log(map1);
// expected output: Array [2, 8, 18, 32]

2. Array.prototype.find() (2. Array.prototype.find())

The find() method returns the value of the first element in the provided array that satisfies the provided testing function.

find()方法返回提供的数组中满足提供的测试功能的第一个元素

const array1 = [5, 12, 8, 130, 44];const found = array1.find(element => element > 10);console.log(found);
// expected output: 12

3. Array.prototype.findIndex() (3. Array.prototype.findIndex())

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test.

findIndex()方法返回满足提供的测试功能的数组第一个元素的索引 。 否则,它返回-1 ,表示没有元素通过测试。

const array1 = [5, 12, 8, 130, 44];const isLargeNumber = (element) => element > 13;console.log(array1.findIndex(isLargeNumber));
// expected output: 3

4. Array.prototype.filter() (4. Array.prototype.filter())

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

filter()方法创建一个新数组,其中所有元素都通过了由提供的函数实现的测试。

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];const result = words.filter(word => word.length > 6);console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

5. Array.prototype.reduce() (5. Array.prototype.reduce())

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.

reduce()方法在数组的每个元素上执行reducer函数(由您提供),从而产生单个输出值。

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

The reducer function takes four arguments:

reducer函数采用四个参数:

  1. Accumulator (acc)

    累加器( acc )

  2. Current Value (cur)

    现值( cur )

  3. Current Index (idx)

    当前索引( idx )

  4. Source Array (src)

    源数组( src )

Your reducer function’s returned value is assigned to the accumulator, whose value is remembered across each iteration throughout the array, and ultimately becomes the final, single resulting value.

reducer函数的返回值分配给累加器,累加器的值在整个数组的每次迭代中都会被记住,并最终成为最终的单个结果值。

6. Array.prototype.concat() (6. Array.prototype.concat())

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

concat()方法用于合并两个或多个数组。 此方法不更改现有数组,而是返回一个新数组。

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);console.log(array3);
// expected output: Array ["a", "b", "c", "d", "e", "f"]

7. Array.prototype.slice() (7. Array.prototype.slice())

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.

所述slice()方法返回一个阵列的一部分的一个浅拷贝到选自新的数组对象startend ( end不包括在内),其中startend代表数组中的项的索引。 原始数组将不会被修改。

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

8. Array.prototype.splice() (8. Array.prototype.splice())

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

splice()方法通过删除或替换现有元素和/或在适当位置添加新元素更改数组的内容。

const months = ['Jan', 'March', 'April', 'June'];months.splice(1, 0, 'Feb');
// inserts at index 1console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]months.splice(4, 1, 'May');
// replaces 1 element at index 4console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]

句法 (Syntax)

let arrDeletedItems = array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

参量 (Parameters)

startThe index at which to start changing the array.

start开始更改数组的索引。

deleteCount | Optional — An integer indicating the number of elements in the array to remove from start. If deleteCount is 0 or negative, no elements are removed. In this case, you should specify at least one new element

deleteCount | 可选—一个整数,指示要从start删除的数组中的元素数。 如果deleteCount0或负数,则不会删除任何元素。 在这种情况下,您应该至少指定一个新元素

item1, item2, ...| Optional — The elements to add to the array, beginning from start. If you do not specify any elements, splice() will only remove elements from the array.

item1, item2, ...| 可选-从start添加到数组的元素。 如果未指定任何元素,则splice()只会从数组中删除元素。

返回值 (Return value)

An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

包含已删除元素的数组。 如果仅删除一个元素,则返回一个元素的数组。 如果没有删除任何元素,则返回一个空数组。

Note — If the specified number of elements to insert differs from the number of elements being removed, the array’s length will be changed.

注—如果要插入的指定元素数与要删除的元素数不同,则数组的length将更改。

Let’s deep dive to understand splice() method better —

让我们深入研究以 更好地 了解 splice() 方法-

1.删​​除索引2之前的0(零)个元素,然后插入“ drum” (1. Remove 0 (zero) elements before index 2, and insert “drum”)

let myFish = ['angel', 'clown', 'mandarin', 'sturgeon']
let removed = myFish.splice(2, 0, 'drum')// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]
// removed is [], no elements removed

2.删除索引2之前的0(零)个元素,并插入“ drum”和“ guitar” (2. Remove 0 (zero) elements before index 2, and insert “drum” and “guitar”)

let myFish = ['angel', 'clown', 'mandarin', 'sturgeon']
let removed = myFish.splice(2, 0, 'drum', 'guitar')// myFish is ["angel", "clown", "drum", "guitar", "mandarin", "sturgeon"]
// removed is [], no elements removed

3.删除索引3处的1个元素 (3. Remove 1 element at index 3)

let myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon']
let removed = myFish.splice(3, 1)// myFish is ["angel", "clown", "drum", "sturgeon"]
// removed is ["mandarin"]

4.删除索引2的1个元素,然后插入“小号” (4. Remove 1 element at index 2, and insert “trumpet”)

let myFish = ['angel', 'clown', 'drum', 'sturgeon']
let removed = myFish.splice(2, 1, 'trumpet')// myFish is ["angel", "clown", "trumpet", "sturgeon"]
// removed is ["drum"]

5.从索引0中删除2个元素,然后插入“鹦鹉”,“ ANEMONE”和“蓝色” (5. Remove 2 elements from index 0, and insert “parrot”, “anemone” and “blue”)

let myFish = ['angel', 'clown', 'trumpet', 'sturgeon']
let removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue')// myFish is ["parrot", "anemone", "blue", "trumpet", "sturgeon"]
// removed is ["angel", "clown"]

6.从索引2中删除2个元素 (6. Remove 2 elements from index 2)

let myFish = ['parrot', 'anemone', 'blue', 'trumpet', 'sturgeon']
let removed = myFish.splice(2, 2)// myFish is ["parrot", "anemone", "sturgeon"]
// removed is ["blue", "trumpet"]

7.从索引-2删除1个元素 (7. Remove 1 element from index -2)

let myFish = ['angel', 'clown', 'mandarin', 'sturgeon']
let removed = myFish.splice(-2, 1)
// -ve index means start indexing from end of the array// myFish is ["angel", "clown", "sturgeon"]
// removed is ["mandarin"]

8.从索引2删除所有元素 (8. Remove all elements from index 2)

let myFish = ['angel', 'clown', 'mandarin', 'sturgeon']
let removed = myFish.splice(2)// myFish is ["angel", "clown"]
// removed is ["mandarin", "sturgeon"]

Hope these methods will be helpful for you to improve your code.

希望这些方法对您改进代码有帮助。

翻译自: https://medium.com/swlh/8-important-array-functions-every-javascript-developer-must-know-a0858f2c4b14

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值