Can I have multiple values ​​in one variable?

Like the heading "Can I have multiple values ​​in one variable?"

Firstly, I have this form:

<form name="myform"> <input type="text" name="mytext"> <input type="button" onClick="clickButton()"> </form> 

Then take a look at my script.

 <script> function clickButton() { var x = document.myform.mytext.value; var a = 13; var b = 17; var c = 19; if (x == a) { alert('hello'); } else if (x == b) { alert('hello'); } else if (x == c) { alert('hello'); } else { alert('goodbye'); } } </script> 

Is there a way to make one variable with multiple values? For example, var myvalues=1,2,3;

+5
source share
3 answers

The correct answer to your question would be to use array . But from what you are trying to do, it looks like you are looking for an object , specifically the notation for parentheses :

 function clickButton() { var x = document.myform.mytext.value, greetings = { "13": "hello", "17": "hello", "19": "hello" } alert(greetings[x] || "goodbye"); } 
 <form name="myform"> <input type="text" name="mytext"> <input type="button" onClick="clickButton()" value="greet"> </form> 
+4
source

Here you need Array . An array is a variable that can contain multiple values ​​and / or elements. You can assign it your values, and then use the [n] selector, where n is a number from 0 (the first element) and 2 (in this case, 2, because you only have 3 variables, so their positions will be 0, 12).

Then, to make the code more understandable, you can use the switch() operator to check the values ​​and execute some code when a certain value is detected.

Here is an example:

 function clickButton() { var x = document.myform.mytext.value, values = [13, 17, 19]; switch (x) { case values[0]: case values[1]: case values[2]: alert("hello"); break; default: alert("goodbye"); break; } } 
0
source

use an object and give callbacks at values

  function abc(val){ alert(val); } var doSomething = { "1": abc('1');, "2": abc('2');, "3": abc('3'); } 
-1
source

Source: https://habr.com/ru/post/1209595/


All Articles