将一个值与多个值进行比较的最漂亮的方法是什么?

发布于 2025-01-01 23:28:14 字数 198 浏览 0 评论 0原文

将一个值与多个选项进行比较的最漂亮方式是什么?

我知道有很多方法可以做到这一点,但我正在寻找最简洁的方法。

我问这个问题是因为我希望这是可行的(事实并非如此,当你看它时很明显):

if (foobar == (foo||bar) ) {
     //do something
}

Whats the prettiest way to compare one value against multiples options?

I know there are loads of ways of doing this, but I'm looking for the neatest.

i ask because i'd hoped this was workable (it isn't, quite obviously when you look at it):

if (foobar == (foo||bar) ) {
     //do something
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

烟沫凡尘 2025-01-08 23:28:14

不要太偷偷摸摸,尤其是当它不必要地影响性能时。
如果你确实有一大堆比较要做,只需很好地格式化它即可。

if (foobar === foo ||
    foobar === bar ||
    foobar === baz ||
    foobar === pew) {
     //do something
}

Don't try to be too sneaky, especially when it needlessly affects performance.
If you really have a whole heap of comparisons to do, just format it nicely.

if (foobar === foo ||
    foobar === bar ||
    foobar === baz ||
    foobar === pew) {
     //do something
}
探春 2025-01-08 23:28:14

我用来做的是将这些多个值放入一个数组中

var options = [foo, bar];

,然后使用 indexOf()

if(options.indexOf(foobar) > -1){
   //do something
}

来美观:

if([foo, bar].indexOf(foobar) +1){
   //you can't get any more pretty than this :)
}

对于较旧的浏览器:
( 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;
    }
}

What i use to do, is put those multiple values in an array like

var options = [foo, bar];

and then, use indexOf()

if(options.indexOf(foobar) > -1){
   //do something
}

for prettiness:

if([foo, bar].indexOf(foobar) +1){
   //you can't get any more pretty than this :)
}

and for the 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;
    }
}
因为看清所以看轻 2025-01-08 23:28:14

由于没有人添加明显的解决方案,但它可以很好地进行两次比较,我将提供它:

if (foobar === foo || foobar === bar) {
     //do something
}

并且,如果您有很多值(可能数百或数千),那么我建议制作一个 Set,因为这使得非常干净和简单的比较代码并且运行时速度很快:

// pre-construct the Set
var tSet = new Set(["foo", "bar", "test1", "test2", "test3", ...]);

// test the Set at runtime
if (tSet.has(foobar)) {
    // do something
}

对于 ES6 之前的版本,您可以获得一个 Set polyfill,其中有很多。 其他答案中描述了其中之一。

Since nobody has added the obvious solution yet which works fine for two comparisons, I'll offer it:

if (foobar === foo || foobar === bar) {
     //do something
}

And, if you have lots of values (perhaps hundreds or thousands), then I'd suggest making a Set as this makes very clean and simple comparison code and it's fast at runtime:

// pre-construct the Set
var tSet = new Set(["foo", "bar", "test1", "test2", "test3", ...]);

// test the Set at runtime
if (tSet.has(foobar)) {
    // do something
}

For pre-ES6, you can get a Set polyfill of which there are many. One is described in this other answer.

星光不落少年眉 2025-01-08 23:28:14

您可以使用开关:

switch (foobar) {
  case foo:
  case bar:
    // do something
}

You can use a switch:

switch (foobar) {
  case foo:
  case bar:
    // do something
}
鲸落 2025-01-08 23:28:14

只是为了好玩,因为这个问答似乎确实是关于语法微观分析,所以对 André Alçada Padez 的建议进行了微小的修改:

(当然还考虑了他所包含的 IE9 之前的 shim/shiv/polyfill )

if (~[foo, bar].indexOf(foobar)) {
    // pretty
}

Just for kicks, since this Q&A does seem to be about syntax microanalysis, a tiny tiny modification of André Alçada Padez's suggestion(s):

(and of course accounting for the pre-IE9 shim/shiv/polyfill he's included)

if (~[foo, bar].indexOf(foobar)) {
    // pretty
}
甜警司 2025-01-08 23:28:14

为什么不像下面这样使用数组中的 indexOf 呢?

if ([foo, bar].indexOf(foobar) !== -1) {
    // do something
}

只是普通的 Javascript,没有框架或库,但它会 工作IE < 9.

Why not using indexOf from array like bellow?

if ([foo, bar].indexOf(foobar) !== -1) {
    // do something
}

Just plain Javascript, no frameworks or libraries but it will not work on IE < 9.

一身软味 2025-01-08 23:28:14

(foobar == foo || foobar == bar) 否则,如果您仅基于单个整数、枚举值或 String 对象比较表达式,则可以使用 switch。请参阅switch 语句。您还可以使用 André Alçada Padez 建议的方法。最终,您的选择需要取决于您正在做的事情的细节。

(foobar == foo || foobar == bar) otherwise if you are comparing expressions based only on a single integer, enumerated value, or String object you can use switch. See The switch Statement. You can also use the method suggested by André Alçada Padez. Ultimately what you select will need to depend on the details of what you are doing.

梦途 2025-01-08 23:28:14

我喜欢用数组测试 indexOf 的漂亮形式,但请注意,这并不适用于所有浏览器(因为旧的 IExplorers 中不存在 Array.prototype.indexOf)。

但是,通过将 jQuery 与 $.inArray() 函数结合使用,可以实现类似的方法:

if ($.inArray(field, ['value1', 'value2', 'value3']) > -1) {
    alert('value ' + field + ' is into the list'); 
}

它可能会更好,所以你不应该测试indexOf是否存在。

比较时要小心(不要使用 == true/false),因为 $.inArray 返回已找到该值的匹配位置的索引,如果索引为 0,则当它真正存在于数组。

I like the pretty form of testing indexOf with an array, but be aware, this doesn't work in all browsers (because Array.prototype.indexOf is not present in old IExplorers).

However, there is a similar way by using jQuery with the $.inArray() function :

if ($.inArray(field, ['value1', 'value2', 'value3']) > -1) {
    alert('value ' + field + ' is into the list'); 
}

It could be better, so you should not test if indexOf exists.

Be careful with the comparison (don't use == true/false), because $.inArray returns the index of matching position where the value has been found, and if the index is 0, it would be false when it really exist into the array.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文