基于Javascript键的值推入数组

时间:2019-04-20 03:42:49

标签: javascript arrays

这是我的代码

PHP示例

$a = [];
$a['test1'][] = 1; 
$a['test1'][] = 2; 

输出:Array ( [test1] => Array ( [0] => 1 [1] => 2 ) )

如何在javascript中做同样的事情?。

3 个答案:

答案 0 :(得分:1)

Javascript中,您可以使用键test1创建一个对象,并将数组分配为value。然后,您可以使用Array.push()在一个调用中插入多个元素:

let a = {};
a['test1'] = []; 
a['test1'].push(1, 2);
console.log(a.test1)
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

或者,您也可以使用Map

let a = new Map();
a.set('test1', []);
a.get('test1').push(1, 2);
console.log(a.get("test1"));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

答案 1 :(得分:0)

工作代码。

{test1: Array(1)}

结果:{{1}}

答案 2 :(得分:0)

只需创建一个对象:

var a = {};
a["test1"] = 1;
a["test2"] = 2;
console.log(a);
.as-console-wrapper { max-height: 100% !important; top: auto; }

如果要使用数组,则必须使用数字索引而不是名称:

var a = [];
a[0] = 1;
a[1] = 2;
console.log(a);

相关问题