简体   繁体   中英

How to get more than one random different item in this javascript

I have this code that picks up a random text link using getJSON. It picks up one random item at a time. I'd like to know how to pick up more than one different item and show them in #randomkeyword . All I can come up with is setting up the script two times, but I think it may have a chance of picking up the same item, Is there any way to do that?

jQuery.getJSON('random.json', function(data) { //Ajax call

var item = data.link[Math.floor(Math.random()*data.link.length)]; 

jQuery('<a title="' + item.des + '" href="http://' + item.url + '">'+ item.title +'</a>').appendTo

('#randomkeyword');

});

JSON File:

{"link":[{"title":"XXXX","url":"google.com","des":"light"},{"title":"CCCCCCC","url":"yahoo.com","des":"dark"},{"title":"DDDDDDDD","url":"song.com","des":"light"},{"title":"CCCCCCCCCCCCCCC","url":"googlemap.com","des":"normal"},{"title":"RRRRRRRRRRRRRRR","url":"fun.com","des":"halo"}]}

为了避免重复,您可以“随机播放”列表,然后从头开始遍历。

You could check if the second item is the same as the first item. If so, you can select an other random item.

jQuery.getJSON('random.json', function(data) { //Ajax call

var item = data.link[Math.floor(Math.random()*data.link.length)];
var item2=item;//set second item same as first item to access the while loop

while(item==item2){
   item2 = data.link[Math.floor(Math.random()*data.link.length)];
}

jQuery('<a title="' + item.des + '" href="http://' + item.url + '">'+ item.title +'</a>').appendTo

('#randomkeyword');

});
//do the same for item2

So, I think you can store the list, then just iterate over it however many times you want, splice out the selected ones as you go (to avoid duplicates), and then run your jQuery on each element in the result array. Note that this does modify the returned array, so make a copy of it first if you need that intact.

For example:

var data = ['one', 'two', 'three'];
var numOfLinks = 2;
var result = [];
for(i = 0; i < numOfLinks; i++) {
    var index = Math.floor(Math.random()*data.length);
    var link = data[index];
    data.splice(index,1);
    result.push(link);
}
// iterate over result, doing your jQuery function over each element

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