Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在JavaScript上的array.push上设置JSON数组键_Javascript_Arrays_Json_Push - Fatal编程技术网

如何在JavaScript上的array.push上设置JSON数组键

如何在JavaScript上的array.push上设置JSON数组键,javascript,arrays,json,push,Javascript,Arrays,Json,Push,我正在编写一些JS代码,其中需要使用Javascriptarray.push()将变量设置为JSON数组中的键: 其中,questNumb是另一个变量。在编写代码时,我刚刚编写test变量的部分变成了键“test”,因此我不知道如何将其付诸实施。怎么可能呢?谢谢 您需要这样做: var test = "dd" + questNumb, obj = {content: {date: ""}}; // Add the attribute under the key specified by

我正在编写一些JS代码,其中需要使用Javascript
array.push()将变量设置为JSON数组中的键:


其中,
questNumb
是另一个变量。在编写代码时,我刚刚编写
test
变量的部分变成了键
“test”
,因此我不知道如何将其付诸实施。怎么可能呢?谢谢

您需要这样做:

var test = "dd" + questNumb,
    obj = {content: {date: ""}};

// Add the attribute under the key specified by the 'test' var
obj[test] = {title: ""};

// Put into the Array
window.voiceTestJSON.push(obj);
var test = 'dd'+questNumb;
var newObject = {"content":{"date":""}}; //this part does not need a variable property name
newObject[test] = {"title":""};

如果希望变量作为键,则需要括号:

var object = {};
object['dd'+questNumb] = {"title":""};
object["content"] = {"date":""};  //Or object.content, but I used brackets for consistency
window.voiceTestJSON.push(object);
(首先,您没有JSON数组,您有一个JavaScript对象。JSON是数据的字符串表示形式,其语法类似于JavaScript的对象文字语法。)

不幸的是,当您使用JavaScript的对象文字语法来创建对象时,您不能使用变量来设置动态属性名称。您必须首先创建对象,然后使用
obj[propName]
语法添加属性:

var test = "dd" + questNumb,
    myObj = { "content" : {"date":""} };

myObj[test] = {"title" : ""};

window.voiceTestJSON.push(myObj);
这是一个JS对象。因此,您正在将一个对象推入voiceTestJSON数组

与JSON不同的是,JS对象属性名可以用引号写,也可以不用引号写

您想做的事情可以通过以下方式实现:

var test = "dd" + questNumb,
    obj = {content: {date: ""}};

// Add the attribute under the key specified by the 'test' var
obj[test] = {title: ""};

// Put into the Array
window.voiceTestJSON.push(obj);
var test = 'dd'+questNumb;
var newObject = {"content":{"date":""}}; //this part does not need a variable property name
newObject[test] = {"title":""};

通过这种方式,您可以将测试中包含的名称的属性设置为{“title”:“}。

可能与@Dennis重复-是的,“subset”是通常使用的单词,尽管严格来说这并不完全正确,因为
“[1,2,3]”“
是有效的JSON,但它是数组文字符号,而不是对象文字符号。(我也相信有一些unicode字符在JSON中是有效的,但在JavaScript中是无效的,尽管我一辈子都记不住细节,也懒得去查。)unicode位听起来很熟悉——我总是忘了
“这”
[“t”、“h”、“I”、“s”]
都是有效的JSON。