【问题标题】:Select a random element from array and check its index从数组中选择一个随机元素并检查其索引
【发布时间】:2012-10-07 12:13:22
【问题描述】:

我已经解决了这个问题的第一部分,我可以像这样从数组中选择一个随机元素

function setImage()
{

var images = ['anemone.gif', 'ball.gif', 'crab.gif', 'fish2.gif', 'gull.gif',  'jellyfish.gif', 'moon.gif', 'sail.gif', 'shell.gif', 'snail.gif', 'sun.gif', 'sunnies.gif', 'whale.gif'];
var slots = [document.getElementById('slot0'), document.getElementById('slot1'), document.getElementById('slot2')];
document.getElementById('slot0').src = images[Math.floor(Math.random() * images.length)];
document.getElementById('slot1').src = images[Math.floor(Math.random() * images.length)];
document.getElementById('slot2').src = images[Math.floor(Math.random() * images.length)];
alert(images.indexOf(document.getElementById('slot2')));
}

但是第二行没有给我正确的元素索引,我不知道还有什么方法可以找到它?

【问题讨论】:

  • slot2中设置索引但是slot0的警告内容对吗?

标签: javascript arrays random


【解决方案1】:

您是否有理由不只是将随机索引设置为变量并仅使用它?

function setImage()
{
    var images = ['anemone.gif', 'ball.gif', 'crab.gif', 'fish2.gif', 'gull.gif',  'jellyfish.gif', 'moon.gif', 'sail.gif', 'shell.gif', 'snail.gif', 'sun.gif','sunnies.gif', 'whale.gif'];
    var slots = [document.getElementById('slot0'), document.getElementById('slot1'),     document.getElementById('slot2')];

    var rnd0 = Math.floor(Math.random() * images.length);
    var rnd1 = Math.floor(Math.random() * images.length);
    var rnd2 = Math.floor(Math.random() * images.length);

    document.getElementById('slot0').src = images[rnd0];
    document.getElementById('slot1').src = images[rnd1];
    document.getElementById('slot2').src = images[rnd2];
    alert(rnd2);
}

如果有,您应该尝试提醒图像的来源,并确保它在格式上与图像数组匹配。

如果您仍然遇到问题,请使用 html 和 JS 设置一个 jsfiddle,以便我们查看发生了什么。

【讨论】:

    【解决方案2】:

    document.getElementById('slot2') 将为您提供节点(在这种情况下为img)。所以你在包含src 值的数组中找不到这个。

    document.getElementById('slot2').src 将为您提供完整路径(如 http://....../file.ext),而不仅仅是文件名。

    使用attributes 属性。

    document.getElementById('slot2').attributes["src"]

    【讨论】:

      【解决方案3】:

      你不是说:

      alert(images.indexOf(document.getElementById('slot2').src));
      

      【讨论】:

      • 还有另外两个插槽 (slot0, slot1) 也需要相同的处理,警报代码给我 -1 作为所有三个实例中数组元素的索引。
      • 您可能应该发布更多代码。数组图像中有什么?如果那里没有带有 ID 属性 == 'slot0' 的图像元素,您将找不到它:)
      • 试试 alert(images.indexOf(document.getElementById('slot2').src));
      • 好吧,如果您之前尝试过将 id 设置为“slot0”,它肯定会失败:)
      猜你喜欢
      • 2014-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-01
      相关资源
      最近更新 更多