使用拼接设置图像阵列

时间:2013-11-30 08:39:57

标签: javascript arrays

我已经设置了一个简单的图像数组,并希望确保数组中的每个图像只使用一次。我是javascript的新手,不知道如何实现splice元素。

指向完整网站的链接:http://p3.katecooperuk.com

这是我的javascript数组:

var calendarImg = [
    "url(/images/tree.jpg)", 
    "url(/images/santa.jpg)", 
    "url(/images/stockings.jpg)",
    "url(/images/snoopy.jpg)",
    "url(/images/stockings2.jpg)",
    "url(/images/bear.jpg)",
    "url(/images/penguins.jpg)",
    "url(/images/baubles.jpg)",
    "url(/images/polarbear.jpg)",
    "url(/images/village.jpg)",
    "url(/images/village2.jpg)",
    "url(/images/nativity.jpg)",
    "url(/images/santa2.jpg)",
    "url(/images/snowman.jpg)",
    "url(/images/snow.jpg)",
    ]

    function imgRandom(imgArr) {
        return imgArr[Math.floor(Math.random() * imgArr.length)];
    }

$('.doors').click(function(){ 

    // Select Random Image
    var doorImage = imgRandom(calendarImg); 

    // Change background image of door that was clicked
    $(this).css('background-image', doorImage); 

});

2 个答案:

答案 0 :(得分:1)

如果您想了解有关拼接的更多信息,请访问此MDN documentation

function getRandomImage(arr) {
    if (arr.length > 0) { 
        random = Math.floor(Math.random()*arr.length)
        return arr.splice(random, 1)[0];
    } 
}

此函数将返回数组中的元素并从数组中删除该元素。因此,每次调用该函数时,都会返回一个唯一的元素,直到数组为空。

如果数组为空,则函数返回undefined

如果有关于实施的更多信息,请随时提出。

答案 1 :(得分:0)

你的逻辑几乎是正确的。请尝试:

$('.doors').bind('click',function(){ 
     // Select Random Image
    var doorImage = imgRandom(calendarImg); 

    // Change background image of door that was clicked
    $(this).css('background-image', doorImage); 
}

同时改善你的随机功能:

function imgRandom(imgArr) {
        var return_item = imgArr[Math.floor(Math.random() * imgArr.length)];
        if (imgArr.length > 0) { 
           calendarImg = [];
           var random = Math.floor(Math.random()*imgArr.length);
           calendarImg = imgArr.splice(random, 1);
        } 

        return return_item;

}