我正在使用javascript和three.js
开始我的第一步。我知道如何使用Math.random
从数组中随机更改图像,如下所示:
Math.floor( Math.random() * imgAr.length );
但是如果每次重新加载我的网站时我想随机选择一组6张图片呢?
我已经尝试了这个,但它不起作用:
var imgAr = [
'sources/instagram2/image1.jpg',
'sources/instagram2/image2.jpg',
'sources/instagram2/image3.jpg',
'sources/instagram2/image4.jpg',
'sources/instagram2/image5.jpg',
'sources/instagram2/image6.jpg',
'sources/instagram2/image7.jpg',
'sources/instagram2/image8.jpg',
'sources/instagram2/image9.jpg',
];
//env map
var url = Math.floor( Math.random() * imgAr.length );
如果有人可以帮助我,那就太棒了。这对我来说是一个非常重要的项目,我正在同时学习。
答案 0 :(得分:1)
这个有效!每次可能120
中的随机序列,连续两次相同序列的1/14400
次机会。
var imgAr = [
'sources/instagram2/image1.jpg',
'sources/instagram2/image2.jpg',
'sources/instagram2/image3.jpg',
'sources/instagram2/image4.jpg',
'sources/instagram2/image5.jpg',
'sources/instagram2/image6.jpg',
'sources/instagram2/image7.jpg',
'sources/instagram2/image8.jpg',
'sources/instagram2/image9.jpg'
];
/*
select takes two arguments, count: the number of urls you want, and array: the array you're gathering from
*/
function select(count, array) {
return recurse([], count, array); // Call the recursive function
}
/*
recurse takes an additional argument, an accumulator, that accumulates the urls selected at random
*/
function recurse(accum, count, array) {
var array = array.slice(); // create a clone of the array, so the original is unaffected
if (count > 0) {
var index = Math.floor( Math.random() * array.length );
accum.push(array.splice(index, 1)[0]); // push element to the accumulator, and remove that element from the array
return recurse(accum, --count, array) // that way the next recursion can't select that element again
}
else {
return accum; // when count reaches 0, return the accumulator
}
}
console.log(select(6, imgAr)); // These two outputs...
console.log(select(6, imgAr)); // ...will usually be different
答案 1 :(得分:1)
更短的变体是:
inv2