JavaScript 如何编写行内IF语句
我们可以使用以下描述的方法在JavaScript中编写行内IF语句。
方法1
在此方法中,我们通过使用下面给出的语句,在行内编写一个不带else的IF语句。
语法:
(a < b) && (your code here)
Above statement is equivalent to
if(a < b){
// Your code here
}
JavaScript
示例: 下面是以上方法的实现:
<script>
// Javascript script
// to write an inline IF
// statement
// Function using inline 'if'
// statement to print maximum
// number
function max(n, m){
// Inline 'if' statement only
// If n > m then this will execute
(n > m) && document.write(n + "<br>");
// Above statement is equivalent to
// if(n > m){
// document.write(n + "<br>");
// }
// Inline 'if' statement only
// If m > n then this will execute
(m > n) && document.write(m + "<br>");
// Above statement is equivalent to
// if(m > n){
// document.write(m + "<br>");
// }
}
//Driver code
var a = -10;
var b = 5;
// Call function
max(a, b);
// Update value
a = 50;
b = 20;
// Call function
max(a, b);
</script>
JavaScript
输出:
5
50
JavaScript
方法2
在这种方法中,我们将使用三元运算符编写内联if语句。
语法:
result = condition ? value1 : value2;
JavaScript
如果条件为真,则将value1赋值给结果变量,如果条件错误,则将value2赋值。
示例: 下面是上述方法的实现:
<script>
// Javascript script
// to write an inline IF
// statement
// Function using inline 'if'
// statement to return maximum
// number
function max(n, m){
// Inline 'if' statement
// using ternary operator
var x = (n > m) ? n : m;
// Above statement is equivalent to
// if(n > m){
// x = n;
// }
// else {
// x = m;
// }
return x;
}
//Driver code
var a = -10;
var b = 5;
var res;
// Call function
res = max(a, b);
// Print result
document.write(res + "<br>");
// Update value
a = 50;
b = 20;
// Call function
res = max(a, b);
// Print result
document.write(res + "<br>");
</script>
JavaScript
输出:
5
50
JavaScript