8.ES6 数组

数组创建

Array.of()
将参数中所有值作为元素形成数组。

console.log(Array.of(1, 2, 3, 4)); // [1, 2, 3, 4]
 
// 参数值可为不同类型
console.log(Array.of(1, '2', true)); // [1, '2', true]
 
// 参数为空时返回空数组
console.log(Array.of()); // []
Array.from()
将类数组对象或可迭代对象转化为数组。
// 参数为数组,返回与原数组一样的数组 console.log(Array.from([1, 2])); // [1, 2] // 参数含空位 console.log(Array.from([1, , 3])); // [1, undefined, 3]
// 伪数组转为数组

 let lis = document.querySelectorAll('li')
  console.log(Array.from(lis));

 

方法  find() findIndex()

 // find()找出第一个符合条件的数组成员 
let num = [1, 2, -10, -20, 9, 2].find(n => n < 0)
console.log(num); //-10

// findIndex()找出第一个符合条件的数组成员的索引
let numIndex = [1, 2, -10, -20, 9, 2].findIndex(n => n < 0)
console.log(numIndex); //2

  

entries() keys() values() 返回一个遍历器 可以使用for...of循环进行遍历
entries() 对键值对遍历

for(let [key, value] of ['a', 'b'].entries()){
    console.log(key, value);
}
// 0 "a"
// 1 "b"
 
// 不使用 for... of 循环
let entries = ['a', 'b'].entries();
console.log(entries.next().value); // [0, "a"]
console.log(entries.next().value); // [1, "b"]
 
// 数组含空位
console.log([...[,'a'].entries()]); // [[0, undefined], [1, "a"]]

 keys() 对键名遍历
 values() 对值遍历

遍历键名。

for(let key of ['a', 'b'].keys()){
    console.log(key);
}
// 0
// 1
 
// 数组含空位
console.log([...[,'a'].keys()]); // [0, 1]
遍历键值。

for(let value of ['a', 'b'].values()){
    console.log(value);
}
// "a"
// "b"
 
// 数组含空位
console.log([...[,'a'].values()]); // [undefined, "a"]
原文地址:https://www.cnblogs.com/sunny666/p/12984555.html