for / in loop Array gotcha [英] for/in loop Array gotcha

查看:52
本文介绍了for / in loop Array gotcha的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想让人们知道在阵列上不使用/

循环的另一个原因。

在以下代码中:


var u = [1,1]

for(var i in u)

print([i,i + 2 ,i-0 + 2] .join());

print(typeof(i)+''''+ typeof(i-0));


0,02,2

1,12,3

字符串数

(i + 1)不获取预期的结果因为我是一个字符串!

迭代数组时总是使用类似C的循环。 JavaScript不是
Python!


Ian

I just wanted to let folks know of one more reason not to use for/in
loops on Arrays.

In the following code:

var u = [1,1]
for (var i in u)
print([i, i+2, i-0+2].join());
print(typeof(i) + '' '' + typeof(i-0));

0,02,2
1,12,3
string number

(i+1) does not obtain the expected results because i is a string!
Always use C-like loops when iterating arrays. JavaScript is not
Python!

Ian

推荐答案

var u = [1,1]

for(var i in u)

print([i,2 + i,-0 + 2 + parseInt(i) ] .join());

打印(typeof(i)+''''+ typeof(i-0));


输出为读者猜测

var u = [1,1]
for (var i in u)
print([i, 2+i, -0+2+parseInt(i)].join());
print(typeof(i) + '' '' + typeof(i-0));

output left for readers to guess


2005年9月29日16:49,Ian Osgood写道:


[snip] ]
On 29/09/2005 16:49, Ian Osgood wrote:

[snip]
for(var i in u)


[snip]

(i + 1)不获得预期的结果,因为我是一个字符串!
for (var i in u)
[snip]
(i+1) does not obtain the expected results because i is a string!




当然,因​​为属性名称是/ always / strings。


[snip]


Mike


-

Michael Winter

前缀主题在通过电子邮件回复之前[新闻]。



Of course, because property names are /always/ strings.

[snip]

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.


" Ian Osgood" < IA ** @ quirkster.com>写道:
"Ian Osgood" <ia**@quirkster.com> writes:
我只是想让人们知道在阵列上不使用/
循环的另一个原因。
在下面代码:

var u = [1,1]
for(var i in u)
print([i,i + 2,i-0 + 2] .join ());
print(typeof(i)+''''+ typeof(i-0));

0,02,2
1,12,3
字符串编号

(i + 1)没有获得预期的结果,因为我是一个字符串!
在迭代数组时总是使用类似C的循环。 JavaScript不是Python!


或者,您可以阅读ecmascript规范,以便找出

" for ... in"语法确实如此。


您的建议听起来更像是一个警告而不是其他任何东西,但是我很高兴他们真的很高兴for ... in语法存在。

Ian
I just wanted to let folks know of one more reason not to use for/in
loops on Arrays.

In the following code:

var u = [1,1]
for (var i in u)
print([i, i+2, i-0+2].join());
print(typeof(i) + '' '' + typeof(i-0));

0,02,2
1,12,3
string number

(i+1) does not obtain the expected results because i is a string!
Always use C-like loops when iterating arrays. JavaScript is not
Python!
Or, you could read the ecmascript spec, in order to find out what the
"for .. in" syntax actually does.

Your "advice" sounds more like a warning than anything else, but I''m
actually glad the "for .. in" syntax exists.

Ian




Arnaud



Arnaud


这篇关于for / in loop Array gotcha的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆