我错过了一个简单的语法规则,所以也许你可以向我指出。
我有一个对象定义如下......
var board = {
//this data structure was heavily discussed with Lydia Brothers. its current form is due to her help
state: {
flipped: true,
ballWasDroppedLastMove: false,
topPlace: 0,
bottomPlace: 0,
top: [[1,2,3,4,5,6],[7,8,9,10,11,99],[12,13,14,15,99,99],[16,17,18,99,99,99],[19,20,99,99,99,99],[21,99,99,99,99,99]],
bottom: [[0,0,0,0,0,0],[0,0,0,0,0,99], [0,0,0,0,99,99], [0,0,0,99,99,99], [0,0,99,99,99,99], [0,99,99,99,99,99]],
}, ...
我对这个对象做了一些操作 - 特别是我对board.state.top
感兴趣。
当我将board.state.top
打印到控制台时,我得到如下图所示的内容......
我想访问值12,11,0,0,99,99
。
我从其他语言的经验告诉我,我应该做这样的事情......
for (i=0; i<6; i++){
console.log(pboard.state.top[i])
}
......而这正是我得到上述图片的方式。我尝试过类似board.state.top[i][j]
(添加额外维度)的内容,但会打印值0,0,0,0,99,99
如何访问这些元素?
如下所述,我尝试了以下(无论如何)......
var i;
var j;
for (i=0; i<6; i++){
row = pboard.state.top[i];
row.forEach(element => {console.log(element);});
// for (j=0; j<6; j++){
// console.log(top[j])
// }
}
答案 0 :(得分:0)
为了简化操作,请按系统顺序进行。
首先从属性array
检索board.state.top
并将其存储在变量中。
然后使用forEach
API迭代元素。
示例:
var board = {
//this data structure was heavily discussed with Lydia Brothers. its current form is due to her help
state: {
flipped: true,
ballWasDroppedLastMove: false,
topPlace: 0,
bottomPlace: 0,
top: [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 99], [12, 13, 14, 15, 99, 99], [16, 17, 18, 99, 99, 99], [19, 20, 99, 99, 99, 99], [21, 99, 99, 99, 99, 99]],
bottom: [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 99], [0, 0, 0, 0, 99, 99], [0, 0, 0, 99, 99, 99], [0, 0, 99, 99, 99, 99], [0, 99, 99, 99, 99, 99]],
}
}
var that_row = board.state.top[2];
that_row.forEach(element => { console.log(element); });
&#13;
答案 1 :(得分:0)
试试这个。它应该工作。您需要达到该值,然后逐个获得所需的值。像这样的东西
state.top.forEach(function(innerItem){
innerItem.forEach(function(item){
console.info(item);
})
})
希望它有所帮助。
快乐学习:)
答案 2 :(得分:0)
以下代码段将在pos属性中打印其数组的每个值:
var board = {
//this data structure was heavily discussed with Lydia Brothers. its current form is due to her help
state: {
flipped: true,
ballWasDroppedLastMove: false,
topPlace: 0,
bottomPlace: 0,
top: [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 99], [12, 13, 14, 15, 99, 99], [16, 17, 18, 99, 99, 99], [19, 20, 99, 99, 99, 99], [21, 99, 99, 99, 99, 99]],
bottom: [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 99], [0, 0, 0, 0, 99, 99], [0, 0, 0, 99, 99, 99], [0, 0, 99, 99, 99, 99], [0, 99, 99, 99, 99, 99]],
}
}
board.state.top.forEach(function(pos, topIndex) {
pos.forEach(function(v, i) {
console.log('From top index', topIndex, 'value in position', i, v);
});
});
&#13;