Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

119
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda