admin管理员组文章数量:1353636
I'm writing a simple for...in
loop in javascript, and wondering why the key
is a string and not a number?
Why is it so, and can I change that to be a number?
var array = ["a", "b", "c"];
for (var key in array) {
console.log(typeof key); //string
console.log(key + 1); //expected output : 01, 11, 21...
}
I'm writing a simple for...in
loop in javascript, and wondering why the key
is a string and not a number?
Why is it so, and can I change that to be a number?
var array = ["a", "b", "c"];
for (var key in array) {
console.log(typeof key); //string
console.log(key + 1); //expected output : 01, 11, 21...
}
Share
Improve this question
asked Jan 28, 2019 at 11:44
PukaPuka
1,5851 gold badge17 silver badges35 bronze badges
2
- It's probably because for y in x treats the x as an object so you can iterate through its properties – Sebastian Oleński Commented Jan 28, 2019 at 11:47
-
Using a foreach with arrays is a bit expensive if you want to access array elements as you'd have to parse
key
on to an int, is best to use foreach loops for objects ({}
) and not arrays ([]
). The standard loops for arrays are eitherfor(let i=..; i < ....; i++) {}
orarray.forEach(function(val, i) { })
. – Bargros Commented Jan 28, 2019 at 11:53
3 Answers
Reset to default 9It's a string because standard arrays in JavaScript aren't really arrays at all¹, they're objects with properties for the array entries, and object property names (keys) are strings, Symbols, or (soonish) private names.
You can't make it a number by default in a for-in
, but you can convert it to a number, or use other forms such as a standard for
or a forEach
call:
for (var key = 0; key < array.length; ++k) {
// ...
}
// ..or
array.forEach((entry, key) => {
// ...
});
Using for-in
to loop through an array is almost always an anti-pattern. See my answer here for a thorough rundown of your various options for looping through arrays.
¹ That's a post on my anemic little blog.
Objects and properties
Please note that all keys in the square bracket notation are converted to String type, since objects in JavaScript can only have String type as key type.
Object property names are always strings.
Use +
, parseInt
, JSON.parse
or any other standard method to convert a string to a number if you want a number.
var array = ["a", "b", "c"];
for (var key in array) {
console.log(+key + 1);
}
本文标签: javascriptWhy is key a string in forinStack Overflow
版权声明:本文标题:javascript - Why is key a string in for ... in - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743923374a2562508.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论