NodeJS TypeError:无法读取未定义的属性(阅读“layers”)

pbpqsu0x  于 2022-12-26  发布在  Node.js
关注(0)|答案(1)|浏览(281)

所有工作完成后,我尝试运行我的代码(node index.js),出现以下错误:

PS C:\Users\mi pc.DESKTOP-1K26KAH\Desktop\generative-art-opensource-3> node index.js
C:\Users\mi pc.DESKTOP-1K26KAH\Desktop\generative-art-opensource-3\index.js:119
 _races[_race].layers.forEach((layer) => {
               ^
TypeError: Cannot read properties of undefined (reading 'layers')
at createDna (C:\Users\mi pc.DESKTOP-1K26KAH\Desktop\generative-art-opensource-3\index.js:119:17)
at startCreating (C:\Users\mi pc.DESKTOP-1K26KAH\Desktop\generative-art-opensource-3\index.js:148:18)
at Object.<anonymous> (C:\Users\mi pc.DESKTOP-1K26KAH\Desktop\generative-art-opensource-3\index.js:180:1)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47

如何修复此错误?

2admgd59

2admgd591#

从这些信息中我可以看出,字典对象_races对于当前键_race没有任何值,因此_races[_race]undefined_races[_race].layersTypeError
TypeError:无法读取未定义的属性(读取"layers")
您可以使用optional chaining?.来抑制可能的错误

_races[_race]?.layers.forEach((layer) => {

或者在尝试访问.layers之前检查if (_races[_race]) {以排除undefined
但是你可能想弄清楚为什么_races[_race]undefined

相关问题