Not to be missed 13 JavaScript Practical tips!

Original link: https://bss.csdn.net/m/topic/dev_survey2019?source_id=zx

640?wx_fmt=gif

For starters, JavaScript which there are unknown but very useful tips it? In this article, we will work together for everyone to share and decryption.

640?wx_fmt=jpeg

Author | Duomly
Translator | meniscus, Zebian | Tu Min
Exhibition | CSDN (ID: CSDNnews)

The following is the translation:

Javascript array is the most common concept, we have many ways to process the data in the array. Considering Javascript array is one of the most basic concept, the concept is new to programming beginners to learn, I think this article describes some of the little-known but very useful tips. let us start!

640?wx_fmt=png

Remove duplicates from an array

In the interview questions related to Javascript arrays, there is a very common problem: how to extract value from the non-repetition Javascript array. I have a quick and easy way: simply use the new Set () can be. The method implemented in two ways: using a .from (), using an extended another operator (...):

var fruits = [“banana”, “apple”, “orange”, “watermelon”, “apple”, “orange”, “grape”, “apple”];

It is easy, is not it?

640?wx_fmt=png

Replace the value specified in the array

When programming, sometimes you need to replace a particular value, there is a very simple way to achieve this. Just use .split (start, you want to delete the value, the value to be added), and then set up three parameters, indicate that you want to modify where, to modify several values, and what new value yes.

var fruits = [“banana”, “apple”, “orange”, “watermelon”, “apple”, “orange”, “grape”, “apple”];
fruits.splice(0, 2, “potato”, “tomato”);
console.log(fruits); // returns [“potato”, “tomato”, “orange”, “watermelon”, “apple”, “orange”, “grape”, “apple”]

640?wx_fmt=png

Not using .map () to implement the mapping

Probably everyone knows .map array () method, but there is another method, you can use the same simple way to achieve a similar effect. This method is .from ():

var friends = [
    { name: ‘John’, age: 22 },
    { name: ‘Peter’, age: 23 },
    { name: ‘Mark’, age: 24 },
    { name: ‘Maria’, age: 22 },
    { name: ‘Monica’, age: 21 },
    { name: ‘Martha’, age: 19 },
]


var friendsNames = Array.from(friends, ({name}) => name);
console.log(friendsNames); // returns [“John”, “Peter”, “Mark”, “Maria”, “Monica”, “Martha”]

640?wx_fmt=png

Empty Array 

If you want an array emptied, but do not want to delete one element of which, how to do? In fact, just one line of code: The length is set to 0.

var fruits = [“banana”, “apple”, “orange”, “watermelon”, “apple”, “orange”, “grape”, “apple”];


fruits.length = 0;
console.log(fruits); // returns []

640?wx_fmt=png

The array into an object

If there is an array, we want to put a data object, then the fastest way is to use the extended operator (...):

var fruits = [“banana”, “apple”, “orange”, “watermelon”];
var fruitsObj = { …fruits };
console.log(fruitsObj); // returns {0: “banana”, 1: “apple”, 2: “orange”, 3: “watermelon”, 4: “apple”, 5: “orange”, 6: “grape”, 7: “apple”}

640?wx_fmt=png

The array is populated with data

有时候需要创建一个数组并用数据填充,或者需要一个所有值都相同的数组,此时可以使用.fill()方法简洁明快地实现:

var newArray = new Array(10).fill(“1”);
console.log(newArray); // returns [“1”, “1”, “1”, “1”, “1”, “1”, “1”, “1”, “1”, “1”, “1”]

640?wx_fmt=png

合并数组

你知道怎样可以不使用.concat()来合并数组吗?最简单的方法只需要一行代码。你也许猜到了,那就是扩展运算符(...),它非常适合处理数组:

var fruits = [“apple”, “banana”, “orange”];
var meat = [“poultry”, “beef”, “fish”];
var vegetables = [“potato”, “tomato”, “cucumber”];
var food = […fruits, …meat, …vegetables];
console.log(food); // [“apple”, “banana”, “orange”, “poultry”, “beef”, “fish”, “potato”, “tomato”, “cucumber”]

640?wx_fmt=png

求两个数组的交集

这也是Javascript面试中最常遇到的问题,因为它能展示出你是否会使用数组方法,以及逻辑如何。要找出两个数组的交集,只需要使用之前使用的技巧,首先保证数组中的值不重复,然后利用.filter和.includes方法即可。这样就能找出同时出现在两个数组中的元素。代码如下:

var numOne = [0, 2, 4, 6, 8, 8];
var numTwo = [1, 2, 3, 4, 5, 6];
var duplicatedValues = […new Set(numOne)].filter(item => numTwo.includes(item));
console.log(duplicatedValues); // returns [2, 4, 6]

640?wx_fmt=png

从数组中删除假值

首先我们来定义假值。在Javascript中,假值包括false、0、''、null、NaN、undefined。现在可以考虑怎样从数组中删除假值了。只需使用.filter()方法即可实现:

var mixedArr = [0, “blue”, “”, NaN, 9, true, undefined, “white”, false];
var trueArr = mixedArr.filter(Boolean);
console.log(trueArr); // returns [“blue”, 9, true, “white”]

640?wx_fmt=png

从数组中获取随机值

有时候需要从数组中随机选择一个值。简单、快捷、简短且干净的方式就是在数组长度的范围内生成一个随机的索引。代码如下:

var colors = [“blue”, “white”, “green”, “navy”, “pink”, “purple”, “orange”, “yellow”, “black”, “brown”];
var randomColor = colors[(Math.floor(Math.random() * (colors.length)))]

640?wx_fmt=png

反转数组

需要反转数组时,我们不需要使用复杂的循环和函数来重新创建数组,因为有一个简单的数组方法可以为我们做这件事,只需一行代码,就能反转数组。代码如下:

var colors = [“blue”, “white”, “green”, “navy”, “pink”, “purple”, “orange”, “yellow”, “black”, “brown”];
var reversedColors = colors.reverse();
console.log(reversedColors); // returns [“brown”, “black”, “yellow”, “orange”, “purple”, “pink”, “navy”, “green”, “white”, “blue”]

640?wx_fmt=png

.lastIndexOf()方法

Javascript中有一个有趣的方法,可以让我们找出指定元素最后出现的位置。例如,如果数组中有重复元素,那么可以找出该元素最后出现的位置。代码如下:

var nums = [1, 5, 2, 6, 3, 5, 2, 3, 6, 5, 2, 7];
var lastIndex = nums.lastIndexOf(5);
console.log(lastIndex); // returns 9

640?wx_fmt=png

对数组中的所有值求和

另一个Javascript工程师面试中常见的问题就是对数组中的所有元素求和。这个完全不需要害怕,只需使用.reduce方法,一行代码就可以实现。代码如下:

var nums = [1, 5, 2, 6];
var sum = nums.reduce((x, y) => x + y);
console.log(sum); // returns 14

640?wx_fmt=png

总结

本文向你展示了13个编程技巧,可以保持代码简短整洁。同时别忘了,Javascript中还有许多不同的技巧值得探索,不仅是有关数组的技巧,也包括许多其他的数据类型。希望你喜欢本文的技巧,并能利用这些技巧改善开发流程。

Original: https://dev.to/duomly/13-useful-javascript-array-tips-and-tricks-you-should-know-2jfo

This article CSDN translation, please indicate the source of the source.

【END】

640?wx_fmt=jpeg

 Thermal paper  recommended 

Article for super books DLT, libraries, development tools which, Hyperledger family members you know a few?
640?wx_fmt=gif Click here to read the original participation questionnaire, Gifts to send non-stop!
640?wx_fmt=png
Your point of each "look", I seriously as a favorite

Guess you like

Origin blog.csdn.net/csdnnews/article/details/102763234