简体   繁体   中英

How can I copy elements from one array to another of a different type given a particular index in JavaScript?

I have two arrays:

var arrayA = [ 0, 0, 0 ];
var arrayB = new Uint8Array( 2 );
arrayB[0] = 1;
arrayB[1] = 2;

I would like to copy the values from arrayB to a particular index in arrayA.

For example:

arrayB.copyTo( arrayA, 1 );

arrayA would now become:

[0, 1, 2, 0, 0];

Is there a way of doing this in vanilla javascript without using an iterator?

This is called "splicing". I'm not sure why you're using the Uint8Array constructor, but if you are working with two normal arrays, this is how I would do it:

 var arrayA = [0,0,0]; var arrayB = [1, 2]; var spliceArrays = function(arr1, arr2, index) { var arrPart1 = arr1.slice(0, index); var arrPart2 = arr1.slice(index); return (arrPart1.concat(arr2)).concat(arrPart2); }; var spliced = spliceArrays(arrayA, arrayB, 1); console.log(spliced); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM