嗨,我在编码时遇到问题,我想检查多维数组中的偶数,然后如果行或列中出现的偶数大于等于3次,则更改为“ X”,但我将其全部更改为“ X”尽管小于3。我的代码如下:
function evenNumbers(numbers){
for(var i = 0; i < numbers.length; i++){
for(var j = 0; j < numbers[i].length; j++){
if(numbers[i][j] % 2 == 0){
numbers[i][j] = 'X'
}
}
}
return numbers
}
console.log(evenNumbers([
[1, 2, 4, 6, 5],
[6, 17, 8, 11, 10],
[8, 11, 10, 18, 16],
[18, 12, 19, 27, 21],
[22, 10, 12, 22, 12]
]));
预期输出:
[1, 'X', 'X', 'X', 5],
['X', 17, 'X', 11, 10],
['X', 11, 'X', 'X', 'X'],
['X', 12, 19, 27 , 21],
[''X, 'X', 'X', 'X', 'X']
我得到了什么:
[ [ 1, 'X', 'X', 'X', 5 ],
[ 'X', 17, 'X', 11, 'X' ],
[ 'X', 11, 'X', 'X', 'X' ],
[ 'X', 'X', 19, 27, 21 ],
[ 'X', 'X', 'X', 'X', 'X' ] ]
先谢谢了 请帮助我,不要使用仅内置JS的内置ES6。再次感谢
答案 0 :(得分:0)
您可以使用其中一些进行检查,然后再映射
const arr = [
[1, 2, 4, 6, 5],
[6, 17, 8, 11, 10],
[8, 11, 10, 18, 16],
[18, 12, 19, 27, 21],
[22, 10, 12, 22, 12]
];
function xEvens(arr) {
return arr.map(row => {
let i = 0;
let shouldChange = row.some(n => n % 2 === 0 && ++i >= 3);
return shouldChange ? row.map(n => n % 2 === 0 ? 'X' : n) : row;
});
}
console.log(xEvens(arr));
es6之前的版本
var arr = [
[1, 2, 4, 6, 5],
[6, 17, 8, 11, 10],
[8, 11, 10, 18, 16],
[18, 12, 19, 27, 21],
[22, 10, 12, 22, 12]
];
function xEvens(arr) {
return arr.map(function(row) {
var i = 0;
var shouldChange = row.some(function(n) {
return n % 2 === 0 && ++i >= 3;
});
return shouldChange ? row.map(function(n) {
return n % 2 === 0 ? 'X' : n
}) : row;
});
}
console.log(xEvens(arr));
答案 1 :(得分:0)
您可以尝试以下方法:
X
替换为偶数的数组。这样,您将不需要额外的循环就可以检查替换的有效性。
function replaceEvensWithCondition(arr, minCount, replaceChar) {
return arr.map(function(row) {
var count = 0;
var updatedArray = row.map(function(n) {
var isEven = n % 2 === 0;
count += +isEven;
return isEven ? replaceChar : n;
});
return count >= minCount ? updatedArray : row
});
}
var arr = [ [1, 2, 4, 6, 5], [6, 17, 8, 11, 10], [8, 11, 10, 18, 16], [18, 12, 19, 27, 21], [22, 10, 12, 22, 12] ];
console.log(replaceEvensWithCondition(arr, 3, 'X'));