Javascript变量中的多个值 [英] Javascript multiple values in variable
问题描述
有没有办法让一个变量具有多个这样的值:
Is there any way to have one variable with multiple values like this:
var variable = 1, 2, 3;
var enteredVal = 1;
if (enteredVal == variable){
alert('You chose the right number');
}
因此,如果变量enteredVal等于1,2或3,它将提醒消息。
我似乎无法理解它。
So if the variable enteredVal is equal to 1, 2 or 3, it will alert the message. I can't seem to get my head around it.
推荐答案
无法分配多个不同的值单个变量。
There is no way to assign multiple distinct values to a single variable.
另一种方法是让变量
成为 数组
,你可以查到看看 enterval
是否在数组中。
An alternative is to have variable
be an Array
, and you can check to see if enteredval
is in the array.
var variable = [1, 2, 3];
var enteredval = 1;
if (variable.indexOf(enteredval) > -1){
alert('you chose the right number');
}
请注意 indexOf
是在IE8及以下版本中无法使用(请参阅要求在底部)。在这种情况下,您需要使用框架/库的方法,或自己编写:
Note that indexOf
on an array is not usable in IE8 and below (see the Requirements section at the bottom). In that case you would need to use a framework/library's method, or write it yourself:
var variable = [1, 2, 3];
var enteredval = 1;
for (var i = 0; i < variable.length; i++) {
if (variable[i] === enteredval) {
alert('you chose the right number');
break; // No need to check all the other values in variable
}
}
要在实例化后修改数组,请查看 push
, pop
, shift
, unshift
。要修改现有值,您可以直接访问索引并重新分配值。
To modify arrays after you have instantiated them, take a look at push
, pop
, shift
, and unshift
for adding/removing values. For modifying existing values, you can directly access the index and reassign the value.
variable[1] = 5;
// variable is now [1, 5, 3] since arrays are 0-indexed
这篇关于Javascript变量中的多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!