我的代码有问题。我尝试使用以下代码在数组中查找元素
Name()
{
console.log(LoadItems.ItemConfigs);
var ItemConfig = LoadItems.ItemConfigs.find(itemconf => itemconf.Id === this.ConfigId);
if(ItemConfig != undefined){
return ItemConfig.Name;
} else {
return "ERROR";
}
}
但它每次都向我显示标题中提到的错误。如您所见,我之前已经在控制台中打印出 Array 用于调试,它给了我很多这样的对象:
ItemConfig {
Id: 25,
Name: 'Accessories',
Category: 'ITEM_CLOTH_ACC',
Density: 0,
Weight: 0,
Value1: '7',
Value2: 'NO_VALUE_SET',
Value3: 'NO_VALUE_SET',
Value4: 'NO_VALUE_SET',
Value5: 'NO_VALUE_SET' },
即使程序知道对象,我也不知道为什么会出现此错误。我得到的确切错误如下:
Invalid argument: expected Number/opt/gameserver/packages/yeet/Models/Item.js:53: TypeError: Cannot read property 'Id' of undefined
var ItemConfig = LoadItems.ItemConfigs.find(itemconf => itemconf.Id == this.ConfigId);
最佳答案
如果您的 LoadItems.ItemConfigs
具有此结构,则没有问题。但也许 LoadItems.ItemConfigs
没有这个结构
var LoadItems = {};
var ConfigId = 20;
LoadItems.ItemConfigs = [{
Id: 20,
Name: 'test_Accessories',
Category: 'ITEM_CLOTH_ACC',
Density: 0,
Weight: 0,
Value1: '7',
Value2: 'NO_VALUE_SET',
Value3: 'NO_VALUE_SET',
Value4: 'NO_VALUE_SET',
Value5: 'NO_VALUE_SET' },{
Id: 25,
Name: 'Accessories',
Category: 'ITEM_CLOTH_ACC',
Density: 0,
Weight: 0,
Value1: '7',
Value2: 'NO_VALUE_SET',
Value3: 'NO_VALUE_SET',
Value4: 'NO_VALUE_SET',
Value5: 'NO_VALUE_SET' }]
function Name()
{
console.log(LoadItems.ItemConfigs);
var ItemConfig = LoadItems.ItemConfigs.find(itemconf => itemconf.Id === this.ConfigId);
if(ItemConfig != undefined){
return ItemConfig.Name;
} else {
return "ERROR";
}
}
console.log(Name());
关于node.js - 如何修复 : "TypeError: Cannot read property ' Id' of undefined"in NodeJS (TypeScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56912972/