What is the new array method in 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.
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); // ['a', 7, 'c'] // 注意,如果填充的类型为对象,那么被赋值的是同一个内存地址的对象,而不是深拷贝对象。 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
[1,23,NaN].includes(NaN) //true
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 arrayReceives three parameters:1. target (required) Replace data starting from this position2、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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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()".

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.

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.

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)".

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.

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.

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.

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.
