Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

118
Views
logging array item by index returning undefiened

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)

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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
about 4 years ago · Juan Pablo Isaza Report

0

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);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!