<分区>
const obj = {
15: 100
};
for(let key in obj)
console.log(key, typeof(key), typeof(+key))
结果是15 串数字
。我正在尝试遍历对象值并将其中一些放入 Map 对象中,但类型兼容性似乎无法实现。我在这里做错了什么还是对象键总是字符串?
Object.keys(obj)
也返回 ["15"]
<分区>
const obj = {
15: 100
};
for(let key in obj)
console.log(key, typeof(key), typeof(+key))
结果是15 串数字
。我正在尝试遍历对象值并将其中一些放入 Map 对象中,但类型兼容性似乎无法实现。我在这里做错了什么还是对象键总是字符串?
Object.keys(obj)
也返回 ["15"]
最佳答案
对象键总是字符串。可以看更多here :
Property names must be strings. This means that non-string objects cannot be used as keys in the object. Any non-string object, including a number, is typecasted into a string via the toString method.
为了能够实现您想要的效果,您需要将 key 转换回整数。
关于javascript - 不能强制对象键为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52060440/