查找元素是否存在,存在就删除不存在就添加
this.collapseList.includes(value) ?
this.collapseList = this.collapseList.filter(item => item !== value) : this.collapseList.push(value);
const index = this.showMenuCheckGroupList.findIndex(item => item == value);
index > -1 ? this.showMenuCheckGroupList.splice(index, 1) : this.showMenuCheckGroupList.push(value);
数组去重
var arr = [1, 1, 2, 2, 3, 4, 5, 5, 4, 3, 2, 1] //输出 [1,2,3,4,5]
Array.from(new Set(arr))
var arr = [1, 1, 2, 2, 3, 4, 5, 5, 4, 3, 2, 1] //输出 [1,2,3,4,5]
[...new Set(arr)]
js中遍历数组并不会改变原始数组的方法总共有12个:
ES5:
forEach、every 、some、 filter、map、reduce、reduceRight
ES6:
find、findIndex、keys、values、entries
const index = Array.findIndex((item) => item[key] == value);
Array.of(3, 11, 8) // [3,11,8]
Array.of(3) // [3]
Array.of(3).length // 1
[1, 4, -5, 10].find((n) => n < 0)
// -5
[1, 5, 10, 15].find((value, index, arr)=> {
return value > 9;
}) // 10
[1, 5, 10, 15].findIndex((value, index, arr)=> {
return value > 9;
}) // 2
[1, 2, 3].includes(3, 3); // false
[1, 2, 3].includes(3, -1); // true
[NaN].indexOf(NaN)
// -1
[1, 2, [3, 4]].flat()
// [1, 2, 3, 4]
[1, 2, [3, [4, 5]]].flat()
// [1, 2, 3, [4, 5]]
[1, 2, [3, [4, 5]]].flat(2)
// [1, 2, 3, 4, 5]
const arr = [5, 12, 8, 130, 44];
arr.at(2) // 8
arr.at(-2) // 130
/ forEach方法
Array.forEach((x,i) => console.log(i)); // 1
// filter方法
Array.filter(x => true) // ['a','b']
// every方法
Array.every(x => x==='a') // true
// reduce方法
Array.reduce((x,y) => x+y) // 3
// some方法
Array.some(x => x !== 'a') // false
// map方法
Array.map(x => 1) // [,1]
copyWithin()会连空位一起拷贝。
Array.copyWithin(2,0) // [,"a",,"a"]
// entries()
Array.entries()
// keys()
Array.keys()
// values()
Array.values()
// find()
Array.find(x => true)
// findIndex()
Array.findIndex(x => true) // 0
es6 常用
于 2021-06-20 19:57:56 首次发布