TypeError:无法读取未定义Javascript的属性“ forEach”

时间:2020-05-28 17:16:56

标签: javascript node.js ecmascript-6 callback

以下是我获得Cannot read property 'forEach' of undefined的代码。

const print2 = function(x, y) {
  console.log(x*y)
}

[1,2,3,4].forEach( x => print2(x, 20) )

让我知道我在这里做错了,尽管我愿意-

function print2(x, y) {
  console.log(x*y)
}

[1,2,3,4].forEach( x => print2(x, 20) )

这很好。

enter image description here

5 个答案:

答案 0 :(得分:9)

由于该函数后没有分号,因此代码段的解释如下:

const print2 = function(x, y) {
  console.log(x*y)
}[1,2,3,4].forEach( x => print2(x, 20) )

这意味着它正在尝试索引该函数。在函数之后或数组文字之前添加分号:

const print2 = function(x, y) {
  console.log(x*y)
};

[1,2,3,4].forEach( x => print2(x, 20) )

const print2 = function(x, y) {
  console.log(x*y)
}

;[1,2,3,4].forEach( x => print2(x, 20) )

有关Javascript自动分号插入的更多信息,请点击此处:What are the rules for JavaScript's automatic semicolon insertion (ASI)?

答案 1 :(得分:5)

变量声明的末尾需要分号。

const print2 = function(x, y) {
  console.log(x*y)
};

[1,2,3,4].forEach( x => print2(x, 20) )

没有分号,它被视为

const print2 = function(x, y) {
  console.log(x*y)
}[1,2,3,4].forEach( x => print2(x, 20) )

[1,2,3,4]被解释为属性访问器,而不是数组,并且逗号运算符返回最后一个值4。由于该函数没有4属性,该属性返回undefined,然后您尝试在该属性上调用.forEach()

答案 2 :(得分:2)

FunctionExpression之后,您缺少分号。

const print2 = function(x, y) {
  console.log(x*y)
}

[1,2,3,4].forEach( x => print2(x, 20) )

更改为

const print2 = function(x, y) {
  console.log(x*y)
};

[1,2,3,4].forEach( x => print2(x, 20) )

它有效。

答案 3 :(得分:0)

我认为,您应该使用[1,2,3,4].forEach( x => print2(x, 20) )之类的变量,而不是array.forEach(x => print2(x, 20));

例如下面给出的示例代码:

let array = [1,2,3,4];
const print2 = function(x, y) {
    console.log(x*y);
};

array.forEach( x => print2(x, 20) );

答案 4 :(得分:0)

作记录。 我想补充一点,就是我在使用该代码时遇到了相同的错误

var createFiltersList = function() {
        window.filterMenu.forEach(function(text) {     /* <== error here */
            filterList.push({
                text: text,
                expr: text !== ALL ? [DevAV.filterField, "=", text] : null,
                type: DevAV.filterCaption,
                custom: false
            });
        });

        var customItems = JSON.parse(window.localStorage.getItem(storageKey));
        Array.prototype.push.apply(filterList, customItems);
    };

我的问题是我没有为window.filterMenu设置任何值,因此filterMenu为null,因此forEach不适用于null。 一旦为filterMenu设置了一个值数组,错误就消失了。