使用javascript

时间:2018-11-30 10:08:03

标签: javascript arrays

我试图按特定顺序将一个阵列推到另一个阵列 使用此javascript代码:

var arr1=["A","B","C","D","E","F"];
var arr2=["1","2","3"]

console.log(arr1.splice(0,-1,arr2));

its reutn [];

my desire rusult : ["1","2","3","A","B","C","D","F"]

请任何人向我展示如何通过拼接功能实现我的愿望 ps:我可以通过循环来实现

Thx

编辑:抱歉,我的问题有误导性。这是我的实际情况:

arr1 :[["A","B","C"],["D","E","F"]]
arr2 :["1","2","3"]

预期输出:[["1,"2","3","A","B","C"],["1","2","3","D","E","F"]]

我尝试过:

arr1.map(function(e) {
    return e.splice(0, -1, arra2)
});

但是我得到了:[],[]

5 个答案:

答案 0 :(得分:2)

您可以像const result = [...arr2, ...arr1];这样使用Spread syntax

代码:

const arr1 = ["A","B","C","D","E","F"];
const arr2 = ["1","2","3"]
const result = [...arr2, ...arr1];

console.log(result);

答案 1 :(得分:1)

由于其他解决方案会创建一个新数组,因此,我们可以使用一种方法,通过结合使用unshift方法来修改原始数组的 具有扩展语法

var arr1=["A","B","C","D","E","F"];
var arr2=["1","2","3"]

arr1.unshift(...arr2);
console.log(arr1);

答案 2 :(得分:1)

您必须使用splice吗? concat方法完全可以实现您想要实现的目标。

var arr1=["A","B","C","D","E","F"];
var arr2=["1","2","3"]

var result = arr2.concat(arr1);
console.log(result);

// If you're okay with using spread syntax (doesn't work in IE), you could just:
console.log([...arr2, ...arr1]);

答案 3 :(得分:0)

拆分适用于给定的数组,如果您想在数组的开头添加arr2的值,则可以将数组与扩展数组拼接在一起。

Array#splice返回通过第二个参数的计数从给定数组中取出ts的数组,这里的id为零,而不是-1,这没有任何意义。

var arr1 = ["A", "B", "C", "D", "E", "F"],
    arr2 = ["1", "2", "3"]

arr1.splice(0, 0, ...arr2); // returns []

console.log(arr1);

答案 4 :(得分:0)

docsArray.splice的返回值为

  

包含删除的元素的数组。如果只有一个元素是   移除后,将返回一个元素的数组。如果没有元素   删除后,将返回一个空数组。

它将不返回更新后的数组,并且由于您不删除任何元素,因此将返回一个空数组。

要使用add在特定索引处splice进入某些条目,您可以尝试关注。

var arr1=["A","B","C","D","E","F"];
var arr2=["1","2","3"]
arr1.splice(0,0, ...arr2);
console.log(arr1);