부울을 강요 !!
을 사용하는 것 외에도 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/
는 "truthy"무엇을 의미합니까? – James
James : http://www.sitepoint.com/javascript-truthy-falsy/는 진리와 거짓에 대한 개념을 설명합니다. –