Reputation: 14866
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?
Upvotes: 0
Views: 88
Reputation: 2238
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]);
}
Upvotes: 1
Reputation: 41223
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.
Upvotes: 4