Extension of the ES6 array

Source: Internet
Author: User

Array.from ()

Array.fromThe Array-like method is used to convert two types of objects to a true array: An array-like object (A. iterable) and an object that can be traversed (including ES6 new data structure set and map).

1Let Arraylike = {2' 0 ': ' A ',3' 1 ': ' B ',4' 2 ': ' C ',5Length:36 };7 8 //the writing of ES59 varARR1 = [].slice.call (arraylike);//[' A ', ' B ', ' C ']Ten  One //the writing of ES6 ALet arr2 = Array.from (arraylike);//[' A ', ' B ', ' C ']

In practice, a common array-like object is the NodeList collection returned by the DOM operation, as well as the objects inside the function arguments . Array.fromthey can be converted to real arrays.

// NodeList Object Let PS = Document.queryselectorall (' P '); Array.from (PS). ForEach (function  (p) {  console.log (p);}); // arguments Object function foo () {  var args = array.from (arguments);   //  ...}

In the above code, the querySelectorAll method returns an array-like object that can only be used if the object is converted to a true array forEach .

As long as the data structure with the iterator interface is deployed, Array.from it can be converted to an array.

Array.fromYou can also accept the second parameter, which acts like an array map , to process each element and put the processed value into the returned array.

Array.from (arraylike, x = x * x); // equivalent to Array.from (arraylike). map (x = = x * x); Array.from ([1, 2, 3], (x) = x * x)//  [1, 4, 9]

Array.of ()

Array.ofmethod is used to convert a set of values into an array.

// [3,11,8] // [3] // 1

Array.ofCan basically be used to replace Array() or new Array() , and there are no overloads caused by different parameters. It behaves very uniformly.

// the Array.of method can be simulated with the following code.  function  arrayof () {  return   [].slice.call (arguments);   //ES5
}

Extension of the ES6 array

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.