Among the flow control statements, the one we are most familiar with is
if( 条件 ){ //代码块 }else { //代码块 }
For a code that executes different code, if a lot of code is executed, it may be necessary to use the above method
But often during our development, we will encounter some assignment operations. If we use the above method, it will be too redundant.
For example:
num1 = 10 num2 = 20
You can see that the above method only outputs a result, but uses five lines of code to implement it.
Next, we will witness how to use one line of code to replace the result achieved by the above five lines of code
var num1 = 10; var num2 = 20; // 第一种方式 也可以使用 三目运算符 alert( num2 > mum1 ? num2 : num1 ); //第二种方式 就是使用 && ,|| alert( num2 > num1 && num2 || num1 );
The advantage of using &&,|| over ternary arithmetic is that it can judge multiple conditions , can also be used alone
Give an && example:
var num1 = 10;var num2 = 5;// 假如 num1,num2 都大于10 则输出 num1+num2; var result = num1>10 && num2 >10 && num1+ num2 || 0; alert(result);
Our developers know that during development, the data returned by reading the backend may not be read for some reason, then If the received data is an object, additional fields that have not been obtained will be added when receiving the field.
Take a || example:
var reuslt = res && res.data || []; if ( result.length ) return;
Using this method, you can pass conditions Determine whether to use the variable. If it is an object, if it is not obtained and the object attribute is used, an error will be reported.
To avoid this pattern, you must judge, judge, judge when using it
The above is the detailed content of && and || usage in JS. For more information, please follow other related articles on the PHP Chinese website!