开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜