2013-05-23 12 views
7

Sto cercando di determinare se un valore di proprietà dell'oggetto è "verità" tramite un'istruzione switch.Valutazione di Truthy in switch

Utilizzando questo blocco di esempio:

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"); 
} 

finisce registrazione:

"no success in switch" 
"success in if" 

Qual è il modo corretto di fare questo?

+0

Cosa si intende per "truthy"? – James

+0

James: http://www.sitepoint.com/javascript-truthy-falsy/ spiega i concetti di verità e falsità. –

risposta

12

Si può fare questo:

case !!test.foo: 

Questo costringerebbe una conversione a booleani.

+0

Bel suggerimento. Non sapevo che – FLX

+0

Hai dimenticato di rispondere a questo. Mi sono dimenticato del buon ole doppio equo. Grazie per l'aggiornamento! –

-1

Oltre a utilizzare !! di costringere un valore booleano, si può fare questo con l'affermazione switch per valutare 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; 
} 

Ecco una serie di funzioni e test in modo da poter vedere per la vostra auto:

(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]); 
    } 
}()); 

E, naturalmente :), il jsFiddle obbligatorio: http://jsfiddle.net/AE8MU/

+0

Grazie per la risposta dettagliata pete. Preferisco il terser !!, ma anche questa è una bella soluzione. –