ES6 Array method of JavaScript learning notes _javascript Tips

Source: Internet
Author: User
Tags array length data structures new set numeric value

ES6 (ECMAScript 6) is the upcoming new version of the JavaScript language standard, code-named Harmony (meaning of harmony, obviously did not keep pace with our country, we have entered the Chinese Dream version). The last standard was enacted in 2009 ES5. The ES6 is currently in the process of standardization and is expected to release the officially finalized version in December 14. But most of the standards are in place, and browser support for ES6 is also being implemented.

ES6 adds some new features to the array, and these new features have so far been fully applied to their business layers. In this section, you will summarize how to use the ES6 to provide some new features to arrays.

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

ES6 the method for array iterations:

Array.prototype.keys
Array.prototype.values
Array.prototype.entries
Array.prototype[symbol.iterator]

The next major look at the use of these methods.

Array.from ()

The Array.from () method is used primarily to convert two types of objects, such as an array object [Array-like object] and a traversal object [iterable], into a real array.

The following methods are often used in ES5 to convert an array-like object into an array:

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

Or you can also write:

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

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

So-called objects of similar array, the essential feature is only one point, that is, there must be a length attribute. Therefore, any object with the length attribute is a similar array object, and can be converted to a true array by the Array.from method.

Let Arraylike = {
' 0 ': ' A ',
' 1 ': ' B ',
' 2 ': ' C ',
length:3
}
console.log (Array.from ( Arraylike)); ["A", "B", "C"]

In ES6, the extension operator (...) You can also convert some data structures to arrays. Only it needs to call the Symbol.iterator interface behind the back of the loop.

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

It is worth noting that if an object does not have an iterator interface deployed, using an extension operator is not possible to convert an array-like object into a group.

Array.from accepts three parameters, but only input is required:

Input: You want to convert similar array objects and traversal objects

Map: A map method similar to an array that is used to process each element and put the processed value into the returned array

Context: The This used in binding map

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

Let arr = Array.from (' w3cplus.com ')
console.log (arr);//["W", "3", "C", "P", "L", "U", "S", ".", "C", "O", "M"]
Let Namesset = new Set ([' A ', ' B ']) let
arr2 = Array.from (namesset) 
console.log (ARR2);//["A", "B"]

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

Let arr = Array.from ([1, 2, 3]);
Console.log (arr); [1,2,3]

As I said before, Array.from can also accept the second parameter, which acts like an array of map methods, which is used to process each element, and the processed value is placed in 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 the This keyword is used in the map function, you can also pass in the third parameter of Array.from, which is used to bind this.

Array.from () can convert various values into real arrays, and also provides map functionality. This actually means that as long as you have an original data structure, you can process 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 ']

In the code above, the first parameter of Array.from specifies the number of times the second argument runs. This feature makes the method more flexible to use.

Another application of Array.from () 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 javascript being larger than \uffff Unicode characters, which count as two-character bugs.

function Countsymbols (string) {return
Array.from (string). length;
}

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

function Typesof () {return
array.from (arguments, value => typeof value)
}
typesof (null, [], NaN)
// <-[' object ', ' object ', ' number ']

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

Function Typesof (... all) {return
All.map (value => typeof value)
}
typesof (null, [], NaN)
//<-[' Object ', ' object ', ' number ']
array.of

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

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

But you can't use array.of to replace 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 to make up for the insufficiency of Array constructor array (), because the difference of the number of parameters will cause the array () behavior to be different:

New Array ()
//<-[]
new Array (undefined)
//<-[undefined]
new Array (1)
//<-[undefined x 1]
new Array (3)
//<-[undefined x 3]
new Array (1, 2)
//<-[1, 2]
new Array ( -1)
//<- Rangeerror:invalid Array length

Array.of can basically be used instead of array () or new array (), and there are no overloads that result from 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]

The Array.of method can simulate the implementation using the following code:

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

Copywidthin

The Copywidthin method can copy the array item at the specified position to another location within the current array (overwriting the original array entry), and then returns the current array. The current array is modified using the Copywidthin method.

Array.prototype.copyWithin (target, start = 0, end = this.length)

Copywidthin will accept three parameters:

Target: This parameter is required to replace the array entry from that location

Start: This is an optional argument from which to begin reading the array entry, the default is 0, and if negative, it means to start reading from the right of the array to the left

End: This is an optional argument to stop the read of the array entries at that location, by default equal to Array.Length. If negative, it means reciprocal

Let's take a look at a simple example, and here we declare an items array:

var items = [1, 2, 3,,,,,,,,]; <-[1, 2, 3, undefined x 7]

The following code will begin pasting the array items at the sixth position in the array items. Pasted past array entries are from the second bit of the items to the end of the third position.

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

Here are more examples:

Copy number 3rd to number No. 0
[1, 2, 3, 4, 5].copywithin (0, 3, 4)
//[4, 2, 3, 4, 5]
//-2 equals 3rd digits,-1 equals 4th digits
[1, 2, 3, 4, 5]. Copywithin (0,-2,-1)
//[4, 2, 3, 4, 5]
//Copy 3rd digits to number No. 0
[].copywithin.call ({length:5, 3:1}, 0, 3)
//{0: 1, 3:1, length:5}
//2nd digits to array end, copied to number No. 0 bit
var i32a = new Int32array ([1, 2, 3, 4, 5]);
I32a.copywithin (0, 2);
Int32array [3, 4, 5, 4, 5]///
need to use the following notation for platforms//requirements for Copywithin methods that do not deploy Typedarray
[].copywithin.call (New Int32array ([1, 2, 3, 4, 5]), 0, 3, 4);
Int32array [4, 2, 3, 4, 5]
Array.prototype.fill

The Array.prototype.fill method populates an array with the given value:

[' 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 already in the array will all be erased.

In addition, the Array.prototype.fill method can accept a second and a third parameter that specifies 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, undef ined x 2]

The value provided by Array.prototype.fill can be arbitrary, not only as a numeric value, but even as an original type:

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

However, this method cannot accept the mapping method of an array, but you can accept an index parameter or a way like the following:

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

The Array.prototype.find method is used to find the first array member that meets the criteria. Its argument is a callback function, in which all the array members execute the callback function until the first array item that returns a value of true is found, and then the array item is returned. Returns undefined if there are no array items that match the criteria.

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

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

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

This method is similar to the. Some and. Find method. Like. Some returns true; Find returns the item. If array[index] = = Item returns its index.

The Array.prototype.findIndex method is used primarily to return the position of an array item in an array. It is very similar to the Array.prototype.find method, accepting a callback function that returns the position of the array entry in the array if the condition of the callback function is met, and returns 1 if all array entries do not conform to the callback function condition.

[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 => item = = Infinity)
//<--1

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

Note: Array.prototype.find and Array.prototype.findIndex two methods can discover Nan, making up for the inadequacy of the array's IndexOf method.

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

In the code above, the IndexOf method does not recognize the Nan member of the array, but the FindIndex method can be done by using the Object.is method.

ES6 method of traversing arrays

ES6 provides three new methods: Entries (), keys (), and values (), which are used to traverse the array. They all return a loop object that can be traversed using for...of loops, the only difference being that the keys () are traversal of the key names of the array, values () are traversal of the array key values, and the entries () method is the traversal of the key value pairs of the numeric values.

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 the For...of loop, you can manually call the next method of the iterator object for traversal:

Let letter = [' A ', ' B ', ' C '];
Let entries = Letter.entries ();
Console.log (Entries.next (). value); [0, ' a ']
Console.log (Entries.next (). value);//[1, ' B ']
Console.log (Entries.next (). value);//[2, ' C ']

Summarize

Here is a simple summary of the relevant methods for arrays in ES6. To tell the truth, the first contact with ES6, a lot of things are seen in the clouds into the fog. This is just a sort of knowledge of the relevant aspects.

About JavaScript Learning Notes ES6 Array method Small series to introduce to everyone here, hope to help everyone!

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.