使用Javascript:比较变量对值数组 [英] Javascript: compare variable against array of values
本文介绍了使用Javascript:比较变量对值数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在JavaScript的我做工作正常以下。
如果(myVar的== || 25 == myVar的26 || myVar的== || 27 == myVar的28)
{
//做一点事
}
我怎样才能缩短?像下面这样。
如果(myVar的IN('25','26','27','28')){
//做一点事
}
或
如果(myVar.indexOf(25,26,27,28)-1个)){//做一些事情}
解决方案
您可以使用<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf\">indexOf(),它返回在该给定元素可以在阵列中被找到的第一个指数,或-1,如果它不是present
使用
如果([25,26,27,28] .indexOf(myVar的)-1个)){//做一些事情}
In javascript I am doing the following which works fine.
if (myVar == 25 || myVar == 26 || myVar == 27 || myVar == 28)
{
//do something
}
How can I shorten it? something like the following.
if (myVar IN ('25','26','27','28')) {
//do something
}
or
if(myVar.indexOf("25","26","27","28") > -1) ) {//do something}
解决方案
You can use indexOf(), it returns the first index at which a given element can be found in the array, or -1 if it is not present.
Use
if([25, 26, 27, 28].indexOf(myVar) > -1) ) {//do something}
这篇关于使用Javascript:比较变量对值数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文