Table of Contents
es6 new array method
Home Web Front-end JS Tutorial What is the new array method in es6?

What is the new array method in es6?

Apr 11, 2022 pm 04:27 PM
es6

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]
Copy after login

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)
})()
Copy after login

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]
Copy after login
  • 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
}
Copy after login

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);
}
Copy after login

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
Copy after login

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 }
Copy after login

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
Copy after login

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
Copy after login

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"}]
Copy after login

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] ]
    Copy after login

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
Copy after login

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
Copy after login

Compatible method:

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

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]]复制代码
    Copy after login

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
Copy after login

【相关推荐: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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1672
14
PHP Tutorial
1277
29
C# Tutorial
1257
24
How to reverse an array in ES6 How to reverse an array in ES6 Oct 26, 2022 pm 06:19 PM

In ES6, you can use the reverse() method of the array object to achieve array reversal. This method is used to reverse the order of the elements in the array, putting the last element first and the first element last. The syntax "array.reverse()". The reverse() method will modify the original array. If you do not want to modify it, you need to use it with the expansion operator "...", and the syntax is "[...array].reverse()".

Is async for es6 or es7? Is async for es6 or es7? Jan 29, 2023 pm 05:36 PM

async is es7. async and await are new additions to ES7 and are solutions for asynchronous operations; async/await can be said to be syntactic sugar for co modules and generator functions, solving js asynchronous code with clearer semantics. As the name suggests, async means "asynchronous". Async is used to declare that a function is asynchronous; there is a strict rule between async and await. Both cannot be separated from each other, and await can only be written in async functions.

Why does the mini program need to convert es6 to es5? Why does the mini program need to convert es6 to es5? Nov 21, 2022 pm 06:15 PM

For browser compatibility. As a new specification for JS, ES6 adds a lot of new syntax and API. However, modern browsers do not have high support for the new features of ES6, so ES6 code needs to be converted to ES5 code. In the WeChat web developer tools, babel is used by default to convert the developer's ES6 syntax code into ES5 code that is well supported by all three terminals, helping developers solve development problems caused by different environments; only in the project Just configure and check the "ES6 to ES5" option.

How to find different items in two arrays in es6 How to find different items in two arrays in es6 Nov 01, 2022 pm 06:07 PM

Steps: 1. Convert the two arrays to set types respectively, with the syntax "newA=new Set(a);newB=new Set(b);"; 2. Use has() and filter() to find the difference set, with the syntax " new Set([...newA].filter(x =>!newB.has(x)))", the difference set elements will be included in a set collection and returned; 3. Use Array.from to convert the set into an array Type, syntax "Array.from(collection)".

How to implement array deduplication in es5 and es6 How to implement array deduplication in es5 and es6 Jan 16, 2023 pm 05:09 PM

In es5, you can use the for statement and indexOf() function to achieve array deduplication. The syntax "for(i=0;i<array length;i++){a=newArr.indexOf(arr[i]);if(a== -1){...}}". In es6, you can use the spread operator, Array.from() and Set to remove duplication; you need to first convert the array into a Set object to remove duplication, and then use the spread operator or the Array.from() function to convert the Set object back to an array. Just group.

What does es6 temporary Zenless Zone Zero mean? What does es6 temporary Zenless Zone Zero mean? Jan 03, 2023 pm 03:56 PM

In es6, the temporary dead zone is a syntax error, which refers to the let and const commands that make the block form a closed scope. Within a code block, before a variable is declared using the let/const command, the variable is unavailable and belongs to the variable's "dead zone" before the variable is declared; this is syntactically called a "temporary dead zone". ES6 stipulates that variable promotion does not occur in temporary dead zones and let and const statements, mainly to reduce runtime errors and prevent the variable from being used before it is declared, resulting in unexpected behavior.

Is require an es6 syntax? Is require an es6 syntax? Oct 21, 2022 pm 04:09 PM

No, require is the modular syntax of the CommonJS specification; and the modular syntax of the es6 specification is import. require is loaded at runtime, and import is loaded at compile time; require can be written anywhere in the code, import can only be written at the top of the file and cannot be used in conditional statements or function scopes; module attributes are introduced only when require is run. Therefore, the performance is relatively low. The properties of the module introduced during import compilation have slightly higher performance.

How to determine how many items there are in an array in es6 How to determine how many items there are in an array in es6 Jan 18, 2023 pm 07:22 PM

In ES6, you can use the length attribute of the array object to determine how many items there are in the array, that is, to get the number of elements in the array; this attribute can return the number of elements in the array, just use the "array.length" statement. Returns a value representing the number of elements of the array object, that is, the length value.

See all articles