【问题标题】:Javascript problem to check dynamic variable [duplicate]检查动态变量的Javascript问题
【发布时间】:2022-12-20 08:38:36
【问题描述】:

我怎样才能避免这个错误。未捕获的类型错误:无法读取未定义的属性(读取“颜色”)

如果未定义,我需要检查动态变量。但是 js 让我给出错误。我知道对象汽车没有位置 [2] 但我需要我的脚本检测到它来调用特定函数

let cars = [ 

{ "color": "purple", "type": "minivan", "capacity": 7 }, { "color": "red", "type": "station wagon", "capacity": 5 } ]

让我= 1; 让变量=cars[2].color

console.log(cars[i].color);

if(typeof eval(variable) === "undefined") { console.log('未定义') }

【问题讨论】:

    标签: javascript arrays object


    【解决方案1】:

    您可以使用可选链接。

    let cars = [ { "color": "purple", "type": "minivan", "capacity": 7 }, { "color": "red", "type": "station wagon", "capacity": 5 } ]
    let variable = cars?.[2]?.color;
    if (!variable) console.log('could not access');

    【讨论】:

      猜你喜欢
      • 2014-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-08
      相关资源
      最近更新 更多