`require()` 将字符串文字 "true" 转换为布尔值 true
`require()` converts the string literal "true" to the boolean true
我在 JSON 文件中有以下映射:
"mapping": [
{
"true": "some string"
},
{
"false": "some other string"
}
]
在这样的映射中,键总是字符串。这就是为什么我需要键是字符串,即使在这种情况下,它们是布尔值的字符串表示形式。
当我用 require(myfile.json)
加载此 JSON 文件时,键会以某种方式转换为实际的布尔值。
这是 require()
中的错误吗?有解决方法吗?
那不是 require
的事情。 Javascript 允许使用任何项目作为对象键,但在保存或检索项目时在后台调用 toString
。例如:
const a = {};
a[true] = 'value from true';
a[{somekey: 'somevalue'}] = 'value from object';
Object.getKeys(a); // ["true", "[object Object]"]
所以您的问题与 javascript 处理对象键的方式有关。在对象键中存储值时,无法区分 true
和 'true'
:
a = {};
a[true] = 'from plain true';
a["true"] = 'from stringified true';
a[true]; // "from stringified true". See how the second assignation messes with the first, even if we are using the boolean true value as key.
供参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
我在 JSON 文件中有以下映射:
"mapping": [
{
"true": "some string"
},
{
"false": "some other string"
}
]
在这样的映射中,键总是字符串。这就是为什么我需要键是字符串,即使在这种情况下,它们是布尔值的字符串表示形式。
当我用 require(myfile.json)
加载此 JSON 文件时,键会以某种方式转换为实际的布尔值。
这是 require()
中的错误吗?有解决方法吗?
那不是 require
的事情。 Javascript 允许使用任何项目作为对象键,但在保存或检索项目时在后台调用 toString
。例如:
const a = {};
a[true] = 'value from true';
a[{somekey: 'somevalue'}] = 'value from object';
Object.getKeys(a); // ["true", "[object Object]"]
所以您的问题与 javascript 处理对象键的方式有关。在对象键中存储值时,无法区分 true
和 'true'
:
a = {};
a[true] = 'from plain true';
a["true"] = 'from stringified true';
a[true]; // "from stringified true". See how the second assignation messes with the first, even if we are using the boolean true value as key.
供参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects