Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a parameter be used to create a new object key and as a variable in the same function?

This is obviously a totally inefficient way to change the background color of a button, but I'm wondering 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 is able to be used inside of a string (e.g. ${variable}) why wouldn't it be able to be used in the above scenario?

like image 506
John R Perry Avatar asked Sep 09 '16 07:09

John R Perry


1 Answers

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

var data = {};

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

changeColor(blueButton);
like image 148
Rory McCrossan Avatar answered Sep 30 '22 03:09

Rory McCrossan