这是我的代码:
var shuffle = function() {
var set = [];
var waiter = [];
var suitset = ["Hearts","Clubs","Diamonds","Spades"];
for (var r = 1;r <= 13;r++) {
for (var s = 0;s < suitset.length;s++) {
card = [];
var cardeval = evalcard(r); //This is an input from another function
card.push(cardeval[0]);
card.push(suitset[s]);
card.push(cardeval[1]);
waiter.push(card);
}
}
while (waiter.length) { //This is what randomizes the deck aka shuffles
set.push(waiter.splice(Math.random() * waiter.length,1));
}
return set;
};
我正在尝试构建一个卡片矩阵(我在这里使用矩阵作为数组数组)。将有52个卡阵列阵列,每个阵列都有卡号,套装和价值。但是在我调用函数之后,card
作为字符串而不是数组返回,即使它是使用数组包含程序[]
定义的。谁能看到我在这里做错了什么?
答案 0 :(得分:2)
<强> Live Demo 强>
function evalcard() { return [1,2]}
var shuffle = function() {
var set = [];
var waiter = [];
var suitset = ["Hearts","Clubs","Diamonds","Spades"];
for (var r = 1;r <= 13;r++) {
for (var s = 0;s < suitset.length;s++) {
var card = {},
cardeval = evalcard(r);
card.num = cardeval[0];
card.suite = suitset[s];
card.val = cardeval[1];
waiter.push(card);
}
}
while (waiter.length) { //This is what randomizes the deck aka shuffles
var randomNum = Math.floor(Math.random() * (waiter.length-1));
set.push(waiter[randomNum]);
waiter.splice(randomNum ,1)
}
return set;
};
var test = shuffle();
console.log(test);
alert(test[0].suite);
将卡片制作成对象,然后将它们传递到数组中,只是为了便于访问。
答案 1 :(得分:0)
为我工作
http://jsfiddle.net/mplungjan/LuUT5/
function evalcard() { return [1,2]}
var shuffle = function() {
var set = [];
var waiter = [];
var suitset = ["Hearts","Clubs","Diamonds","Spades"];
for (var r = 1;r <= 13;r++) {
for (var s = 0;s < suitset.length;s++) {
card = [];
var cardeval = evalcard(r); //This is an input from another function
waiter.push([cardeval[0],suitset[s],cardeval[1]]);
}
}
while (waiter.length) { //This is what randomizes the deck aka shuffles
var x = waiter.splice(Math.random() * waiter.length,1);
set.push(x);
}
return set;
};
var deck = shuffle()[0];
alert(deck[0][1])