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);
答案 0 :(得分: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
每次在循环中都会发生变化(它会减少一个,因为他把其中的所有物品都搬走了。
因此,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
答案 1 :(得分: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 ]
您得到相同的结果吗?
答案 2 :(得分: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
“解决”您的问题。