javascript - 在编写Chrome扩展时, "var i in windows"(在回调函数(windows)内)是如何编译的?

标签 javascript

传递给回调的 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 and Object have inherited non–enumerable properties from Object.prototype and String.prototype, such as String's indexOf() method or Object's toString() 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/

相关文章:

javascript - 如何比较 ul li 文本和数组值

javascript - 在 iframe 点击时触发某些内容

javascript - JS中的自定义日期和时间解决方案

JavaScript/jQuery 倒计时

javascript - 在 Javascript/Jquery 中传递值

javascript - 在 Angular 和 Node 中使用 socket.io 时出现 404 错误

javascript - 在 Shiny 数据表中为每个单元格显示工具提示或弹出窗口?

javascript - D3 字体大小过渡

javascript - JQuery 不删除类?

javascript - IE7无法加载jqgrid