1

我有一个奇怪的问题。我正在尝试使用 Javascript 从多维数组中获取一些值,它给了我一些奇怪的输出。

这是我的代码:

foo = [['3','4'],['5','6']];

for (bar in foo) {

    baz = bar[0];
    alert(baz);

    qux = bar[1];
    alert(qux);

}

这是上面的输出:

// These are all alerts, by the way
0,undefined,1,undefined,$,f,$,c,e,a,c,l,c,l,i,i,n,a,s,l,i,c,o,a,p,g,e,g,e,i,n,c,o,e,r,e,m,f,l,p,i,h,e,r,g       

有人可以告诉我发生了什么吗?

这是问题的 jsFiddle:http: //jsfiddle.net/Jey6w/

编辑:

这是另一个 jsFiddle,还有一层“Inception”:http: //jsfiddle.net/8vyGq/

输出:

// Again, these are all alerts, and * signifies undefined
0**1**$ff$ceaacllcllinnassliicooappgeegeeinncooerremmfllpiiheergg 
4

2 回答 2

6

JavaScriptfor ... in循环为您提供对象属性的名称,而不是值。

不要for ... in用于真正的数组。使用数字索引或.forEach().

您获得输出的原因是复杂且无趣的,因为您不应该这样做,但这是一个开始。属性名称将被强制转换为字符串for ... in。因此,在第一次迭代中,“bar”是字符串“0”,所以("0")[0]只是“0”,因为“bar”("0")[1]undefined一个单字符字符串。

之后,您的for ... in循环会错开到从某处继承的其他一些属性;也许你正在使用原型或其他东西。然后循环提醒前两个字符所有其他属性的名称。

于 2012-08-09T22:06:36.287 回答
1

我可能是错的,但我认为这是由于bar返回对对象内属性的引用。将您的选择器更改为foo[bar][0]一种享受。

foo = [['3','4'],['5','6']];

for (bar in foo) {
    alert(foo[bar][0]);
    alert(foo[bar][1]);
}​

如果您的对象只是一个多维数组,我会使用该for in语句来改变数组,因为它可以选择不需要的属性。我会坚持好的老式for(start, stop, increment)

foo = [['3','4'],['5','6']];

for (i = 0; i < foo.length; i++) {
    alert(foo[i][0]);
    alert(foo[i][1]);
}​

更新 - jQuery

由于已经提到 jQuery 的.each方法,我想我也会发布一个如何使用它的示例。jQuery 的 each 方法传递 2 个可选参数indexInArray, 和valueOfElement。此外,jQuery 文档还指出

该值也可以通过this关键字访问,但Javascript总是将这个值包装为一个对象,即使它是一个简单的字符串或数字值

考虑到这一点,我们可以使用以下 jQuery ( jsFiddle ) 获得与前面示例相同的结果:

var foo = [['3','4'],['5','6']];

$.each(foo, function() {
    // 'this' is the context of the current item within the array
    alert(this[0]);
    alert(this[1]);
}​)​
于 2012-08-09T22:08:51.880 回答