代码之家  ›  专栏  ›  技术社区  ›  seriously

按返回未定义的索引记录数组项

  •  0
  • seriously  · 技术社区  · 3 年前

    我正在制作一个程序,记录每一个按键,并把它推到一个数组中,它工作得很好。问题是,当我尝试访问数组的第一个元素并记录它时,它会打印未定义的内容。但是整个阵列的日志记录都很好。为什么它打印时没有定义?我已经在代码中添加了数组的控制台日志和数组项,并在它们之外添加了注释以指示。感谢您的帮助。提前谢谢。

    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)
    2 回复  |  直到 3 年前
        1
  •  3
  •   knittl    3 年前

    Javascript通过索引访问数组项。 -1 是无效的索引。要访问最后一项,请使用 arr[arr.length - 1] .

    arr.slice(-1)[0] ,但这将创建一个临时单项数组,然后访问该数组的第一项。

    事实上 -1 是一个 ,不是有效的索引。属性名称首先字符串化,然后添加到对象(每个数组都是一个对象):

    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
    
        2
  •  1
  •   selbie    3 年前

    与此相反:

    //doesn't work
    setInterval(function() {
      console.log(cacheW[0])//logs undefined, should have logged the first element
    }, 50)
    

    setInterval(function() {
      if (cacheW.length > 0) {
          console.log(cacheW[0]);
      } else {
          console.log("<empty>");
      }
    }, 50);
    

    使现代化

    setInterval(function() {
      if (cacheW.length > 0) {
          console.log(cacheW[cacheW.length-1]);
      } else {
          console.log("<empty>");
      }
    }, 50);