13 JS array of techniques to streamline

Invasion deleted from https://juejin.im/post/5db62f1bf265da4d560906ab

Array is the most common type of data structure JS, it also often used in development, in this article, some tips, and help us to improve development efficiency.

1. Delete duplicates array

 

 

2. Alternatively a particular value in an array

Sometimes need to be replaced when you create code for a specific value in the array, there is a good short ways to do this, you can use .splice(start、value to remove、valueToAdd)these parameters to specify where we want to start to modify, amend and how many values replaced by the new value.

 

 

3. Array.from achieve the effect of .map

We all know the .map()method, .from()the method can also be used to obtain a similar effect and the code is very simple.

 

 

4. The blanking array

Sometimes we need to empty array, a quick method is to directly make an array of lengthattributes 0, you can empty the array.

 

 

5. The array is an object converts

Sometimes, for certain purposes, needs to be converted into an array of objects, a quick and easy way is to use the expanded operation symbol ( ...):

 

 

6. The array is populated with data

In some cases, when we want to create an array and fill it with some data, then the .fill()method it can help.

 

 

7. array merge

Using Expand operator, or a plurality of arrays may be combined.

 

 

8. The intersection of the sum of two arrays

Find the intersection of two arrays in the interview also a certain difficulty punctual, in order to find the intersection of the two arrays, first use the above method to ensure that the values will not be repeated in the array is checked, then use the .filtermethods and .includesmethods. As follows:

 

 

9. Remove the dummy values ​​from the array

In JS, dummy values are false, 0, '', null, NaN, undefined. You can .filter()approach to filter these dummy value.

 

 

10. A random value acquired from the array

有时我们需要从数组中随机选择一个值。一种方便的方法是可以根据数组长度获得一个随机索引,如下所示:

 

 

11.反转数组

现在,咱们需要反转数组时,没有必要通过复杂的循环和函数来创建它,数组的 reverse 方法就可以做了:

 

 

12 lastIndexOf() 方法

 

 

13.对数组中的所有值求和

JS 面试中也经常用 reduce 方法来巧妙的解决问题

 



 

总结

在本文中,介绍了13个技巧,希望它们可以帮助编写简洁代码,如果你还有更好的办法,欢迎留言讨论。

代码部署后可能存在的BUG没法实时知道,事后为了解决这些BUG,花了大量的时间进行log 调试,这边顺便给大家推荐一个好用的BUG监控工具 Fundebug



Guess you like

Origin www.cnblogs.com/Byme/p/11757162.html