在随机化后从数组中删除一个项

Deleting an item from an array after randomization

本文关键字:一个 删除 随机化 数组      更新时间:2023-09-26

所以这里有一个包含两个不同的图像url的数组。我的代码要求将数组随机化,并将随机化的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吗?

尝试使用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);

重新排列数组:

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 -