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; } }
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) { //做一些操作 }