Home  >  Q&A  >  body text

What's the best beautiful way to present your data, using multiple values ​​for efficient comparison?

<p>What is the most beautiful way to compare a value with multiple options? </p> <p>I know there are many ways to do this, but I'm looking for the neatest way. </p> <p>I ask this question because I hope it is possible to do this (obviously not when you see it): </p> <pre class="brush:php;toolbar:false;">if (foobar == (foo||bar) ) { //do something }</pre> <p><br /></p>
P粉384366923P粉384366923403 days ago398

reply all(2)I'll reply

  • P粉416996828

    P粉4169968282023-08-16 09:20:05

    My previous approach was to put these multiple values ​​into an array, as follows:

    var options = [foo, bar];

    Then use the indexOf() method:

    if(options.indexOf(foobar) > -1){
       //做一些事情
    }

    If you want to be more beautiful:

    if([foo, bar].indexOf(foobar) +1){
       //你再也找不到比这更漂亮的了 :)
    }

    For older browsers:

    ( https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/IndexOf )

    if (!Array.prototype.indexOf) {
        Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
            "use strict";
            if (this == null) {
                throw new TypeError();
            }
            var t = Object(this);
            var len = t.length >>> 0;
            if (len === 0) {
                return -1;
            }
            var n = 0;
            if (arguments.length > 0) {
                n = Number(arguments[1]);
                if (n != n) { // shortcut for verifying if it's NaN
                    n = 0;
                } else if (n != 0 && n != Infinity && n != -Infinity) {
                    n = (n > 0 || -1) * Math.floor(Math.abs(n));
                }
            }
            if (n >= len) {
                return -1;
            }
            var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
            for (; k < len; k++) {
                if (k in t && t[k] === searchElement) {
                    return k;
                }
            }
            return -1;
        }
    }

    reply
    0
  • P粉244730625

    P粉2447306252023-08-16 00:39:25

    Don't try to be too cunning, especially if it affects performance unnecessarily. If you really have a lot of comparisons to do, just format it nicely.

    if (foobar === foo ||
        foobar === bar ||
        foobar === baz ||
        foobar === pew) {
         //做一些操作
    }

    reply
    0
  • Cancelreply