检查动态变量时出现Javascript问题[重复]

axzmvihb  于 2022-12-21  发布在  Java
关注(0)|答案(2)|浏览(123)
    • 此问题在此处已有答案**:

Javascript to check dynamic key from object from variable(2个答案)
昨天关门了。
如何避免此错误?未捕获的TypeError:无法读取未定义的属性(读取"color")
我需要检查动态变量是否未定义。但是js让我给出错误。我知道对象cars没有position [2],但是我需要我的脚本检测到这一点,以调用特定的函数

let cars = [
  {
    color: "purple",
    type: "minivan",
    capacity: 7,
  },
  {
    color: "red",
    type: "station wagon",
    capacity: 5,
  },
];

let i = 1;
let variable = cars[2].color;

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

if (typeof eval(variable) === "undefined") {
  console.log("it was not defined");
}

gupuwyp2

gupuwyp21#

您可以使用可选的链接。

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

fhg3lkii2#

使用lodash get方法,您可以轻松地获得值,而无需使用eval。

const cars = [
  {
    color: "purple",
    type: "minivan",
    capacity: 7,
  },
  {
    color: "red",
    type: "station wagon",
    capacity: 5,
  },
];

const path1 = "cars[1].color";
const path2 = "cars[2].color";

console.log(_.get({ cars }, path1));
console.log(_.get({ cars }, path2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

相关问题