indexOf()函数不适用于数组 [英] indexOf() function not working on arrays

查看:370
本文介绍了indexOf()函数不适用于数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个div,如下所示:

I have two divs as shown below:

<div class="container"></div>
<div class="container"></div>

我使用以下两个div创建了一个数组:

I created an array using these two divs:

var containers = document.querySelectorAll(".container");

我还创建了一个变量来表示第一个div:

I also created a variable to represent the first div:

var div1 = document.querySelectorAll(".container")[0];

当我使用 indexOf()来获取数组中第一个div的索引,我得到一个错误:

When I use indexOf() to get the index of the first div in the array, I get an error:


containers.indexOf不是函数

containers.indexOf is not a function

这是一个摘要,总结了我的问题:

Here is a snippet summarizing my problem:

var containers = document.querySelectorAll(".container");
var div1 = document.querySelectorAll(".container")[0];
containers.indexOf(div1); // returns the error

<div class="container"></div>
<div class="container"></div>

推荐答案

querySelectorAll 返回 NodeList ,而不是数组。您可以通过调用来将NodeList转换为数组。 Array.from(...)

querySelectorAll returns a NodeList, not an array. You can convert the NodeList to an array by calling Array.from(...).

这篇关于indexOf()函数不适用于数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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