本文介绍了使用array.splice()卡住洗牌组数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图将 Card 对象的套牌数组随机改组为 newDeck 的<$ c数组$ c> Card 对象,使用 array.splice()。我想我的问题可能与可变范围有关,或者是对 array.splice()的误解。

I'm trying to randomly shuffle a deck array of Card objects into a newDeck array of Card objects using array.splice(). I imagine my problem is either something to do with variable scope, or a misapprehension about array.splice().

var deck = [new Card(), new Card(), new Card(), new Card(), new Card(), new Card()];
var newDeck = [];
var shuffle = function(){
    var i = "";
    for (i = 0; i < deck.length; i++){      
        newDeck[i] = deck.splice(Math.floor(Math.random() * deck.length, 1));
}    
};

shuffle();

有没有更好的方法来洗牌了?

Is there a better way to shuffle a deck?

推荐答案

是的,关于 array.splice()的理解有误。阅读:它将返回已删除元素的数组,如果您使用一张卡: [<对象卡>] 。此外,使用 deck.splice(Math.floor(Math.random()* deck.length,1))时, 1 (我猜应该是要删除多少张卡)是 Math.floor 的参数,而不是 splice -您将删除索引之后的所有元素。因此,您似乎想要:

Yes, there is a misapprehension about array.splice(). Read the docs: It will return an array of the removed elements, in your case with one card: [<object Card>]. Also, with deck.splice(Math.floor(Math.random() * deck.length, 1)), the 1 (which i guess should be how many cards to remove) is an argument to Math.floor, not splice - you will remove all elements after the index. So, you seem to want:

function shuffle(deck) {
    var newDeck = [];
    for (var i = 0; i < deck.length; i++)    
        newDeck[i] = deck.splice(Math.floor(Math.random() * deck.length), 1)[0];
    return newDeck;
}    
shuffle([new Card(), new Card(), new Card(), new Card(), new Card(), new Card()]);

您还要求其他方法进行洗牌:可以使用非常常见的

You have asked for other ways to shuffle: You could use the very common

deck.sort(function(a, b){ return 0.5-Math.random(); })

或:

function shuffle(deck) {
    var newDeck = [];
    for (var i = 0; i < deck.length; i++) {    
        var rand = Math.floor(Math.random() * (i + 1));  
        newDeck[i] = newDeck[rand];
        newDeck[rand] = deck[i];
    }
    return newDeck;
}  

这篇关于使用array.splice()卡住洗牌组数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 08:59