Home>Article>Web Front-end> 15 common array operations in JavaScript development

15 common array operations in JavaScript development

hzc
hzc forward
2020-06-23 09:52:29 1554browse
Author: Dmitri Pavlutin
Translator: Front-end Xiaozhi
Source: dmitripavlutin.com
Like and read again, develop a habit

This articleGitHubhttps://github.com/qq44924588... has been included. More past high praise articles have been classified, and many of my documents and tutorial materials have also been compiled. Welcome to Star and Perfect. You can refer to the test points for review during the interview. I hope we can learn something together.

Array is a widely used data structure in JS. Array objects provide a large number of useful methods, such asarray. forEach(),array.map(), etc. to operate arrays.

In actual combat, I am often at a loss about the possible operations on arrays and which is the better method to use accordingly, so this article lists15common data methods for us to review Strengthen your memory.

1. Array traversal

1.1for..ofLoop

for(const item of items)Loop traversal Array items, traverse thecolorslist as follows:

const colors = ['blue', 'green', 'white']; for (const color of colors) { console.log(color); } // 'blue' // 'green' // 'white'

Tip:

We can stop at any time using thebreakstatement Traverse.

1.2forLoop

for(let i; i < array.length; i)Loop through the array items using an incrementing index variable .

forUsually you need to increment theindexvariable in each loop

const colors = ['blue', 'green', 'white']; for (let index = 0; index < colors.length; index++) { const color = colors[index]; console.log(color); } // 'blue' // 'green' // 'white'

indexThe variable starts from0Increments tocolors.length-1. This variable is used to access items by the following index:colors [index].

Tips

We can use thebreakstatement to stop traversal at any time.

1.3array.forEach()Method

array.forEach(callback)Method by callingcallback on each array itemFunction to iterate over array items.

On each traversal, callcallback(item [, index [, array]])with the following parameters: the current traversal item, the current traversal index, and the array itself.

const colors = ['blue', 'green', 'white']; colors.forEach(function callback(value, index) { console.log(value, index); }); // 'blue', 0 // 'green', 1 // 'white', 2

Tip:

We cannot interrupt thearray.forEach()iteration.

2. Array mapping

2.1Array.map()method

array.map(callback)method passes Create a new array using thecallbackcall result on each array item.

callback(item[, index[, array]])in each traversal is called with arguments: the current item, index, and the array itself, and should return the new item.

As shown below we increment each array element1:

const numbers = [0, 2, 4]; const newNumbers = numbers.map(function increment(number) { return number + 1; }); newNumbers; // => [1, 3, 5]

Tip:

##array .map()Creates a new mapped array without changing the original array.

2.2

Array.from()Method

Array.from(arrayLike[, callback])Method by using on each array item callback Call the result to create a new array.

In each traversal

callback(item[, index[, array]]) Called with arguments: the current item, index and the array itself and should return the new item.

As shown below we increment each array element

1:

const numbers = [0, 2, 4]; const newNumbers = Array.from(numbers, function increment(number) { return number + 1; } ); newNumbers; // => [1, 3, 5]

Tip:

  • Array.from()Creates a new mapped array without changing the original array.
  • Array.from()is more suitable for mapping from array-like objects.
3. Data simplification

3.1

Array.reduce()Method

array.reduce(callback[, initialValue ])Reducing the array to a single value by calling thecallbackfunction.

callback(accumulator, item[, index[, array]])in each traversal is used and should be called with parameters: accumulator, current item, index and array itself Return the accumulator.

The classic example is to sum an array of numbers:

const numbers = [2, 0, 4]; function summarize(accumulator, number) { return accumulator + number; } const sum = numbers.reduce(summarize, 0); sum; // => 6
The first step is to initialize the

accumulatorto0. Then, thesummaryfunction is called on each array item that accumulates the sum of numbers.

Tip:

If initialValue is not used to set the initial value, the first element of the array will be used as the initial value by default.

4. Data connection

4.1

array.concat()Method

array.concat(array1[, array2, .. .])Concatenate one or more arrays to the original array. Concatenate two arrays as shown below:

const heroes = ['小智', '前端小智']; const villains = ['老王', '小三']; const everyone = heroes.concat(villains); everyone // ["小智", "前端小智", "老王", "小三"]

Tip:

    ##concat()
  • Creates a new array without Change the original array
  • array.concat(array1 [,array2,...])
  • Accepts multiple arrays to be concatenated.
  • 4.2 Expansion operator symbol

We use the expansion operator together with array literals to connect arrays:

[...array1, ...array2]

.

const heroes = ['小智', '前端小智']; const villains = ['老王', '小三']; const names = [...heroes, ...villains]; names; // ["小智", "前端小智", "老王", "小三"]

Tips:

[...arr1, ...arr2, ...arrN]

: We can use the spread operator Concatenate the required number of arrays.

获取数组的片段

5.1 array.slice()方法

array.slice([fromIndex [,toIndex]])返回数组的一个片段,该片段从fromIndex开始,以toIndex结尾(不包括toIndex本身)。fromIndex可选参数默认为0toIndex可选参数默认为array.length

const names = ["小智", "前端小智", "老王", "小三"] const heroes = names.slice(0, 2) const villains = names.splice(2) heroes // ["小智", "前端小智"] villains // ["老王", "小三"]

提示:

array.slice()创建一个新数组,而不改变原始数组。

6. 数组的拷贝

6.1 展开操作符

拷贝数组的一种简单方法是使用展开运算符:const clone = [... array],如下所示,拷贝colors数组:

const colors = ['white', 'black', 'gray']; const clone = [...colors]; clone; // => ['white', 'black', 'gray'] colors === clone; // => false

提示:

[...array]创建一个浅拷贝。

6.2array.concat()方法

[].concat(array)是另一种拷贝数组的方法。

const colors = ['white', 'black', 'gray']; const clone = [].concat(colors); clone; // => ['white', 'black', 'gray'] colors === clone; // => false

提示:

[].concat(array)创建一个浅拷贝。

6.3array.slice()方法

array.slice())是另一种拷贝数组的方法。

const colors = ['white', 'black', 'gray']; const clone = colors.slice(); clone; // => ['white', 'black', 'gray'] colors === clone; // => false

提示:

colors.slice()创建一个浅拷贝。

7. 查找数组

7.1array.includes()方法

array.includes(itemToSearch [,fromIndex])返回一个布尔值,array是否包含itemToSearch。 可选参数fromIndex,默认为0,表示开始搜索的索引。如下所示:判断299是否存在于一组数字中:

const numbers = [1, 2, 3, 4, 5]; numbers.includes(2); // => true numbers.includes(99); // => false

7.2array.find()方法

array.find(predicate)方法返回数组中满足提供的测试函数的第一个元素的值。否则返回undefined

如下所示,找到数组中的第一个偶数:

const numbers = [1, 2, 3, 4, 5]; function isEven(number) { return number % 2 === 0; } const evenNumber = numbers.find(isEven); evenNumber; // => 2

7.3array.indexOf()方法

array.indexOf(itemToSearch[, fromIndex])返回array中第一个出现的itemToSearch的索引。默认为0的可选参数fromIndex表示开始搜索的索引。

如下所示,找到前端小智的索引:

const names = ["小智", "前端小智", "老王", "小三"] const index = names.indexOf('前端小智') index // 1

提示:

  • 如果找不到该项,则array.indexOf(itemToSearch)返回-1
  • array.findIndex(predicate)是使用predicate函数查找索引的替代方法。

8. 查询数组

8.1array.every()方法

如果每个项都通过predicate检查,则array.every(predicate)返回true

在每个遍历predicate(item[, index[, array]])上,用参数调用predicate函数:当前遍历项、索引和数组本身。

如下所示,确定数组是否只包含偶数:

const evens = [0, 2, 4, 6]; const numbers = [0, 1, 4, 6]; function isEven(number) { return number % 2 === 0; } evens.every(isEven); // => true numbers.every(isEven); // => false

8.2array.some()方法

如果每个项只要一下通过predicate检查,则array.every(predicate)返回true

在每个遍历predicate(item[, index[, array]])上,用参数调用predicate函数:当前遍历项、索引和数组本身。

如下所示:确定数组是否至少包含一个偶数:

const numbers = [1, 5, 7, 10]; const odds = [1, 3, 3, 3]; function isEven(number) { return number % 2 === 0; } numbers.some(isEven); // => true odds.some(isEven); // => false

9. 数组的过滤

9.1array.filter()方法

array.filter(predicate)方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。

在每个遍历predicate(item[, index[, array]])上,用参数调用predicate函数:当前遍历项、索引和数组本身。

如下所示:将一个数组过滤为仅包含偶数:

const numbers = [1, 5, 7, 10]; function isEven(number) { return number % 2 === 0; } const evens = numbers.filter(isEven); evens; // => [10]

提示:

array.filter()创建一个新数组,而不改变原始数组。

10. 数组的插入

10.1array.push()方法

array.push(item1 [...,itemN])方法将一个或多个项追加到数组的末尾,并返回新的长度。

如下所示,在names数组的末尾添加'小智'

const names = ['小智'] names.push('前端小智') names // ["小智", "前端小智"]

提示:

  • array.push()会改变原数组
  • array.push(item1, item2, ..., itemN)可以添加多个元素。

10.2array.unshift()方法

array.unshift(item1[..., itemN])方法将一个或多个项追加到数组的开头,返回数组的新长度

const names = ['小智'] names.unshift('前端小智') names // ["前端小智", "小智"]

提示:

  • array.unshift()会改变原数组
  • array.unshift(item1, item2, ..., itemN)可以添加多个元素。

10.3 展开操作符

可以通过组合展开操作符和数组字面量以不可变的方式在数组中插入项。

在数组末尾追加一个项:

const names = ['小智', '大治'] const names2 = [...names, '王大冶'] names2 // ["小智", "大治", "王大冶"]

在数组的开头追加一个项:

const names = ['小智', '大治'] const names2 = [ '王大冶', ...names ] names2 // ["王大冶", "小智", "大治"]

在任何索引处插入元素:

const names = ['小智', '大治'] const indexToInsert = 1 const names2 = [ ...names.slice(0, indexToInsert), '前端小智', ...names.slice(indexToInsert) ] names2 // ["小智", "前端小智", "大治"]

11. 删除数组元素

11.1array.pop()方法

array.pop()方法从数组中删除最后一个元素,然后返回该元素。如下所示,删除colors数组的最后一个元素:

const colors = ['blue', 'green', 'black']; const lastColor = colors.pop(); lastColor; // => 'black' colors; // => ['blue', 'green']

提示:

array.pop()会改变原数组。

11.2array.shift()方法

array.shift()方法从数组中删除第一个元素,然后返回该元素。

const colors = ['blue', 'green', 'black']; const firstColor = colors.shift(); firstColor; // => 'blue' colors; // => ['green', 'black']

提示:

  • array.shift()会改变原数组。
  • array.shift()有O(n)复杂度。

11.3array.splice()方法

array.splice(fromIndex[, removeCount[, item1[, item2[, ...]]]])从数组中删除元素,并插入新的元素。

例如,咱们从索引1处删除2个元素:

const names = ['张三', '李四', '王五', '赵六'] names.splice(1, 2) names // => ["张三", "赵六"]

names.splice(1,2)删除元素'张三''赵六'

names.splice()可以插入新元素,而不是插入已删除的元素。 咱们可以替换索引1处开始的的2个元素,然后插入一个新的元素'小智'

const names = ['张三', '李四', '王五', '赵六'] names.splice(1, 2, '小智') names // ["张三", "小智", "赵六"]

提示:

  • array.splice()会改变原数组。

11.4 展开操作符号

可以通过组合展开操作符和数据字面量以不可变的方式从数组中删除项。

const names = ['张三', '李四', '王五', '赵六'] const fromIndex = 1 const removeCount = 2 const newNames = [ ...names.slice(0, fromIndex), ...names.slice(fromIndex + removeCount) ] newNames // ["张三", "赵六"]

12. 清空数组

12.1array.length属性

array.length是保存数组长度的属性。 除此之外,array.length是可写的。

如果咱们写一个小于当前长度的array.length = newLength,多余的元素从数组中移除。

如下所示:使用array.length = 0删除数组中的所有项目:

const colors = ['blue', 'green', 'black']; colors.length = 0; colors; // []

12.2array.splice()方法

array.splice(fromIndex[, removeCount[, item1[, item2[, ...]]]])从数组中删除元素,并插入新的元素。

如果removeCount参数被省略,那么array.splice()将删除从fromIndex开始的数组的所有元素。咱们使用它来删除数组中的所有元素:

const colors = ['blue', 'green', 'black']; colors.splice(0); colors; // []

13. 填充数组

13.1array.fill()方法

array.fill(value[, fromIndex[, toIndex]])用从fromIndextoIndex的值填充数组(不包括toIndex本身)。fromIndex可选参数默认为0,toIndex可选参数默认为array.length

例如,使用用零值填充数组:

const numbers = [1, 2, 3, 4]; numbers.fill(0); numbers; // => [0, 0, 0, 0]

不仅如此,还可以使用Array(length).fill(initial)来初始化特定长度和初始值的数组。

const length = 3; const zeros = Array(length).fill(0); zeros; // [0, 0, 0]

提示:

  • array.splice()会改变原数组。

13.2Array.from()函数

Array.from()有助于初始化带有对象的特定长度的数组:

const length = 4; const emptyObjects = Array.from(Array(length), function() { return {}; }); emptyObjects; // [{}, {}, {}, {}]

14. 数组的扁平化

14.1array.flat()方法

array.flat([depth])方法通过递归扁平属于数组的项直到一定深度来创建新数组。depth可选参数默认为1

const arrays = [0, [1, 3, 5], [2, 4, 6]]; const flatArray = arrays.flat(); flatArray; // [0, 1, 3, 5, 2, 4, 6]

arrays包含数字和数字数组的混合。arrays.flat()对数组进行扁平,使其仅包含数字。

提示:

array.flat()创建一个新数组,而不会改变原始数组。

15. 数组的排序

15.1array.sort()方法

array.sort([compare])方法对数组的元素进行排序。

可选参数compare(a, b)是一个自定义排序顺的回调函数。如果比较compare(a, b)返回的结果:

  • 如果a小于b,在排序后的数组中a应该出现在b之前,就返回一个小于0的值。
  • 如果a等于b,就返回0
  • 如果a大于b,就返回一个大于0的值。

如下所示,对数组numbers时行排序

const numbers = [4, 3, 1, 2]; numbers.sort(); numbers; // => [1, 2, 3, 4]

numbers.sort()以升序对数字进行排序。

使用比较函数,让偶数排在奇数前面:

const numbers = [4, 3, 1, 2]; function compare(n1, n2) { if (n1 % 2 === 0 && n2 % 2 !== 0) { return -1; } if (n1 % 2 !== 0 && n2 % 2 === 0) { return 1; } return 0; } numbers.sort(compare); numbers; // => [4, 2, 3, 1]

提示:

  • array.sort()会改变原数组。

推荐教程:《JS教程

The above is the detailed content of 15 common array operations in JavaScript development. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete