使用 IIFE 时抛出“`TypeError`: `[0,1]` 不是函数”

“`TypeError`: `[0,1]` is not a function” is thrown when using an IIFE

这是代码

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] is not a function

这是一个工作片段

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);
  })();
})();

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.

中的每个语句后使用分号 (;)