开发者

Javascript: What's a better way to splice arrays together than what I'm using now?

开发者 https://www.devze.com 2023-01-14 04:07 出处:网络
var newlist = list.slice( 0, pos ).concat( tasks ).concat( list.slice( p开发者_JAVA百科os ) ); This makes me shudder just looking at it.There is a splice method for Array.If you didn\'t want to modi
var newlist = list.slice( 0, pos ).concat( tasks ).concat( list.slice( p开发者_JAVA百科os ) );

This makes me shudder just looking at it.


There is a splice method for Array.


If you didn't want to modify the original array, you can shorten yours a little like this:

var newlist = ​list.slice(0,pos).concat(tasks,list.slice(pos));

http://jsfiddle.net/RgYPw/


Your method is as good as any- you'd have to splice each member of your second array individually.

var list=[1,2,3,4,5,6,7,8,9], tasks= ['a','b','c'], pos=3;


while(tasks.length ) list.splice(pos,0,tasks.pop());

alert(list.join('\n'))

/*  returned value:
1
2
3
a
b
c
4
5
6
7
8
9
*/
0

精彩评论

暂无评论...
验证码 换一张
取 消