使用 for..in 并包含 MooTools 进行 Javascript 数组迭代
我正在 MooTools 中迭代数组,但在使用简写 for..in
循环迭代数组时看到了其他项目。当我使用常规 for
循环时,它工作得很好。这是 MooTools 污染全局命名空间的问题还是我在这里做错了什么?
有一个 createTabs() 函数,它迭代数组并为数组中的每个值创建一个选项卡:
function createTabs() {
var myTabs = [["First", "a.png"], ["Second", "b.png"]];
for(var i in myTabs) {
var tab = new Tab(myTabs[i][0], myTabs[i][1]);
console.log(i);
}
}
这是 console.log(i) 的输出:
0
1
$family
each
clean
associate
link
contains
extend
getLast
getRandom
include
combine
erase
empty
flatten
hexToRgb
rgbToHex
toJSON
I理解了前两个索引,但是其余的从哪里来呢?
编辑:感谢 Chetan 和 k Prime 的快速解答。这是有道理的,MooTools 的 Array.each
添加是更简洁的迭代方式!
现在看起来好多了:
myTabs.each(function(item) {
var tab = new Tab(item[0], item[1]);
console.log(item);
});
I am iterating over an array in MooTools but seeing additional items when iterating through the array using the shorthand for..in
loop. It works fine when I use the regular for
loop. Is this a problem with MooTools polluting the global namespace or am I doing something wrong here?
There is a createTabs()
function that iterates over an array and creates a tab for each value in the array:
function createTabs() {
var myTabs = [["First", "a.png"], ["Second", "b.png"]];
for(var i in myTabs) {
var tab = new Tab(myTabs[i][0], myTabs[i][1]);
console.log(i);
}
}
This is the output of console.log(i)
:
0
1
$family
each
clean
associate
link
contains
extend
getLast
getRandom
include
combine
erase
empty
flatten
hexToRgb
rgbToHex
toJSON
I understand the first 2 indexes, but where is the rest coming from?
Edit: Thanks for the quick answers Chetan and k Prime. That makes sense, and the Array.each
addition by MooTools is much cleaner way to iterate!
Looks a lot better now:
myTabs.each(function(item) {
var tab = new Tab(item[0], item[1]);
console.log(item);
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如 Chetan 指出的,
for .. in
用于对象属性迭代,而不是数组。但是,您可以使用hasOwnProprty
迭代当前成员(而不是 MooTools 设置的继承成员),如下所示:Orr,更好的是,因为您使用的是 MooTools,只需使用 <代码>Array.each方法:
As Chetan pointed out,
for .. in
is meant for object property iteration, not arrays. however, you can iterate over the current members (and not the inherited members set by MooTools), by usinghasOwnProprty
, like so:Orr, better still, since you're using MooTools, just use the
Array.each
method:for..in
并不意味着数组迭代。它迭代对象的所有非内置属性。由于 MooTools 向数组原型添加了更多函数,因此它们现在也是数组属性。请参阅此https://developer.mozilla.org/En/Core_JavaScript_1 .5_Reference/Statements/For...in只需使用基本的 for 循环即可进行数组迭代。
for..in
is not meant for array iteration. It iterates over all the properties of an object that are not built-in. Since MooTools has added more functions to Array prototype, they are now array properties as well. See this https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Statements/For...inJust use a basic for loop for array iteration.