简体   繁体   English

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

[英]Deleting an item from an array after randomization

So there is an array of two different urls for images. 因此,图像包含两个不同的URL数组。 My code calls for the array to be randomized and to put the randomized src in one of the img tags. 我的代码要求将数组随机化,并将随机化的src放入img标签之一。 Here is what it looks like: 看起来像这样:

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 + '');

This works fine, but now there is the problem of having the two images being the same. 这很好用,但是现在存在两个图像相同的问题。 I don't know how to prevent this. 我不知道如何防止这种情况。 After the first src is given to the movie1_img tag do i need to delete that src from the array using .grep or something else? 在第一个src提供给movie1_img标签之后,我是否需要使用.grep或其他方法从数组中删除该src?

Try using Array.prototype.slice() , Array.prototype.splice() 尝试使用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);

Shuffle the array instead: 改组数组

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- -jsFiddle-

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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