Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript multiple values in variable

Tags:

javascript

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.

like image 625
user1826795 Avatar asked Apr 04 '13 17:04

user1826795


1 Answers

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
like image 175
ajp15243 Avatar answered Nov 14 '22 07:11

ajp15243