I was making a program that recoreded every keypress and pushed it to an array and it works fine. The problem is when I try to access the first element of the array and log it, it prints undefined. But the whole array logs fine.Why is it printing undefiened? I have added both console log of the array and the array item in my code and have commented besides them to indicate. Any help is appreciated. Thanks in advance.
EDIT: turn out what doesn't work is accessing the last item. I have updated the code above
var cacheW = []
var cacheA = []
var cacheD = []
var cacheS = []
// (B1) CAPTURE KEY STROKES
window.addEventListener("keydown", function(evt) {
if (evt.key == "w") {
cacheW.push('w');
//console.log("this: " + evt.key)
} else if (evt.key == "a") {
cacheA.push('a');
//console.log("this: " + evt.key)
} else if (evt.key == "d") {
cacheD.push('d');
//console.log("this: " + evt.key)
} else if (evt.key == "s") {
cacheS.push('s');
//console.log("this: " + evt.key)
}
});
window.addEventListener("keyup", function(evt) {
if (evt.key == "w") {
cacheW.push("!w");
//console.log("this: " + evt.key + " removed")
} else if (evt.key == "a") {
cacheA.push("!a");
//console.log("this: " + evt.key + " removed")
} else if (evt.key == "d") {
cacheD.push("!d");
//console.log("this: " + evt.key + " removed")
} else if (evt.key == "s") {
cacheS.push("!s");
//console.log("this: " + evt.key + " removed")
}
});
//works
setInterval(function() {
console.log(cacheW) //logs an array
}, 50)
//doesn't work
setInterval(function() {
console.log(cacheW[-1]) //logs undefined, should have logged the last element
}, 50)
cacheW[0], the index 0 is not exist in the array[]is an empty array. It has length 0, not 1. As soon as you have pressed a key at least once, both your interval functions will print the array and first item respectivelycacheW[-1]doesnt' do what you think it does. Javascript is different from Python.