Number of elements in array

how can I get the number of elements in an array


function get_active_link(myul, myclass, menuItems){
var menu_unidades_yolo = document.getElementById(myul);
menu_unidades_yolo = menu_unidades_yolo.getElementsByTagName('a');
var number=0;
var current_url = document.location;
while (number <= menuItems){
if (menu_unidades_yolo[number].href == current_url){
menu_unidades_yolo[number].className = myclass;
}
number++;
}
}

In that function one has to specify the number of menu items for the menu that I want to make the changes, but how can I get the number of items that are stored by getElementsByTagName?

menu_unidades_yolo.length

The getElementsByTagName doesn’t give you an array, but instead gives you a node list. It is an array-like structure though, so the number of elements is obtained from the length property, which would be menu_unidades_yolo.length

I tried that before coming here and it gives me undefined

That seems to imply then that the getElementById is resulting in undefined as well.

Can you provide a test page that demonstrates the problem, so that a proper diagnosis/solution can be provided?

I’m not sure exactly what’s going on in your code but i’m guessing you want menuItems to be the number of elements in the array to avoid running over it’s the arrays indices

if that’s correct… you should use the equivalent of foreach;
ie:


for(var i in YourArray)
{
if (menu_unidades_yolo[i].href == current_url){
menu_unidades_yolo[i].className = myclass;
} 

no need to increment i

yes that is what I was trying to achieve thank you.

Do you know why the lenght property gives me undefined?

can I see how you were using it? i’m thinking it’s because you may have been accidentally setting the length of the array rather than retrieving it

lol… I can’t believe the guru didn’t tell you to use foreach xD
bad programming practices are bad, mmkay? j/k

Using foreach to loop over an array, even an array-like structure of a node list, is a bad programming practice.

The best practice for arrays is to obtain the length of the array and use that array length to loop through the array.
If you are changing the node list that you’re looping through, you should loop backwards through the node list.

The foreach method should only be used when accessing properties of an object, and even then you should use hasOwnProperty to check that the properties you are accessing aren’t inherited, and belong to the object itself.

hmm, I don’t follow bud. don’t take it personally. I’m a scrub with JS.

why would a foreach ever be a bad idea when dealing with an array?.. what if one would like to add another element on the last sequence through the array? if .length isn’t called within the actual for loop parameter than you’ll pass through without properly assessing the array.

you said;

The foreach method should only be used when accessing properties of an object, and even then you should use hasOwnProperty to check that the properties you are accessing aren’t inherited, and belong to the object itself.

Arrays in javascript ARE objects and .length is a property of said object… from what I can tell stepping through the process making a call to .length is a time consuming method which literally counts the number of indices within the array to return the index of the last node…

i just don’t see how counting the indices every single iteration of a loop through an array could ever be as efficient as calling upon (whatever it’s called in javascript) movenext() upon iteration.

That’s a good question: the for…in documentation page explicitly states that it should not be used for arrays.

The reason why is that for…in loops over all of the properties of an object, even properties that aren’t array indexes, and properties and methods that others may have added to the array object without your knowledge.

It’s not about efficiency in this case, but in brittleness of your code. Using for…in for arrays results in code that can be easily broken when other code modifies the array object. That’s why even the for…in documentation explicitly declares that it should not be used for looping over arrays.

That is the reason i also use the length property as well, at one point i was writing a script and while using for…in i found values that only became part of the array while the loop was in progress. When i simply used…

for (var i = 0; i < array.length; i++)

The issue was fixed because the increment length was the absolute length and not the dynamic length.

hmm. i guess that’s one of the drawbacks of javascript having such loose variable classification. While I get your point, it seems like an indefinite amount of work more to use .length than stepping through the array and manually skipping anything not of the type you’re looking for.

for instance (going a little pseudo here cuz i suck at JS):


var i = 0;
for(i in array){
if check.typeof == string
do this
}

i’m guessing this is warned against because the browser might be changing the type dynamically to optimize the foreach?

damn loose languages X_X - loose languages sink methods O_O

JavaScript is different, that’s for sure. There are many differences that can cause problems when bringing habits in from other programming languages.

People like Douglas Crockford have been doing good work though when it comes to plumbing the depths of the language.

If you want an in-depth intro to the language, the Crockford on JavaScript series of videos lectures are a must-see.

meh, i comprehend the concepts behind JS and it’s ability to be dynamic but it pains me to be inefficient :lol: thanks for the link

couldn’t you bypass all of these problems by declaring private variables in the function to build the array with?

The prototypal inheritance that JavaScript has is capable of simulating classes and public/private variables, but arrays are all prototyped from the Array object so you’ll still be at mercy of any code that runs before your own. Also instead of class-based patterns, there are better design patterns available to JavaScript due to prototypal inheritance which was inspired from languages such as Scheme and Self.

You may have been able to get away with using for…in in a different language. In JavaScript though, it’s used only for iterating over the properties of an object. It’s time to do things in JavaScript the proper way.’

If your JavaScript interpreter is recent enough, at version 1.6 or better, arrays have a built-in .foreach() method that can be used. However, you’ll find that web browsers such as Internet Explorer are only at version 1.3 so array length techniques must be used there instead.

You’ll find that cross-browser compatibility issues across several web browsers are commonly responsible for many JavaScript coding patterns that at first glance don’t seem to make sense.

heh… i’d rather just avoid JS all togethor when possible. I’d hardly call it a programming language. foreach in most languages is designed specifically for handling arrays with the benefit of processing objects in an array-like processing fashion. hopefully .net schemas will become more popular in the future

As mentioned earlier, JavaScript has forEach() for arrays too.


var nums = [1, 2, 3, 4],
    sum = 0;
nums.forEach(function (value, index, array) {
    sum += value;
});

The problem you’ll face though is that web browsers don’t all use the same version of JavaScript. The forEach() method is a version 1.6 feature, where-as some web browsers only support an earlier version of JavaScript. That’s why web browsers are known to be one of the most hostile programming environment to develop in.

There are many other method available to arrays too from version 1.8, such as filter(), map() and reduce(), but while modern web browsers can support such features, it is the capabilities of other web browsers such as Internet Explorer (or the lack of them) that frustrates the best of intentions.