Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/426.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用javascript中另一个数组的值生成一个数组_Javascript_Arrays_Random - Fatal编程技术网

使用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]);
});
返回结果;
}
小结:我有一个图像数组,我随机化显示在页面上,然后我用显示的随机化图像创建另一个数组

您也可以尝试
无序。推(一个[随机];
),但
随机化
方法是一个更通用的解决方案