Reputation: 9
var myArray = ['burak', 'mirhan', new Date(), 'ibrahim'];
for (var i = 0; i <= myArray[i].toString ().length; i++) {
alert (myArray [i].toString ().length);
}
ı wrote the code above. it works. but firebug alerts that "myArray[i] is not defined". I can't solve it. Can you help me on this ? As you can understand I am little bit noob on javascript. I am trying to learn so thank you for your help.
Upvotes: 0
Views: 120
Reputation: 97691
When you iterate over an array, you should be simply be looking at the length of the array, not the length of the string in the current element of the array:
for (var i = 0; i < myArray.length; i++)
Upvotes: 4
Reputation: 150080
In JavaScript, array indices start at 0
, and an array's .length
property will be one higher than the current highest element index. So for your array with four contiguous elements the .length
will be 4 and the element indices are 0, 1, 2 and 3.
You need to set up your loop to run from 0
to .length - 1
, so use i < myArray.length
rather than i <= myArray[i].toString ().length
:
for (var i = 0; i < myArray.length; i++)
The reason you though your code was working other than that error is that because you had i <= myArray[i].toString ().length
it was testing i
against the length of the toString()
values of elements in the array rather than against the length of the array itself. So on the first iteration when i
was 0 it would test if 0 is less than or equal to the length of the first element in the array, on the second iteration it tests if i
is less than the length of the second element, and so forth. Because all items in your array had a .toString().length
greater than the length of the array itself your loop did iterate through all of the elements, but then when i
got to 4
it tried to test an element that didn't exist.
Upvotes: 2
Reputation: 30092
Assuming you want to loop over each item in the array, you need to get the array length:
var myArray = ['burak', 'mirhan', new Date(), 'ibrahim'];
for (var i = 0; i < myArray.length; i++) {
alert (myArray [i].toString ().length);
}
Upvotes: 1
Reputation: 28511
var myArray = ['burak', 'mirhan', new Date(), 'ibrahim'];
for (var i = 0, len = myArray.length; i < len; i++) {
console.log(myArray[i]);
};
If you are a JS efficienado:)
Upvotes: 2