有一个二维数组。我必须得到没有符号“ o”的项目。我可以使用forEach循环来做到这一点。可以使用filter方法做同样的事情吗?
1)工作正常
var array = [
['first1', 'second1', 'third1'],
['first2', 'second2', 'third2'],
['first3', 'second3', 'third3']
];
var filtered = [];
array.forEach(function (row) {
row.forEach(function (item) {
if(item.indexOf('o') === -1)
filtered.push(item);
})
});
console.log(filtered);
2)不起作用
var filtered = array.forEach(function (row) {
row.filter(function (element) {
return element.indexOf('o') === -1;
})
});
console.log(filtered); //undefined
答案 0 :(得分:0)
forEach
不返回任何内容。首先展平数组,然后过滤:
var array = [
['first1', 'second1', 'third1'],
['first2', 'second2', 'third2'],
['first3', 'second3', 'third3']
];
const filtered = array
.flat()
.filter(str => str.includes('o'));
console.log(filtered);