Arrays with the help of ES6 now have uber kool methods in them! Let's have a look at them with few simple examples to understand them.
Array:
from()
of()
Array.prototype:
copyWithin()
fill()
find()
findIndex()
keys()
entries()
values()
Array.from():
Coverts arrayLike
and interator
objects to arrays.
Simple senario in ES5 to enumarate over a NodeList:
1 2 3 4 |
|
Same with ES6:
1 2 3 4 |
|
Also:
1 2 |
|
Array.of():
This creates a new Array instance with a variable number of arguments, regardless of the type.
1 2 |
|
A simple implementation of the same in ES5
would be:
1 2 3 |
|
Array.copyWithin():
Given the target starting index, source start and end indices, this method copies the sequence of array elements.
If the starting or the ending indices are negitive values, then the array length is added to them.
1 2 3 4 5 6 7 8 |
|
Array.fill():
Fills all the elements of an array from a start index to an end index with a static value.
1 2 3 4 5 6 7 8 |
|
Array.find():
This returns a value in the array or undefined, based on the testing function that is passed to this method.
1
|
|
1 2 3 4 5 |
|
Array.findIndex():
Similar to find()
but retruns the matching index if found, or else returns -1
1 2 3 4 5 |
|
Array.{keys, entries, values}():
keys
, entires
and values
methods returns a new Array Iterator
object that contains keys
, values
and key/value pairs
respectively.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
Bonus for scrolling till the end ;)
ES7
will have Array.contains
as a matter of fact it's already there in FF35+
1 2 3 |
|
Hope this helped, happy hacking! :)
Update 0 After publishing this post noticed one more uber kool post by Dr. Axel Rauschmayer don't miss it!