-1

HTML

<div class="one_in"></div>

CSS

.one_in{
width:100px;
height:100px;
border:1px solid #000;
}

JS

var ar = ["one_in", "two_in", "three_in"]; 
var colors = {
    ar[0]: 'blue',
    ar[1]: 'green',
    ar[2]: 'red'
};
x = document.getElementsByClassName('one_in');
for (var i = 0 ; i < x.length ; i++ ){
    x[i].style.backgroundColor = colors[x[i].className];
}

How to use the array ar's value "one_in", "two_in", "three_in" inside the object so my div get automatically colored in blue green red respectively

http://www.w3schools.com/code/tryit.asp?filename=FAYMJN2T8KU2

Anjali
  • 329
  • 2
  • 15
  • 1
    Why not just use the array values directly as the object keys? – Matt Dec 21 '16 at 11:19
  • Object expects keys as static string. Try `var colors = {}; color[ar[0]] = 'blue'` This will create a dynamic property named `one_in` – Rajesh Dec 21 '16 at 11:22

1 Answers1

2

You have to wrap it with [ ].

var colors = {
    [ar[0]]: 'blue',
    [ar[1]]: 'green',
    [ar[2]]: 'red'
};
Gregor Menih
  • 5,036
  • 14
  • 44
  • 66