JavaScript 关联数组到 JSON [英] JavaScript associative array to JSON

查看:28
本文介绍了JavaScript 关联数组到 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 JavaScript 关联数组转换为 JSON?

How can I convert a JavaScript associative array into JSON?

我尝试了以下方法:

var AssocArray = new Array();

AssocArray["a"] = "The letter A"

console.log("a = " + AssocArray["a"]);

// result: "a = The letter A"

JSON.stringify(AssocArray);

// result: "[]"

推荐答案

数组应该只包含带有数字键的条目(数组也是对象,但你真的不应该混合这些).

Arrays should only have entries with numerical keys (arrays are also objects but you really should not mix these).

如果您将数组转换为 JSON,则该过程将仅考虑数字属性.其他属性被简单地忽略,这就是为什么你得到一个空数组的原因.如果您查看数组的 length,也许这会更明显:

If you convert an array to JSON, the process will only take numerical properties into account. Other properties are simply ignored and that's why you get an empty array as result. Maybe this more obvious if you look at the length of the array:

> AssocArray.length
0

通常所说的关联数组"实际上只是JS中的一个对象:

What is often referred to as "associative array" is actually just an object in JS:

var AssocArray = {};  // <- initialize an object, not an array
AssocArray["a"] = "The letter A"

console.log("a = " + AssocArray["a"]); // "a = The letter A"
JSON.stringify(AssocArray); // "{"a":"The letter A"}"

对象的属性可以通过数组表示法或点表示法访问(如果键不是保留关键字).因此 AssocArray.aAssocArray['a'] 相同.

Properties of objects can be accessed via array notation or dot notation (if the key is not a reserved keyword). Thus AssocArray.a is the same as AssocArray['a'].

这篇关于JavaScript 关联数组到 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆