数组显示不正确的长度

var cards = [1, 2, 3, 4, 5, 6, 7 , 8, 9, 10];

// here is shows the length as 5, but there are 10 values
console.log(cards);

// If I remove this function, the array shows the correct length

var randomizeCards = function (deck){

    var randomizer, randomizedDeck, randomPosition;
    randomizer = deck;
    randomizedDeck = [];

    for(var i = 0; i < deck.length; i++) {

        //max value 10, min value 0
        randomPosition = Math.floor(Math.random() * randomizer.length);

        //assigns value of randomPosition to the place of i in randomized deck
        randomizedDeck[i] = randomizer[randomPosition];

        //removes value of randomizer at randomPosition index
        randomizer.splice(randomPosition, 1);
    }
    return randomizedDeck;
}

var randomCards = randomizeCards(cards);

// These end up being shuffled arrays with only 5 values
console.log(randomCards);

console.log(cards);
评论
  • 没文化
    没文化 回复

    .splice() removes an element from an array.

    randomizer.splice(randomPosition, 1);
    

    切勿在拼接后再将项目添加回数组中,因此数组长度当然会有所不同