gpt4 book ai didi

javascript - 带有二维数组的嵌套 for 循环

转载 作者:行者123 更新时间:2023-11-29 21:02:56 24 4
gpt4 key购买 nike

如何替换数组中可以乘以 2 的数字,字符串“偶数”和“奇数”。

var numbers = [
[243, 12, 23, 12, 45, 45, 78, 66, 223, 3],
[34, 2, 1, 553, 23, 4, 66, 23, 4, 55],
[67, 56, 45, 553, 44, 55, 5, 428, 452, 3],
[12, 31, 55, 445, 79, 44, 674, 224, 4, 21],
[4, 2, 3, 52, 13, 51, 44, 1, 67, 5],
[5, 65, 4, 5, 5, 6, 5, 43, 23, 4424],
[74, 532, 6, 7, 35, 17, 89, 43, 43, 66],
[53, 6, 89, 10, 23, 52, 111, 44, 109, 80],
[67, 6, 53, 537, 2, 168, 16, 2, 1, 8],
[76, 7, 9, 6, 3, 73, 77, 100, 56, 100]
];

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] += " even";
} else {
numbers [i][j] += " odd";
}

console.log(numbers[j][i]);
}
}

最佳答案

如果你的意思是用字符串替换数字,你可以这样做,但数组必须定义为任何:

 const numbers: any = [
[243, 12, 23, 12, 45, 45, 78, 66, 223, 3],
[34, 2, 1, 553, 23, 4, 66, 23, 4, 55],
[67, 56, 45, 553, 44, 55, 5, 428, 452, 3],
[12, 31, 55, 445, 79, 44, 674, 224, 4, 21],
[4, 2, 3, 52, 13, 51, 44, 1, 67, 5],
[5, 65, 4, 5, 5, 6, 5, 43, 23, 4424],
[74, 532, 6, 7, 35, 17, 89, 43, 43, 66],
[53, 6, 89, 10, 23, 52, 111, 44, 109, 80],
[67, 6, 53, 537, 2, 168, 16, 2, 1, 8],
[76, 7, 9, 6, 3, 73, 77, 100, 56, 100]
];

for (let i = 0; i < numbers.length; i++) {
for (let j = 0; j < numbers[i].length; j++) {
if ( numbers[i][j] % 2 === 0) {
numbers [i][j] = 'even';
} else {
numbers [i][j] = 'odd';
}
}
}

关于javascript - 带有二维数组的嵌套 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45562650/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com