1

var x = [];

$('input').click(function(){
  $(this.value).push('Hello'); //x.push('Hello');
  alert(x) //Expected Result: 'Hello'
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='button' value='x'>

I want to push the value Hello to the local variable array with the identifier equal to that of the value of the button that was clicked. For example, if the button with the value="x" is clicked, I want var x = ... to be updated. Similarly, if value="y" is clicked, var y = ... should be updated.

Is that possible?

mhodges
  • 10,938
  • 2
  • 28
  • 46
Toleo
  • 764
  • 1
  • 5
  • 19

1 Answers1

1

The easiest way to do that would be to use an object to contain your variables. By default, the window object is used, but that is bad practice. You can wrap the variables yourself, like so:

var values = {
  x: [],
  y: [],
  z: []
};

$('input').click(function(){
  values[this.value].push('Hello'); //x.push('Hello');
  alert(values[this.value]) //Expected Result: 'Hello'
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='button' value='x'>
<input type='button' value='y'/>
<input type='button' value='z'/>
mhodges
  • 10,938
  • 2
  • 28
  • 46
  • Wouldn't a multi dimensional array work too? giving it a key name of the `value` – Toleo Mar 07 '18 at 18:32
  • @Toleo I suppose it could, but you'd have to have some sort of map that said `[0]` was for `x` and `[1]` was for `y`, etc. Or you'd have to have a key/value array and nest your arrays multiple levels deep. It's doable, but highly unnecessary. Using an object is the correct way to do this. – mhodges Mar 07 '18 at 18:34
  • 1
    @Toleo There are numerous ways, [here are a few](https://repl.it/@ugam44/MajesticBoldFunction) – mhodges Mar 07 '18 at 21:19
  • 1
    @Toleo Depends on JS engine. You can look at perf tests, or [this SO question/answers](https://stackoverflow.com/questions/1232040/how-do-i-empty-an-array-in-javascript), but with less than several hundred thousand iterations, the difference is too negligible to worry about. – mhodges Mar 07 '18 at 21:28