短絡評価
6818 ワード
簡単な三項演算子のような簡単な方法を使用することは、常に素晴らしいことです.
三項演算子は使用するのに適していますが、常にそうとは限りません.そのため、JavaScript は式を評価する方法を導入しました.これは
1. && - これは最初の
2. || - 次は || です.オペレーター. || の使用最初の真または「真の」値を返します.すべてのオペランドが false と評価された場合、最後に評価された式が返されます.
これは、条件ステートメントを小さくするのに非常に便利です.このようなもの:
次のように変換できます.
ショートリードを読んでくれてありがとう.寄付したい方は画像をクリックしてください.
// example 1:
let x = 3;
let answer = x > 5 ? true : false; // false since 3 is less than 5
// example 2:
let y = [1,2,3];
let z = [4,5];
let answer = y.includes(5) ? (z.includes(5) ? true : false) : false; // true
三項演算子は使用するのに適していますが、常にそうとは限りません.そのため、JavaScript は式を評価する方法を導入しました.これは
&&
(AND) と ||
(または) です.どのように機能しますか?
1. && - これは最初の
falsy
値を返します.すべてが true の場合、最後の値を返します.console.log(5 && 6 && null && false && 0);
/**
result: null
- because the null is the first `falsy`.
*/
console.log(true && 1 && 4);
/**
result: 4
- because everything is `truthy`.
*/
let a = [1,2,3].includes(3) && 5 && 'good';
/**
result: 'good'
- because everything is truthy
*/
2. || - 次は || です.オペレーター. || の使用最初の真または「真の」値を返します.すべてのオペランドが false と評価された場合、最後に評価された式が返されます.
console.log(5 || 6 || null || false || 0);
/**
result: 5
- because the 5 is the first `truthy`.
*/
console.log(false || 6 || null || false || 0);
/**
result: 6
- because the 6 is the first `truthy`.
*/
console.log(true || 1 || 4);
/**
result: true
- because true is thruthy.
*/
let a = [1,2,3].includes(3) || 5 || 'good';
/**
result: true
- because the first condition is truthy.
*/
これは、条件ステートメントを小さくするのに非常に便利です.このようなもの:
if (data) {
return data;
} else {
return 'No Data';
}
次のように変換できます.
return (data || 'No Data');
ショートリードを読んでくれてありがとう.寄付したい方は画像をクリックしてください.
Reference
この問題について(短絡評価), 我々は、より多くの情報をここで見つけました https://dev.to/brojenuel/short-circuit-evaluation-22c1テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol