在调用push函数时,处理for循环中的TypeError



我正在开发一个webdata连接器,目前正在努力处理一个错误。WDC是用Javascript编写的。现在来谈谈我的问题。假设API返回以下JSON有效负载:

[
{
"type": "foo",
"licensePlate": "bar",
"mainEngine": null
},
{
"type": "foo",
"licensePlate": "bar",
"mainEngine": {
"fuelType" "fooBar"
}
}
]

来自API的数据被推送到带有for循环的表中。在以下示例循环中:

// some code
for (var i = 0, len = jsonData.length; i < len; i++) {
tableData.push({
"type": jsonData[i].type,
"licensePlate": jsonData[i].licensePlate,
"fuelType": jsonData[i].mainEngine.fuelType
});
}
// some code

出现类型错误是因为jsonData[i].mainEngine为null。我想把for循环包装在一个try-and-catch块中,参见:

// some code
for (var i = 0, len = jsonData.length; i < len; i++) {
try {
tableData.push({
"type": jsonData[i].type,
"licensePlate": jsonData[i].licensePlate,
"fuelType": jsonData[i].mainEngine.fuelType
});
} catch (e) {
console.log("An error occurred")
}
}
// some code

for循环现在将完全执行,但数据并没有完全推送到表中。我可以观察到,对于一些条目,每当表中的fuelType属性为null时,像licensePlate这样的属性都没有正确填充,这意味着它们完全丢失了。

非常感谢!

for (var i = 0, len = jsonData.length; i < len; i++) {
tableData.push({
"type": jsonData[i].type,
"licensePlate": jsonData[i].licensePlate,
"fuelType": jsonData[i].mainEngine && jsonData[i].mainEngine.fuelType
});
}

最新更新