gpt4 book ai didi

javascript - 为什么数组中的 var 返回字符串索引?

转载 作者:行者123 更新时间:2023-11-28 19:30:53 26 4
gpt4 key购买 nike

我真的很惊讶,在 Javascript 中:

> vals = ["a", "b", "c"]
> for (v in vals) console.log(v + 1)
01
11
21

这是因为:

> for (v in vals) console.log(typeof(v))
string
string
string

所以我被迫做这样的事情:

> for (v in vals) console.log(parseInt(v) + 1)
1
2
3

为什么会发生这种情况?

我知道我能做到

> for (var v = 0; v < vals.length; v++) console.log(v + 1)
1
2
3

但与 python 一起使用时,我的想法是 for ... in ...迭代

最佳答案

我的 friend ,看看原型(prototype)继承的奇迹和诅咒。您正在迭代的内容 for..in不是一个数组。您正在迭代 Array 对象。看一下文档:

Array indexes are just enumerable properties with integer names and are otherwise identical to general Object properties. There is no guarantee that for...in will return the indexes in any particular order and it will return all enumerable properties, including those with non–integer names and those that are inherited.

Because the order of iteration is implementation dependent, iterating over an array may not visit elements in a consistent order. Therefore it is better to use a for loop with a numeric index (or Array.forEach or the for...of loop) when iterating over arrays where the order of access is important.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

因此,您正在处理的是 Array 对象中属性的可枚举“整数名称”,而不是数字顺序。

编辑 for v in array JavaScript 中的 不等于 for v in list在Python中。相当于for k, v in dict.iteritems()但是 k 是作为带有整数名称的字符串隐式提供给您的,可以这么说,即“1”、“2”、“3”等。我认为从面向对象的 Angular 来看,这也是违反直觉的。列表/数组如何成为类似字典的对象?但从原型(prototype)的 Angular 来看,只要任何东西继承自 Object.prototype ,它可以被认为是一个具有键和属性的对象。

关于javascript - 为什么数组中的 var 返回字符串索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26819769/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com