JSON.stringify 不适用于普通的 Javascript 数组 [英] JSON.stringify doesn't work with normal Javascript array
问题描述
我一定在这里遗漏了一些东西,但以下代码(Fiddle)返回一个空字符串:>
I must be missing something here, but the following code (Fiddle) returns an empty string:
var test = new Array();
test['a'] = 'test';
test['b'] = 'test b';
var json = JSON.stringify(test);
alert(json);
JSON 处理这个数组的正确方法是什么?
What is the correct way of JSON'ing this array?
推荐答案
JavaScript 数组旨在保存带有数字索引的数据.您可以向它们添加命名属性,因为数组是一种对象(这在您想要存储有关保存正常、有序、数字索引数据的数组的元数据),但这不是它们的设计目的.
JavaScript arrays are designed to hold data with numeric indexes. You can add named properties to them because an array is a type of object (and this can be useful when you want to store metadata about an array which holds normal, ordered, numerically indexed data), but that isn't what they are designed for.
JSON 数组数据类型不能在数组上命名键.
The JSON array data type cannot have named keys on an array.
当您将 JavaScript 数组传递给 JSON.stringify
时,命名的属性将被忽略.
When you pass a JavaScript array to JSON.stringify
the named properties will be ignored.
如果您想要命名属性,请使用对象,而不是数组.
If you want named properties, use an Object, not an Array.
const test = {}; // Object
test.a = 'test';
test.b = []; // Array
test.b.push('item');
test.b.push('item2');
test.b.push('item3');
test.b.item4 = "A value"; // Ignored by JSON.stringify
const json = JSON.stringify(test);
console.log(json);
这篇关于JSON.stringify 不适用于普通的 Javascript 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!