如何修复:NodeJS(TypeScript)中的“ TypeError:无法读取未定义的属性'Id'”

时间:2019-07-06 09:50:44

标签: node.js linux typescript

我的代码有问题。我尝试使用以下代码在数组中找到一个元素

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);

2 个答案:

答案 0 :(得分:0)

如果您具有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());

答案 1 :(得分:0)

仅通过查看您发布的代码,您似乎并没有做错任何事情。 我迅速尝试重现您的问题,并且看起来工作正常(如下面的代码片段所示)。请对照我的代码检查我的代码,看看是否可以发现问题。

  

从阵列中移出所有空对象,以确保安全

let ConfigId = 25;
let LoadItems = {
    ItemConfigs: Array()
};
LoadItems.ItemConfigs = [{},{
        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'
    },{},{}];


//Remove empty objects from the object array
 LoadItems.ItemConfigs = LoadItems.ItemConfigs.filter(item=> Object.keys(item).length !== 0);
function Name() {
    console.log(LoadItems.ItemConfigs);
    var ItemConfig = LoadItems.ItemConfigs.find(itemconf => itemconf.Id === ConfigId);
    if (ItemConfig != undefined) {
        return ItemConfig.Name;
    }
    else {
        return "ERROR";
    }
}
;
console.log(Name());