0
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.

0

4 Answers 4

4

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++) 
Sign up to request clarification or add additional context in comments.

1 Comment

Maybe an explanation why the OP's code doesn't work and how this is different and why it works? I don't want to steal your thunder :)
2
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:)

Comments

2

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.

1 Comment

+1 for an array's .length property will be one higher than the current highest element index
1

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); 
}

1 Comment

Note that < is needed rather than <=.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.