Newbie question regarding the length property

Discussion in 'JavaScript' started by supra411, May 2, 2013.

  1. #1
    Hi, Everybody:

    I am trying to learn JavaScript, and have a question regarding the length property. I read that you can use length to calculate the amount of members in an array. But I also read that you can use the length property to calculate the length of the string (as in how many characters that string has). Is this true? If so, how do I type the command so JavaScript know which version of length I'm trying to use?

    In a more complicated situation: I want to use a “for” loop to compare the length of a certain variable (variable name = letters) to every member of an array (array name = words). So the first length I will use is in the “for” loop condition. The second length will be used for comparing the length of the string in both the variable “letters” and each member of the array “words”. In both cases, how can I tell JavaScript which length I want to use?

    Thanks!
    Supra411
     
    Solved! View solution.
    supra411, May 2, 2013 IP
  2. #2
    It magically knows what you the variable that calls it is.

    Try out something like this:
    <script>
    var thiscar = 'Toyota';
    var mycars = new Array();
    mycars[0] = "Saab";
    mycars[1] = "Volvo";
    mycars[2] = "BMW";
    alert(thiscar.length);
    alert(mycars.length);
    </script>
    Code (markup):
     
    sarahk, May 2, 2013 IP
  3. supra411

    supra411 Peon

    Messages:
    10
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    1
    #3
    Thanks! Played around with that script, and found my answer.

    supra411
     
    supra411, May 2, 2013 IP
  4. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #4
    You can also access a string AS an array.

    var test = 'abcdef';
    alert(test[2]);

    will alert 'c'

    Just beware that if the string has any funky encoding like UTF-8, you'll only get one byte not a full multi-byte character -- hence the 'charAt' method.
     
    deathshadow, May 3, 2013 IP
    sarahk likes this.
  5. supra411

    supra411 Peon

    Messages:
    10
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    1
    #5
    T Thanks, death shadow! That was the question that I was trying to figure out.
     
    supra411, May 4, 2013 IP