在数组中查找indexOf值

时间:2016-03-08 18:55:45

标签: javascript arrays

这让我发疯了...... 我用" getElementsByTagName"制作了一个数组。现在,通过使用onclick其中" this"方法返回该数组的一个值,我不能使用" indexOf"找到它的索引。控制台告诉我" arrayThumbs.indexOf不是函数"。

这是代码:

var arrayThumbs = listThumbs.getElementsByTagName("img"); //Makes the array with the img tags

for(i=0;i<maxFiles-1;i++){
    arrayThumbs[i].onclick = function(){
        imgSelect = this; //Returns a valid value of the array, so far so good
        indexThumb = arrayThumbs.indexOf(imgSelect); //Returns an ERROR...
    };
}

真正奇怪的部分是在其他数组中使用相同的语法,这非常有效......

谢谢!

1 个答案:

答案 0 :(得分:4)

msdn page这是“类似数组”但不是数组,因此没有Array.from函数。要将其转换为数组,您可以使用arrayThumbs = Array.from(arrayThumbs); ,如果您的浏览器支持它:

arrayThumbs = Array.prototype.slice.call(arrayThumbs);

或者您可以使用众所周知的技巧将其转换为数组:

{{1}}