Home > Web Front-end > JS Tutorial > Five super useful uses of Array.from() (detailed explanation)

Five super useful uses of Array.from() (detailed explanation)

青灯夜游
Release: 2019-11-29 17:57:01
forward
2282 people have browsed it

Five super useful uses of Array.from() (detailed explanation)

Any programming language has capabilities beyond basic usage, and it benefits from successful design and attempts to solve a wide range of problems.

There is such a function in JavaScript: Array.from: allows JavaScript collections (such as arrays, array-like objects, or iterable objects such as strings, maps, and sets) perform useful conversions.

[Related course recommendations: JavaScript Video Tutorial]

In this article, I will describe 5 useful and interesting Array.from() Example.

1. Introduction

Before we begin, let’s recall the role of Array.from(). Syntax:

Array.from(arrayLike[, mapFunction[, thisArg]])
Copy after login
  • arrayLike: Required parameter, the pseudo-array object or iterable object that you want to convert into an array.

  • mapFunction: optional parameter, mapFunction(item, index){...} is the function called on each item in the collection. The returned value will be inserted into the new collection.

  • thisArg: Optional parameter, this object when executing the callback function mapFunction. This parameter is rarely used.

For example, let us multiply each item of the class array by 2:

const someNumbers = { '0': 10, '1': 15, length: 2 };
Array.from(someNumbers, value => value * 2); // => [20, 30]
Copy after login

2. Convert class array to array

Array.from() First use: Convert array-like objects into arrays.

Usually, the array-like objects you will encounter include: the arguments keyword in a function, or a DOM collection.

In the following example, let us sum the arguments of a function:

function sumArguments() {
    return Array.from(arguments).reduce((sum, num) => sum + num);
}
sumArguments(1, 2, 3); // => 6
Copy after login

Array.from(arguments) Convert array-like objects arguments Convert to an array, and then use the reduce method of the array to sum.

In addition, the first parameter of Array.from() can be any iterable object. Let’s continue to look at some examples:

Array.from('Hey');                   // => ['H', 'e', 'y']
Array.from(new Set(['one', 'two'])); // => ['one', 'two']

const map = new Map();
map.set('one', 1)
map.set('two', 2);
Array.from(map); // => [['one', 1], ['two', 2]]
Copy after login

3. Clone an array

There are many ways to clone an array in JavaScript. As you can imagine, Array.from() makes it easy to perform shallow copies of arrays.

const numbers = [3, 6, 9];
const numbersCopy = Array.from(numbers);

numbers === numbersCopy; // => false
Copy after login

Array.from(numbers) creates a shallow copy of the numbers array, the result of numbers === numbersCopy is false means that although numbers and numbersCopy have the same items, they are different array objects.

Is it possible to use Array.from() to create a clone of an array, including all nested ones? Challenge yourself!

function recursiveClone(val) {
    return Array.isArray(val) ? Array.from(val, recursiveClone) : val;
}

const numbers = [[0, 1, 2], ['one', 'two', 'three']];
const numbersClone = recursiveClone(numbers);

numbersClone; // => [[0, 1, 2], ['one', 'two', 'three']]
numbers[0] === numbersClone[0] // => false
Copy after login

recursiveClone() can make a deep copy of the array by judging whether the item of the array is an array. If it is an array, continue to call recursiveClone () to implement a deep copy of the array.

Can you write a shorter array deep copy than using Array.from() recursively? If you can, please write in the comment section below.

4. Fill the array with values ​​

If you need to initialize the array with the same values, then Array.from() would be a good choice.

Let’s define a function to create an array filled with the same default value:

const length = 3;
const init   = 0;
const result = Array.from({ length }, () => init);

result; // => [0, 0, 0]
Copy after login

result is a new array with a length of 3, and each element of the array All items are 0. Call the Array.from() method, passing in an array-like object { length } and a mapFunction function that returns the initialized value.

However, there is an alternative method array.fill() that achieves the same functionality.

const length = 3;
const init   = 0;
const result = Array(length).fill(init);

fillArray2(0, 3); // => [0, 0, 0]
Copy after login

fill() Correctly fills the array with initial values.

4.1 Filling the array with objects

When initializing each item of the array should be a new object, Array.from() is a better solution:

const length = 3;
const resultA = Array.from({ length }, () => ({}));
const resultB = Array(length).fill({});

resultA; // => [{}, {}, {}]
resultB; // => [{}, {}, {}]

resultA[0] === resultA[1]; // => false
resultB[0] === resultB[1]; // => true
Copy after login

The resultA returned by Array.from is initialized with a different empty object instance. This happens because mapFunction, here () => ({}), returns a new object every time it is called.

Then, the resultB created by the fill() method is initialized with the same empty object instance. Empty items will not be skipped.

4.2 How about using array.map?

Can I use the array.map() method to achieve this? Let’s try it:

const length = 3;
const init   = 0;
const result = Array(length).map(() => init);

result; // => [undefined, undefined, undefined]
Copy after login

map() The method seems to be abnormal. The array created is not the expected [0, 0, 0], but a Array with 3 empty items.

This is because Array(length) creates an array with 3 empty items (also called a sparse array), but the map() method will jump Empty items passed.

5. Generate number range

你可以使用 Array.from() 生成值范围。例如,下面的 range 函数生成一个数组,从0开始到 end - 1

function range(end) {
    return Array.from({ length: end }, (_, index) => index);
}
range(4); // => [0, 1, 2, 3]
Copy after login

range() 函数中,Array.from() 提供了类似数组的 {length:end} ,以及一个简单地返回当前索引的 map 函数 。这样你就可以生成值范围。

6.数组去重

由于 Array.from() 的入参是可迭代对象,因而我们可以利用其与 Set 结合来实现快速从数组中删除重复项。

function unique(array) {
  return Array.from(new Set(array));
}
unique([1, 1, 2, 3, 3]); // => [1, 2, 3]
Copy after login

首先,new Set(array) 创建了一个包含数组的集合,Set 集合会删除重复项。

因为 Set 集合是可迭代的,所以可以使用 Array.from() 将其转换为一个新的数组。

这样,我们就实现了数组去重。

7.结论

Array.from() 方法接受类数组对象以及可迭代对象,它可以接受一个 map 函数,并且,这个 map 函数不会跳过值为 undefined 的数值项。这些特性给 Array.from() 提供了很多可能。

如上所述,你可以轻松的将类数组对象转换为数组,克隆一个数组,使用初始化填充数组,生成一个范围,实现数组去重。

实际上,Array.from() 是非常好的设计,灵活的配置,允许很多集合转换。

英文原文地址:https://dmitripavlutin.com/javascript-array-from-applications/

本文来自 js教程 栏目,欢迎学习!

The above is the detailed content of Five super useful uses of Array.from() (detailed explanation). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:dmitripavlutin.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template