Skip to main content

Posts

Showing posts with the label copy

javascrip Copy each element of the first array into the second array with second array unchanged

  You are given two arrays and an index. Copy each element of the first array into the second array, in order. Begin inserting elements at index  n  of the second array. Return the resulting array. The input arrays should remain the same after the function runs. 给你两个数组和一个索引。 按顺序将第一个数组的每个元素复制到第二个数组中。 开始在第二个数组的索引 n 处插入元素。 返回结果数组。 函数运行后,输入数组应保持不变。 这个题目的难点在于输入数组不能改变,所以需要创建第三个数组,把输入数组深度拷贝过去。 function   frankenSplice ( arr1 ,  arr2 ,  n ) {    var   newarr  = [];    for  ( let   j  =  0 ; j < arr2 . length ; j ++)   {      newarr . push ( arr2 [ j ]);   }    for  ( let   i = arr1 . length - 1 ; i >= 0 ; i --)   {      newarr . splice ( n , 0 , arr1 [ i ]);   }    console . log ( newarr );    return   newarr ; } frankenSplice ([ 1 ,  2 ,  3 ], [ 4 ,  5 ,  6 ],  1 );