什么是document.querySelectorAll的返回类型 [英] What is the return type of document.querySelectorAll
问题描述
假设我有以下列表:
Let's say I have the following list:
<ol>
<li>Cookies <ol>
<li>Coffee</li>
<li>Milk</li>
<li class="test1">Chocolate </li>
</ol>
并且我在我的html
and I perform this selection at the end of my html
var nodes = document.querySelectorAll('li:first-of-type');
当我尝试使用Chrome nodes.forEach
它给了我一个错误。当我看着它看起来像一个数组的值。我实际上可以使用常规的方式导航它,例如:
When I tried in Chrome nodes.forEach
it gave me an error. When I looked at the value it looked like an array. I actually was able to navigate it using a regular for like:
for(var i=0;i<nodes.length;i++){
nodes[i].onclick= function(){ alert('Hello!'); };
}
那么,实际返回的文档类型是什么.querySelectorAll
?为什么数组方法不起作用?
So, what is the actual returned type of document.querySelectorAll
? why array methods did not work?
因此,它看起来像一个数组,可以解决它,使它像一个数组一样工作,但它不是一个数组? >
So, it looks like an array, can workaround it to make it work like an array but it is not an array?
推荐答案
结果的类型是一个NodeList。
因为它是一个类似数组的对象,所以可以运行 map
, forEach
和其他数组。原型函数就像这样:
The type of the result is a NodeList.
Since it is an Array-like object, you can run the map
, forEach
and other Array.prototype functions on it like this:
var result = document.querySelectorAll('a');
Array.prototype.map.call(result, function(t){ return t; })
forEach
,任何
以及其他Array原型中的函数在类似Array的对象上工作。例如,让我们定义一个带有数字索引(0,1)和长度属性的对象字面值:
The map
, forEach
, any
and other functions in the Array prototype work on Array-like objects. For example, let's define an object literal with numerical indexes (0,1) and a length property:
var arrayLike = { '0': 'a', '1': 'b', length: 2};
forEach方法应用于 arrayLike
对象会喜欢真正的Array。
The forEach method, applied to the arrayLike
object will like on a real Array.
Array.prototype.forEach.call(arrayLike, function(x){ console.log(x) } ); //prints a and b
这篇关于什么是document.querySelectorAll的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!