問題描述
JavaScript 中的條件語句 (Conditional Statement in JavaScript)
In C#.Net, We would use Conditional Statement like this below:
string Place = TextBox1.Text == "" ? "School" : TextBox1.Text;
How to use Conditional Statement in JavaScript. I am assigning one value to the TextBox, If there is no value then I want to assign "1" to the TextBox.
Here I used like this,
document.getElementById('<%=txtPlace.ClientID %>').value = obj[1];
If obj[1] == "" then I want to assign "1" to the TextBox. How to assign? It can be done easily by using If statement. But I want to know how to use Conditional Statement in JavaScript? Is there Conditional Statement in JavaScript? If so then how to use it?
參考解法
方法 1:
Yes, Javascript does support the conditional operator:
document.getElementById('<%=txtPlace.ClientID %>').value = obj[1] ? obj[1] : "1";
Alternatively, you can take advantage of its short-circuiting logical OR operator:
document.getElementById('<%=txtPlace.ClientID %>').value = obj[1] || "1";
方法 2:
Yes, there is conditional statement in javascript, it works the same way:
document.getElementById('<%=txtPlace.ClientID %>').value = obj[1] === "" ? "1" : obj[1];
方法 3:
The conditional (or ternary) operator is the same in JavaScript:
condition ? true-value : false-value
So your code would look like this:
document.getElementById('<%=txtPlace.ClientID %>').value = obj[1] === "" ? "1" : obj[1];
方法 4:
Yes, there is and it behaves in the same way as in C#.
document.getElementById('<%=txtPlace.ClientID %>').value = obj[1]==""?"1":"something";
(by thevan、Frédéric Hamidi、dcp、FishBasketGordo、Mathias Schwarz)