为什么JSON.stringify对于似乎具有属性的对象返回空对象符号"{}"?

Mat*_*s S 12 javascript json text-to-speech stringify

以下示例显示JSON.stringify()返回"{}"SpeechSynthesisVoice对象的字符串:

var voiceObject = window.speechSynthesis.getVoices()[0];
JSON.stringify(voiceObject); //returns "{}"?
Run Code Online (Sandbox Code Playgroud)

完整示例:JSFiddle

它为什么会返回,"{}"而不是像"{voiceURI: "Google Deutsch", name: "Google Deutsch", lang: "de-DE", localService: false, default: false}"什么?

请注意,上面的示例不适用于chrome或iOS; 它针对的是Mozilla Firefox.

T.J*_*der 15

JSON.stringify包括一个对象自己的,可枚举的属性(spec),它们的值不是函数或undefined(因为JSON没有那些),遗漏了它从其原型继承的那些,任何定义为不可枚举的,以及任何其value是函数引用或undefined.

很明显,您从中获取的对象getVoices()[0]没有可以用JSON表示的自己的可枚举属性.它们的所有属性必须是继承的,定义为不可枚举的,或者(尽管可能不是这里的情况)函数或undefined.

  • 或者属于非有效JSON数据类型的属性,尽管这可能与问题的示例无关. (3认同)

小智 6

TJ Crowder 的答案对我有用,我正在创建我的对象,如下所示:

Object.defineProperties(completeObj, {
    [attributeName]: {
        value: finalValue
    }
});
Run Code Online (Sandbox Code Playgroud)

我为此进行了更改,问题解决了:

Object.defineProperties(completeObj, {
    [attributeName]: {
        value: finalValue,
        enumerable: true
    }
});
Run Code Online (Sandbox Code Playgroud)