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?

3
  • lol... Commented Mar 7, 2018 at 18:23
  • I'm not at all clear on what it is that you're trying to do. Commented Mar 7, 2018 at 18:26
  • @j08691 Updated the question to better explain what the OP is trying to do Commented Mar 7, 2018 at 18:33

1 Answer 1

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'/>

Sign up to request clarification or add additional context in comments.

4 Comments

Wouldn't a multi dimensional array work too? giving it a key name of the value
@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.
@Toleo There are numerous ways, here are a few
@Toleo Depends on JS engine. You can look at perf tests, or this SO question/answers, but with less than several hundred thousand iterations, the difference is too negligible to worry about.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.