如何用另一个数组的元素替换数组中的元素 [英] How to replace elements in array with elements of another array

查看:132
本文介绍了如何用另一个数组的元素替换数组中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从0元素替换某些数组中的元素,另一个数组的元素具有可变长度。喜欢:

I want to replace elements in some array from 0 element, with elements of another array with variable length. Like:

var arr = new Array(10), anotherArr = [1, 2, 3], result;
result = anotherArr.concat(arr);
result.splice(10, anotherArr.length);

有更好的方法吗?

推荐答案

您可以使用 splice 方法将数组的一部分替换为另一个数组中的项目,但您必须在特殊情况下调用它方式,因为它期望项目作为参数,而不是数组。

You can use the splice method to replace part of an array with items from another array, but you have to call it in a special way as it expects the items as parameters, not the array.

splice 方法需要像<$ c这样的参数$ c>(0,anotherArr.Length,1,2,3),所以你需要创建一个带参数的数组并使用 apply 使用以下参数调用 splice 方法的方法:

The splice method expects parameters like (0, anotherArr.Length, 1, 2, 3), so you need to create an array with the parameters and use the apply method to call the splice method with the parameters:

Array.prototype.splice.apply(arr, [0, anotherArr.length].concat(anotherArr));

示例:

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);

输出:

[ 1, 2, 3, 'd', 'e', 'f', 'g', 'h', 'i', 'j']

演示: http://jsfiddle.net/Guffa/ bB7Ey /

这篇关于如何用另一个数组的元素替换数组中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆