ES6 new feature 7: array expansion details, es6 new feature expansion details

Source: Internet
Author: User

ES6 new feature 7: array expansion details, es6 new feature expansion details

This article describes how to expand the array of ES6's new features. We will share this with you for your reference. The details are as follows:

1. Array. from ()

1) Array. the from method is used to convert two types of objects into real Arrays: array-like objects and iterable objects) (including the data structure Set and Map added by ES6, both of which deploy the iterator interface, and the string is also ).

Let arrayLike = {'0': 'A', '1': 'B', '2': 'C', length: 3 }; // ES5 statement var arr1 = []. slice. call (arrayLike); console. log (arr1) // ['A', 'B', 'C'] // let arr2 = Array. from (arrayLike); console. log (arr2) // ['A', 'B', 'C'] Array. from ('hello') // ['h', 'E', 'l', 'l', 'O'] let namesSet = new Set (['A ', 'B']) Array. from (namesSet) // ['A', 'B']

2) The extension operator (...) calls the Symbol. iterator interface. If an object does not deploy this interface, it cannot be converted. The Array. from method also supports objects similar to arrays. Objects similar to arrays have only one essential feature, that is, they must have the length attribute.

Array. from ({length: 3}); // The extension operator cannot be converted. // [undefined, undefined, undefined]

3) Array. from can also accept the second parameter, which is similar to the map method of the Array. It is used to process each element and put the processed value into the returned Array.

Var a = Array. from ([1, 2, 3], x => x * x); console. log (a) // equivalent to var a1 = Array. from ([1, 2, 3]). map (x => x * x); console. log (a1) var a2 = Array. from ([1, 2, 3], (x) => x * x) console. log (a2) // [1, 4, 9] // if there is an original data structure, you can process the value first, // convert it to a standard array structure, and then you can use a large number of array methods. Var a3 = Array. from ({length: 2}, () => 'jack') console. log (a3) // ['jack', 'jack']

2. Array. ()

An array composed of return parameter values. If no parameter exists, an empty Array is returned to make up for the deficiency of Array constructor Array. Because of the number of parameters, the behavior of Array () varies.

console.log(Array()) // []console.log(Array(3)) // [, , ,]console.log(Array(3, 11, 8)) // [3, 11, 8]console.log(Array.of(3, 11, 8))// [3,11,8]console.log(Array.of(3)) // [3]console.log(Array.of()) // []

3. find () and findIndex () of the array instance ()

① Array instancefindMethod to find the first qualified array member. Its parameters are a callback function. All array members execute the callback function in sequence until they find the first member whose return value is true and then return the Member. If no qualified member exists, undefined is returned.

Var a = [1, 4,-5, 10]. find (n) => n <0) console. the callback function of log (a) // find method can accept three parameters, which are the current value, the current position, and the original array in turn. [1, 5, 10, 15]. find (function (value, index, arr) {return value> 9;}) // 10

② Array instancefindIndexMethod usage andfindThe method is very similar. Return the position of the first qualified array member. If all the Members do not meet the condition, return-1.

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

4. array instance fill ()

fillUse the given value to fill an array. All existing elements in the array are erased.

['a', 'b', 'c'].fill(7) // [7, 7, 7]new Array(3).fill(7) // [7, 7, 7]

fillThe method can also accept the second and third parameters, which are used to specify the starting position and ending position of the filling (package left without package right ).

['a', 'b', 'c'].fill(7, 1, 2)// ['a', 7, 'c']

5. array instance entries (), keys (), and values ()

ES6 provides three new methods --entries(),keys()Andvalues()-- Used to traverse arrays. They all return a traversal object. for... of will automatically callnext().

for (let index of ['a', 'b'].keys()) { console.log(index);}// 0// 1for (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 callnextMethod.

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']

6. sort des () of the array instance ()

Array.prototype.includesMethod returns a Boolean value indicating whether an array contains the given value. The second parameter of this method indicates the start position of the search. The default value is 0. If the second parameter is negative, it indicates the reciprocal position.

[1, 2, 3].includes(2);   // true[1, 2, 3].includes(4);   // false[1, 2, NaN].includes(NaN); // true

In addition, there is an has method for Map and Set data structures, which must be distinguished from des.

The has method of the Map structure is used to find the key name:

For exampleMap.prototype.has(key),WeakMap.prototype.has(key),Reflect.has(target, propertyKey).

The has method of the Set structure is used to find the value:

For exampleSet.prototype.has(value),WeakSet.prototype.has(value).

7. Empty array space

The empty position of the array indicates that there is no value at a certain position of the array. The blank space is not undefined. The value of a position is equal to undefined, and it is still a value.

Array(3) // [, , ,]

ES6 explicitly converts a blank space into undefined space.

console.log(Array.from(['a',,'b']))//[ 'a', undefined, 'b' ]console.log([...['a',,'b']])// [ "a", undefined, "b" ]let arr = [, 'a',,];for (let i of arr) {  console.log(i);}//undefined a undefined
// entries()[...[,'a'].entries()] // [[0,undefined], [1,"a"]]// keys()[...[,'a'].keys()] // [0,1]// values()[...[,'a'].values()] // [undefined,"a"]// find()[,'a'].find(x => true) // undefined// findIndex()[,'a'].findIndex(x => true) // 0

I hope this article will help you design the ECMAScript program.

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.