Home  >  Article  >  Web Front-end  >  How to use the from method in es6

How to use the from method in es6

WBOY
WBOYOriginal
2022-05-05 15:31:501818browse

In es6, the from method is used to convert array-like objects and traversable objects into real arrays. The returned result is a new array instance that has been converted. The syntax is "Array.from( The pseudo-array object or iterable object that you want to convert to an array, the callback function, and the this object when the callback function is executed)".

How to use the from method in es6

The operating environment of this tutorial: Windows 10 system, ECMAScript version 6.0, Dell G3 computer.

How to use the from method in es6

This method is used to convert two types of objects into real arrays: array-like objects and traversable objects;

Syntax

Array.from( arrayLike, mapFun, thisArg );

Parameters

arrayLike: Required. A pseudo-array object or iterable object that you want to convert to an array;

mapFun: Optional. If this parameter is specified, the callback function will be executed for each element in the new array.

thisArg: optional. This object is used when executing the callback function mapFun.

Return value

A new array instance

The example is as follows:

Generate array from String

Array.from('foo'); 
// [ "f", "o", "o" ]

Generate array from Set

const set = new Set(['foo', 'bar', 'baz', 'foo']);
Array.from(set);
// [ "foo", "bar", "baz" ]

Generate array from Map

const map = new Map([[1, 2], [2, 4], [4, 8]]);
Array.from(map);
// [[1, 2], [2, 4], [4, 8]]
const mapper = new Map([['1', 'a'], ['2', 'b']]);
Array.from(mapper.values());
// ['a', 'b'];
Array.from(mapper.keys());
// ['1', '2'];

Generate array from array-like object (arguments)

function f() {
  return Array.from(arguments);
}
f(1, 2, 3);
// [ 1, 2, 3 ]

[Related recommendations:javascript video tutorialweb front-end

The above is the detailed content of How to use the from method in es6. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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