node.js - 如何修复 : "TypeError: Cannot read property ' Id' of undefined"in NodeJS (TypeScript)

标签 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";
    }
}

但它每次都向我显示标题中提到的错误。如您所见,我之前已经在控制台中打印出 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/

相关文章:

java - 在 Java 中执行 Linux nodejs 命令行

c - 为什么kfifo在某些博客中是Circular queue

linux - C代码中的段错误

Angular 9 + eslint : error Definition for rule '@angular-eslint/...' was not found

typescript 编译器不显示错误

reactjs - Material-UI : Rating Component, 根据值改变颜色

javascript - 异步更改 javascript 函数/"class"的参数?

javascript - 将Powershell对象传递给Node.JS/Electron并将其 package 在HTML标记中

javascript - Expressjs 服务器地址主机不返回任何内容

linux - 64位Linux内核占用哪个地址空间?