Julsy Julsy - 1 month ago 16
Javascript Question

How to access the properties of a random object in an array?

I have an array of objects. Each of them has the same properties as the others, but different values. I want to access the properties of a random object in this array, but just one time - so when I get that object randomly, it won't be in the array anymore.

So, I make the array with just three objects as beginning, and make a function which will be invoked by clicking on a button. The function creates 2 variable - one is for storing a random number received from the multiplication of Math.random() and the length of the array, rounded by Math.floor().

The second variable is storing one removed item from the array (and it is random every time), and should return it.

The idea is every time when the user clicks on the button to get an unique card, and not to be able to get the same card again.
It works but not exactly - sometimes, after clicking the button, the user gets nothing, and the message in the console is "Uncaught TypeError: Cannot read property 'background' of undefined".

Any advice is welcome. Thanks.

Here's my code:

var TarotContainer = [];
TarotContainer[0] = {name: "The Fool", background: "url('theFool.jpg')"}
TarotContainer[1] = {name: "The Magician", background: "url('theMagician.jpg')"}
TarotContainer[2] = {name: "The High Priestess", background: "url('theHighPriestess.jpg')"}

function getRandomTaroCard(){
var randomCard = Math.floor(Math.random() * TarotContainer.length);
var pickedRandomCard = TarotContainer.splice(randomCard, 1);
document.getElementById('card').style.backgroundImage = pickedRandomCard[randomCard].background;
document.getElementById('card').style.backgroundRepeat = "no-repeat";


}

Answer

From the Mozilla Javascript Reference on what Array.prototype.splice() returns:

an array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

This means that you must be taking the first element ([0]) of pickedRandomCard.

Like so:

var TarotContainer = [];
TarotContainer[0] = {name: "The Fool", background: "url('theFool.jpg')"}
TarotContainer[1] = {name: "The Magician", background: "url('theMagician.jpg')"}
TarotContainer[2] = {name: "The High Priestess", background: "url('theHighPriestess.jpg')"}

function getRandomTaroCard(){
    var randomCard = Math.floor(Math.random() * TarotContainer.length); 
    var pickedRandomCard = TarotContainer.splice(randomCard, 1);
    document.getElementById('card').style.backgroundImage = pickedRandomCard[0].background;
    document.getElementById('card').style.backgroundRepeat = "no-repeat";   
Comments