javascript - 不能强制对象键为整数

标签 javascript arrays object types

<分区>

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/

相关文章:

php - 表的 Id 列在发送到客户端之前是否应该加密/散列

将对象推送到数组时出现 Javascript 意外标记点

javascript - 未捕获的类型错误 : Cannot read property 'transitionDuration' of undefined

python - 查找数组中整数游程的索引

java - 在数组中查找多对(两对和/或葫芦)

C++ 排序数组。为什么需要其他排序方法?

android - 过滤列表 Activity

javascript - 性能: findIndex vs Array.原型(prototype).map

javascript - 默认情况下选中的复选框

javascript - Object.create 中的可枚举参数是什么?