var $arr = {
field_hide : '',
field_values: '',
field_triggers: {}
}
function setTrigger ($trigger, $values, $show, $arr) {
$arr.field_hide += $show + ',';
$arr.field_values += $values + ',';
$arr.field_triggers[$trigger] = [];
$arr.field_triggers[$trigger].push([$values, $show]);
return $arr;
}
$arr = setTrigger('file_drive','local','local_key,local_duk',$arr);
$arr = setTrigger('file_drive','cloud','cloud_key,cloud_duk',$arr);
console.log($arr)

为什么我只获得一维数组?谁能帮我解决这个问题? 我想要的结果如下:
{
"field_hide": "local_key,local_duk,cloud_key,cloud_duk,",
"field_values": "local,cloud,",
"field_triggers": {
"file_drive": [
["local","local_key,local_duk"],
["cloud","cloud_key,cloud_duk"]
]
}
}

答案 0 :(得分:0)
每次使用此行将数组设置为空数组:
$arr.field_triggers[$trigger] = [];
相反,您需要检查数组是否已经定义,如下所示:
var $arr = {
field_hide: '',
field_values: '',
field_triggers: {}
}
function setTrigger($trigger, $values, $show, $arr) {
$arr.field_hide += $show + ',';
$arr.field_values += $values + ',';
if (!$arr.field_triggers[$trigger]) {
$arr.field_triggers[$trigger] = [];
}
$arr.field_triggers[$trigger].push([$values, $show]);
return $arr;
}
$arr = setTrigger('file_drive', 'local', 'local_key,local_duk', $arr);
$arr = setTrigger('file_drive', 'cloud', 'cloud_key,cloud_duk', $arr);
console.log($arr)
答案 1 :(得分:0)
这是因为您在使用此行file_drive
添加新内容之前,每次都会将$arr.field_triggers[$trigger] = [];
重置为空数组。您可以添加if
语句来确定是否创建新数组。
var $arr = {
field_hide : '',
field_values: '',
field_triggers: {}
}
function setTrigger ($trigger, $values, $show, $arr) {
$arr.field_hide += $show + ',';
$arr.field_values += $values + ',';
if (!$arr.field_triggers[$trigger]) {
$arr.field_triggers[$trigger] = [];
}
$arr.field_triggers[$trigger].push([$values, $show]);
return $arr;
}
$arr = setTrigger('file_drive','local','local_key,local_duk',$arr);
$arr = setTrigger('file_drive','cloud','cloud_key,cloud_duk',$arr);
console.log($arr)
答案 2 :(得分:-1)
您每次都使用空arry初始化$arr.field_triggers[$trigger] = [];
,请使用下面的代码
var $arr = {
field_hide : '',
field_values: '',
field_triggers: {$trigger:[]}
};
function setTrigger ($trigger, $values, $show, $arr) {
$arr.field_hide += $show + ',';
$arr.field_values += $values + ',';
$arr.field_triggers.$trigger.push([$values, $show]);
return $arr;
}
$arr = setTrigger('file_drive','local','local_key,local_duk',$arr);
$arr = setTrigger('file_drive','cloud','cloud_key,cloud_duk',$arr);
console.log($arr)