Eat*_*lad 5 javascript arrays json object
这是我的阵列(来自Chrome控制台):

这是代码的相关部分:
console.log(hours);
var data = JSON.stringify(hours);
console.log(data);
Run Code Online (Sandbox Code Playgroud)
在Chrome的控制台中,我[]从最后一行获得.我应该得到{'Mon':{...}...}
以下是重现问题的最小JavaScript数量:
var test = [];
test["11h30"] = "15h00"
test["18h30"] = "21h30"
console.log(test);
console.log(JSON.stringify(test)); // outputs []
Run Code Online (Sandbox Code Playgroud)
我尝试了一些其他的东西,如 将数组转换为JSON或将javascript对象或数组转换为json以获取ajax数据,但问题仍然存在.
Jam*_*iec 23
这是重现问题的最小量的javascript
var test = [];
test["11h30"] = "15h00"
test["18h30"] = "21h30"
console.log(test);
console.log(JSON.stringify(test)); // outputs []
Run Code Online (Sandbox Code Playgroud)
上面的问题是,虽然javascript很乐意让你将新属性绑定到后期Array,但JSON.stringify()只会尝试序列化数组中的实际元素.
使对象成为实际对象的最小更改,并按JSON.stringify预期工作:
var test = {}; // here is thre only change. new array ([]) becomes new object ({})
test["11h30"] = "15h00"
test["18h30"] = "21h30"
console.log(test);
console.log(JSON.stringify(test)); // outputs {"11h30":"15h00","18h30":"21h30"}
Run Code Online (Sandbox Code Playgroud)