【问题标题】:“`TypeError`: `[0,1]` is not a function” is thrown when using an IIFE使用 IIFE 时抛出“`TypeError`: `[0,1]` is not a function”
【发布时间】:2023-03-20 20:51:01
【问题描述】:

这里是代码

var numberArray = [0, 1]

(function() {
  numberArray.push(2)

  function nestedFunction() {
    numberArray.push(3)

    function anotherNestedFunction() {
      numberArray.push(4)
    }

    console.log(numberArray)
  }
})()

我期待 numberArray 的值为 [0,1,2,3,4] 但它给出了这个错误:

TypeError[0,1] 不是函数

【问题讨论】:

标签: javascript arrays function iife


【解决方案1】:
var numberArray = [0, 1]
(function() {

等价于

var numberArray = [0, 1] (function() {

这就是错误上升的地方。

要解决问题,请在数组声明之后放置 ;,JavaScript 引擎会将这两行视为单独的语句:

var numberArray = [0, 1];

(function() {
  numberArray.push(2);

  function nestedFunction() {
    numberArray.push(3);

    function anotherNestedFunction() {
      numberArray.push(4);
    }
    
    anotherNestedFunction();
    console.log(numberArray);
  }
  nestedFunction();
})();

要忽略所有这些意外问题,最好在 JavaScript 中的每个语句后使用分号 (;)。

【讨论】:

  • 很高兴知道为什么我在 JS 的每一行末尾都使用分号:D(我只知道这可能会导致问题,但我从未见过它的实际案例)跨度>
【解决方案2】:

这是一个有效的 sn-p

const numberArray = [0, 1];

(function() {
  numberArray.push(2);

  (function nestedFunction() {
    numberArray.push(3);

    (function anotherNestedFunction() {
      numberArray.push(4);
    })();

    console.log(numberArray);
  })();
})();

如果您在numberArray 之后删除;,这就是您遇到问题的地方。您还必须将 IIFE 与您的内部声明 functions 一起使用。

const numberArray = [0, 1]

(function() {
  numberArray.push(2);

  (function nestedFunction() {
    numberArray.push(3);

    (function anotherNestedFunction() {
      numberArray.push(4);
    })();

    console.log(numberArray);
  })();
})();

【讨论】:

    猜你喜欢
    • 2021-05-30
    • 2015-11-06
    • 2014-01-31
    • 2021-01-07
    • 2018-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多