ES6数组扩展

2020-06-08  本文已影响0人  时不我与_

ES6 引入了许多有用的数组方法,例如:

const array = [{ id: 1, checked: true }, { id: 2,checked: false }];
array.find(item => item.id === 2 )
// {id: 2, checked: false}
array.findIndex(item => item.id === 1)
// 0
array.findIndex(item => item.id === 2) 
// 1
array.findIndex(item => item.id === 3) 
//-1
const array = [{ id: 1, checked: false }, { id: 2,checked: false }];
array.some(item => item.checked)  //false

const array = [{ id: 1, checked: false }, { id: 2,checked: true }];
array.some(item => item.checked)  //true
const array = ['a','b','c','d','e']
array.includes('a') //true
array.includes('1') // false

该方法的第二个参数表示搜索的起始位置,默认为 0。如果第二个参数为负数,则表示倒数的位置,如果这时它大于数组长度(比如第二个参数为 -4,但数组长度为 3 ),则会重置为从 0 开始。

[1, 2, 3].includes(3, 3);  // false
[1, 2, 3].includes(3, -1); // true
const arr1 = ['a', 'b'];
const arr2 = ['c'];
const arr3 = ['d', 'e'];

// ES5 的合并数组
arr1.concat(arr2, arr3);
// ES6 的合并数组
[...arr1, ...arr2, ...arr3]
// [ 'a', 'b', 'c', 'd', 'e' ]
[...'hello']
// [ "h", "e", "l", "l", "o" ]
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"
上一篇下一篇

猜你喜欢

热点阅读