2013-05-23 7 views
7

switch 문을 통해 객체 속성 값이 "truthy"인지 확인하려고합니다. switch 문에서 Truthy를 평가하는 중

var test = { 
    foo: "bar" 
} 

switch(true) { 
    case test.foo: 
    console.log("success in switch"); 
    break 
    default: 
    console.log("no success in switch"); 
    break 
} 

if (test.foo) { 
    console.log("success in if"); 
} else { 
    console.log("no success in if"); 
} 

로깅을 끝

:

"no success in switch" 
"success in if" 

이 작업을 수행하는 적절한 방법은 무엇입니까

이 샘플 블록을 사용하십니까?

+0

는 "truthy"무엇을 의미합니까? – James

+0

James : http://www.sitepoint.com/javascript-truthy-falsy/는 진리와 거짓에 대한 개념을 설명합니다. –

답변

12

이 작업을 수행 할 수 있습니다

case !!test.foo: 

이 논리 값으로 변환을 강제 것이다.

+0

멋진 팁. 나는 그것을 모른다. – FLX

+0

답장을 잊어 버렸다. 나는 좋은 ole double equals을 잊어 버렸다. 재교육을 해주셔서 감사합니다! –

-1

부울을 강요 !!을 사용하는 것 외에도 truthy/falsy 평가하기 위해 switch 문이 작업을 수행 할 수 있습니다 : 당신이 당신 자신을 위해 볼 수 있도록 여기에

switch (true) {    // use a boolean to force case statement to evaluate conditionals 
case (val ? true : false): // force a truthy/falsy evaluation of val using parentheses and the ternary operator 
    console.log(val + ' evaluates as truthy in the switch statement.'); 
    break; 
default: 
    console.log(val + ' evaluates as falsy in the switch statement.'); 
    break; 
} 

는 기능과 테스트 세트를의를 : 물론
(function() { 
    'use strict'; 
    var truthitizeSwitch = function (val) { 
      switch (true) {    // use a boolean to force case statement to evaluate conditionals 
      case (val ? true : false): // force a truthy/falsy evaluation of val using parentheses and the ternary operator 
       console.log(val + ' evaluates as truthy in the switch statement.'); 
       break; 
      default: 
       console.log(val + ' evaluates as falsy in the switch statement.'); 
       break; 
      } 
      return !!val; // use !! to return a coerced boolean 
     }, 
     truthitizeIf = function (val) { 
      if (val) {  // if statement naturally forces a truthy/falsy evaluation 
       console.log(val + ' evaluates as truthy in the if statement.'); 
      } else { 
       console.log(val + ' evaluates as falsy in the if statement.'); 
      } 
      return !!val; // use !! to return a coerced boolean 
     }, 
     tests = [ 
      undefined,        // falsey: undefined 
      null,         // falsey: null 
      parseInt('NaNificate this string'),  // falsey: NaN 
      '',          // falsey: empty string 
      0,          // falsey: zero 
      false,         // falsey: boolean false 
      {},          // truthy: empty object 
      {"foo": "bar"},       // truthy: non-empty object 
      -1,          // truthy: negative non-zero number 
      'asdf',         // truthy: non-empty string 
      1,          // truthy: positive non-zero number 
      true         // truthy: boolean true 
     ], 
     i; 
    for (i = 0; i < tests.length; i += 1) { 
     truthitizeSwitch(tests[i]); 
     truthitizeIf(tests[i]); 
    } 
}()); 

그리고, :), 의무 jsFiddle : http://jsfiddle.net/AE8MU/

+0

답장을 보내 주셔서 감사합니다. 나는 더 간결한 사람을 더 좋아한다 !!, 그러나 이것은 좋은 해결책이다. –

관련 문제