【问题标题】:How to change the position randomly?如何随机改变位置?
【发布时间】:2014-10-16 02:07:28
【问题描述】:
var imgOut = function(){
    var outImg = Math.floor(Math.random()*slideRandom.length);
    document.getElementById("random").src = imgRandom[outImg];
    var outSlide = slideRandom[outImg]; 
    outSlide();
    var wr = Math.floor(Math.random()*imgRandom.length);
    var btl = Math.floor(Math.random()*bottle.length);

     document.getElementById("bottle2").src = bottle[outImg];
     document.getElementById("bottle1").src = bottle[btl];
     document.getElementById("bottle3").src = bottle[wr];

      /* try below but doesn't work or syntax error occured*/
     var position= ['bottle[outImg]','bottle[btl]','bottle[wr]'];
     var pos = Math.floor(Math.random()*position.length);
     var pos1 = position[pos];
      pos1();   
}

我想做的是 使用不同的数组在不同的随机位置获得不同的每个图像。 我已经完成了不同的图像来获取,但是将三个不同的数组放在随机位置是行不通的。我做错了什么?或者如何更改上面的代码?

【问题讨论】:

  • 几次,你重写了你应该调用的函数“从这个数组中随机选择项目”并且你至少做错了一次。此外,您(随机)选择一个字符串并尝试将其作为函数执行。解决这两个问题,看看会发生什么。
  • 感谢您的回答。了解将字符串放入数组中不起作用。但没听懂你在第一时间写的内容。

标签: javascript arrays arraylist


【解决方案1】:

我不完全理解您的要求,但请考虑以下代码:

var setImage = function(id, src) {
   document.getElementById(id).src = src;
};

var chooseOne = function(array) {
   return array[Math.floor(Math.random()*array.length)];
};

var setRandomImages = function() {
   setImage("bottle1", chooseOne(bottle));
   setImage("bottle2", chooseOne(bottle));
   setImage("bottle3", chooseOne(bottle));
};

如果数组 bottle 是一个 URL 列表,这会做一些事情,但我不能保证它会做你想要的。

【讨论】:

    【解决方案2】:
     var position= ['bottle[outImg]()','bottle[btl]()','bottle[wr]()'];
     var pos = Math.floor(Math.random()*position.length);
     var pos1 = position[pos];
     //pos1();   
     eval( pos1 );
     // or
     (new Function("return pos1"))();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-04
      • 2021-11-11
      相关资源
      最近更新 更多