【问题标题】:Why array is not working on object [duplicate]为什么数组不适用于对象[重复]
【发布时间】:2016-12-21 11:17:37
【问题描述】:

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];
}

如何在对象内部使用数组ar的值"one_in", "two_in", "three_in",以便我的div自动在bluegreenred中分别着色

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

【问题讨论】:

  • 为什么不直接使用数组值作为对象键?
  • Object 期望键为静态字符串。试试var colors = {}; color[ar[0]] = 'blue' 这将创建一个名为one_in的动态属性

标签: javascript html arrays object


【解决方案1】:

你必须用[ ]包裹它。

var colors = {
    [ar[0]]: 'blue',
    [ar[1]]: 'green',
    [ar[2]]: 'red'
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-11
    • 2018-04-03
    • 2023-04-01
    • 2015-09-26
    相关资源
    最近更新 更多