数组中的IndexOf元素 [英] IndexOf element in array

查看:60
本文介绍了数组中的IndexOf元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试从元素数组中获取索引。

I try to get index from array of elements.

 var arr = document.getElementsByClassName('class'); //3 elements

 console.log(arr);
 output// [div.class.selected, div.class, div.class, item: function, namedItem: function]

 var selected = document.getElementsByClassName('selected');
 var selected_id = arr.indexOf(selected[0]); 

最后一行代码给我一个错误未捕获TypeError:undefined不是一个函数
我还尝试添加 toString()并搜索,但同样的错误。

The last line of code give me an error Uncaught TypeError: undefined is not a function. I also tried to add toString() and search, but the same error.

推荐答案

这是因为 arr 是(实时)NodeList而不是数组;你想要的是,我想:

It's because arr is a (live) NodeList not an array; what you want is, I think:

console.log([].indexOf.call(arr, selected[0]));

 var arr = document.getElementsByClassName('class');
 var selected = document.getElementsByClassName('selected');
 var selected_id = [].indexOf.call(arr, selected[0]);
 console.log(selected_id);

<div class="class"></div><div class="class"></div><div class="class selected"></div><div class="class"></div>

行:

var selected_id = [].indexOf.call(arr, selected[0]);

使用原生 Array.prototype.indexOf()方法,提供 arr 作为这个(基本上使用 arr 作为调用该方法的数组),提供选择[0] 作为要传递给方法的参数,因此它排序在您自己调用时应用:

Uses the native Array.prototype.indexOf() method, supplying the arr as the this (basically using arr as the array on which the method is called), supplying selected[0] as the argument to be passed to the method, so it sort of gets applied as you called it yourself:

var selected_id = arr.indexOf(selected[0]);

但它是以识别 indexOf()方法不可用于 NodeList 对象(以合法的方式调用它,因此可以防止错误)。

but does it in a way that recognises the indexOf() method isn't available to the NodeList object (calling it in a legitimate way, and therefore preventing the error).

参考文献:

  • Array.prototype.indexOf().
  • document.getElementsByClassName().
  • Function.prototype.call().

这篇关于数组中的IndexOf元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆