[英]“`TypeError`: `[0,1]` is not a function” is thrown when using an IIFE
Here is the code 这是代码
var numberArray = [0, 1] (function() { numberArray.push(2) function nestedFunction() { numberArray.push(3) function anotherNestedFunction() { numberArray.push(4) } console.log(numberArray) } })()
I am expecting numberArray
with value [0,1,2,3,4]
but it is giving this error: 我期待
numberArray
的值[0,1,2,3,4]
但它给出了这个错误:
TypeError
:[0,1]
is not a functionTypeError
:[0,1]
不是函数
var numberArray = [0, 1]
(function() {
is equivalent to 相当于
var numberArray = [0, 1] (function() {
That is where the error rise. 这就是错误上升的地方。
To resolve the issue place ;
解决问题的地方
;
after the array declaration which JavaScript engine will consider both the line as separate statement: 在数组声明之后哪个JavaScript引擎会将该行视为单独的语句:
var numberArray = [0, 1]; (function() { numberArray.push(2); function nestedFunction() { numberArray.push(3); function anotherNestedFunction() { numberArray.push(4); } anotherNestedFunction(); console.log(numberArray); } nestedFunction(); })();
To ignore all these unexpected issue, it is always good practice to use semicolons ( ;
) after every statement in JavaScript. 要忽略所有这些意外问题,最好在JavaScript中的每个语句后使用分号(
;
)。
Here is a working snippet 这是一个工作片段
const numberArray = [0, 1]; (function() { numberArray.push(2); (function nestedFunction() { numberArray.push(3); (function anotherNestedFunction() { numberArray.push(4); })(); console.log(numberArray); })(); })();
If you remove the ;
如果你删除
;
after numberArray
this is where you got a problem. 在
numberArray
之后,这是你遇到问题的地方。 You also have to use IIFE with your inner declared functions
. 您还必须在内部声明的
functions
使用IIFE。
const numberArray = [0, 1] (function() { numberArray.push(2); (function nestedFunction() { numberArray.push(3); (function anotherNestedFunction() { numberArray.push(4); })(); console.log(numberArray); })(); })();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.