最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Evaluating Truthy in switch statement - Stack Overflow

programmeradmin6浏览0评论

I am trying to determine if an object property value is "truthy" via a switch statement.

Using this sample block:

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

ends up logging:

"no success in switch"
"success in if"

What is the proper way to do this?

I am trying to determine if an object property value is "truthy" via a switch statement.

Using this sample block:

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

ends up logging:

"no success in switch"
"success in if"

What is the proper way to do this?

Share Improve this question asked May 23, 2013 at 19:03 Paul TPaul T 1,47512 silver badges17 bronze badges 2
  • What do you mean by "truthy"? – James Commented May 23, 2013 at 19:12
  • James: sitepoint./javascript-truthy-falsy explains the concepts of truthy and falsy. – Joel Anair Commented May 24, 2013 at 13:49
Add a ment  | 

2 Answers 2

Reset to default 19

You can do this :

case !!test.foo:

This would force a conversion to boolean.

In addition to using !! to coerce a boolean, you can do this with the switch statement to evaluate 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;
}

Here's a set of functions and tests so you can see for your self:

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

And, of course :), the obligatory jsFiddle: http://jsfiddle/AE8MU/

发布评论

评论列表(0)

  1. 暂无评论