我该如何将新值推到以下数组中?
json = {"cool":"34.33","alsocool":"45454"}
我尝试使用json.push("coolness":"34.33");
,但它没有起作用。
我该如何将新值推到以下数组中?
json = {"cool":"34.33","alsocool":"45454"}
我尝试使用json.push("coolness":"34.33");
,但它没有起作用。
它不是一个数组。
var json = {"cool":"34.33","alsocool":"45454"};
json.coolness = 34.33;
或者var json = {"cool":"34.33","alsocool":"45454"};
json['coolness'] = 34.33;
您可以使用数组来实现,但这将是一种不同的语法(而且这几乎肯定不是您想要的)
var json = [{"cool":"34.33"},{"alsocool":"45454"}];
json.push({"coolness":"34.33"});
请注意,这个变量名非常误导人,因为这里并没有JSON。我会给它取一个别的名字。
var array = new Array(); // or the shortcut: = []
array.push ( {"cool":"34.33","also cool":"45454"} );
array.push ( {"cool":"34.39","also cool":"45459"} );
你的变量是一个JavaScript对象{}
而不是一个数组[]
。
你可以这样做:
var o = {}; // or the longer form: = new Object()
o.SomeNewProperty = "something";
o["SomeNewProperty"] = "something";
并且
var o = { SomeNewProperty: "something" };
var o2 = { "SomeNewProperty": "something" };
然后,将这些对象添加到数组中: 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
var json = { cool: 34.33, alsocool: 45454 };
json.supercool = 3.14159;
console.dir(json);
json['BRK.A'] = 3.14159;
- CodeHxrobject["property"] = value;
或者
object.property = value;
push()
函数将元素添加到数组中:// initialize array
var arr = [
"Hi",
"Hello",
"Bonjour"
];
// append new value to the array
arr.push("Hola");
var arr = [
"Hi",
"Hello",
"Bonjour"
"Hola"
];
// append multiple values to the array
arr.push("Salut", "Hey");
var arr = [
"Hi",
"Hello",
"Bonjour"
"Hola"
"Salut"
"Hey"
];
// display all values
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
Hi
Hello
Bonjour
Hola
Salut
Hey
更新
如果您想将一个数组的项添加到另一个数组中,可以使用Array.concat:
var arr = [
"apple",
"banana",
"cherry"
];
arr = arr.concat([
"dragonfruit",
"elderberry",
"fig"
]);
console.log(arr);
["apple", "banana", "cherry", "dragonfruit", "elderberry", "fig"]