使用javascript中另一个数组的值生成一个数组
我有一个数组,其中包含一些值,用来显示一些随机的图像。我要做的是用随机图像的名称创建另一个数组使用javascript中另一个数组的值生成一个数组,javascript,arrays,random,Javascript,Arrays,Random,我有一个数组,其中包含一些值,用来显示一些随机的图像。我要做的是用随机图像的名称创建另一个数组 var one = new Array("0.jpg", "1.jpg");//first array of images for(i=0; i<=6;i++) { var random=Math.floor(Math.random()*(length));//randomize the images of array one document.write('<img src=
var one = new Array("0.jpg", "1.jpg");//first array of images
for(i=0; i<=6;i++)
{
var random=Math.floor(Math.random()*(length));//randomize the images of array one
document.write('<img src="'+one[random])//display images
varone=新数组(“0.jpg”、“1.jpg”)//第一组图像
对于(i=0;i,您可以向数组添加随机化方法。prototype
:
Array.prototype.random = function () {
var result = [],
that = this.slice();
this.forEach(function () {
result.push(that.splice(Math.floor(Math.random() * that.length), 1)[0]);
});
return result;
}
然后,您可以使用以下工具获得洗牌阵列:
var shuffled=one.random();
我使用顶部样本作为参考,并对其进行了格式化,因为它正在创建副本
<script type = "text/javascript">
var images = new Array('0.jpg', '1.jpg' , '2.jpg', '3.jpg'), result=[] ;
Array.prototype.random = function () {
var that = this.slice();
var length=images.length;
this.forEach(function () {
var rand=Math.floor(Math.random()*(length));
result.push(images[rand]);
});
return result;
var images=new数组('0.jpg','1.jpg','2.jpg','3.jpg'),result=[];
Array.prototype.random=函数(){
var that=this.slice();
var-length=images.length;
this.forEach(函数(){
var rand=Math.floor(Math.random()*(长度));
结果。推送(图像[rand]);
});
返回结果;
}
小结:我有一个图像数组,我随机化显示在页面上,然后我用显示的随机化图像创建另一个数组您也可以尝试无序。推(一个[随机];
),但随机化
方法是一个更通用的解决方案