2013-05-23 6 views
7

Я пытаюсь определить, является ли значение свойства объекта «правдивым» с помощью оператора switch.Оценка Truthy в инструкции switch

Используя этот пример блок:

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

Джеймс: http://www.sitepoint.com/javascript-truthy-falsy/ объясняет понятия правды и фальши. –

ответ

12

Вы можете сделать это:

case !!test.foo: 

Это вынудит преобразование в булево.

+0

Хороший отзыв. Я не знал, что – FLX

+0

Забыл ответить на это. Я забыл о хорошем двойном оле. Спасибо за переподготовку! –

-1

В дополнение к использованию !! принуждать логическое значение, вы можете сделать это с помощью switch заявления оценить truthy/falsy:

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

Спасибо за подробный ответ pete. Я предпочитаю терпение !!, но это тоже хорошее решение. –

Смежные вопросы