Javascript,查看“对象节点列表”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6880773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript, viewing "object nodelist"
提问by Ryan
Doing an alert() on one of my variables gives me this result
对我的一个变量执行 alert() 会给我这个结果
[object NodeList]
How can I see all the values in that?
我怎样才能看到其中的所有值?
Note; I am on Firefox and dont know how to use chromebug so its not installed.
笔记; 我在 Firefox 上,不知道如何使用 chromebug,所以它没有安装。
回答by aroth
You can iterate the values in a NodeList
the same way you would an array:
您可以NodeList
以与数组相同的方式迭代这些值:
for (var index = 0; index < nodeList.length; index++) {
alert(nodeList[index]);
}
Here is a good resource with some more in-depth information: https://web.archive.org/web/20170119045716/http://reference.sitepoint.com/javascript/NodeList
这是一个很好的资源,其中包含一些更深入的信息:https: //web.archive.org/web/20170119045716/http: //reference.sitepoint.com/javascript/NodeList
回答by Juan Mendes
The better alternative is not to use alert, since that will display the object's toString(). Using console.log from FF and Chrome will give you a nice expandable object that you can click on to drill into it
更好的选择是不使用警报,因为这将显示对象的 toString()。使用来自 FF 和 Chrome 的 console.log 会给你一个很好的可扩展对象,你可以点击它来钻取它
And if you really need serialization, you can use outerHTML
如果你真的需要序列化,你可以使用outerHTML
// Firefox doesn't support outerHTML on nodes, so here's a method that does it
// http://stackoverflow.com/questions/1700870/how-do-i-do-outerhtml-in-firefox
function outerHTML(node){
return node.outerHTML || new XMLSerializer().serializeToString(node);
}
for (var index = 0; index < nodeList.length; index++) {
alert(outerHTML( nodeList[i] ) );
}
回答by Artur Beljajev
Nowadays I would definitely use the following:
现在我肯定会使用以下内容:
Chrome, Firefox 3.5+, IE8+
Chrome、火狐 3.5+、IE8+
var elements = document.querySelectorAll('a');
for (var i = 0, element; (element = elements[i]); i++) {
console.log(element);
}
IE11+, Firefox 24+, Chrome 30+ (with experiments enabled)
IE11+、Firefox 24+、Chrome 30+(已启用实验)
let elements = document.querySelectorAll('a');
for (let i = 0, element; (element = elements[i]); i++) {
console.log(element);
}
"element = elements[i]" is preferred over "elements.length" since:
“element = elements[i]”优于“elements.length”,因为:
Node lists are often implemented as node iterators with a filter. This means that getting a property like length is O(n), and iterating over the list by re-checking the length will be O(n^2).
节点列表通常被实现为带有过滤器的节点迭代器。这意味着获得像长度这样的属性是 O(n),通过重新检查长度来迭代列表将是 O(n^2)。
Unlike array access, which is as far as I remember O(1).
与数组访问不同,据我所知,这是 O(1)。
More details:
更多细节: