传递给回调的 Window windows 数组有许多属性,那么编译器如何知道“var i in windows”指的是什么?
代码片段如下所示:
chrome.windows.getAll({"populate":true}, function(windows) {
for (var i in windows) {
var tabs = windows[i].tabs;
在下一行中,windows[i].tabs
windows 作为数组传递,因此我了解其工作原理,但不了解var i in windows
。
最佳答案
这可能不是最好的方法,但它适用于Array
。
您应该阅读MDN entry on for...in
了解它是如何工作的。
这会迭代对象的可枚举属性。
这解释了为什么像 windows.length
这样的东西不会进入循环。它们通过 .propertyIsEnumerable() 的方式简单地由数组定义为不可枚举,对于继承的事物也是如此:
Objects created from built–in constructors like
Array
andObject
have inherited non–enumerable properties fromObject.prototype
andString.prototype
, such asString
'sindexOf()
method or Object'stoString()
method.
特别是关于数组:
Array indexes are just enumerable properties with integer names and are otherwise identical to general Object properties. There is no guarantee that
for...in
will return the indexes in any particular order and it will return all enumerable properties, including those with non–integer names and those that are inherited.
进一步阅读:
请注意,文档建议使用标准 for
循环、for...of
循环或 .forEach()
(如果是数组) .
关于javascript - 在编写Chrome扩展时, "var i in windows"(在回调函数(windows)内)是如何编译的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29768529/