I'm stuck trying to figure out how to loop trough nested arrays.
I have an array called worldShapes that contains child arrays. I want to loop trough the parent array and get all the child arrays from it.
Here's my attempt:
//Nested array
worldShapes = [
[33,108,66,141,99,174,99,207,132,207,165,207,165,240],
[132,306,165,306,165,339,165,372,132,405,99,405,99,438,132,438,165,438],
[198,339,231,339,264,372,297,372,330,405,363,438,396,438],
[198,174,198,273,231,306,264,306],
[231,174,231,240,264,273,297,273],
[396,306,462,306,495,339,495,372,528,405,528,438,561,438,594,471],
[660,504,561,504,495,504]
];
//trying to loop trough each item in the child array
(function(){
var wShapes = worldShapes; //create a local variable
var wLen = wShapes.length; //store the length as a variable
for (var i = 0; i < wLen; i++) {
for (var j = 0; j < wShapes[i].length; j++){
console.log(wShapes[i][j]); //this is propably wrong, trying to access the current child item of the current parent array
}
}
})
asked Oct 5, 2013 at 17:16
Sony packman
8402 gold badges10 silver badges21 bronze badges
-
What is the expected output?thefourtheye– thefourtheye2013年10月05日 17:18:55 +00:00Commented Oct 5, 2013 at 17:18
-
What's wrong with your code? Did you tried to run it?leesei– leesei2013年10月05日 17:19:08 +00:00Commented Oct 5, 2013 at 17:19
-
1You've wrapped it in a function, but you don't execute the function. But why wrap it in a function at all?user2625787– user26257872013年10月05日 17:19:09 +00:00Commented Oct 5, 2013 at 17:19
-
Are you getting an error message with that code?lurker– lurker2013年10月05日 17:19:19 +00:00Commented Oct 5, 2013 at 17:19
-
1Your code looks absolutely correct. What is it not doing that you think it should be?Matt Patenaude– Matt Patenaude2013年10月05日 17:19:21 +00:00Commented Oct 5, 2013 at 17:19
2 Answers 2
Just add (); to the very end of your code ;-)
You've simply forgotten to invoke your anonymous function
answered Oct 5, 2013 at 17:21
gzak
4,1007 gold badges38 silver badges61 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
To execute the function, add ()
(function () {
var wShapes = worldShapes; //create a local variable
var wLen = wShapes.length; //store the length as a variable
for (var i = 0; i < wLen; i++) {
for (var j = 0; j < wShapes[i].length; j++) {
console.log(wShapes[i][j]); //this is propably wrong, trying to access the current child item of the current parent array
}
}
}()); // here
Comments
lang-js