developer tip

JavaScript에는 "단락"평가가 있습니까?

optionbox 2020. 9. 8. 07:54
반응형

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 in expr1 && expr2 is executed followingly:

If expr1 can be converted to true, returns expr2; else, returns expr1.

So this means, in our practical example, the const res is evaluated the following way:

  1. Invoking expr1 - sanitise(0xFF)
  2. 0xFF is a valid hexadecimal number for 250, otherwise I'd return NaN
  3. The expr1 returned a "truthy" value, time to execute expr2 (otherwise I'd stop as NaN is falsy)
  4. Since userinput is truthy (a number), I can add +5 to it
  • "Truthy" means that expression can be evaluated as true. Here's a list of truthy and falsy expressions.

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 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:

  1. We said the && operator has precedence, so it gets evaluated as first. To help us better imagine the evaluation, think of the definition

    expr1 && expr2
    

    Where:

    • expr2 is false
    • expr1 is true || false
  2. So that was the tricky part, now true || false is evaluated (the expr1 - left-side of the &&).

    • Given the || operator stops execution if expr1 || expr2 in expr1 evaluates as truthy, the expr1 is executed and code execution stops.
  3. 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

반응형