在javascript中,假设我有一个预分配的n
项数组,并且我有另一个数组,我想将其复制到给定起始索引的第一个数组中,以下是一种方法:
let arr = new Array(25);
console.log(arr);
let arrB = Array(5).fill(1);
let insertAt = 5;
for(let ix = 0; ix < arrB.length; ix++)
arr[ix + insertAt] = arrB[ix];
console.log(arr);
有没有更有效/标准的方法?
我在C++中正在考虑相当于以下内容的东西:http://www.cplusplus.com/forum/general/199358/
效率方面,我认为没有比您发布的代码更好的方法了。您将需要遍历数组中需要复制的所有项目。
我同意其他人的观点,使用slice
可能是这样做的标准方法。
尝试
arr.splice(insertAt,5, ...arrB)
let arr = new Array(25);
console.log(arr);
let arrB = Array(5).fill(1);
let insertAt = 5;
arr.splice(insertAt,5, ...arrB)
console.log(arr);
接下来是 MDN 文档 splice() 方法通过删除或替换现有元素和/或添加新元素来更改数组的内容。 语法: arr.splice(start[, deleteCount[, item1[, item2[, ...]]]])
.上述代码段中的示例用法
更新
确实拼接是标准方式,但它比 for 循环慢 - 我在这里执行测试以检查它。拼接比 for 循环慢 ~28%。
如果您的数组包含浮点数,那么您可以使用 Float32Array 或 Uint32array,它几乎比Array
快 2 倍(铬不支持拼接)
let arr = new Float32Array(25);
console.log(arr);
let arrB = new Float32Array(5).fill(1);
let insertAt = 5;
for(let ix = 0; ix < arrB.length; ix++)
arr[ix + insertAt] = arrB[ix];
console.log(arr);
更新 2
我读了你的答案并与Uint32Array
进行比较(如果你想使用整数数组) - 它比普通数组快 2 倍 - 在这里。
Uint32Array.prototype.copyInto = function(arr,ix = 0) {
for(let i = 0; i < arr.length; i++)
this[ix+i] = arr[i];
return this;
}
let a = new Uint32Array(2).fill(1);
let x = new Uint32Array(5).fill(0).copyInto(a,2);
console.log(x);
不确定这段代码的性能效率如何(因为我仍然是学习者),但建议将其作为实现此类结果的另一种方式。
let arr = new Array(25);
let arrB = Array(5).fill(1);
let insertAt = 5;
function copy(index) {
if (arrB.length === 0 || index > 9) {
return;
}
arr[index] = arrB.shift();
copy(index + 1);
}
copy(insertAt);
我最终制作了一个模块来简化此操作:
const checks = require("checks"); //NB, NOT ON NPM....
(()=>{
Array.prototype.copyInto = function(arr,ix = 0){
if(!checks.isArray(arr))
throw new Error("'arr' argument must be an array");
if(!checks.isInteger(ix) || ix < 0)
throw new Error("'ix' must be a positive integer");
for(let i = 0; i < arr.length; i++)
this[ix+i] = arr[i];
return this;
}
})();
这意味着它可以像这样使用:
let x = Array(5).fill(0).copyInto([1,1],2);
console.log(x);
不确定这是否是正确的方法,但它对我有用。