我在JavaScript的某些部分有代码,如下所示:
$('table#coa-list').find('tbody').append(
'<tr align="center">'+
' <td class="text-nowrap">'+(element.customer_ID == null? '-' : element.customer_name )+'</td>'+
' </td>'+
' </tr>'
)
以上代码代表if(customer_ID == null){echo ...}
如何在条件语句中将另一个条件添加到表达式并与OR运算符(即OR
)结合使用?例如,此代码if(customer_ID == null || customer_ID == "0"){echo ...}
答案 0 :(得分:1)
如何执行OR语句?例如,此代码
if(customer_ID == null || customer_ID == "0"){echo ...}
[在三元运算符/语句中]
一种选择是添加logical OR operator(即||
),然后添加其他条件:
' <td class="text-nowrap">'+((element.customer_ID == null || element.customer_ID == "0")? '-' : element.customer_name )+'</td>'+
请参阅以下代码段中的演示:
var element = {};
console.log('result of first ternary with OR: ',(element.customer_ID == null || element.customer_ID == "0")? 'null or zero' : element.customer_name );
element.customer_ID = 4;
element.customer_name = 'Bert';
console.log('result of second ternary with OR: ',(element.customer_ID == null || element.customer_ID == "0")? 'null or zero' : element.customer_name );
另一种可能性是用函数调用替换该表达式。首先将逻辑抽象为函数:
function customerIdIsNullOrZero() {
return element.customer_ID == null || customer_ID == "0";
}
然后使用它,用对该函数的调用替换三元运算符的条件:
' <td class="text-nowrap">'+(customerIdIsNullOrZero()? '-' : element.customer_name )+'</td>'+
var element = {};
function customerIdIsNullOrZero() {
return element.customer_ID == null || element.customer_ID == "0";
}
console.log('result of first ternary with OR: ',customerIdIsNullOrZero()? 'null or zero' : element.customer_name );
element.customer_ID = 4;
element.customer_name = 'Bert';
console.log('result of second ternary with OR: ',customerIdIsNullOrZero()? 'null or zero' : element.customer_name );