Javascrip ES6 Array method

Source: Internet
Author: User
Tags array length

Two static methods provided by ES6:

    • Array.from
    • Array.of

ES6 provides methods for manipulating, populating, and filtering arrays:

    • Array.prototype.copyWidthin
    • Array.prototype.fill
    • Array.prototype.find
    • Array.prototype.findIndex

The methods in ES6 for array iterations:

    • Array.prototype.keys
    • Array.prototype.values
    • Array.prototype.entries
    • Array.prototype[Symbol.iterator]

The next step is to look at the use of these methods.

Array.from()

Array.from()The Array-like method is primarily used to convert two types of objects (array-like objects [object] and Ergodic objects [iterable]) to true arrays.

In ES5, you often use the following method to convert an array-like object into an array:

function cast () {    return  Array.prototype.slice.call (arguments);} Cast (//  ["A", "B", "C", "D"]

In ES6, you can use Array.from an array-like object to convert to a real array.

Let Arraylike = {    ' 0 ': ' A ',    ' 1 ': ' B ',        ' 2 ': ' C ', 3//  ["A", "B", "C"]

In ES6, the extension operator ( ... ) can also convert some data structures into arrays. It just needs to call the Walker interface behind it Symbol.iterator .

function cast () {  return  [... arguments]}cast (//  ["A", "B", "C"]

It is important to note that if an object does not have a walker interface deployed, it is not possible to convert similar array objects into arrays using an extension operator.

Array.fromThree parameters are accepted, but only input necessary:

    • input: You want to convert similar array objects and objects that can be traversed
    • map: An array-like map method used to process each element, placing the processed value in the returned array
    • context: Used in Bindings mapthis

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

Let arr = Array.from (' w3cplus.com '//  ["W", "3", "C", "P", "L", "U", "S", ".", "C", "O", "M"]  New Set ([' A ', ' B '=//["A", "B"]

The above code, because both the character Fulu and the set structure have iterator interfaces, can be Array.from converted to a real array. If the argument is a true array, Array.from It also returns an identical new array:

Let arr =  Array.from ([1, 2, 3//  [+]

As I said earlier, Array.from you can also accept the second parameter, which acts like an array map method, which is used 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]

If you map use a keyword inside a function, this you can also pass Array.from in the third parameter, which is used to bind this .

Array.from()You can convert various values to real arrays and also provide map functionality. This actually means that as long as there is an original data structure, you can work with its value first, then turn it into a canonical array structure, and you can use a large number of array methods.

Array.from ({length:2}, () = ' Jack ')//  [' Jack ', ' Jack ']

Array.fromthe first parameter in the preceding code specifies the number of times the second parameter is run. This feature makes the method more flexible to use.

Array.from()Another application is to convert the string to an array and then return the length of the string. Because it handles a variety of Unicode characters correctly, you can avoid a bug that JavaScript will be larger than \uFFFF the Unicode character, which counts as two characters.

function Countsymbols (String) {    return  array.from (string). length;

Array.from()you can also return various data types using:

function typesof () {    returntypeof  value)}typesof (null, [], NaN) // <-[' object ', ' object ' , ' number ']

You can also use map the method to implement the functionality of the above code:

function typesof (... all)    {returntypeof  value)}typesof (null, [], NaN)  //  <-[' object ', ' object ', ' number ']
Array.of

Use Array.of a method to convert a set of values to an array.

function of () {    return  Array.prototype.slice.call (arguments)}

But you can't use Array.of them instead Array.prototype.slice.call , they behave differently:

Array.prototype.slice.call ([1, 2, 3])//  <-[1, 2, 3]array.of (1, 2, 3)//  <-[1, 2, 3]array.of (3)//  <-[1]

The main purpose of this method is mainly to compensate for the insufficiency of the array constructor Array() , because the different number of parameters leads to the Array() difference in behavior:

NewArray ()//<-[]NewArray (undefined)//<-[undefined]NewArray (1)//<-[undefined x 1]NewArray (3)//<-[undefined x 3]NewArray (1, 2)//<-[1, 2]NewArray (-1)//<-rangeerror:invalid Array length

Array.ofCan basically be used to replace Array() or new Array() , and there are no overloads caused by different parameters, and their behavior is very uniform:

Array.of () // <-[] array.of (undefined) // <-[undefined] Array.of (1)//  <-[1]Array.of (3)//  <-[3]Array.of (1 , 2)//  <-[1, 2]array.of ( -1)//  <-[-1]

Array.ofMethod can use the following code to simulate the implementation:

function arrayof () {    return  [].slice.call (arguments);}
copyWidthin

copyWidthinMethod can copy an array item of the specified position to another location (overwriting the original array item) inside the current array, and then return the current array. The copyWidthin current array is modified using the method.

this. Length)

copyWidthinThree parameters will be accepted:

    • target: This parameter is required to replace the array item from that position
    • start: This is an optional parameter from which to begin reading array items, by default 0 , if negative, to start reading from right to left of the array
    • end: This is an optional parameter that stops reading the array item to that location, by default equals Array.length . If negative, indicates the reciprocal

Let's start with a simple example, which declares an items array:

var // <-[1, 2, 3, undefined x 7]

The following code items begins by pasting the array item in the sixth position of the array. Pasting past array items is items the second bit from the beginning to the end of the third position.

Items.copywithin (6, 1, 3)//  <-[1, 2, 3, UNDEFINEDX3, 2, 3, UNDEFINEDX2]

Here are more examples:

//Copy the 3rd number to the number No. 0 bit[1, 2, 3, 4, 5].copywithin (0, 3, 4)//[4, 2, 3, 4, 5]//-2 is equivalent to 3rd digits, 1 is equivalent to the number of 4th digits[1, 2, 3, 4, 5].copywithin (0,-2,-1)//[4, 2, 3, 4, 5]//Copy the 3rd number to the number No. 0 bit[].copywithin.call ({length:5, 3:1}, 0, 3)//{0:1, 3:1, length:5}//end the number 2nd to the array and copy it to the number No. 0 bitvarI32A =NewInt32array ([1, 2, 3, 4, 5]); I32a.copywithin (0, 2);//Int32array [3, 4, 5, 4, 5]//for platforms that do not have a Copywithin method deployed Typedarray//you need to use the following notation[].copywithin.call (NewInt32array ([1, 2, 3, 4, 5]), 0, 3, 4);//Int32array [4, 2, 3, 4, 5]
Array.prototype.fill

Array.prototype.fillmethod to populate an array with the given values:

[' A ', ' B ', ' C '].fill (0)//  <-[0, 0, 0]new Array (3). Fill (0)// <-[0, 0, 0]

The above method is convenient for initializing an empty array. The elements that are already in the array are erased.

In addition, the Array.prototype.fill method can accept the second and third parameters, which specify the starting and ending positions of the fill.

[' A ', ' B ', ' C ',,,].fill (0, 2)//  <-[' A ', ' B ', 0, 0, 0]new Array (5). Fill (0, 0, 3 )//  <-[0, 0, 0, undefined x 2]

Array.prototype.fillThe provided value can be arbitrary, not only a numeric value, but also a primitive type:

New Array (3). Fill ({})//  <-[{}, {}, {}]

However, this method can not accept the array mapping method, but can accept an index parameter or similar to the following way:

New  Array (3). Fill (function  foo () {})//  <-[function foo () {}, function foo () {}, function Foo () {}]
Array.prototype.find

Array.prototype.findmethod is used to find the first array member that matches a condition. Its argument is a callback function, and all array members execute the callback function sequentially until they find the first true array item that returns a value, and then return the array item. Returns if there are no array items that match the criteria undefined .

[1, 2, 3, 4, 5].find (item = item > 2)//  <-3[1, 2, 3, 4, 5].find (item, i) = = = = 3)//  <-4[1, 2, 3, 4, 5].find (item = = = = Infinity)//  <- Undefined

In addition, the callback function of this method can accept three parameters, which are the current value, the current position, and the original array.

[1, 5, 15].find (function(value, index, arr) {    return value > 9  // Ten
Array.prototype.findIndex

This method is similar to .some and .find method. Like .some return true ; .find item If array[index] === item it is returned index .

Array.prototype.findIndexmethod is used primarily to return the position of an array item in an array. It Array.prototype.find is very similar to the method, which accepts a callback function that returns the position of the array item in the array if it conforms to the condition of the callback function, and returns if all array items do not conform to the callback function condition -1 .

[1, 2, 3, 4, 5].find (item = item > 2)//  <-2[1, 2, 3, 4, 5].find (item, i) => ; i = = 3)//  <-3[1, 2, 3, 4, 5].find (item = = = = Infinity)// <--1

This method can also accept the second parameter, which is used to bind the object of a callback function this .

Note: Array.prototype.find And Array.prototype.findIndex two methods can be found NaN to compensate for the lack of array indexOf methods.

[Nan].indexof (NaN) // -1  = = object.is (NaN, y))//  0

In the preceding code, the indexOf method does not recognize the members of the array NaN , but the method findIndex can do so Object.is .

ES6 How to iterate through an array

ES6 provides three new methods: entries() , keys() and values() , to iterate over an array. They all return a Walker object that can be traversed with a loop, with the only difference being the traversal of the for...of keys() key name of the array, the traversal of the values() array key value, and the entries() traversal of the value's key-value pairs.

 for (Let index of [' A ', ' B '].keys ()) {    console.log (index);} // 0 // 1  for (Let elem of [' A ', ' B '].values ()) {    console.log (elem);} // ' A ' // ' B '  for (Let [index, Elem] of [' A ', ' B '].entries ()) {    Console.log (index, elem);} // 0 "a" // 1 "B"

If you do not use for...of loops, you can manually invoke the method of the Walker object to next Traverse:

Let letter = [' A ', ' B ', ' C '=//  [0, ' a ']//  [1, ' B ']//  [2, ' C ']

Javascrip ES6 Array method

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.