随机化后从数组中删除项目

时间:2015-10-18 14:55:34

标签: javascript php jquery

因此,有两个不同的图像网址数组。我的代码要求将数组随机化并将随机化的src放入其中一个img标记中。这是它的样子:

var movieArray = ['http://gdj.gdj.netdna-cdn.com/wp-content/uploads/2011/12/grey-movie-poster.jpg', 'http://www.hollywoodreporter.com/sites/default/files/custom/Blog_Images/avengers-movie-poster-1.jpg'];
    var randomSrc1 = movieArray[Math.floor(Math.random() * movieArray.length)];
    var randomSrc2 = movieArray[Math.floor(Math.random() * movieArray.length)];
        $('#movie1_img').attr('src', '' + randomSrc1 + '');
        $('#movie2_img').attr('src', '' + randomSrc2 + '');

这很好用,但现在存在两个图像相同的问题。我不知道如何防止这种情况。在第一个src被赋予movie1_img标签后,我是否需要使用.grep或其他东西从数组中删除该src?

2 个答案:

答案 0 :(得分:0)

尝试使用Array.prototype.slice()Array.prototype.splice()

var movieArray = ['http://gdj.gdj.netdna-cdn.com/wp-content/uploads/2011/12/grey-movie-poster.jpg', 'http://www.hollywoodreporter.com/sites/default/files/custom/Blog_Images/avengers-movie-poster-1.jpg'];
// create copy of `movieArray`
var movies = movieArray.slice();
// get random item from within `movies`
var randomSrc1 = movies.splice(Math.floor(Math.random() * movies.length), 1);
// get remainding item from within `movies`
var randomSrc2 = movies.splice(0, 1);

答案 1 :(得分:0)

Shuffle the array代替:

function shuffle(o){
    for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
}

var movieArray = shuffle(['http://gdj.gdj.netdna-cdn.com/wp-content/uploads/2011/12/grey-movie-poster.jpg', 'http://www.hollywoodreporter.com/sites/default/files/custom/Blog_Images/avengers-movie-poster-1.jpg']);
$('img[id^=movie][id$=_img]').attr('src', function(i){
    return movieArray[i];
});

-jsFiddle-