Sorry I’m new here and my code will probably not be properly displayed…
how would I iterate through document to find arrays with .each()?
I was thinking something like this:
//-----START OF CODE----\\
var a = new Array("a0", "a1", "a3");
var b = new Array("b0", "b1", "b3");
var i = 0;
function CountArrays()
{
$('Array').each(function(){
i++;
});
alert("There are " + i + " arrays in this document!");
}
CountArrays();
//-----END OF CODE----\\
But $(‘Array’) doesn’t seem like the way to go, because I don’t receive an alert!
Thanks for your help! 🙂
No, no. This does not work. Please get familiar with the jQuery Library.
The
$()function excepts a CSS Selector as a Parameter and returns an jQuery object, you can’t put just variables into it. Your Javascripts and your HTML are two different things.If you want to iterate over arrays in your code use the following:
There are plenty of ways to iterate over an array, see this for a reference.
Second: As mentioned using
alert()to debug is not a good idea, especially when looping something.Use
console.log('string', variable)instead when you are using Chrome or Firefox. It’s writing your variables straight into the console and it also logs complete objects which is not possible withalert().Update after comment: It’s not possible to iterate over all existing arrays in your javascript. That’s because you can’t list all existing variables. One problem is, that your creating a new scope with every new function.
The variables inside the function don’t know about the ones outside. So for example this is a valid piece of code:
Both variables are called
a, but they contain different data.For further info see this answer: https://stackoverflow.com/a/2051693/735226
And just by the way: Why do you even want to know how many arrays there are in your scripts? And since objects can contain arrays like this
there is no way to get all arrays. Javascript is a typeless and mutable language.