将字符串数组添加到字符串数组

时间:2018-06-22 07:54:05

标签: node.js

我想在查询的最终数组中添加mongo id,这是我要尝试的操作

var arr = [];

// array1 =  [ "59ae3b20a8473d45d11987f8",
 "59bb8a9c8f541e060054580e",
  "59ae905f43d38f64d85d3c21"]
//array2 =  [ 
  "59bce938cbe9c90271742c1a",
  "59bcebb4cbe9c90271742c2e" ]

,当我将其添加为arr.push(array1)时,arr.push(array2) 那我得到这个结果

//arr = [ 59ae3b20a8473d45d11987f8,
  59bb8a9c8f541e060054580e,
  59ae905f43d38f64d85d3c21,
  59bce938cbe9c90271742c1a,
  59bcebb4cbe9c90271742c2e ]

结果数组的类型已更改(从字符串开始),我希望这些元素作为字符串,就像它们在array1和array2中一样,我尝试使用concat但不起作用,请帮忙

2 个答案:

答案 0 :(得分:1)

使用concat方法,您可以按照以下步骤操作:

arr = [].concat(array1, array2)

,甚至只是arr = array1.concat(array2)。这里,由于arr不会使原始数组发生突变,因此将结果分配给concat

或者,使用传播语法:

arr = [...array1, ...array2]

答案 1 :(得分:0)

array1 =  [ "59ae3b20a8473d45d11987f8",
 "59bb8a9c8f541e060054580e",
  "59ae905f43d38f64d85d3c21"]
array2 =  [ 
  "59bce938cbe9c90271742c1a",
  "59bcebb4cbe9c90271742c2e" ]
var finalArr = array1.concat(array2);
console.log(finalArr);

array1 =  [ "59ae3b20a8473d45d11987f8",
 "59bb8a9c8f541e060054580e",
  "59ae905f43d38f64d85d3c21"]
array2 =  [ 
  "59bce938cbe9c90271742c1a",
  "59bcebb4cbe9c90271742c2e" ]
var finalArr = [...new Set([...array1 ,...array2])];
console.log(finalArr);