The method of the array in ES6

from

The method may be from the array into two types of objects, one is the array object type (array-like-object), one is traversable (Iterable) of objects (including the new set of data structures and ES6 Map).

An array of array-turn

      
      
1
2
3
4
5
      
      
let list = document.querySelectorAll( 'ul.fancy li')
Array.from(list).forEach( function(li){
document.write(li)
})

The above code, querySelectorAllthe method returns an array-like objects, only the object into a real array, in order to use forEachthe method.

There are no lengthobjects to pass through Array.frominto the array method

      
      
1
2
3
4
5
6
7
8
      
      
let obj = {
0: 'a',
1: 'b',
2: 'c',
length: 3
}
let arr = Array.from(obj)

fromAccept parameters

Array.fromCan accept a second parameter, the array acts like mapa method, for each element processed.

      
      
1
2
3
4
5
      
      
let arr = [ 0, 1, 2, 4]
let arrnew = Array.from(arr, x => x*x)
console.log(arrnew)
// Equivalent to
let arrnew = arr.map( x => x*x)

Turn an array of strings

Array.fromString to the array, return the string length. This prevents javascriptlarger than uFFFFthe Unicodecharacters, counted as two charactersbug

      
      
1
2
3
      
      
function (string) {
return Array.from(string).length
}

of方法

of方法用于将一组值,转为数组

      
      
1
2
      
      
Array.of( 3, 11, 8) // [3 大专栏  ES6中数组的方法, 11, 8]
Array.of( 3) // [3]

find方法

find方法,用于找出第一个符合条件的数组成员,它的参数是一个回掉函数,找出一个返回值为true的成员,然后返回该成员。如果没有符合条件的则返回undefined

      
      
1
2
      
      
let array = [ 1, 2, -3, 4].find( n => n < 0)
console.log(array) // -5

find回掉函数接受三个参数,分别为当前的值当前的位置原数组

findIndex方法

用法于find方法类似,返回第一个符合条件的数组成员的位置,没有找到的话返回-1.

      
      
1
2
3
4
      
      
let index = [ 1, 5, 11, 16].findIndex( function(value, index, arr) {
return value > 9
})
console.log(index)

findfindIndex都可以借助Object.is方法做到发现数组中的NaN,而indexOf发现不了。

      
      
1
2
      
      
[ NaN].indexOf( NaN) // -1
[ NaN].findIndex( y => Object.is( NaN, y)) // 0

fill方法

fill()使用一个值来填充一个数组。

      
      
1
2
3
4
      
      
let arr = [ 'a', 'b', 'c'].fill( 7)
// [7, 7, 7]
let arrNew = new Array( 3).fill( 7)
// [7, 7, 7]

The above code shows that fillthe initialization method is very convenient for an empty array. Array elements are already erased all of them.
fillYou can also accept the second and third argument specifies the fill start position and an end position

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

Guess you like

Origin www.cnblogs.com/wangziqiang123/p/11711205.html