Reputation: 25
I'm trying to create a very simple nested for loop to print out every item in an NxN (for any N) array. It seems easy, but I keep getting this error:
"TypeError: Cannot read property '0' of undefined"
I've tried multiple ways of accessing each item/sub-item in the array, but no luck. I keep getting the same error. (And the array bing fed into the function is definitely NxN.)
This is my code:
const twoDimensionalArray = [
[3, 4, 2, 4],
[2, 1, 5, 7],
[5, 3, 3, 2],
[3, 6, 1, 5]
];
function printMatrix(arr) {
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length[i]; i++) {
console.log(arr[i][j]);
};
};
}
console.log(printMatrix(twoDimensionalArray));
Upvotes: 1
Views: 45
Reputation: 566
import React, { Component, Fragment } from "react";
class App extends Component {
constructor() {
super();
this.state = {
twoDimensionalArray: [
[3, 4, 2, 4],
[2, 1, 5, 7],
[5, 3, 3, 2],
[3, 6, 1, 5]
]
};
this.printMatrix(this.state.twoDimensionalArray);
}
printMatrix = arr => {
arr.forEach(sub => {
sub.forEach(item => {
console.log(item);
});
});
};
render() {
return <Fragment />;
}
}
export default App;
Upvotes: 0
Reputation: 6112
You could use for..of
to stop worrying about the indices. It becomes really simple.
const twoDimensionalArray = [
[3, 4, 2, 4],
[2, 1, 5, 7],
[5, 3, 3, 2],
[3, 6, 1, 5]
];
function printMatrix(arr) {
for (let i of arr) {
for (let j of i) {
console.log(j);
}
}
}
printMatrix(twoDimensionalArray);
This has been mentioned in a comment above, as well.
Upvotes: 1
Reputation: 191
Please use below code with small correction. always try to store the intermediate stage into local variables and use it for better performance
function printMatrix(arr) {
let mainArrayLength = arr.length;
for (let i = 0; i < mainArrayLength; i++) {
let subArray = arr[i];
let subArrayLength = subArray.length;
for (let j = 0; j < subArrayLength ; i++) {
console.log(subArray[j]);
};
};
}
Upvotes: 1
Reputation: 14927
Here's your code with the corrections pointed out in the comments
arr.length[i]
-> arr[i].length
i++
-> j++
console.log(printMatrix(twoDimensionalArray))
-> printMatrix(twoDimensionalArray)
const twoDimensionalArray = [
[3, 4, 2, 4],
[2, 1, 5, 7],
[5, 3, 3, 2],
[3, 6, 1, 5]
];
function printMatrix(arr) {
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
console.log(arr[i][j]);
};
};
}
printMatrix(twoDimensionalArray);
Upvotes: 2