0

I'm trying to implement jquery hotkeys in a for loop.

acKey = [
    ["keydown", "alt+d", open],
    ["keydown", "alt+a", close],
    ["keydown", "alt+s", max],
];
for(i=0;i<=acKey.length;i++)
{
    $(document).bind(acKey[i][0], acKey[i][1], acKey[i][2]);
}

However, it turned out error Uncaught TypeError: Cannot read property '0' of undefined. What's wrong with my code?

4
  • 4
    Your loop is for(i=0;i<=acKey.length;i++) (note the i<=acKey.length). What happens when i==acKey.length. Does acKey[3] exist? Commented Mar 11, 2014 at 9:29
  • So what should I do in this case? Commented Mar 11, 2014 at 9:30
  • 1
    Remove the =; it should be just i<acKey.length Commented Mar 11, 2014 at 9:30
  • 2
    Sometimes you do need "<=" in a for loop, but it's very much the exception. Any time you do use "<=", think about adding a comment to say why. Commented Mar 11, 2014 at 9:31

2 Answers 2

4

With due credit to @Matt who's comment points it out.

The commonest format for looping through an array is:

 for(var i=0; i<array.length; i++) {
     doSomethingWith(array[i];
 }

Note that's a "less than" operator, not a "less than or equal to" operator.

This loop counts from 0 to array.length - 1, because the second part of the for statement: i < array.length, means "keep repeating for as long as i is less than array.length.

... and that's what you want, because arrays are numbered from 0 to length-1. That is, an array of length 4 is numbered 0,1,2,3.

If you loop while i <= 4, then the loop will execute for 0,1,2,3,4 -- and in Javascript, it will get undefined when it references array[4].

Sometimes you do need "<=" in a for loop, but it's very much the exception. Any time you do use "<=", think about adding a comment to say why.

Sign up to request clarification or add additional context in comments.

Comments

1

Your problem is your index (out of bounds) when i=acKey.length.

You can use i<acKey.lenght or implement a "for each" iteration to avoid confusion:

acKey = [
    ["keydown", "alt+d", open],
    ["keydown", "alt+a", close],
    ["keydown", "alt+s", max],
];

var sub;
for(i in acKey) {
    sub = acKey[i];
    $(document).bind(sub[0], sub[1], sub[2]);
}

7 Comments

That's quite new to me. Thank you, cardeol.
in shouldn't be used to loop over arrays generally. See explanation here: stackoverflow.com/a/3010848/355499
In this case is completely safe.
Could you guys all point out this in several lines? Which cases are not safe?
I.E. If you use an object inherited properties are also enumerated. but in case of arrays shouldn't be any problem. I use a lot this structure. Even with objects. stackoverflow.com/questions/11846484/each-for-object
|

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.