JSON.parse允许将null作为值 [英] JSON.parse allows null as value
问题描述
我正在将null传递给 JSON.parse (),尽管记录了第一个参数说它应该是字符串值,但它仍然可以提供null
.
I am passing null to JSON.parse() and although the first parameter is documented saying that it should be a string value, it still works to supply null
.
即使文档说明这是针对字符串的,这怎么也不会引发错误,并且可以在多个浏览器中安全可靠地使用它吗?
How come this does not throw an error even though even though the documentation state this is for strings and can this be safely and reliable used in multiple browsers?
推荐答案
ECMAScript规范表示JSON.parse
的第一步:
- 让
JText
为ToString(text)
.
- Let
JText
beToString(text)
.
意味着它将把给定的任何参数强制转换为字符串,而null
强制转换为"null"
,这是null
的有效JSON表示形式.
Meaning it'll cast whatever argument it's given to a string, and null
casts to "null"
, which is the valid JSON representation of null
.
请注意,单个这样的JSON原语 无效,JSON字符串应包装在对象或数组中.但是解析器传统上对此一无所知,部分原因在于解析器使我想的实现更简单.
Note that a single such JSON primitive shouldn't be valid, a JSON string should be wrapped in an object or array. But parsers have traditionally been lax with that, partially due to it making the implementation simpler I suppose.
这篇关于JSON.parse允许将null作为值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!