我将一些棋子存储为一组对象,并且我想使用for循环访问键,但是收到一条错误消息:“无法读取未定义的属性'0'。”为什么会这样?
感谢您的帮助!
Javascript:
pawn = {
color: [
{c1: 'white'}, {c2: 'white'}, {c3: 'white'}, {c4: 'white'}, {c5: 'white'}, {c6: 'white'},
{c7: 'white'}, {c8: 'white'}, {c9: 'black'}, {c10:'black'}, {c11: 'black'}, {c12: 'black'},
{c13:'black'}, {c14:'black'}, {c15:'black'}, {c16:'black'}
],
playable: function()
{
k1 = [];
for (i = 0; i < 16; i++)
{
k1.push(Object.keys(pawn.color[i]));
console.log(k1); //[['c1'], ['c2'], ['c3'], ['c4'], ['c5'], ['c6'], ['c7'], ['c8'],
// ['c9'], ['c10'], ['c11'], ['c12'], ['c13'], ['c14'], ['c15'], ['c16']];
}
for (piece = 0; piece < 16; piece++)
{
if (pawn.color[piece].k1[piece][0] == 'white'){ //error msg.
console.log('white');
}
if (pawn.color[piece].k1[piece][0] == 'black'){ //error msg.
console.log('black');
}
}
};
您的color
数组有16个条目。这些条目中的每一个都是以下形式的对象:
{ key: color }
key
为“ c1”至“ c16”,color
为“黑色”或“白色”。
在您的for循环中,您可以尝试以下操作:
if (pawn.color[piece].k1[piece][0] == 'white'){
让我们分解一下:
{c1: 'white'}
]的对象>undefined
值,所以得到k1
。undefined
您可能想要的是:
if (pawn.color[piece][k1[piece][0]] == 'white') {
但是如果将其拆分成这样,则更容易阅读:
const firstKey = k1[piece][0];
if (pawn.color[piece][firstKey] == 'white') {