简体   繁体   中英

Display unique image from array using javascript

I have a following code that displays random images from array. It generates random images, but however it fails to load unique image. For more info i would like to add that this code is for Solitaire game so i need to generate unique image.

  var imgArray = ['c1.png', 'c2.png', 'd3.png', 'd4.png', 'h5.png', 'h6.png', 'd7.png', 'h8.png'];

  var basePath="card/";

    function imgRandom() {

        for (var i = 2; i < 8; i++) {
        var rand = imgArray[Math.floor(Math.random() * imgArray.length)];
        var image = new Image();
        image.src = basePath+rand;
        image.id = 'imageid';
        image.width = '100';
        image.height = '130';
        image.style.position = 'absolute';

        document.getElementById('myimg'+i).appendChild(image);
        }
    }
 var imgArray = ['c1.png', 'c2.png', 'd3.png', 'd4.png', 'h5.png', 'h6.png', 'd7.png', 'h8.png'];

 var basePath="card/";

function imgRandom() {
    var imgArrayCopy = imgArray.slice(0); //make a copy of the array.
    for (var i = 2; i < 8; i++) {
    var rNumber = Math.floor(Math.random() * imgArrayCopy.length);
    var rand = imgArrayCopy.splice(rNumber, 1); //deletes the img from the array and returns it;
    var image = new Image();
    image.src = basePath+rand;
    image.id = 'imageid';
    image.width = '100';
    image.height = '130';
    image.style.position = 'absolute';

    document.getElementById('myimg'+i).appendChild(image);
    }
}

This should do that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM