0

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)

5
  • its showed undefine becuase cacheW[0] , the index 0 is not exist in the array Commented Oct 31, 2021 at 7:56
  • @AlexYu but I just logged the whole array above ana it clearly has a length > 1 so index 0 should exist Commented Oct 31, 2021 at 7:59
  • 1
    @seriously [] 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 respectively Commented Oct 31, 2021 at 8:02
  • @knittl turn out what doesn't work is accessing the last item. I have updated the code above Commented Oct 31, 2021 at 8:15
  • cacheW[-1] doesnt' do what you think it does. Javascript is different from Python. Commented Oct 31, 2021 at 8:18

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

1

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);

3 Comments

turn out what doesn't work is accessing the last item. I have updated the code above
@seriously - What do you think cacheW[-1] does? Hint: Javascript isn't Python.
was treating it like python you are right. Thanks

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.