JSON.stringify() 和 JavaScript 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6021167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:10:43  来源:igfitidea点击:

JSON.stringify() and JavaScript Objects

javascriptajaxjsonstringify

提问by BuddyJoe

I'm thinking maybe I missed something in JavaScript that I'm just picking up now.

我想也许我错过了 JavaScript 中的一些东西,而我现在才刚刚开始学习。

I tried this code in Chrome console:

我在 Chrome 控制台中尝试了这段代码:

a = [];
a.name = "test";
JSON.stringify(a); 
// which returns value []
a = new Object();
a.name = "test";
JSON.stringify(a); 
// which returns value {"name":"test"}

What is the difference? I thought new Object() was a Microsoft JScript thing? What am I missing? Must have missed something in a spec somewhere. Thanks.

有什么区别?我以为 new Object() 是 Microsoft JScript 的东西?我错过了什么?一定是在某个地方遗漏了规范中的某些内容。谢谢。

回答by Anurag

a = new Object()

and

a = []

are not equivalent. But,

不等价。但,

a = {}

and

a = new Object()

are.

是。

回答by Dan Davies Brackett

new Object()is equivalent to {}(except when it's not because of weird redefinition issues - but ignore that for now.) []is equivalent to new Array(), to which you're then adding a .nameproperty. JSON stringifies arrays in a special way that doesn't capture arbitrary property assignment to the array itself.

new Object()等效于{}(除非它不是因为奇怪的重新定义问题 - 但现在忽略它。)[]等效于new Array(), 然后您要向其添加.name属性。JSON 以一种特殊的方式对数组进行字符串化,该方式不会捕获对数组本身的任意属性分配。

回答by lonesomeday

Setting the nameproperty of an array does nothing to its serialized (JSON-stringified) form. It doesn't put an entry into the array. To do that, you need a.push('test').

设置name数组的属性对其序列化(JSON 字符串化)形式没有任何影响。它不会将条目放入数组中。为此,您需要a.push('test').

Objects are standard parts of Javascript (see, for instance, the MDC docs). The normal way to create an object is with {}, but new Object()works too.

对象是 Javascript 的标准部分(例如,参见MDC 文档)。创建对象的正常方法是使用{},但new Object()也可以使用。

So...

所以...

var a = [];
a.push('test');
JSON.stringify(a); //"["test"]"

a = {};
a.name = 'test';
JSON.stringify(a); //"{"name":"test"}"

回答by user113716

For JSON data, Arrays are meant to have numeric indices, and objects have key/value pairs.

对于 JSON 数据,数组意味着具有数字索引,而对象具有键/值对。

a = [];
a[ 0 ] = "test";

JSON.stringify(a); // returns value ["test"]

回答by Quintin Robinson

Yes you are using []to define your object which is actually an array, but depending on the language you are coming from could be confusing because it is not an associative array.

是的,您[]用于定义实际上是数组的对象,但根据您来自的语言可能会令人困惑,因为它不是关联数组。

Default objects are all maps of key->data and are instantiated with curly brackets {}

默认对象都是 key->data 的映射,并用大括号实例化 {}

If you did

如果你做了

a = {};
a.name = "test";
JSON.stringify(a); 

It should work.

它应该工作。