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)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Javascript access array items by their index. -1
is an invalid index. To access the last item, use arr[arr.length - 1]
.
Other languages such as python offer syntactic sugar to access items from the end of an array. JavaScript does not have such syntactic sugar. The closest which you can get is to write arr.slice(-1)[0]
, but this will create a temporary single-item array and then access the first item of this array.
In fact -1
is a property, not a valid index. Property names are first stringified, then added to the object (every array is an object):
a = [];
a[-1] = 42;
console.log(a); // [], array itself is still empty
console.log(a[-1]); // 42, property -1 on the object has value assigned
console.log(a['-1']); // 42, object property keys are always converted to string first
CodePudding user response:
Instead of this:
//doesn't work
setInterval(function() {
console.log(cacheW[0])//logs undefined, should have logged the first element
}, 50)
This:
setInterval(function() {
if (cacheW.length > 0) {
console.log(cacheW[0]);
} else {
console.log("<empty>");
}
}, 50);
Update If you want to print the last item:
setInterval(function() {
if (cacheW.length > 0) {
console.log(cacheW[cacheW.length-1]);
} else {
console.log("<empty>");
}
}, 50);