如何动态更改for循环中的键

时间:2018-12-17 07:16:58

标签: javascript arrays javascript-objects

我希望能够在for循环中更改键,很难解释我需要什么,所以我基于https://www.w3schools.com/js/tryit.asp?filename=tryjs_loop_for进行了演示。

我需要能够根据逻辑交换密钥,因为数组数据密钥将根据json feed进行更改,因此无法对密钥进行硬编码。

预先感谢

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Loops</h2>

<p id="demo"></p>

<script>

var cars = [{"name":"BMW", "colour":"blue"}, {"name":"Volvo", 
"colour":"green"}, {"name":"Saab", "colour":"pink"}, {"name":"Ford", 
"colour":"grey"}, {"name":"Fiat", "colour":"yellow"}, {"name":"Audi", 
"colour":"silver"}];

var text = "";
var i;
for (i = 0; i < cars.length; i++) {

var keyToChoose = "name"; /// or I could choose "colour"

text += cars[i].keyToChoose + "<br>";  /// how do I dynamically change 'keyToChoose'?

}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

2 个答案:

答案 0 :(得分:2)

您可以像这样使用它。

text += cars[i][keyToChoose] + "<br>";

现在它取决于变量keyToChoose的值。

答案 1 :(得分:1)

您可以使用全局变量来确定密钥。

<script>

// 1 = name , 2 = colour
var currentKey = 1;

var cars = [{"name":"BMW", "colour":"blue"}, {"name":"Volvo", 
"colour":"green"}, {"name":"Saab", "colour":"pink"}, {"name":"Ford", 
"colour":"grey"}, {"name":"Fiat", "colour":"yellow"}, {"name":"Audi", 
"colour":"silver"}];

var text = "";
var i;
for (i = 0; i < cars.length; i++) {

// the key is chosen based on the currentKey which can be made a global variable and changed dynamically.
var keyToChoose = currentKey === 1 ? "name" : "colour";

text += cars[i].keyToChoose + "<br>";  /// how do I dynamically change 'keyToChoose'?

}
document.getElementById("demo").innerHTML = text;
</script>