JSON.stringify不适用于普通的Javascript数组 [英] JSON.stringify doesn't work with normal Javascript array
问题描述
我必须在这里遗漏一些内容,但以下代码(小提琴)会返回一个空字符串:
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数组用于保存带有数字索引的数据。您可以将命名键填充到它们上(当您想要存储关于包含正常,有序,数字索引数据的数组的元数据时,这可能很有用),但这不是它们的设计目的。 JSON数组数据类型不能在数组上具有命名键。
Normal JavaScript arrays are designed to hold data with numeric indexes. You can stuff named keys on to them (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. The JSON array data type cannot have named keys on an array.
如果需要命名键,请使用Object,而不是Array。 / p>
If you want named keys, use an Object, not an Array.
var test = {}; // Object
test['a'] = 'test';
test['b'] = []; // Array
test['b'].push('item');
test['b'].push('item2');
test['b'].push('item3');
var json = JSON.stringify(test);
alert(json);
这篇关于JSON.stringify不适用于普通的Javascript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!