奇怪的Javascript警报输出

时间:2012-08-09 22:03:16

标签: javascript arrays multidimensional-array alert

我有一个奇怪的问题。我正在尝试使用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       

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

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

修改

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

输出:

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

2 个答案:

答案 0 :(得分:6)

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

不要将for ... in用于实数组。使用数字索引或.forEach()

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

之后,你的for ... in循环交错进入从某个地方继承的其他属性;也许你正在使用Prototype或其他东西。然后循环警告所有其他属性的名称的前两个字符。

答案 1 :(得分: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的每个方法都传递了2个可选参数indexInArrayvalueOfElement。此外,jQuery文档还声明了

  

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

考虑到这一点,我们可以使用以下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]);
}​)​
相关问题