Node.js forEach:不能读取未定义的属性''
我从来没有见过这个。 这个错误发生在Node.js 6.3.0和6.9.1 LTS上,为了解决这个问题,我更新了这个错误。
我试图根据一些数据build立一个游戏的统计数据,并不是特别重要。 重要的是,下面的函数是我的游戏类的一部分,失败了:
computeStats() { var stats , roster , team, opp, scoreState, oppScoreState , TOI = this.calculateTOIData() , eventCounter = this.calculateEventData() [['home', 'away'], ['away', 'home']].forEach((teams) => { //this is line 74 / error source team = teams[0]; opp = teams[1]; roster = this[team].roster; stats = { //some assignments occur here from my TOI and eventCounter objects } this.setStats(team, stats); }) }
抛出的错误是
TypeError: Cannot read property '[object Array]' of undefined at GameTracker.computeStats (/Users/nawgszy/repo/lib/Game.js:74:5) at new GameTracker (/Users/nawgszy/repo/lib/Game.js:39:10)
我不知道这是如何可能的。 arrays是硬编码的,在那里。 有任何想法吗? 我可以解决它,但我觉得这个特定的结构是最简单的方法来生成我想要使用的统计信息。
我想这是ASI与你搞砸了。 在eventCounter = this.calculateEventData()
之后添加一个分号,看看它是如何运行的。
更多信息: http : //benalman.com/news/2013/01/advice-javascript-semicolon-haters/
在this.calculateEventData()
之后缺less的分号导致下面的括号表示行为作为下标访问,而不是就地数组表示法。
代码如下所示:
var eventCounter = (this.calculateEventData()[['home', 'away'], ['away', 'home']]).forEach((teams) => { ... });
请注意我添加的括号。 逗号运算符使['away', 'home']
成为通过Object.prototype.toString()
传递的下标,变成'[object Array]'
。
this.calculateEventData()
返回undefined
。 语句变成undefined['[object Array]']
。
基本上,使用分号,也许避免内联数组(或用分号作为前缀,因为这是安全的)。
var stats , roster , team, opp, scoreState, oppScoreState , TOI = this.calculateTOIData() , eventCounter = this.calculateEventData(); // <-- Right there.
最小的复制:
// test.js const func = () => {}; const result = func() [[]].forEach(() => {});
使用Node.js运行 在浏览器中也会失败。
$ node -v v6.5.0 $ node test.js /home/foo/test.js:4 [[]].forEach(() => {}); ^ TypeError: Cannot read property '[object Array]' of undefined at Object.<anonymous> (/home/foo/test.js:4:1) at Module._compile (module.js:556:32) at Object.Module._extensions..js (module.js:565:10) at Module.load (module.js:473:32) at tryModuleLoad (module.js:432:12) at Function.Module._load (module.js:424:3) at Module.runMain (module.js:590:10) at run (bootstrap_node.js:394:7) at startup (bootstrap_node.js:149:9) at bootstrap_node.js:509:3
我认为你的问题就是你所performance的[['home', 'away'], ['away', 'home']]
实际上是一个variables。 而且这个variables是未定义的(可能错误input或者不被声明)
我认为@Oka已经制定了你所看到的错误。
但是,它看起来像是另一个问题,你在索引到一个string数组而不是一个string值的对象 :
(teams) => { // teams: string[][]; team = teams[0]; // team: string[]; opp = teams[1]; // opp: string[]; // Issue here: Trying to index `this[team]` with a string array, not a string value. roster = this[team].roster; //... }