奇怪的 Javascript 警报输出

Odd Javascript alert output

本文关键字:输出 Javascript      更新时间:2023-09-26

我有一个奇怪的问题。我正在尝试使用 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,带有另一层"盗梦空间":http://jsfiddle.net/8vyGq/

输出:

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

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

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

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

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

我可能是错的,但我认为这是因为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 将始终将此值包装为对象,即使它是 简单的字符串或数字值

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