how can I compare a string with several values?
Possible Duplicate:
array.contains(obj) in JavaScript
Something like:
if (mystring == "a" || mystring == "b" || mystring =="c")
I was hopping to do:
if (mystring in ("a", "b", "c"))
is it possible?
You could use indexOf()
like this
if ( [ 'a', 'b', 'c' ].indexOf( mystring ) > -1 ) { ... }
EDIT With ES7 comes a little simplification. As of today just Chrome 47+ and FF 43+ seem to support it:
if ( [ 'a', 'b', 'c' ].includes( mystring ) ) { ... }
Array.prototype.includes()
Using indexOf is first thing that comes to mind, however you have to keep in mind, that there's no .indexOf
function in older IEs (so you would have to use your custom code to simulate it, or just go straight to something like jQuery.inArray or underscore.js indexOf).
if ([ 'a', 'b', 'c' ].indexOf( mystring ) > -1 ) { ... }
Side note: as you can see by looking at inArray definition in jQuery source, writing your own indexOf replacement is pretty easy. So like I said - write your own method, copy-paste it from other libraries or just use those libs if you want to be able to use indexOf in every browser out there.
You could do it the old way
a = "a";
b = ["a","b","c","d"];
function check(a,b){
i = 0;
for (i=0;i<b.length;i++) {
if (a === b[i]) {
return true;
}
}
return false;
}
alert(check (a,b))
note that indexOf is a recent addition to the ECMA-262 standard; as such it may not be present in all browsers If you're going to use this with IE it will only work with version 9 or above
链接地址: http://www.djcxy.com/p/13048.html上一篇: 应该在JavaScript比较中使用哪个等于运算符(== vs ===)?
下一篇: 我怎样才能比较一个字符串与几个值?