Hi Community I struggle to understand the following behavior. Its a typicall Monday problem. All I want is to fill the empty array slots with the integer 0.
myArray = [
[1, ,1, ],
[ , ,1, ],
[ , ,1, ],
[1, , , ],
]
for (var a = 0; a < myArray.length; a ) {
for (var b = 0; b < myArray[a].length; b ) {
if (myArray[a][b] == undefined) {
myArray[a][b] = 0
}
}
console.log("myArray[" a "][" b "]" " = " myArray[a][b])
}
CodePudding user response:
You are trying to access b
outside the loop
Just move it to the loop
myArray = [
[1, , 1, ],
[, , 1, ],
[, , 1, ],
[1, , , ],
]
for (var a = 0; a < myArray.length; a ) {
for (var b = 0; b < myArray[a].length; b ) {
if (myArray[a][b] == undefined) {
myArray[a][b] = 0
}
console.log("myArray[" a "][" b "]" " = " myArray[a][b])
}
}
Also, better never use var
:
myArray = [
[1, , 1, ],
[, , 1, ],
[, , 1, ],
[1, , , ],
]
for (let a = 0; a < myArray.length; a ) {
for (let b = 0; b < myArray[a].length; b ) {
if (myArray[a][b] == undefined) {
myArray[a][b] = 0
}
}
console.log("myArray[" a "][" b "]" " = " myArray[a][b])
}
If you would use let
you will get an error without debugging
CodePudding user response:
Another way to fill-in empty values with zerro
const myArray = [
[1, ,1, ],
[ , ,1, ],
[ , ,1, ],
[1, , , ],
];
const filled = myArray.map(level1 => [...level1].map(value => value ? value : 0));
console.log(filled);
.as-console-wrapper { max-height: 100% !important; top: 0 }
CodePudding user response:
The OP code was logging values within the outer loop which is out of scope of b
which was defined within the inner loop. Log properties right after they are defined which in your case should be the inner loop.
const arrArrs = [
[ 1, '', 1, '' ],
[ '', '', 1, '' ],
[ '', '', 1, '' ],
[ 1, '', '', '' ]
];
for (let a = 0; a < arrArrs.length; a ) {
for (let b = 0; b < arrArrs[a].length; b ) {
if (arrArrs[a][b] != '') {
console.log(`arrArrs[${a}][${b}] = ${arrArrs[a][b]}`);
continue;
}
arrArrs[a][b] = 0;
console.log(`arrArrs[${a}][${b}] = ${arrArrs[a][b]}`);
}
}
console.log(JSON.stringify(arrArrs));