我想从0元素替换某些数组中的元素,另一个数组的元素具有可变长度.喜欢:
var arr = new Array(10), anotherArr = [1, 2, 3], result;
result = anotherArr.concat(arr);
result.splice(10, anotherArr.length);
Run Code Online (Sandbox Code Playgroud)
有更好的方法吗?
Guf*_*ffa 48
您可以使用该splice
方法将数组的一部分替换为另一个数组中的项,但您必须以特殊方式调用它,因为它期望项作为参数,而不是数组.
该splice
方法需要参数(0, anotherArr.Length, 1, 2, 3)
,因此您需要使用参数创建一个数组,并使用apply
该splice
方法使用以下参数调用该方法:
Array.prototype.splice.apply(arr, [0, anotherArr.length].concat(anotherArr));
Run Code Online (Sandbox Code Playgroud)
例:
var arr = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
var anotherArr = [ 1, 2, 3 ];
Array.prototype.splice.apply(arr, [0, anotherArr.length].concat(anotherArr));
console.log(arr);
Run Code Online (Sandbox Code Playgroud)
输出:
[ 1, 2, 3, 'd', 'e', 'f', 'g', 'h', 'i', 'j']
Run Code Online (Sandbox Code Playgroud)
演示:http://jsfiddle.net/Guffa/bB7Ey/
cae*_*sol 28
在具有单个操作的ES6中,您可以执行此操作来替换阵列的整个内容:
let a = [1, 2, 3, 4, 5]
let b = [10, 20, 30]
a.splice(0, b.length, ...b)
console.log(a) // -> [10, 20, 30, 4, 5]
Run Code Online (Sandbox Code Playgroud)
该b.length
阵列的内容将被完全替代a
的内容.
请注意,这应仅用于性能关键型应用程序,例如高FPS动画,以避免创建新阵列.
通常我会创建一个新的数组来维护不变性.
编辑:我刚刚意识到这并没有完全回答这个问题,但它可以帮助一些谷歌.
对于任何想要在保留原始数组的同时用另一个数组的全部内容替换一个数组的整个内容的方法:
Array.prototype.replaceContents = function (array2) {
//make a clone of the 2nd array to avoid any referential weirdness
var newContent = array2.slice(0);
//empty the array
this.length = 0;
//push in the 2nd array
this.push.apply(this, newContent);
};
Run Code Online (Sandbox Code Playgroud)
原型函数将数组作为参数,将其作为新的数组内容,克隆它以避免任何奇怪的引用内容,清空原始数组,然后将传入的数组作为内容推送.这会保留原始数组和任何引用.
现在你可以简单地这样做:
var arr1 = [1, 2, 3];
var arr2 = [3, 4, 5];
arr1.replaceContents(arr2);
Run Code Online (Sandbox Code Playgroud)
我知道这不是最初问题的严格要求,但是当你在谷歌搜索时,这个问题首先出现,我认为其他人可能会觉得这很有用,因为这是我需要的答案.
在ES6,TypeScript,Babel或类似的中你可以这样做:
arr1.length = 0; // Clear your array
arr1.push(...arr2); // Push the second array using the spread opperator
Run Code Online (Sandbox Code Playgroud)
简单.
归档时间: |
|
查看次数: |
42763 次 |
最近记录: |