I’m creating a small game and I have a peace of code that collects the pressed keys during an interval of time.
var pressedKeys = [];
setTimeout(function() {
for(var i = 0; i < pressedKeys.length; i++)
alert("Time is up you have inputed " + pressedKeys[i] + " length " + pressedKeys.length);
}, 3000);
$(document).keydown(function(evt) {
var key = evt.keyCode;
if (pressedKeys.length < 1) {
pressedKeys[0] = key;
} else {
pressedKeys[pressedKeys.length + 1] = key;
}
});
I’m new to javascript and I can’t understand why I have unidentified values in the array. The funny thing to me is if I do the loop with a foreach I do not get the unidentified values.
Can some one please explain this to me. I would be very thankful.
This…
should be this…
Since Array indices are zero-based, the current last item in the Array will be its
length - 1, which means the next item to fill will be the one at its.length.You can actually get rid of the
ifstatement…It starts off with a
.lengthof0, so the first entry will be at index0, which makes the.lengthequal to1, so the next entry will be at index1, and so on…