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');
}
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.
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');
}
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
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With