使用JSON发布.Stringify转换关联数组
Issue using JSON.stringify to convert associative array
该问题仅在通过文字定义以编程方式对应关联数组时发生。在字面定义上使用stringify可以工作。
试着去理解,我用这个来测试一个文字定义。
var test = {
voice : { state : 'Ready' }
};
console.log('Stringify test: ' + JSON.stringify(test));
输出正是我所期望的:
Stringify test: {"voice":{"state":"Ready"}}
当我以编程方式初始化它时,这不会发生。我应该提到,变量是我创建的对象的私有成员,该对象具有访问器/getter方法。在构造函数中,我有:
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()没有格式化它。现在,我有点糊涂了
我不知道你是如何创建你的customObj,但以下工作:
var CustomObj = function () {
var states = {};
this.getStates = function()
{
return states;
}
this.setState = function(newState, mediaType)
{
states[mediaType] = newState
}
};
var customObj = new CustomObj();
customObj.setState({ state: 'Ready' }, 'voice');
var test = customObj.getStates();
console.log('Stringify test: ' + JSON.stringify(test));
输出:
Stringify test: {"voice":{"state":"Ready"}}
相关文章:
- 多维关联数组的最后一个索引
- node.js/javascript/couchdb视图到关联数组似乎不起作用
- 具有关联数组数据集的D3.js表
- 后关联数组使用jquery ajax
- 返回一个关联数组,而不是mongoose中的文档数组
- 如何在 Angular JS 中从关联数组创建多个复选框
- 存储在变量中的关联数组中的访问键
- 如何在具有相同 ID 的 Javascript 中按排序函数对关联数组进行排序
- 在主要的JavaScript引擎中,在JavaScript关联数组(动态对象属性)中检索/插入的复杂性是多少
- 关联数组,并使用父数组d作为selection.data()的源数组
- 获取关联数组的标签
- JavaScript:如何在最接近值的关联数组中查找键
- 单击时显示关联数组的元素
- 关联数组 - 使用图像滑块显示键值
- Javascript从关联数组中查找最低数字(气泡排序方法)
- AngularJS过滤器不适用于我的数据:关联数组
- 获取关联数组中当前函数的键
- 如何按一个仍保持字母顺序的特性值(另一个特性值)对关联数组进行排序
- 正在检查JavaScript中是否存在关联数组
- 将数据附加到关联数组或维度数组