我有以下回圈呼叫 api 并將資料推送到陣列,問題是 API 為某些屬性回傳空值,即 "primaryTag": null破壞了我的代碼,如果有任何一個,我如何處理它以放置靜態值值為空?
for (var a in audience) {
var aId = audience[a];
var url = base '?' query '&AudienceId=' aId
var req = new HttpClientRequest(url);
req.header["Content-Type"] = "application/json"
req.method = "GET"
req.execute();
var resp = req.response;
if( resp.code != 200 )
throw "HTTP request failed with " resp.message
var posts = JSON.parse(resp.body)
logInfo(resp.code ' ' url);
for (i = 0; i < 11; i ) {
articlesList_json.push({
"title":posts[i].title,
"pubDate":posts[i].publishedDate,
"link":posts[i].url,
"imageURL":posts[i].imageUrl,
"description": posts[i].description,
"category": posts[i].category.name,
"audience": posts[i].audience.name '-' posts[i].audience.id,
"tag": posts[i].primaryTag.name,
"episerverId":posts[i].episerverId,
});
}
}//for loop end


uj5u.com熱心網友回復:
看看可選鏈
"tag": posts[i].primaryTag?.name ?? "N/A"
或者使用三元:
"tag": posts[i].primaryTag ? posts[i].primaryTag.name : "N/A"
uj5u.com熱心網友回復:
像 null、undefined、空字串、0 和 NaN 這樣的值在 Javascript 中被評估為 false。
您可以使用 if 條件檢查值是否為空
if(value) {
// value is not null
// do something with the value
}
在您的示例中,您可以使用三元運算式來檢查這一點
for (i = 0; i < 11; i ) {
articlesList_json.push({
// check if value is not falsy and provide a default when it is
"title":posts[i].title ? posts[i].title : "no value",
// ...
});
}
檢查https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator了解更多資訊
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/355053.html
標籤:javascript 数组 xml 接口
