What's the best beautiful way to present your data, using multiple values ​​for efficient comparison?
P粉384366923
P粉384366923 2023-08-15 17:03:59
0
2
478
<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粉384366923
P粉384366923

reply all(2)
P粉416996828

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;
    }
}
P粉244730625

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) {
     //做一些操作
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template