我正在尝试拼接奇数/偶数,看这个,我试图找到奇数,但在结果数组中,偶数仍然存在,
function find(index){
for(var i = 0 ; i < index.length;i++) {
for(var j = 0 ; j < index[i].length ; j++) {
if(index[i][j] % 2 === 1) { // trying to find odd numbers
index[i].splice(j, 1)
}
}
}
return index
}
var data = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
var another = [
[2, 2, 7],
[1, 3, 5, 6],
[1, 3, 5, 7, 9, 11]
]
console.log(find(data))
console.log(find(another))
我的代码有问题吗??或者我错过了什么? :)
最佳答案
问题是你在遍历数组时改变了它。
即。在第二个数组的第二行 ([1,3,5,6]
),让我们想想会发生什么:
- 我=1,j=0
- 数字 (1) 是奇数,所以拼接它,数组现在看起来像
[3,5,9]
- i = 1, j = 1, 数是5,是奇数,所以你把它去掉。你跳过了 3 个。
- i=1,j=2,行长为2,循环结束。
我已经在您的代码中添加了一个控制台日志来演示这一点。
function find(index){
for(var i = 0 ; i < index.length;i++) {
for(var j = 0 ; j < index[i].length ; j++) {
if (i ===1) console.log(`i = ${i}, j=${j}, index[i] = ${index[i]}, index[i].length=${index[i].length}`);
if(index[i][j] % 2 === 1) { // trying to find odd numbers
index[i].splice(j, 1)
}
}
}
return index
}
var another = [
[2, 2, 7],
[1, 3, 5, 6],
[1, 3, 5, 7, 9, 11]
]
console.log(find(another))
所以一般来说,作为一个规则,不要遍历数组并改变它们。
相反,我建议使用 Array.prototype methods在你可以的地方,而不是循环。
A CertainPerformance 建议 - 您可以在此处使用过滤器。
function find(array){
//Assuming array is a 2d array.
return array.map(row => row.filter(v => v%2 ===0));
}
var data = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
var another = [
[2, 2, 7],
[1, 3, 5, 6],
[1, 3, 5, 7, 9, 11]
]
console.log(find(data))
console.log(find(another))
请注意,这确实会返回一些空数组,您可能想保留这些空数组,或者您可能想再次过滤以删除空数组。
请注意,如果您不熟悉它 - 我使用的是 ES6 fat arrow我的回答中的语法。
关于javascript - 在多维数组中拼接奇数/偶数但结果一两个奇数/数字炫耀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54174988/