JavaScript不会将我的变量视为变量(数组问题)

时间:2018-06-21 12:20:30

标签: javascript html arrays

正如标题中所述,我很难尝试制作一件看起来很简单的东西。这是一个简单的示例,更容易理解。

var reccords = {
  1: {
    1: [10, 'zorro'],
    2: [25, 'ro']
  },
  2: {
    1: [20, "dim"]
  }
}

var time = 5;
reccords[3] = {
  time: [2, 'michel']
}; //time isn't considered as a variable

document.getElementById("demo2").innerHTML = reccords[3]['time'][0];
document.getElementById("demo1").innerHTML = reccords[3][5][0]; //does not work, how to make it work?
<p id="demo1"></p>
<p id="demo2"></p>

1 个答案:

答案 0 :(得分:1)

尝试以下使用[time]设置time的值,即5作为对象的属性。这样,在reccords[3]['time'][0]的情况下,您需要使用reccords[3][time][0],因为records[3]不具有time属性。

var reccords = {1:{1:[10,'zorro'],2:[25,'ro']}, 2:{1:[20,"dim"]}}

var time=5;
reccords[3] = {[time]:[2, 'michel']}; //time isn't considered as a variable

document.getElementById("demo2").innerHTML = reccords[3][time][0];
document.getElementById("demo1").innerHTML = reccords[3][5][0];
<p id="demo1"></p>
<p id="demo2"></p>