更准确地说,我理解为什么这在技术上会发生 - 因为 undefined
不是有效的 JSON 类型:
var breakfast = {
"cereal" : "fruit loops",
"pastry" : undefined
};
console.log(breakfast);
// -> { cereal: 'fruit loops', pastry: undefined }
console.log(JSON.stringify(breakfast));
// -> {"cereal":"fruit loops"}
我的问题是 - 为什么这被认为是可接受的行为?我想将 undefined
作为 API 或其他内容的一部分进行传递,这显然是有正当理由的。这似乎有些危险——为什么函数不引发错误,而是厚颜无耻地自行更改我的数据而不发出警告?这看起来有点像 JS 的运行线程。
最佳答案
这个问题的答案在于 ECMA-262 spec .在 24.3.2 JSON.stringify ( value [ , replacer [ , space ] ] )
部分,规范明确指出:
NOTE 2
The undefined value is not rendered.
进一步:
NOTE 5
Values that do not have a JSON representation (such as undefined and functions) do not produce a String. Instead they produce the undefined value. In arrays these values are represented as the String null. In objects an unrepresentable value causes the property to be excluded from stringification.
因此,您使用的 JSON.stringify()
完全遵循现有的 ECMA 规范。
即使使用替换器,没有特别指定您自己的函数,默认替换器规则声明items 应该只被附加:
24.3.2 Subsection 4.b.5.g
If item is not undefined and item is not currently an element of PropertyList
关于javascript - 为什么 JSON.stringify 会忽略值未定义的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31284216/