Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/460.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,我已经记下了这个问题的第一部分,我可以像这样从数组中选择一个随机元素 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 sl

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

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')));
}
但是,第二行没有给我元素的正确索引,我不知道如何找到它?

你的意思是:

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

你为什么不把随机索引设置成一个变量并使用它呢

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设置一个JSFIDLE,这样我们就可以看到发生了什么。

document.getElementById('slot2')
将为您管理节点(
img
)。因此,在包含
src
值的数组中找不到该值


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

使用属性


document.getElementById('slot2')。attributes[“src”]

slot2
中设置索引,但是在
slot0
中设置警报内容是否正确?还有另外两个插槽(slot0,slot1)也需要相同的处理,警报代码在所有三个实例中都给我-1作为数组元素的索引。您可能应该发布更多代码。阵列图像中有什么?如果其中没有ID属性为“slot0”的图像元素,您将无法找到它:)请尝试使用alert(images.indexOf(document.getElementById('slot2').src));如果您早些时候在id设置为“slot0”的情况下尝试,它肯定会失败:)