我的 javascript 代码中有一个地方需要执行如下操作
将一个数组中的指定范围复制到另一个数组中的指定范围。
操作类似于
1) java中的System.arraycopy ->
System.arraycopy(array1, index1, array2, index3, index4 - index4 + 1);
Run Code Online (Sandbox Code Playgroud)
2)复制进去 ->
copy(array2[index3:index4 + 1], array1[index1:index2+1])
3) 在 python 中切片 ->
array2[index3: index4 + 1] = arr[index1: index2+1]
Run Code Online (Sandbox Code Playgroud)
现在我正在手动迭代它并执行它。但是我没有在 js 中使用任何 util 函数来做到这一点。真的有吗?
更新 1:它应该完全复制而不是从两个给定数组中的任何一个中添加或删除元素。
它的行为应该像这样的实现:
function arraycopy(src, srcPos, dst, dstPos, length) {
let j = dstPos;
let tempArr = src.slice(srcPos, srcPos + length);
for (let e in tempArr) {
dst[j] = tempArr[e];
j++;
}
};
Run Code Online (Sandbox Code Playgroud)
更新 2:(请谨慎查看下面的一些答案,看看它是否适合您的用例(例如在巨大的数据集案例中))下面的许多答案都以这种方式使用了拼接,如果范围在源数组中开始到结束,它会中断巨大的。它将抛出“RangeError:超出最大调用堆栈大小”...因为它将超过函数中允许的最大参数数。(在此处尝试演示脚本)“
据我所知,没有一个函数,但我认为可以使用slice()和来实现此功能splice()。
slice() 方法将数组的一部分切片成一个新数组。
splice() 方法可用于向数组添加新项。