阵列显示错误的长度

问题描述 投票:0回答:1

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);
javascript arrays shuffle splice
1个回答
1
投票

输出似乎是(来自一个在线Javascript IDE)。

(10) [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 (5) [10, 9, 7, 1, 5]
 (5) [ 2, 3, 4, 6, 8]

所以它是 正如你的第一条评论所说,长度为5。它确实 成为 五最终。该函数将,在循环。去掉 项,并将其添加到新的列表中。

棘手的是,这个循环的运行次数是由以下因素决定的。

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

现在你可以 认为 那会发生十次,但它不会,只是因为。deck.length变化 每次通过循环(由于物品从循环中移出,它的数量减少了1)。

所以,随着 i 每一次迭代都会上升一个,而 deck.length`会下降一个,它们在五次迭代后在中间相遇。

Iteration   i   length
---------  ---  ------
    1        0     10
    2        1      9
    3        2      8
    4        3      7
    5        4      6
    6        5      5 <- exits loop

0
投票

浏览器,如Chrome和Firefox,可以实时查看打印到控制台的对象,通过 console.log. 这意味着,如果你打开 "开发者工具 "窗格,就会发现 之后 代码运行后,你将看到你的数组在你打开开发者工具查看控制台时的值,而不是数组在运行时的值。console.log 行被执行。

尝试改变你的 console.log 的调用。

console.log(cards, JSON.stringify(cards));

以下是我在Chrome浏览器的控制台中看到的内容 如果我加载页面然后打开开发者工具面板。

> Array(5) "[1,2,3,4,5,6,7,8,9,10]"
> Array(5)
> Array(5)

以下是我在Chrome浏览器控制台中看到的,如果我保持开发者工具窗格打开并重新加载页面。

Array(10) [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] [1,2,3,4,5,6,7,8,9,10]
Array(5) [ 4, 8, 7, 9, 3 ]
Array(5) [ 1, 2, 5, 6, 10 ]

你得到同样的结果吗?


0
投票

有一点值得注意的是,你的函数是在数组引用上操作的,这意味着你在函数内部修改了你的原始数组。

function(deck) {
  var randomizer, randomizedDeck, randomPosition;
  // Here you assign deck reference to randomizer variable
  randomizer = deck;
  randomizedDeck = [];

这就是为什么你的 cards 当执行以下代码时,数组会发生变化 randomizer.splice(...).

由于你要从函数中返回随机的卡片作为结果,你应该用克隆数组代替引用。为了做到这一点,请将上面的内容替换为。

function(deck) {
  var randomizer, randomizedDeck, randomPosition;
  // Let's clone our input array instead of working on reference
  randomizer = deck.slice();
  randomizedDeck = [];

这个解决方案应该也能 "解决 "你的问题。console.log.

© www.soinside.com 2019 - 2024. All rights reserved.