我正在使用 API 获取要附加到 DOM 的值,数组中的一些值返回 null
,使表中的值保持为空。我的问题是否可以返回一个表示“信息丢失”的字符串而不是返回空?
success: function(currency) {
// loop through currency
for (var i = 0; i < currency.length; i++) {
if (currency[i].currency == userCurrency) {
var $tr = $("<tr />");
$tr.append($("<td />").text(currency[i].volume));
$tr.append($("<td />").text(currency[i].latest_trade));
$tr.append($("<td />").text(currency[i].bid));
$tr.append($("<td />").text(currency[i].high));
$("#theTable tbody").append($tr);
}
}
}
});
});
});
最佳答案
使用|| “信息丢失”
像这样:-
$tr.append( $("<td />").text(currency[i].volume || "information is missing"));
然后,这将对任何错误值使用“信息丢失”
,即:0、null、未定义、“”、false
。
如果您只想检查 null
,则可以使用内联 if:-
$tr.append( $("<td />").text(currency[i].volume != null ? currency[i].volume : "information is missing"));
关于javascript - 返回字符串而不是 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34607576/