Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/431.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript:forEach在内置数组上经常失败_Javascript_Arrays_Foreach - Fatal编程技术网

Javascript:forEach在内置数组上经常失败

Javascript:forEach在内置数组上经常失败,javascript,arrays,foreach,Javascript,Arrays,Foreach,我经常想做这样的事情: ["string1", "string2"].forEach(function(str) { // Handle string }) 这似乎偶尔奏效,但通常(至少是Chrome)会抛出错误 Cannot read property 'forEach' of undefined 为什么我的就地数组“未定义” 相比之下,这将按预期工作: var myStrings = ["string1", "string2"] myStrings.forEach(functi

我经常想做这样的事情:

["string1", "string2"].forEach(function(str) { 
    // Handle string
})
这似乎偶尔奏效,但通常(至少是Chrome)会抛出错误

Cannot read property 'forEach' of undefined
为什么我的就地数组“未定义”

相比之下,这将按预期工作:

var myStrings = ["string1", "string2"]
myStrings.forEach(function(str) {
    // Handle string
})
有什么好处

编辑

代码示例:

// This works:
var methods = {}
,   methodNames = ["move", "x", "y", "cx", "cy", "opacity", "attr", "fill", "stroke", "front", "after", "back", "dx", "dmove", "dy", "remove"]

methodNames.forEach(function(method) {
    methods[method] = { value: function() { return this.mainGroup[method].apply(this.mainGroup, arguments) }}
})

// This throws "Cannot read property 'forEach' of undefined
methods = {}
["move", "x", "y", "cx", "cy", "opacity", "attr", "fill", "stroke", "front", "after", "back", "dx", "dmove", "dy", "remove"].forEach(function(method) {
    methods[method] = { value: function() { return this.mainGroup[method].apply(this.mainGroup, arguments) }}
})

“methods={}”旁边缺少分号会导致错误

// This throws "Cannot read property 'forEach' of undefined
methods = {};  // <-- HERE
["move", "x", "y", "cx", "cy", "opacity", "attr", "fill", "stroke", "front", "after", "back", "dx", "dmove", "dy", "remove"].forEach(function(method) {
    methods[method] = { value: function() { return this.mainGroup[method].apply(this.mainGroup, arguments); }}
});

虽然没有必要,但作为一种良好的做法,我建议在适当的时候使用分号。

无法复制,forEach在chrome中对我来说很好。请提供一个示例代码。@Mr_Pouet-提供的代码示例。谢谢!但是为什么呢?为什么{}[]本身无效?
var a = {};
a['a', 'b'] = 1;  // a = {'a':1 , 'b':1}