我的代码有问题。我试图在数组中找到一个元素,代码如下

Name()
{
    console.log(LoadItems.ItemConfigs);
    var ItemConfig = LoadItems.ItemConfigs.find(itemconf => itemconf.Id === this.ConfigId);
    if(ItemConfig != undefined){
        return ItemConfig.Name;
    } else {
        return "ERROR";
    }
}

但它每次都显示出标题中提到的错误。如您所见,我在调试之前已经在控制台中打印出了数组,它给了我许多这样的对象:
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 - 如何修复:NodeJS(TypeScript)中的“TypeError:无法读取未定义的属性'Id'”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56912972/

10-13 07:46
查看更多