Javascript multiple values in variable

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

Tags:

Javascript