【问题标题】:Why can't I use an anonymous function expression for accessing an array index position?为什么我不能使用匿名函数表达式来访问数组索引位置?
【发布时间】:2021-10-15 06:04:42
【问题描述】:

在 JavaScript 中,可以使用这种语法访问数组值...

const arr = ["one", "two", "three"];
console.log(arr[0]); // "one"

...或使用返回数字的已定义函数来实现相同的结果:

const arr = ["one", "two", "three"];
const fn = () => 0;
console.log(arr[fn()]); // "one"

我可能是个脑残,但我就是不明白为什么在使用匿名函数表达式时完全相同的事情不起作用?我不是清楚地以0 作为数组索引位置评估器吗?

const arr = ["one", "two", "three"];
console.log(arr[() => 0]); // undefined

【问题讨论】:

    标签: javascript arrays function anonymous-function


    【解决方案1】:

    () => 0 返回一个函数,而不是调用时返回的值。

    您需要调用该函数:

    const arr = ["one", "two", "three"];
    console.log(arr[(() => 0)()]);

    【讨论】:

    • 我知道我的头脑很迟钝。我终于可以问心无愧地入睡了。无论如何,谢谢,很快就会接受。
    【解决方案2】:

    主要区别在于匿名函数的概念。

    const arr = ["one", "two", "three"];
    const fn = () => 0;
    console.log(arr[fn()]);
    

    在这里,您将匿名函数分配给 fn 常量,并且您正在调用此函数在索引中返回 0。

    在您的最后一个示例中,您只是分配函数而不调用函数,这就是它返回未定义的原因。

    如果你想自动调用一个匿名函数,你只需要这样调用它:

    (() =>0)() // check the last pair of parentheses
    

    【讨论】:

      猜你喜欢
      • 2021-05-13
      • 2020-11-22
      • 2013-02-14
      • 2017-08-08
      • 2017-12-04
      • 2014-09-16
      • 1970-01-01
      • 2020-12-02
      • 2021-02-11
      相关资源
      最近更新 更多