ES6 - Some common methods added to arrays

This article introduces some common methods added to ES6 arrays.

1,Array.from()

Array.from()The method is used to convert two types of objects into real arrays: array-like objects and iterable objects
(including ES6 new data structures Set and Map).

Here's an array-like object that Array.from()turns it into a real array.

let arrayLike = {
    
    
    '0': 'a',
    '1': 'b',
    '2': 'c',
    length: 3
};

// ES5 的写法
var arr1 = [].slice.call(arrayLike); // ['a', 'b', 'c']

// ES6 的写法
let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']

In practical applications, the common array-like objects are the NodeList collection or HTMLCollection collection for obtaining DOM nodes, as well as the argumentsobjects inside the function. Array.from()can turn them into real arrays.

See the following examples:

    <div class="container">
      <div class="item">安柏</div>
      <div class="item">优菈</div>
      <div class="item">神里绫华</div>
    </div>
      // HTMLCollection 伪数组
	  const itemList = document.getElementsByClassName("item") // HTMLCollection(3) [div.item, div.item, div.item]
	  // NodeList 伪数组
      const itemList2 = document.querySelectorAll(".item") //NodeList(3) [div.item, div.item, div.item]

      // 1,直接进行遍历会报错 因为不是一个真正的数组,所以不能使用forEach,map,filter等数组遍历的方法
      itemList.map((item)=>{
    
    console.log(item);}) // 报错信息: itemList.map is not a function

      // 2,使用Array.from转为真数组
      const newItemList = Array.from(itemList)

      // 3,可以遍历成功
      newItemList.map((item)=>{
    
    console.log(item);})
	  // 遍历结果
 	  <div class="item">安柏</div>
      <div class="item">优菈</div>
      <div class="item">神里绫华</div>

In the above code, the sum method returns an array of object-like objects (also called a pseudo-array), which can be converted into a real array, and then use array methods such as map() querySelectorAll().getElementsByClassName

注意:As long as it is a data structure that deploys the Iterator interface, Array.from()it can be converted into an array.

      Array.from("Eula-优菈"); // ['E', 'u', 'l', 'a', '-', '优', '菈']

      let mySet = new Set(["Eula", "优菈"]);
      Array.from(mySet); //['Eula', '优菈']

In the above code, both String and Set structures have Iterator interface, so they can be Array.from()converted into real arrays.

-----( If you don't know about Iterator, you can read this article )------

If the argument is a real array, Array.from()an identical new array is returned.

Array.from([1, 2, 3])
// [1, 2, 3]

The spread operator ( ...) can also convert some data structures into arrays; the following case is to pass in the function to 不定参数perform cumulative calculation and return.

      function sum() {
    
    
        let sum = 0;
        const args = [...arguments];
        //  [...arguments] 已经转为真正的数组 [1, 2, 3, 4]  然后累加求和
        args.forEach((item) => {
    
    
          return (sum += item);
        });
        return sum;
      }
      let mySum = sum(1, 2, 3, 4);
      console.log("mySum:", mySum); // 10

Symbol.iteratorThe traverser interface ( ) is called behind the spread operator . If an object does not deploy this interface, it cannot be converted.

Array.from()It can also accept a function as the second parameter, which acts like an array map()method to process each element and put the processed value into the returned array.

      let arrayLike = [1, 2, 3, 4, 5];
      let newArray1 = Array.from(arrayLike, (item) => item * 2);
      console.log("newArray1:", newArray1); // [2, 4, 6, 8, 10]
      // 等同于
      let newArray2 = Array.from(arrayLike).map((item) => item * 2);
      console.log("newArray2:", newArray2); // [2, 4, 6, 8, 10]

Array.from()Various values ​​can be converted into real arrays, and mapfunctions are also provided. This actually means that as long as you have an original data structure, you can process its values ​​first, and then convert it into a canonical array structure, and then you can use a large number of array methods.


2,Array.of()

Array.of()方法Convert a set of values ​​to an array.

	  Array.of(1, 2, 3, 4); // [1, 2, 3, 4]
      Array.of(3); // [3]
      Array.of(3).length; // 1
      
      // 字符也可以
      Array.of("1",2,"3",4) //  ['1', 2, '3', 4]
      Array.of("1",2,"3",4).length // 4

The main purpose of this method is to make up for the lack of array constructors Array(). Because the number of parameters is different, Array()the behavior will be different. as follows:

  console.log(new Array()); // []
  console.log(new Array(3)); // [empty × 3]
  console.log(new Array(3,11,8)); // [3, 11, 8]

In the above code, new Array()when the method has no parameters, one parameter, or three parameters, the returned results are different. new Array()A new array of parameters is returned only if the number of parameters is at least 2 .

When the parameter has only one positive integer, it actually specifies the length of the array.

Array.of()Basically, it can be used to replace Array()or new Array(), and there is no overload caused by different parameters. It behaves very uniformly.

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 are no parameters, an empty array is returned.

Array.of()The method can be simulated with the following code.

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

3,find(),findIndex(),findLast()和findLastIndex()

find():

A method of an array instance find()that finds the first array member that meets the criteria. Its parameter is a callback function, which is executed in sequence for all array members until the first truemember whose return value is found, and then returned. Returns if there are no eligible members undefined.

[1, 4, -5, 10].find((n) => n < 0)
// -5

The above code finds the first member of the array that is less than 0.

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

In the above code, find()the callback function of the method can accept three parameters, which are the current value, the current position and the original array in turn.

findIndex:

findIndex()The method of the array instance find()is used very similar to the method, returning the position (index) of the first array member that meets the condition, or if all members do not meet the condition -1.

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

Both methods can accept a second parameter, thisthe object used to bind the callback function.

function f(v){
    
    
  return v > this.age;
}
let person = {
    
    name: 'John', age: 20};
[10, 12, 26, 15].find(f, person);    // 26

In the above code, find()the function receives the second parameter object, and the object personin the callback function points to the object.thisperson

find()and findIndex()both are checked backwards from the 0th bit of the array.

findLast()和findLastIndex():

findLast()And findLastIndex()it starts from the last member of the array, checks forward in turn, and keeps everything else the same.

const array = [
  {
    
     value: 1 },
  {
    
     value: 2 },
  {
    
     value: 3 },
  {
    
     value: 4 }
];

array.findLast(n => n.value % 2 === 1); // { value: 3 }
array.findLastIndex(n => n.value % 2 === 1); // 2

In the above example, findLast()and findLastIndex()start from the end of the array, looking for the first valuemember whose attribute is odd. As a result, the member is { value: 3 }, and the position is number 2.


4,Array.fill()

fillmethod fills an array with the given value.

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

new Array(3).fill(7)
// [7, 7, 7]

The above code shows that fillthe method is very convenient for the initialization of empty arrays. All existing elements in the array will be erased.

fillThe method can also accept second and third parameters, which specify the start and end positions of the padding.

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

The above code indicates that fillthe method starts from position 1, fills the original array with 7, and ends before position 2.

Note that if the filling type is an object, then the object at the same memory address is assigned instead of a deep copy object.

let arr = new Array(3).fill({
    
    name: "Amber"});
arr[0].name = "Eula";  // 只改了第一个, 但是后面的所有全都改变了
console.log(arr);
// [{name: "Eula"}, {name: "Eula"}, {name: "Eula"}]

5,keys(),values() 和 entries()

ES6 provides three new methods: entries(), keys()and values()— for iterating over an array.

They all return an iterator object (Iterator), which can for...ofbe traversed with a loop. The only difference is keys()the traversal of the key name, values()the traversal of the key value, entries()and the traversal of the key-value pair.

1, keys() is a traversal of key names

      let obj = {
    
    
        Amber: "安柏",
        Eula: "优菈",
        KamisatoAyaka: "神里绫华"
      };
	  // for of不支持遍历普通对象,可通过与Object.keys()搭配使用遍历
      for (let key of Object.keys(obj)) {
    
    
        console.log(key); // Amber,Eula,KamisatoAyaka  拿到的都是对象的键名
      }
      console.log(Object.keys(obj)); //(3) ['Amber', 'Eula', 'KamisatoAyaka']

2, values() is a traversal of key values

      let obj = {
    
    
        Amber: "安柏",
        Eula: "优菈",
        KamisatoAyaka: "神里绫华"
      };
      for (let key of Object.values(obj)) {
    
    
        console.log(key); // 安柏,优菈,神里绫华  拿到的都是对象的值
      }
      console.log(Object.values(obj)); //(3) ['安柏', '优菈', '神里绫华']

3. entries() is a traversal of key-value pairs

 let obj = {
    
    
        Amber: "安柏",
        Eula: "优菈",
        KamisatoAyaka: "神里绫华"
      };
      for (let key of Object.entries(obj)) {
    
    
        console.log(key);
        // ['Amber', '安柏']
        // ['Eula', '优菈']
        // ['KamisatoAyaka', '神里绫华']
      }

      console.log(Object.entries(obj));
      // 会以一个数组重新包装起来
      // [
      //   ["Amber", "安柏"],
      //   ["Eula", "优菈"],
      //   ["KamisatoAyaka", "神里绫华"]
      // ];

Another usage of the entries method is: to Objectconvert to Map, new Map()the constructor accepts an iterable entries. With Object.entriesmethod you can easily Objectconvert to Map:

  	let obj = {
    
    
        name: "Eula",
        age: 18
      };
      let map = new Map(Object.entries(obj));
      console.log(map); // Map(2) {'name' => 'Eula', 'age' => 18}

6,Array.includes()

includes can determine whether an array contains an element and return it true 或者false;

      const inc = ["a", "b", "c"].includes("a");
      console.log("inc:", inc); // true

The second parameter of this method indicates the starting position of the search, which is by default 0. If the second parameter is a negative number, it means the position of the reciprocal. If it is greater than the length of the array (for example, the second parameter is -4, but the length of the array is 3), it will be reset to 0the beginning.

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

Before this method, we usually use the array indexOfmethod to check whether it contains a certain value.

	if (arr.indexOf(el) !== -1) {
    
    
	  // ...
	}

indexOfThe method has two shortcomings. One is that it is not semantic enough. Its meaning is to find the first occurrence of the parameter value, so it is not intuitive enough to compare whether it is not equal -1. The second is that it internally uses the strict equality operator ( ===) for judgment, which will lead to NaNmisjudgment of right.

	[NaN].indexOf(NaN)
	// -1

includesUsing a different judgment algorithm, there is no such problem.

	[NaN].includes(NaN)
	// true

7. flat() and flatMap()

The array flattening method Array.prototype.flat()is also called array flattening and array dimensionality reduction.

  • When no parameter is passed, a layer is "flattened" by default, and an integer can be passed in to indicate the number of layers to be "flattened".
  • Passing an integer <=0 will return the original array, not "flattened".
  • When the Infinity keyword is used as a parameter, it will be converted into a one-dimensional array no matter how many levels of nesting.
  • If the original array has space, Array.prototype.flat() will skip the space.

See the following example:

      const arr = [1, ["a", "b"], [2, ["c"], 3]];

      // 1,不传参数时,默认“拉平”一层
      console.log(arr.flat());
      // [1, 'a', 'b', 2, ['c'], 3]

      // 2,传入一个整数参数,整数即“拉平”的层数
      console.log(arr.flat(2));
      //  [1, 'a', 'b', 2, 'c', 3]

      // 3,Infinity 关键字作为参数时,无论多少层嵌套,都会转为一维数组
      console.log(arr.flat(Infinity));
      // [1, 'a', 'b', 2, 'c', 3]

      // 4,传入 <=0 的整数将返回原数组,不“拉平”
      console.log(arr.flat(0));
      console.log(arr.flat(-6));
      // [1, ['a', 'b'], [2, ['c'], 3]]

      // 5,如果原数组有空位,flat()方法会跳过空位
      console.log([1, 2, 3, 4, 5, 6, ,].flat());
      //  [1, 2, 3, 4, 5, 6]

flatMap:

flatMap()The method executes a function (equivalent to execute Array.prototype.map()) on each member of the original array, and then executes flat()the method on the array composed of return values. This method returns a new array without changing the original array.

flatMap()The parameter of the method is a traversal function, which can accept three parameters, which are the current array member, the position of the current array member (starting from zero), and the original array.

  
  let newFlatList = [[2, 4], [3, 6], [4, 8]].flatMap((item,index,arr) => {
    
    
  	console.log("item:",item);//  [2, 4]   [3, 6]  [4, 8]
  	return [item[0]*2,item[1]*3] // 第一项*2,第二项*3,每个item都执行这个操作,最后flat扁平化数组并返回
  });
  
  console.log("newFlatList:",newFlatList); 
  //最终返回一维数组: [4, 12, 6, 18, 8, 24]

In the above case, a two-dimensional array is passed in, the first item of the two-dimensional array is multiplied by 2, and the second item is multiplied by 3; finally, the processed one-dimensional array is returned;

Notice:

  1. The flatMap method does not change the original array
  2. The flatMap method is equivalent to array.map().flat()
  3. flatMap()Only one level of array can be expanded

8,Array.reduce()

The reduce() method sequentially executes a reducer function provided by you for each element in the array. Each run of the reducer
will pass in the calculation results of the previous elements as parameters, and finally summarize the results into a single return value.

Please see this article: Explanation of ES6's new high-order function reduce()

Guess you like

Origin blog.csdn.net/qq_43886365/article/details/132087214