Extension Details of ES6 arrays

The instance of this paper tells the extension of the ES6 array. Share to everyone for your reference, specifically:

1.From ()

array.from () A array-like object The object that can be traversed into an array and returns.

The following is a category

  Let Arr = {'0': 'A', '1': 'b', '2': 'c', length: 3};  
ES5 we may write:

VAR Arr1 = [ ]. SLICE.CALL (ARR);
 ES6 can convert a class array into a true array   
VAR Arr2 = array.from (arr)

In practical applications, the object of commonly similar arrays is a DOM operation returns a NodeList collection, and the Arguments object inside the function. Array.From converts them into a real array.
 // NodeList object Let ps = document.queryselectoralL ('p'); array.from (ps) .foreach (function (p) {console.log (P );}); // arguments object function fooction foo () {var args = array.from (arguments); // ...}   
aboveThe QuerySelectoralL method returns an object of a similar array that only converts this object into a true array, can use the foreach method.

As long as it is a data structure that deploys the Iterator interface, Array.From can turn it into an array.

Array.From (‘Hello’) // [‘h’, ‘E’, ‘L’, ‘L’, ‘o’] let Namesset = New Set ([‘a’, ‘b’]) array.from (name, ‘b’]
   
above code, string And the SET structure has an Iterator interface, so it can be converted to a true array by Array.From.

If the parameter is a real array, Array.From will return an exproprant new array.

Array.From ([1, 2, 3]) / / [1, 2, 3]
   It is worth reminding that the extension operator (...) can also convert some data structures into arrays. 
// Arguments object function fooction foo () {var args = [… arguments];} // nodelist object [… Document.QuerySelectorall (‘Div’

The expansion operator is called a Symbol.iterator. If an object is not deployed, it cannot be converted.
Array.FROM method is also an object similar to array. The so-called object, essential characteristics, mustThere must be a Length attribute. Therefore, any object with the Length property can be converted to an array via the array.from method, and the extended operator cannot be converted.
  Array.From ({Length: 3}); // [undefined, undefined, undefined]  

In the above code, Array.From returns an array with three members, and the values ​​of each location are undefined. The extended operator cannot be converted.

For browsers that have not been deployed, I can replace it with array.prototype.slice method.
  Const toArray = (() => array.from? Array.From: obj => [] .slice.call (obj)) ();  
Array.FROM can also accept the second parameter, effect similar to the MAP method of the array, used to process each element, put the processed value into the returned array .

Array.From (arraylike, x => x * x); / / equivalent to array.from (arraylike) .map (x => x * x); the following example Array.from ([1, 2, 3], (x) => x * x) // [1, 4, 9]

  is withdrawn A set of text contents of a set of DOM nodes.  

let spans = document.querySelectorAll ( ‘span.name’); //Map () let names1 = array.prototype.map.call (spans, s => s.TextContent); // array.from () letn names2 = array.from (spans, s => s.TextContent)

The following example converts members of the Pooler value of the array to 0.
  Array.From ([1, 2, 3], (N) => n || 0) // [1, 0, 2, 0, 3]  
Another example is the type returns to various data.

unification type.from (arguments, value => typeof value)} typeesof (null, [], nan) // [‘Object’, “Number ‘]
   
If the THIS key is used in the MAP function, you can also pass the third parameter of Array.From for binding. THIS. Array.From () can convert various values ​​into a true array and also provides MAP functions. This actually means that as long as there is an original data structure, you can process its value, then turn into a specific set of array structures, and then use a large number of array methods.

Array.From ({Length: 2}, () => ‘jack’) // [‘jack’, ‘jack’]
 In the face code, the first parameter of Array.From specifies the number of times the second parameter run. This feature allows us to use it very flexible.  Another application of array.from () is to convert the string into an array and then return the length of the string. Because it can properly handle various Unicode characters, avoid JavaScript will greater than \ uffff Unicode characters, count the bugs of two characters. 

Function CountSymbols (String) {Return Array.From (String) .length;}

   2. Array.Of () 
Array.OF method is used to convert a set of values ​​to an array.

Array.of (3, 11, 8) // [3, 11, 8] Array.Of (3) // [3] Array.of (3 ) .length // 1
 The main purpose of this method is to compensate for the lack of array constructor array (). Because the number of parameters is different, there is a difference in behavior of Array ().   
Array () // [] Array (3) // [,,] Array (3, 11, 8) // [3, 11, 8]

In the above code, the Array method does not have the parameters, a parameter, and three parameters, the return result is different. Array () returns new arrays consisting of parameters when the number of parameters is not less than 2. When the number of parameters is only one, it is actually the length of the specified array.

Array.Of basically can be used to replace Array () or NewArray () and no overload due to parameters. Its behavior is very unified.

Array.Of () // [] array.of (undefined) // [undefined] Array.Of (1) // [1] array.of 1, 2) // [1, 2]
  Array.Of always returns an array of parameter values. If there is no parameters, an empty array is returned.  Array.OF method can be implemented with the following code simulation. 
Function Arrayof () {Return []. Slick.Call (arguments);}

3. CopyWithin ()
   of the array instance, copy the member of the specified location to other locations inside the current array, and then returns the current array. That is to say, use this method, modify the current array. 
Array.Prototype.copywithin (target, start = 0, end = this.Length)
It accepts three parameters:

Target (required): from this location Start replacement data. START: Start reading data from this location, default is 0. If it is a negative value, it represents the countdown.

End (optional): Stop reading data before this location, is equal to the length of the array by default. If it is a negative value, it represents the countdown.

These three parameters should be a value, if not, it will automatically turn to a value.
  [1, 2, 3, 4, 5] .coPywithin (0, 3) // [4, 5, 3, 4, 5]  
The above code indicates a member (4, and) from the 3rd position until the end. 5) Copy to the position starting from the 0 position, and the result covers the original 1 and 2.

// Copy the 3rd position to zero [1, 2, 3, 4, 5]. Copywithin (0, 3, 4) // [4 , 2, 3, 4, 5] // -2 equivalent to the line 3, – 1 is equivalent to the 4th position [1, 2, 3, 4, 5] .copywithin (0, -2, -1) // [4, 2, 3, 4, 5] // Copy the line 3 to the 0 position [] .copywithin.call ({Length: 5, 3: 1}, 0, 3) // {0: 1, 3: 1, Length: 5} // At the end of the number 2 to the array, copy to the 0 position VAR i32a = new int32a. ([1, 2, 3, 4, 5]); i32a.copywithin (0, 2) // int32Array [3, 4, 5, 4, 5] // For platforms that do not deploy TypeDarray, the following Writings need to be used [] .copywithin.call (New Int32aRRAY ([1, 2, 3, 4, 5]), 0, 3, 4); // INT32ARRAY [4, 2, 3, 4, 5]

4. Array example Find () and Findex ()
  Find methods of array instances are used to find the first eligible array member. Its parameters are a callback function, and all array members perform this callback function in turn until the first return value is a member of True, and then returns to the member. If there is no complianceThe member of the part returns undefined.  
[1, 4, -5, 10] .find ((N) => N

The code finds a member of the first less than 0 in the array.
 [1, 5, 10, 15] .find (Function (Value, INDEX, ARR) {Return Value> 9;}) // 10   In the above code, the callback function of the Find method can accept three parameters, sequentially, the current value, the current position and the original Array. 
The usage of the FindEx method of the array instance is very similar to the FIND method. Returns the position of the first eligible array member, returns -1 if all members do not meet the conditions. (Found a compliance Stopping)

[1, 5, 10, 15] .findex (Function (Value, INDEX, ARR) {Return Value> 9;} // 2

Find () returns the value, FindIndex returns the location.
 These two methods can accept the second parameter for tie THIS object of the transfer function.   In addition, both methods can find NAN to compensate for the shortcomings of the INDEXOF method of the array. 

[NAN ] .indexof (nan) ///1 [nan] .findex (y => Object.is (nan, y)) // 0

In the above code, IndexOf method does not recognizeGroup of NAN members, but the FindIndex method can do it with the Object.is method.

5. Fill ()


Fill method for array instances uses a given value to populate an array.

[‘A’, ‘B’, ‘C’]. Fill (7) // [7, 7, 7] New Array (3) .fill ( 7) / / [7, 7, 7]

The above code shows that the Fill method is used for initialization of an empty array. Elements in arrays will be erased.
The Fill method can also accept the second and third parameters for specifying the starting position and end position of the fill.
  ['A', 'B', 'C']. Fill (7, 1, 2) // ['A', 7, 'c']  
The above code indicates that the Fill method starts from the 1st position and fills 7 to the original array, and ends before the 2 position.

6. Entires (), keys () and value ()

ES6 provide three new methods () () () () () ENTIRES () () “ENTIRES () And values ​​() – used to traverse an array. They all return a traveler object, can be traversed with for … of loop, and the only difference is that keys () is the traversal of the key name, and VALUES () is the traversal of the key value. Entries () is the key value Pair of traversal.
   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 not … OF loop, you can manually call the NEXT of the traveler object. Method, 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’]

7. Includes ()

array.prototype.includes method returns one The Boolean value indicates whether an array contains a given value, similar to the SRUDES method of the string. This method belongs to ES7, but the Babel transcoder has supported.
  < 0)
// -5

 
[1, 2, 3] .includes (2); // True [1, 2, 3] .includes (4); // False [1, 2, nan] .includes (nan); // true
The second parameter of the method represents the starting position of the search, default is zero. If the second parameter is negative, represent the position of the countdownIf it is greater than the array length (such as the second parameter of -4, but the array length is 3), it will be reset to start from 0.

[1, 2, 3] .includes (3, 3); // False [1, 2, 3] .includes (3, -1); / / TRUE
   Before we do not use the INDEXOF method of the array, check if a certain value is included. 
IF (Arr.indexOf (EL)! == -1) {// …}

The indexof method has two shortcomings, one is not semantic, its meaning is the first appearance location of the parameter value, so it is not equivalent to -1, it is not intuitive. Second, it uses a strict quasi-operator (===) inside, which will result in misjudgment of NAN.
   

INCLUDES is not the same judgment Algorithm, there is no such problem.

[NAN]

// true

  The following code is used to check if the current environment is supported This method is not supported, deploying a simple alternative version.  
Const contacts = (() => Array.Prototype.includes? (Arr, value) => arr.includes (value): (arr, value) => Arr.some (EL => EL=== Value)) (); Contains ([“” “” “” “BAR”], “baz”); // => false

In addition, MAP and The SET data structure has an HAS method, and it is necessary to pay attention to the INCLUDES.

The HAS method of the Map structure is used to find key names, such as map.prototype.has (key), weakmap.prototype.has (key), reflect.has (target, propertyKey).

The HAS method for the SET structure is used to look for values, such as set.Prototype.has (value), WeakSet.Prototype.has (Value).

8. A group of vacant
  The idling of the array refers to a certain position of the array does not have any value. For example, the array returned by the Array constructor is space.  
Array (3) // [,,]

Among the above code, Array (3) returns An array with 3 vacancy.

Note that the space is not undefined, the value of a position is equal to undefined, still having a value. The vacancy is no value, the in operator can explain this.
0 in [undefined, undefined, undefined] // true0 in [,,,] // false
   
The above code description, the first array 0 position is value, and the number 0 position of the second array does not have a value.

The processing of ES5 to vacancies is very inconsistent, and the vacancy will be ignored in most cases.

foreach (), filter (), every () and some () will skip. MAP () will skip the space, but will retain this value

Join () and toString () will treat the space as undefined, and undefined and null will be processed into empty strings .

// foreach method [, ‘a’]. Foreach (x, i) => console.log (i)); // 1 // filter method [‘a’, ‘b’]. filter (x => true) // [‘a’, ‘b’] // EVERY method [, ‘a’]. every (x => x ==== A ‘) // true // Some method [,’ a ‘]. Some (x => x! ==’ a ‘) // false // map method [,’ a ‘]. map (x => 1 ) // [, 1] // join method [, ‘a’, undefined, null] .join (‘## “//” #a ## “// toString method [,’ a ‘, undefined, null]. Tostring () // “, A,”
ES6 is clearly converted to undefined.
  Array.From method will turn the array to undefined, that is, this method will not ignore the vacancy.  
Array.FROM ([‘A’,, ‘B’]) / / [“A”, undefined, “B”]

The extended operator (…) will also turn the space to undefined.
   [... ['a', 'b']] // ["a", undefined, "b"] 

Copywithin () will be empty Copy together.

[, ‘a’, ‘b’,]. Copywithin (2, 0) // [, “a”, “a”]

Fill () will regard vacancy as a normal array position.
   New Array (3) .fill ('A') / / ["A", "A", "A"] 

for … of loop is also traversed.
 Let Arr = [,,]; for (Let I Of Arr) {Console.log (1);} // 1 // 1   
In the above code, the array Arr has two spaces, and for … of it does not ignore them. If it is changed to the MAP method, the vacancy is skipped.
Entries (), keys (), values ​​(), find (), and findex () are processed into 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’]. Findex (x => true) // 0
  Since the processing rules of the vacancy are very uniform, it is recommended to avoid There is a vacancy.  
More about JavaScript-related content, readers who are interested in JavaScript can be viewed on this site: “ECMAScript6 (ES6) Getting Started Tutorial,” JavaScript Array Operation Skills Summary “,” JavaScript Character and String Operation Skill Summary “, “JavaScript Data Structure and Algorithm Skill Summary”, “JavaScript Error and Debug Skill Summary” and “Summary of JavaScript Mathematical Computing Method”
I hope this article will help you JavaScript programming.

© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment