[英]Push array of elements inside another array at a index in javascript
我需要在 javascript 中的特定索引处将元素数组推入另一个数组中,而不使用扩展运算符,也不使用另一个数组。
输入:
let firstArray = [4,5,6];
let secondArray = [1,2,3,7,8,9];
预期 Output:
console.log(secondArray); //[1,2,3,4,5,6,7,8,9];
我尝试使用拼接并应用function 如下所示。
let firstArray = [4,5,6];
let secondArray = [1,2,3,7,8,9];
firstArray.splice(0, 0, 3, 0);
secondArray.splice.apply(secondArray, firstArray);
此代码给出了预期的 output,但也在更新 secondArray 之前更新了 firstArray 中的元素。
有没有更好的方法来实现预期的 output 而无需更新 firstArray 中的元素?
编辑 1:我试图在没有新数组的情况下实现这一点,因为 firstArray 和 secondArray 的大小很大。 因此感觉它可能会为新数组创建不需要的 memory 分配,以便将元素推入另一个数组。 避免传播运算符,因为它在 IE 浏览器中不受支持编辑 2:在不使用循环条件的情况下删除。
您已经说过限制的原因是:
...因为
firstArray
和secondArray
的大小很大。 因此感觉它可能会为新数组创建不需要的 memory 分配,以便将元素推入另一个数组。
在这种情况下,您要避免在 firstArray 上使用.splice(0, 0, 3, 0)
,因为它需要将firstArray
中的所有内容firstArray
以为元素腾出空间。
您的 memory 问题并没有解释禁止使用循环(毕竟, splice
使用循环)和copyWithin
(也是循环)结合循环来填充新元素将是一个干净、简单且不记忆的问题-密集的方法来解决问题。 所以:
function insert(target, source, index) {
// Get the count of elements to copy
let count = source.length;
if (count) {
// 1. First, make room by copying elements out of the way
let targetIndex = index + source.length;
target.length += count;
target.copyWithin(targetIndex, index, index + count);
// 2. Now, fill in the new elements
while (count-- > 0) {
target[targetIndex--] = source[count];
}
}
return target;
}
现场示例:
let firstArray = [4,5,6]; let secondArray = [1,2,3,7,8,9]; function insert(target, source, index) { // Get the count of elements to copy let count = source.length; if (count) { // 1. First, make room by copying elements out of the way let targetIndex = index + source.length; target.length += count; target.copyWithin(targetIndex, index, index + count); // 2. Now, fill in the new elements while (count-- > 0) { target[targetIndex--] = source[count]; } } return target; } insert(secondArray, firstArray, 3); console.log(JSON.stringify(secondArray)); // [1,2,3,4,5,6,7,8,9]; console.log(JSON.stringify(firstArray)); // [4,5,6];
如果while
循环对您来说有点不透明,您也可以像这样编写循环部分:
for (let index = 0; index < count; ++index) {
target[targetIndex + index] = source[index];
}
现场示例:
let firstArray = [4,5,6]; let secondArray = [1,2,3,7,8,9]; function insert(target, source, index) { // Get the count of elements to copy let count = source.length; if (count) { // 1. First, make room by copying elements out of the way let targetIndex = index + source.length; target.length += count; target.copyWithin(targetIndex, index, index + count); // 2. Now, fill in the new elements for (let index = 0; index < count; ++index) { target[targetIndex + index] = source[index]; } } return target; } insert(secondArray, firstArray, 3); console.log(JSON.stringify(secondArray)); // [1,2,3,4,5,6,7,8,9]; console.log(JSON.stringify(firstArray)); // [4,5,6];
请注意,IE11 可能不支持copyWithin
,但很容易填充。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.