当 JavaScript 中存在未定义的值时无法解析 json



我有这个json[object Object],[object Object],[object Object],[object Object],,,[object Object],你可以看到有3个未定义的对象。当我解析这个json文件时,我使用这个;

for (x=0;x<json.length;x++) {
src=json[x].file.src
list.push(src)
}

当x为4(未定义(时,它停止工作。如果这个未定义,我怎么能说脚本跳过这个对象。示例json:


{
"posts":[
{
"id":2236659,
"updated_at":"2020-05-02T19:58:43.763-04:00",
"file":{
"width":933,
"height":1200,
"ext":"png",
"size":1325351,
"md5":"d1f501df73f7d1daec07a86657baae01"
}
},
{
"id":2227726,
"created_at":"2020-04-23T08:06:37.907-04:00",
"file":{
"width":933,
"height":1200,
"ext":"png",
"size":1182791,
"md5":"112cadaaaa89841e8bb7633ba272a409"
}
},
{
"id":2218681,
"created_at":"2020-04-16T07:56:56.849-04:00",
"file":{
"width":933,
"height":1200,
"ext":"png",
"size":1241188,
"md5":"c3c13b8e5c72913fa7db03ffc8b6f3c4"
}
}
]
}

尝试使用if语句检查json[i]是否为null或未定义。

var json = [void 0, void 0, void 0, { file: { src: 'test' } }];
var list = [];
for (x = 0; x < json.length; x++) {
if (json[x]) {
src = json[x].file.src
list.push(src)
}
}
console.log(list);

或者您可以使用Array.filterArray.map函数。

var json = [void 0, void 0, void 0, { file: { src: 'test' } }];
var list = json.filter(e => Boolean(e)).map(e => e.file.src);
console.log(list);

最新更新