JavaScript推送到数组

Jac*_*ack 55 javascript arrays json multidimensional-array

如何将新值推送到以下数组?

json = {"cool":"34.33","alsocool":"45454"}
Run Code Online (Sandbox Code Playgroud)

我试过了json.push("coolness":"34.33");,但没办法.

Lig*_*ica 117

它不是一个数组.

var json = {"cool":"34.33","alsocool":"45454"};
json.coolness = 34.33;
Run Code Online (Sandbox Code Playgroud)

要么

var json = {"cool":"34.33","alsocool":"45454"};
json['coolness'] = 34.33;
Run Code Online (Sandbox Code Playgroud)

你可以把它作为一个数组,但它将是一个不同的语法(这几乎肯定不是你想要的)

var json = [{"cool":"34.33"},{"alsocool":"45454"}];
json.push({"coolness":"34.33"});
Run Code Online (Sandbox Code Playgroud)

请注意,此变量名称具有高度误导性,因为此处没有JSON.我会把它命名为别的.


jen*_*ent 37

var array = new Array(); // or the shortcut: = []
array.push ( {"cool":"34.33","also cool":"45454"} );
array.push (  {"cool":"34.39","also cool":"45459"} );
Run Code Online (Sandbox Code Playgroud)

您的变量是javascript对象{}而不是数组[].

你可以这样做:

var o = {}; // or the longer form: = new Object()
o.SomeNewProperty = "something";
o["SomeNewProperty"] = "something";
Run Code Online (Sandbox Code Playgroud)

var o = { SomeNewProperty: "something" };
var o2 = { "SomeNewProperty": "something" };
Run Code Online (Sandbox Code Playgroud)

稍后,您将这些对象添加到您的数组: array.push (o, o2);

JSON只是javascript对象的字符串表示,因此:

var json = '{"cool":"34.33","alsocool":"45454"}'; // is JSON
var o = JSON.parse(json); // is a javascript object
json = JSON.stringify(o); // is JSON again
Run Code Online (Sandbox Code Playgroud)


Jam*_*ers 8

这是一个对象,而不是一个数组.所以你会这样做:

var json = { cool: 34.33, alsocool: 45454 };
json.supercool = 3.14159;
console.dir(json);
Run Code Online (Sandbox Code Playgroud)


KJY*_*葉家仁 7

object["property"] = value;
Run Code Online (Sandbox Code Playgroud)

要么

object.property = value;
Run Code Online (Sandbox Code Playgroud)

JavaScript中的对象和数组在使用方面有所不同.如果你理解它们是最好的:

对象与数组:JavaScript