仅当关联数组通过文字定义以编程方式并置时才会发生此问题。在文字定义上使用 stringify 是可行的。
试图理解,我用它来测试一个字面定义。
var test = {
voice : { state : 'Ready' }
};
console.log('Stringify test: ' + JSON.stringify(test));
输出正是我所期望的:
Stringify test: {"voice":{"state":"Ready"}}
当我以编程方式初始化它时,这不会发生。我应该提到该变量是我创建的对象的私有成员,它具有访问器/获取器方法。在构造函数中,我有:
var states = {};
this.getStates = function()
{
return states;
}
this.setState = function(newState, mediaType)
{
states[mediaType] = newState
}
现在我运行相同的测试。
customObj.setState('{ state: 'Ready' }', 'voice');
var test = customObj.getStates();
console.log('Stringify test: ' + JSON.stringify(test));
输出不是我所期望的:
Stringify Test: []
最后,我仔细检查了测试变量的内容:
for(var x in test)
{
console.log('State in test: ' + x);
console.log('Value of ' + x + ': ' + JSON.stringify(test[x]));
}
有了这个,我得到:
State in test: voice
Value of voice: {"state":"Ready"}
好的,这告诉我它包含我所期望的,但 stringify() 没有格式化它。现在,我对发生了什么感到有些困惑。