Is it possible to use a parameter to create a new key of an object and as a variable in the same function?

This is obviously a completely inefficient way to change the background color of a button, but I wonder why this doesn't work:

<button id="blueButton">Button</button> 
 var data = {}; function changeColor(e){ data.e = "blue"; $('#' + e).css('background-color', data.e); } changeColor(blueButton); 

If a variable can be used inside a string (for example, ${variable} ), why not use it in the above script?

+5
source share
2 answers

To set the object key of a variable, you need to use parenthesis notation: Keep in mind that javascript only allows string or Symbol as Object . If you want to use some other type of key, you need to take a look at Map

 var data = {}; function changeColor(e){ data[e] = "blue"; $('#' + e).css('background-color', data[e]); } changeColor(blueButton); 
+5
source

I think you need to save the changed background color of each button id. below code should help you. check console.log

 var data = {}; function changeColor(e){ data[e] = "blue"; $('#' + e).css('background-color', data[e]); } changeColor('btn1'); console.log(data); changeColor('btn2'); console.log(data); changeColor('btn3'); console.log(data); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <button id="btn1">Button1</button> <button id="btn2">Button2</button> <button id="btn3">Button3</button> 

In your code, it seems like you passed id as an object, not a string. data.e , where e is a data property, the parameter value is not passed.

0
source

All Articles