JavaScript에는 "단락"평가가 있습니까?
JavaScript에 C #의 && 연산자와 같은 "단락"평가가 있는지 알고 싶습니다. 그렇지 않은 경우 채택 할 수있는 해결 방법이 있는지 알고 싶습니다.
예, JavaScript에는 "단락"평가가 있습니다.
if (true == true || foo.foo){
// Passes, no errors because foo isn't defined.
}
if (false && foo.foo){
// Passes, no errors because foo isn't defined.
}
이 답변은 JavaScript에서 단락이 작동 하는 방법에 대해 자세히 설명 합니다. 빠른 정의를 찾고 있고 단락이 작동하는 방식을 이미 이해하고 있다면 모든 문제와 연산자 우선 순위와 같은 관련 주제 를 사용하여 단락이 작동하는 방식을 권장합니다. 다른 답변을 확인합니다.
우리가 지금까지 알고있는 것 :
먼저 두 가지가 있는지 확인하는 데 if()
사용 하는 블록 내부에서 우리 모두에게 익숙한 동작을 살펴 보겠습니다 .&&
true
if (true && true) {
console.log('bar');
}
: 지금, 당신의 첫번째 본능 말을 아마 '아 그래, 아주 간단한 코드는 두 경우 문을 실행 expr1
하고 expr2
로 평가됩니다 true
'
글쎄, 예 그리고 아니오. 당신은 기술적으로 정확합니다. 그것은 당신이 기술 한 행동입니다. 그러나 그것은 정확히 코드가 평가되는 방식이 아니며 우리는 완전히 이해하기 위해 더 깊이 탐구해야 할 것입니다.
&&
과 는 정확히 어떻게 ||
해석 됩니까 ? :
" 자바 스크립트 엔진의 내부" 를 살펴볼 때 입니다. 이 실용적인 예를 살펴 보겠습니다.
function sanitise(x) {
if (isNaN(x)) {
return NaN;
}
return x;
}
let userinput = 0xFF; // as an example
const res = sanitise(userinput) && userinput + 5
console.log(res);
결과는 260
.. 인데 왜? 답을 얻으려면 단락 평가가 어떻게 작동하는지 이해해야합니다.
By the MDN Definition the
&&
operator inexpr1 && expr2
is executed followingly:If
expr1
can be converted totrue
, returnsexpr2
; else, returnsexpr1
.
So this means, in our practical example, the const res
is evaluated the following way:
- Invoking
expr1
-sanitise(0xFF)
0xFF
is a valid hexadecimal number for 250, otherwise I'd returnNaN
- The
expr1
returned a "truthy" value, time to executeexpr2
(otherwise I'd stop asNaN
is falsy) - Since
userinput
is truthy (a number), I can add+5
to it
So here, we were able to avoid additional if
blocks and further isNaN
checks with a simple usage of the &&
operator.
How it really works:
By now, we should at least have a picture how the short-circuit operators work. The universal rule goes:
(some falsy expression) && expr
will evaluate to falsy expression(some truthy expression) || expr
will evaluate to truthy expression
Here are some further examples for better comprehension:
function a() { console.log('a'); return false; }
function b() { console.log('b'); return true; }
if ( a() && b() ){
console.log('foobar');
}
//Evaluates a() as false, stops execution.
function a() { console.log('a'); return false; }
function b() { console.log('b'); return true; }
if ( a() || b() ){
console.log('foobar');
}
/* 1. Evaluates a() as false
2. So it should execute expr2, which is `b()`
3. b() returned as true, executing statement `console.log('foobar');`
*/
One last pesky, but very important thing [Operator Precedence]:
Nice, hopefully you're getting the hang of it! Last thing we need to know is a rule about operator precedence, that is:
- The
&&
operator is always executed prior to the||
operator.
Consider the following example:
function a() { console.log('a'); return true;}
function b() { console.log('b'); return false;}
function c() { console.log('c'); return false;}
console.log(a() || b() && c());
// returns a() and stops execution
This will return as, perhaps confusingly to some as a()
. Reason is quite simple, it's just our eye-sight that's kind of deceiving us, because we're used to reading left-to-right. Let's take the console.log()
and what not out and focus purely on the evaluation
true || false && false
Now to wrap your head around this:
We said the
&&
operator has precedence, so it gets evaluated as first. To help us better imagine the evaluation, think of the definitionexpr1 && expr2
Where:
expr2
isfalse
expr1
istrue || false
So that was the tricky part, now
true || false
is evaluated (theexpr1
- left-side of the&&
).- Given the
||
operator stops execution ifexpr1 || expr2
inexpr1
evaluates as truthy, theexpr1
is executed and code execution stops.
- Given the
The returned value is
true
음 .. 그건 꽤나 까다로 웠습니다. 이상한 규칙과 의미론이 거의 없기 때문입니다. 하지만 당신은 항상 함께 연산자 우선 순위를 탈출 할 수 기억 ()
- 단지 수학처럼
function a() { console.log('a'); return true;}
function b() { console.log('b'); return false;}
function c() { console.log('c'); return false;}
console.log((a() || b()) && c());
/* 1. The () escape && operator precedence
2. a() is evaluated as false, so expr2 (c()) to be executed
3. c()
*/
참고 URL : https://stackoverflow.com/questions/12554578/does-javascript-have-short-circuit-evaluation
'developer tip' 카테고리의 다른 글
Rails는 마법을 만들거나 업데이트합니까? (0) | 2020.09.09 |
---|---|
기능적 언어 (특히 Erlang)는 어떻게 / 왜 잘 확장됩니까? (0) | 2020.09.09 |
ADO.NET Entity Framework : 업데이트 마법사가 테이블을 추가하지 않습니다. (0) | 2020.09.08 |
GPS 또는 인터넷을 사용하지 않고 Android에서 사용자의 현재 위치를 가져옵니다. (0) | 2020.09.08 |
명명 된 함수 식을 사용하는 이유는 무엇입니까? (0) | 2020.09.08 |