为什么javascript在迭代时会将数组索引转换为字符串? [英] Why does javascript turn array indexes into strings when iterating?

查看:56
本文介绍了为什么javascript在迭代时会将数组索引转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个Javascript逻辑让我很困惑。我正在创建一个数组并将其第一个元素设置为数字。当我使用for循环进行交互时,Javascript将数组键转换为字符串。为什么?我希望它保留一个数字。

This Javascript logic puzzles me. I'm creating an array and setting the first element of it to a number. When I interate through it using a "for" loop Javascript turns the array key into a string. Why? I want it to stay a number.

stuff = [];
stuff[0] = 3;

for(var x in stuff) {
    alert(typeof x);
}


推荐答案

这是因为你正在循环通过数组使用 for ... in ,它通常用于循环对象的属性。 javascript引擎可能会转换为字符串,因为字符串类型适用于对象属性的名称。

It's because you're looping through the array using for...in which is generally used for looping over properties of objects. The javascript engine is probably casting to a string because the string type is suitable for names of object properties.

尝试这种更传统的方法:

Try this more traditional approach:

stuff = [];
stuff[0] = 3;

for(var i=0; i<stuff.length; i++) {
    var x = stuff[i];
    alert(typeof x);
}

这篇关于为什么javascript在迭代时会将数组索引转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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