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
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):
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.