Several methods to change data to array

Several methods to change data to array


id method scenes to be used
1 Array.from() 1. Array-like objects 2. Traversable objects
2 Spread operator... 1. Obtain the argumentsparameter object of the function 2. NodeList obtained by Dom operation
3 split('') 1. Split the string into an array
4 Array.of() 1. Convert a set of values ​​into an array

1. Array.from() method (method in es6)

  • Usage scenario: This method can only convert array-like objects and traversable objects into arrays.
  • eg1: Array-like objects (including the arguments object inside the function and the NodeList returned by Dom)
//  这里的对象得有伪索引,数组长度
let arr = {
    
    
  0: 'a',
  1: 'b',
  length: 2
}

a = Array.from(arr)
console.log(a) // [ 'a', 'b' ]
  • eg2: Traversable objects
//  字符串部署了Iterator接口,可遍历
let arr = Array.from('hello')
console.log(arr)// [ 'h', 'e', 'l', 'l', 'o' ]

2. Spread operator...

  • Usage scenario: 1) NodeList returned by Dom operation. 2) Arguements object of function.
  • eg1: Dom operation
//  获取所有的P标签
let a = document.querySelectorAll('p');
//  将p标签转换成数组,并过滤到p中文字长度小于等于100的标签
a = Array.from(a).filter(n => n.textContent.length > 100) // (4) [p, p, p, p]

-eg2: the arguments object of the function

//  
function foo() {
    
    
  return [...arguments]
}
console.log(foo(1, 2, 3, 4, 5, 6)) //[ 1, 2, 3, 4, 5, 6 ]

3. Split('') method

  • Usage scenario: convert a string into an array
  • eg1:
let arr = Array.from('hello')
console.log(arr) // [ 'h', 'e', 'l', 'l', 'o' ]

4. Array.of() method (es6)

  • Usage scenario: Convert a set of values ​​into an array
  • This method is to make up for the shortcomings of Array(), because only when the parameter length of Array() exceeds two, it will return an array, otherwise it will only specify the length of the array.
  • eg1:
//  只有一个参数时也会返回新的数组,Array()不会.
let arr = Array.of(1)
console.log(arr);

//  返回新的数组
let arr = Array.of(1, 2, 3, 4, 5)
console.log(arr);// [ 1, 2, 3, 4, 5 ]

Guess you like

Origin blog.csdn.net/weixin_40944062/article/details/105045204