JavaScript If Statement

时间:2014-01-28 21:17:30

标签: javascript jquery

我使用下面的代码来解析JSON DATA。如果没有列出字符,我可以在' as ' + entries.credits.cast[actor].character);之前使用此代码的mod吗?这样它可能看起来像演员1作为角色1,演员2,演员3作为角色3

var acting = [];
var maxCount = 5;
var count = entries.credits.cast.length;
if(count > maxCount) count = maxCount;
for (var actor = 0; actor < count; actor++) {
    acting.push(entries.credits.cast[actor].name + ' as ' + entries.credits.cast[actor].character);
}

document.getElementById('cast').innerHTML = acting.join(', ');

2 个答案:

答案 0 :(得分:2)

使用三元运算符怎么样?

for (var actor = 0; actor < count; actor++) {
    acting.push(entries.credits.cast[actor].name + (entries.credits.cast[actor].character ? ' as ' + entries.credits.cast[actor].character : "");
}

答案 1 :(得分:1)

您可以使用Conditional Ternary Operator

for (var actor = 0; actor < count; actor++) {
    acting.push(entries.credits.cast[actor].name + (entries.credits.cast[actor].character  ? ' as ' + entries.credits.cast[actor].character : ''));
}