使用javascript,只获取长度大于2的数组元素的更简洁的方法是什么:例如,我有这样的数组:
const myArray = [ [1,2,2,2], [1,5,7,8,2,0,2,3,5], [1,3], [4], [1,2,6,8] ];我正在使用一个令人讨厌但功能强大的for来做这件事。像这样:
for(let i=0; i<myArray.lenght; i++) {
if (myArray[i].lenght > 2) {
myfilteredarray.push(myArray);
}
}什么是一种更干净的方法?
发布于 2020-11-23 01:12:27
使用filter函数:
const myArray = [ [1,2,2,2], [1,5,7,8,2,0,2,3,5], [1,3], [4], [1,2,6,8] ];
const filtered = myArray.filter(arr => arr.length > 2);
console.log(filtered);
发布于 2020-11-23 01:14:39
只需添加:
const myArray = [ [1,2,2,2], [1,5,7,8,2,0,2,3,5], [1,3], [4], [1,2,6,8] ];
const newArr = myArray.filter(item => item.length > 2);
console.log(newArr) // result [[1,2,2,2], [1,5,7,8,2,0,2,3,5], [1,2,6,8]]https://stackoverflow.com/questions/64957081
复制相似问题