Int*_*Guy 1 javascript arrays alert multidimensional-array
我有一个奇怪的问题.我正在尝试使用Javascript从多维数组中获取一些值,它给了我一些奇怪的输出.
这是我的代码:
foo = [['3','4'],['5','6']];
for (bar in foo) {
baz = bar[0];
alert(baz);
qux = bar[1];
alert(qux);
}
Run Code Online (Sandbox Code Playgroud)
以下是上述输出:
// 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
Run Code Online (Sandbox Code Playgroud)
有人能告诉我发生了什么吗?
这是问题的一个问题:http://jsfiddle.net/Jey6w/
编辑:
这是另一个jsFiddle,另一层"Inception":http://jsfiddle.net/8vyGq/
输出:
// Again, these are all alerts, and * signifies undefined
0**1**$ff$ceaacllcllinnassliicooappgeegeeinncooerremmfllpiiheergg
Run Code Online (Sandbox Code Playgroud)
JavaScript for ... in循环为您提供对象属性的名称,而不是值.
不要for ... in用于真正的数组.使用数字索引或.forEach().
你得到你的输出的原因是复杂和无趣的,因为你不应该这样做,但这是一个开始.属性名称将被强制转换为字符串for ... in.因此,在第一迭代中,"杆"是字符串"0",所以("0")[0]只是"0",("0")[1]是undefined因为"酒吧"是一个单字符串.
在那之后,你的for ... in循环交错进入从某个地方继承的其他一些属性; 也许你正在使用Prototype或其他东西.然后循环警告所有其他属性的名称的前两个字符.