每次重新加载我的网站时,从阵列中随机选择一组6个不同的图像
Randomly select a group of 6 different images from an array each time that I reload my site
我也在使用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 );
如果有人能帮助我,那就太棒了。这对我来说是一个非常重要的项目,同时我也在学习。
这很管用!每次可能的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
一个更短的变体是:
var urls = imgAr.sort(function(){return .5 - Math.random()}).slice(0,6);
相关文章:
- fluxxor向一个flux实例添加一组以上的操作
- 我们怎样才能将内含子J用于一组特定的元素
- 使用linq.js按当前日期订购一组momentjs日期
- 正则表达式,从一组关键字中获取奇数
- 创建一组元素JointJS
- 如何在javascript中获取一组复选框值
- 一组(共组..)
- 使用JS将页面中的每个字母设置为随机颜色.为什么在页面的每个打开标记之前总是有一组额外的span标记
- 在一组复选框中,一次只允许选择一个
- 为什么在fabricjs中可选择的不适用于一组圆
- 如何在不刷新页面的情况下每次单击一组选项卡时刷新视图内容窗格
- 从一组具有相同起始和结束的所有段落的段落中提取包含特定字符串的段落
- 简单的Javascript文本编辑器或一组函数
- 如何从自动填充随机数字的下拉菜单中生成一组文本框
- 每次重新加载我的网站时,从阵列中随机选择一组6个不同的图像
- 换行一组没有标记和随机的段落
在p标签中 - 将一组数字分成等份的子数组,并从给定的整数随机化
- 三个Js如何在一组立方体的立方体的所有侧面映射不同的随机图像
- JavaScript中一组数字的随机排列
- 如何使用 jQuery 随机显示一组元素