Home  >  Article  >  Web Front-end  >  What is the new array method in es6?

What is the new array method in es6?

青灯夜游
青灯夜游Original
2022-04-11 16:27:4510918browse

New array methods: 1. from(), which can convert an array-like or iterable object into a real array; 2. of(), which can convert a set of values ​​into an array, which complements the array construction Shortcomings of the function Array(); 3. find() and findIndex(), return the first array element that meets the conditions; 4. fill(), etc.

What is the new array method in es6?

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

es6 new array method

1. Array.from()

Array. The from method is used to convert two types of objects into real arrays:

  • Array-like object

  • Can be traversed (iterable) objects (including ES6’s new data structures Set and Map)

means that as long as the data structure of the Iterator interface is deployed, Array.from can convert it into Array

In actual development, it can generally be used to convert the NodeList collection returned by DOM operations, as well as the arguments object inside the function

When passing a parameter, it is used to convert the class array into a real array

  • Array deduplication

const arr = [1,2,3,3,3,2,5];
console.log(Array.from(new Set(arr))); //[1,2,3,5]
//...也可实现相同的效果
console.log([...new Set(arr)]) //[1,2,3,5]

For browsers that do not deploy this method, you can use the Array.prototype.slice method instead

cosnt toArray = (() => {
    Array.from ? Array.from : obj => [].slice.call(obj)
})()

You can also receive a second parameter. The second parameter is passed into a function to achieve an effect similar to the map method, processing each element and returning the processed array

Array.from([1,2,3] , item => item *2)    //[2,4,6]
  • Return the length of the string

can be used to convert the string into an array, and then return the length of the string, because it can correctly handle various Unicode characters, thus Avoid JS’s own bug of counting Unicode characters greater than /uFFFF as 2 characters

function countLength(string) {
    return Array.from(string).length
}

2, Array.of()

Array The .of method is used to convert a set of values ​​into an array. Make up for the shortcomings of the array constructor Array(). Because the number of parameters is different, the behavior of Array() will be different

//如下代码看出差异
Array.of(3); // [3]
Array.of(3, 11, 8); // [3,11,8]

new Array(3); // [, , ,]
new Array(3, 11, 8); // [3, 11, 8]

// Array.of方法可以用下面的代码模拟实现。

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

3. Find() and findIndex() of array instances

find()

Returns the first array member that meets the conditions. Its parameter is a callback function. All array members execute the function in sequence until the first one is found. A member that meets the conditions, and then returns the member. If there is no member that meets the conditions, it returns undefined

The callback function of this method receives three parameters: current value, current position, original array

Example 1

[1,12,4,0,5].find((item,index , arr) => return item < 1)   // 0

Example 2

// find()
var item = [1, 4, -5, 10].find(n => n < 0);
console.log(item); // -5
// find 也支持这种复杂的查找
var points = [
  {
    x: 10,
    y: 20
  },
  {
    x: 20,
    y: 30
  },
  {
    x: 30,
    y: 40
  },
  {
    x: 40,
    y: 50
  },
  {
    x: 50,
    y: 60
  }
];
points.find(function matcher(point) {
  return point.x % 3 == 0 && point.y % 4 == 0;
}); // { x: 30, y: 40 }

findIndex()

The writing and usage are basically the same as the find() method, except that the first matching The position of the array member of the condition, if there is none, -1 is returned

Example 1

[1,2,4,15,0].findIndex((item , index ,arr) => return item > 10)   //3

Example 2

var points = [
  {
    x: 10,
    y: 20
  },
  {
    x: 20,
    y: 30
  },
  {
    x: 30,
    y: 40
  },
  {
    x: 40,
    y: 50
  },
  {
    x: 50,
    y: 60
  }
];
points.findIndex(function matcher(point) {
  return point.x % 3 == 0 && point.y % 4 == 0;
}); // 2
points.findIndex(function matcher(point) {
  return point.x % 6 == 0 && point.y % 7 == 0;
}); //1

4, fill( of array instance )

  • fill() method uses the given value to fill an array
  • fill method can also accept the second and third parameters for Specify the starting position and end position of filling
// fill方法使用给定值, 填充一个数组。
var fillArray = new Array(6).fill(1);
console.log(fillArray); //[1, 1, 1, 1, 1, 1]
//fill方法还可以接受第二个和第三个参数,用于指定填充的起始位置和结束位置。
["a", "b", "c"].fill(7, 1, 2);
// [&#39;a&#39;, 7, &#39;c&#39;]
// 注意,如果填充的类型为对象,那么被赋值的是同一个内存地址的对象,而不是深拷贝对象。
let arr = new Array(3).fill({
  name: "Mike"
});
arr[0].name = "Ben";
console.log(arr);
// [{name: "Ben"}, {name: "Ben"}, {name: "Ben"}]

Both methods can find NaN in the array, but indexOf() in ES5 cannot find NaN

5. Entries(), keys() and values() of array instances

All three methods are used to traverse the array and return a traverser object, which can be used for...of loop traversal

The difference is:

  • keys() is a traversal of key names

  • ##values( ) is a traversal of key-value pairs

  • entries() is a traversal of key-value pairs

  • 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"
    var a = [1, 2, 3];
    [...a.values()]; // [1,2,3]
    [...a.keys()]; // [0,1,2]
    [...a.entries()]; // [ [0,1], [1,2], [2,3] ]

6, The includes() method returns a Boolean value

This method returns a Boolean value indicating whether an array contains a given value

[1, 2, 3].includes(2) // true
[(1, 2, 3)].includes(4) // false
can also receive a second parameter, indicating the starting position of the search, the default is 0. If the second parameter is a negative number, it indicates the position of the number. If the second parameter is greater than the length of the array, it starts from subscript 0

includes method makes up for the shortcomings of the indexOf method that is not semantic enough and misjudges NaN

[1,23,NaN].includes(NaN)   //true

Compatible method:

function contains = ( () => {
    Array.prototype.includes
    	?(arr , val) => arr.includes(val)
    	:(arr , val) => arr.some(item => return item === val)
})()

7. Flat() of array instances, flatMap()

    flat() is used to "flatten" nested arrays ", into a one-dimensional array. This method returns a new array and has no effect on the original data. The parameter passed represents how many layers to flatten. The default is one layer.
  • flatMap() can only expand one layer of array. The method executes a function on each member of the original array (equivalent to executing Array.prototype.map()), and then executes the flat() method on the array composed of the return value. This method returns a new array without changing the original array
  // flat()
  [1, 2, [3, [4, 5]]].flat()
  // [1, 2, 3, [4, 5]]
  [1, 2, [3, [4, 5]]].flat(2)
  // [1, 2, 3, 4, 5]
  //flatMap()
  [2, 3, 4].flatMap((x) => [x, x * 2])
  //map执行完后是[[2, 4], [3, 6], [4, 8]]
  //然后在执行flat()方法得到下边的结果
  // [2, 4, 3, 6, 4, 8]
  // flatMap()只能展开一层数组。
  // 相当于 .flat()
  [1, 2, 3, 4].flatMap(x => [
    [x * 2]
  ])
  //map执行完后是[[[2]], [[4]], [[6]], [[8]]]
  //然后在执行flat()方法得到如下结果
  // [[2], [4], [6], [8]]复制代码

8. The copywithin() of the array instance

is in the current array Internally copies the members at the specified position to other positions, and then returns the current array, which will change the original array

Receives three parameters:

1. target (required) Replace data starting from this position

2、start(可选) 从该位置开始读取数据,默认为0,如果为负数,则表示到数

3、end(可选) 到该位置前停止读取数据,默认等于数组长度。如果是负数,表示到数

三个参数都应该是数字,如果不是,会自动转为数值

[1,2,3,4,5].copywithin(0,3);  //[4,5,3,4,5]  表示从下标3位置直到结束的成员(4,5),复制到从下标0开始的位置,结果替换掉了原来的1和2

【相关推荐:javascript视频教程web前端

The above is the detailed content of What is the new array method in es6?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn