Answer the question
In order to leave comments, you need to log in
Why does an array sometimes have an undefined value?
Guys, please explain where is the miscalculation in my algorithm?
var deck = {
allCards: ["ch-6", "ch-7", "ch-8", "ch-9", "ch-10", "ch-v", "ch-d", "ch-k", "ch-t", "bu-6", "bu-7", "bu-8"],
randomCards: [],
randomizer: function(min, max) {
var i = 0;
while(i < deck.allCards.length) {
var rand = Math.round(Math.random() * (max-min - 1));
var copyCard = deck.randomCards.push(deck.allCards[rand]);
var cutCard = deck.allCards.splice(rand, 1);
i++;
//console.log(deck.randomCards);
//console.log(deck.allCards);
console.log(rand);
console.log(cutCard);
console.log(copyCard);
}
}
};
deck.randomizer(0, deck.allCards.length);
Answer the question
In order to leave comments, you need to log in
1. Let's start with the fact that while is a bad sign. desk in inner function is bad too, better use this
Refactor -
var deck = {
allCards: ["ch-6", "ch-7", "ch-8", "ch-9", "ch-10", "ch-v", "ch-d", "ch-k", "ch-t", "bu-6", "bu-7", "bu-8"],
randomCards: [],
randomizer: function(min, max) {
for(var i = 0; i < this.allCards.length; i++) {
var rand = Math.round(Math.random() * (max - min - 1));
this.randomCards.push(this.allCards[rand]);
this.allCards.splice(rand, 1);
}
}
};
deck.randomizer(0, deck.allCards.length);
var deck = {
allCards: ["ch-6", "ch-7", "ch-8", "ch-9", "ch-10", "ch-v", "ch-d", "ch-k", "ch-t", "bu-6", "bu-7", "bu-8"],
randomCards: [],
randomizer: function(min, max) {
for(var i = 0; i < this.allCards.length; i++) {
var rand = min + Math.round(Math.random() * (max - min - 1));
this.randomCards.push(this.allCards[rand]);
this.allCards.splice(rand, 1);
}
}
};
deck.randomizer(0, deck.allCards.length);
var deck = {
allCards: ["ch-6", "ch-7", "ch-8", "ch-9", "ch-10", "ch-v", "ch-d", "ch-k", "ch-t", "bu-6", "bu-7", "bu-8"],
randomCards: [],
randomizer: function(min, max) {
for(var i = 0; i < this.allCards.length; i++) {
var rand = Math.round(Math.random() * (this.allCards.length - 1));
this.randomCards.push(this.allCards[rand]);
this.allCards.splice(rand, 1);
}
}
};
deck.randomizer();
var deck = {
allCards: ["ch-6", "ch-7", "ch-8", "ch-9", "ch-10", "ch-v", "ch-d", "ch-k", "ch-t", "bu-6", "bu-7", "bu-8"],
randomCards: [],
randomizer: function(min, max) {
for(var i = 0; i < this.allCards.length; i++) {
var rand = min + Math.round(Math.random() * ((max > this.allCards.length ? this.allCards.length : max) - min - 1));
this.randomCards.push(this.allCards[rand]);
this.allCards.splice(rand, 1);
}
}
};
deck.randomizer(0, deck.allCards.length);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question