我最近需要从 HTML 文档中提取几个节点的值。我使用 querySelectorAll 获取节点,它返回满足条件的节点列表。我以前用过 arr.map,所以我尝试这样做(没有用):
var elems = document.querySelectorAll('select option:checked');
values = elems.map(function(obj) {return obj.value});
当我阅读 MDN 中的文档时,我看到我不得不使用这样的东西:
var elems = document.querySelectorAll('select option:checked');
var values = Array.prototype.map.call(elems, function(obj) {
return obj.value;
});
我的问题是,如果我从 querySelectorAll 得到的是一个数组,为什么我不能像使用任何其他数组那样使用第一个表达式?
最佳答案
My question is, if what I get from querySelectorAll is an array, why can't I use the first expression, like I would for any other array?
querySelectorAll
确实不 返回一个数组,它返回一个 NodeList
.
来自 MDN (强调我的):
Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) that match the specified group of selectors. The object returned is a NodeList.
NodeList
在其原型(prototype)链中没有 Array.prototype
,因此它没有数组方法。
关于javascript - 为什么我不能在 querySelectorAll 的结果上使用 map?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39300213/