我跟随终端中node.js的输出:
node server.js
{ hand:
[ [ [Object], [Object] ],
[ [Object], [Object] ],
[ [Object], [Object] ],
[ [Object], [Object] ] ],
deck:
[ { suit: 'c', rank: 'a' },
{ suit: 'd', rank: 'a' },
{ suit: 'h', rank: 'a' },
{ suit: 's', rank: 'a' },
{ suit: 'c', rank: 'k' },
{ suit: 'd', rank: 'k' },
{ suit: 'h', rank: 'k' },
{ suit: 's', rank: 'k' },
{ suit: 'c', rank: 'q' },
{ suit: 'd', rank: 'q' },
{ suit: 'h', rank: 'q' },
{ suit: 's', rank: 'q' },
{ suit: 'c', rank: 'j' },
{ suit: 'd', rank: 'j' },
{ suit: 'h', rank: 'j' },
{ suit: 's', rank: 'j' },
{ suit: 'c', rank: '10' },
{ suit: 'd', rank: '10' },
{ suit: 'h', rank: '10' },
{ suit: 's', rank: '10' },
{ suit: 'c', rank: '9' },
{ suit: 'd', rank: '9' },
{ suit: 'h', rank: '9' },
{ suit: 's', rank: '9' },
{ suit: 'c', rank: '8' },
{ suit: 'd', rank: '8' },
{ suit: 'h', rank: '8' },
{ suit: 's', rank: '8' },
,
,
,
,
,
,
,
] }
首先,为什么我不能在手中看到Object
?我在这个对象上做console.dir。
其次,为什么我的空逗号区域?我只是做delete deck[i]
这可能更像是一个javascript问题:)
JS:
function deal(num_cards,num_players,deck) {
var hand = [];
var i = deck.length - 1;
for (var p = num_players - 1; p >= 0; p--) {
var player = [];
for (var c = num_cards - 1; c >= 0; c--) {
player.push(deck[i]);
delete deck[i];
i--;
};
hand[p] = player;
};
return {"hand":hand,"deck":deck};
}
答案 0 :(得分:1)
对于第一个问题:您的deck[i]
没有toString
方法。定义一个可以为您提供所需信息的文件,它将替换您获得的[object Object]
输出。例如,如果您的数组包含Card
个对象,则可以执行以下操作:
Card.prototype.toString = function() {
return 'suit=' + this.suit + ';rank=' + this.rank;
}
对于第二个问题:delete
不删除元素。它基本上将其设置为undefined
。请尝试使用deck.splice(i, 1)
。
答案 1 :(得分:1)
console.dir
使用util.inspect
,其默认深度为2.要使用正确的嵌套显示,请使用util.inspect(obj,{depth:null});
delete
将索引的值设置为undefined
。所以你仍然会看到钥匙。就像DoorknobChatbot所说,splice
可以达到目的。