I created the following 2D array in Javascript
// Create basic linear array
var ImgArray = new Array(4);
// Do the 2D array for each or the linear array slots
for (i=0; i < 4 ; i++) {
ImgArray[i] = new Array(4)
}
Now i want to iterate through it using 2 ‘ enhanced for loops’. But am stuck on how to use the loop as there is only ImgArray stated a such. For example;
// Load the images
for(var i in ImgArray) {
for( ??? ) { // How would i do this? What do i state as an array?
///...
}
document.write("<br>");
}
Any advise well appreciated
Assuming the array you’ve created, the loop looks like this:
This is because there are no two-dimensional arrays in JavaScript. (In fact, even arrays aren’t really arrays, but let’s not go there.) There are “arrays”, and an array entry can be another array, but one array entry might be longer or shorter than others. So you retrieve that array and loop through its length, which may be different than others in the same “dimension”.
Note that I didn’t use
for..inabove. Don’t usefor..into loop through arrays unless you really know what you’re doing; details here. (If you do really know what you’re doing and take adequate precautions, it’s fine, but your quoted code isn’t taking the necessary precautions.)for..indoes not iterate the indexes of an array, it enumerates the property names of an object.Off-topic #1: In JavaScript, the convention (which you’re free to ignore) is to only use initial caps (
ImgArray) for constructor functions.Off-topic #2: You might look at using array literals (
[entry, entry, entry]) rather thannew Array(...), but it depends on what you’re doing.Off-topic #3: It’s a very bad idea to rely on semicolon insertion (as with your
ImgArray[i] = new Array(4)line). Make sure to put in the semicolons where they’re needed, or you’ll find that you can’t minify your scripts properly and/or that you’ll fight odd bugs that waste your time. 🙂