所有工作完成后,我尝试运行我的代码(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
如何修复此错误?
1条答案
按热度按时间2admgd591#
从这些信息中我可以看出,字典对象
_races
对于当前键_race
没有任何值,因此_races[_race]
是undefined
,_races[_race].layers
是TypeError
:TypeError:无法读取未定义的属性(读取"layers")
您可以使用optional chaining
?.
来抑制可能的错误或者在尝试访问
.layers
之前检查if (_races[_race]) {
以排除undefined
。但是你可能想弄清楚为什么
_races[_race]
是undefined
。