如何使用数组作为属性循环遍历对象

时间:2018-02-05 15:19:15

标签: javascript arrays object

这是我的代码: 我想在每个属性中获取数组的第一个值,但它不起作用。谢谢你的帮助。

var arena = {
 o1: ['gate',1,1],
 o2: ['block',1,1]
};

$(document).ready(function(){
    var canvas = document.getElementById('canvas.arena');
    var xpercent = canvas.width/100;
    var ypercent = canvas.height/100;

    for (var key in arena) {
        if (arena.hasOwnProperty(key)) {
        console.log(key + " -> " + arena[key[0]]);
        }
    }
});

2 个答案:

答案 0 :(得分:2)

几乎:

@FXML
private ChoiceBox<...> categoryDrop ;

public void initialize() {
    categoryDrop.setOnAction(this::folderByCategory);
    // existing code ...
}

@FXML
private void folderByCategory(ActionEvent event) {
    // existing code...
}

键永远是属性,无需检查。

答案 1 :(得分:0)

你非常接近:

var arena = {
 o1: ['gate',1,1],
 o2: ['block',1,1]
};

$(document).ready(function(){
    for (var key in arena) {
      console.log(key + " -> " + arena[key][0]);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

准备好这个小提琴:

https://jsfiddle.net/njvf58ow/1/