Skip to content Skip to sidebar Skip to footer

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 numbe

Solution 1:

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

Solution 2:

You can store them in an array and use indexOf (as long as you don't need IE 8 support):

var supportedOptions = [1, 2, 3],
    enteredVal = 1;

if(supportedOptions.indexOf(enteredVal) !== -1) alert("Yep!");

Solution 3:

Try using an array:

var variables = [1, 2, 3];

You can access members of the array with variables[i], where i is the index of the array, starting at 0.

variables[0] returns 1

variables[1] returns 2

variables[2] returns 3

This way you can use a for loop to iterate through the array:

var enteredval = 1; //your guessfor(var i = 0; i < variables.length; i++) { //go through each elementif(variables[i] == enteredval) { //if they match...
        alert("You chose the right number!"); //...then you got it!
    }
}

Solution 4:

You can store values of the variable as keys in an object. eg:

let variable={
  1:0,
  2:0,
  3:0
}

enteredVal=3

if (enteredVal in variable) {
  alert('You chose the right number');
}

Solution 5:

You are going to want to create an array which can hold multiple values. You would then want to use index of to determine if the value is found in the array.

var myArray = newArray();

myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;

Check the value:

if(myArray.indexOf(1) > -1){
// exists
}

Post a Comment for "Javascript Multiple Values In Variable"