Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/388.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在javascript中将变量与多个整数进行比较的最佳方法_Javascript - Fatal编程技术网

在javascript中将变量与多个整数进行比较的最佳方法

在javascript中将变量与多个整数进行比较的最佳方法,javascript,Javascript,我正在做一个游戏,我有一个变量id。我需要将它与多个整数(比如10)进行比较。我知道你可以简单地使用| |和 这很好,除了在这种情况下,我需要做10-15次。有没有更快的方法呢?这和我比较的变量是一样的。只是不同的数字 我不想要一个需要switch语句的答案,而switch语句也几乎需要同样多的工作。我也不希望像我在上面的代码中显示的那样,使用| |运算符得到答案 将要检查的数字放入数组中,并使用indexOf检查其中是否存在id: 常数id=2; 常数arr=[1,2,3]; 如果arr.i

我正在做一个游戏,我有一个变量id。我需要将它与多个整数(比如10)进行比较。我知道你可以简单地使用| |和

这很好,除了在这种情况下,我需要做10-15次。有没有更快的方法呢?这和我比较的变量是一样的。只是不同的数字


我不想要一个需要switch语句的答案,而switch语句也几乎需要同样多的工作。我也不希望像我在上面的代码中显示的那样,使用| |运算符得到答案

将要检查的数字放入数组中,并使用indexOf检查其中是否存在id:

常数id=2; 常数arr=[1,2,3]; 如果arr.indexOfid>-1
console.log'it exists' 您可以使用一个数组来保存比较id的所有值,并使用ArrayindexOf检查id是否在数组中

var values = [1, 2, 3];
if(values.indexOf(id)!==-1){
  //id equals one of the elements of the values array
}
如果需要知道哪个元素id等于,可以将在数组中找到的索引存储为,然后在该索引处获取数组的元素

var values = [1, 2, 3];
var index = values.indexOf(id);
if(index!==-1){
  var value = values[index];//this is the value of id
  //id equals one of the elements of the values array
}

您可以使用数组,然后使用函数includes验证该id

常数id=2; 常量数组=[1,2,3];
如果array.includesid console.logI在!;回答得很好。谢谢你的邀请response@AniketG没问题。这个答案在这里找不到了。应该将其添加到常用副本中。已在中给出,但没有另一份副本:
var values = [1, 2, 3];
var index = values.indexOf(id);
if(index!==-1){
  var value = values[index];//this is the value of id
  //id equals one of the elements of the values array
}