SitePoint Sponsor

User Tag List

Page 1 of 2 12 LastLast
Results 1 to 25 of 29
  1. #1
    SitePoint Addict tlacaelelrl's Avatar
    Join Date
    Apr 2011
    Location
    Mexico city, Mexico
    Posts
    353
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    number of elements in array

    how can I get the number of elements in an array

    Code JavaScript:
    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?

  2. #2
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    menu_unidades_yolo.length

  3. #3
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,713
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    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
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  4. #4
    SitePoint Addict tlacaelelrl's Avatar
    Join Date
    Apr 2011
    Location
    Mexico city, Mexico
    Posts
    353
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by mrhoo View Post
    menu_unidades_yolo.length

    I tried that before coming here and it gives me undefined

  5. #5
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,713
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by tlacaelelrl View Post
    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?
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  6. #6
    SitePoint Enthusiast
    Join Date
    Jun 2011
    Posts
    52
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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:

    Code:
    for(var i in YourArray)
    {
    if (menu_unidades_yolo[i].href == current_url){
    menu_unidades_yolo[i].className = myclass;
    }
    no need to increment i

  7. #7
    SitePoint Addict tlacaelelrl's Avatar
    Join Date
    Apr 2011
    Location
    Mexico city, Mexico
    Posts
    353
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by anarch View Post
    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:

    Code:
    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?

  8. #8
    SitePoint Enthusiast
    Join Date
    Jun 2011
    Posts
    52
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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

  9. #9
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,713
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by anarch View Post
    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.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  10. #10
    SitePoint Enthusiast
    Join Date
    Jun 2011
    Posts
    52
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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...

  11. #11
    SitePoint Enthusiast
    Join Date
    Jun 2011
    Posts
    52
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.

  12. #12
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,713
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by anarch View Post
    why would a foreach ever be a bad idea when dealing with an array?
    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.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  13. #13
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,713
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by anarch View Post
    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.
    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.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  14. #14
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,192
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Quote Originally Posted by paul_wilkins View Post
    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.
    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...
    Code JavaScript:
    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.

  15. #15
    SitePoint Enthusiast
    Join Date
    Jun 2011
    Posts
    52
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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):
    Code:
    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

  16. #16
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,713
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by anarch View Post
    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.
    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.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  17. #17
    SitePoint Enthusiast
    Join Date
    Jun 2011
    Posts
    52
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    meh, i comprehend the concepts behind JS and it's ability to be dynamic but it pains me to be inefficient thanks for the link

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

  18. #18
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,713
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by anarch View Post
    meh, i comprehend the concepts behind JS and it's ability to be dynamic but it pains me to be inefficient 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.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  19. #19
    SitePoint Enthusiast
    Join Date
    Jun 2011
    Posts
    52
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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

  20. #20
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,713
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by anarch View Post
    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.

    Code javascript:
    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.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  21. #21
    SitePoint Addict tlacaelelrl's Avatar
    Join Date
    Apr 2011
    Location
    Mexico city, Mexico
    Posts
    353
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Going back to the question, you asked how I was using length here it is

    Code JavaScript:
    var menu = document.getElementById('someid');
    menu_ = menu.getElementsByTagName('a');
    alert(menu_.lenght);
    var x = menu_.lenght;
    alert(x);

    Both alerts give me undefined however if I assign the lenght of the array myself I can loop through the elements without any problems, also what anarch posted works fine although it works I would like to learn what am I doing wrong when using the lenght property

  22. #22
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,713
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by tlacaelelrl View Post
    I would like to learn what am I doing wrong when using the lenght property
    The spelling is length, not lenght

    When you assign it yourself to lenght you are instead creating a separate property value on that array.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  23. #23
    SitePoint Enthusiast
    Join Date
    Jun 2011
    Posts
    52
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    lol... i already told you I understood all of that

    now lets see your views on x64 assembly arrays before you start drilling people's spelling
    Code:
    PUBLIC TestU
    TestU PROC
       ADD    ECX, DWORD PTR [RSP+11H] 
       ADD    ECX, R9D                 
       ADD    ECX, R8D                 
       ADD    ECX, EDX                 
       MOVD   XMM0, ECX                
       CVTDQ2PD  XMM0, XMM0            
       MOVSD  XMM1, realVal            
       ADDSD  XMM1, MMWORD PTR [RSP+20H]
       DIVSD  XMM0, XMM1               
       RET                             
    TestU ENDP
    End
    how r i implementing your beloved JS?

  24. #24
    SitePoint Addict tlacaelelrl's Avatar
    Join Date
    Apr 2011
    Location
    Mexico city, Mexico
    Posts
    353
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by paul_wilkins View Post
    The spelling is length, not lenght

    When you assign it yourself to lenght you are instead creating a separate property value on that array.
    WOW, I canīt beleive this, the spelling was my problem oh well, next time when something does not work as expected I will step back and look closely before I ask any more of this stupid questions.

    Thank you

  25. #25
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,713
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by anarch View Post
    now lets see your views on x64 assembly arrays before you start drilling people's spelling
    This is when people need to stop and take another think about things.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •