JavaScript - 嵌套函数删除 .length 数组

JavaScript - Nested function dropping .length of array

我正在尝试编写一个可以记录按键并将其存储到名为 "hotkey" 的变量中的应用程序。这个想法是创建一个按键数组来定义同时按键输入的热键并用它们触发动作。

问题是我将 运行 保留在函数范围问题中。根据我对函数作用域的理解,嵌套函数(在本例中为 anyKey)应该可以访问其父作用域(在本例中为 testFunc())的所有变量。

我觉得我在这里遗漏了一些重要的东西,但我不确定是什么。我知道它与保留变量的嵌套函数有关,但它似乎应该如何工作。有任何想法吗?我需要在这里自学任何主要概念吗?

提前致谢。

function testFunc() { 
  var hotkey = [];  
    console.log("hotkey length is:"+hotkey.length) //Yields "hotkey length is:0"
  hotkey[0] = "dummy";

  input.addEventListener("keydown", anyKey);

}

function anyKey(ev, txt, hotkey){  //If I don't enter hotkey as a paremeter, I'm notified "hotkey is not defined".  If I _do_ enter it, I get "nested hotkey length is: undefined

console.log("nested hotkey length is:"+hotkey);

let target = ev.currentTarget;
  let tag = target.tagName;
  let char = ev.char || ev.charCode || ev.which;
  log(char, tag);
  let s = String.fromCharCode(char);
  log(s);

/***
The following code, consequentially, doesn't work because hotkey.length isn't defined
***/
        for(i = 0; i <= hotkey.length + 1; i++){
        if (hotkey[i] === undefined || hotkey[i] === "dummy"){
          hotkey[i] = char;
        }
    } 

正如评论所指出的 anyKey() 不是 嵌套在 testFunc() 中,它只是从 testFunc() 中调用。这不足以共享相同的范围。这是一个嵌套在另一个函数中的函数示例,显示它们共享一个变量 keyCount,该变量跟踪按键被按下的次数:

function testFunc() {
  let keyCount = {}
  let input = document.getElementById('myInput')
  input.addEventListener("keydown", addCount);
  
  // addCount is nested here
  function addCount(ev) {
    let key = ev.key
    // this functin has access to keyCount because it's nested
    // within testFunc
    keyCount[key] = (keyCount[key] || 0) + 1
    console.log("counts: ", keyCount)
  }
}
testFunc()
<input id='myInput' type="text" />

嵌套你的两个函数可能不方便。另一种方法是简单地在函数之外定义 hotkey ,它会在两者的范围内,或者重新设计逻辑,这样只有一个函数需要访问它。例如,您的事件处理程序不需要执行太多逻辑 — 它只需找出按下的键并将其传递给管理状态的对象。