Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

javascript - Returning an array without a removed element? Using splice() without changing the array?

I want to do something like:

var myArray = ["one","two","three"];
document.write(myArray.splice(1,1));
document.write(myArray);

So that it shows first "one,three", and then "one,two,three". I know splice() returns the removed element and changes the array, but is there function to return a new array with the element removed? I tried:

window.mysplice = function(arr,index,howmany){
    arr.splice(index,howmany);
    return arr;   
};

If I try:

var myArray = ["one","two","three"];
document.write(mySplice(myArray,1,1));
document.write(myArray);

It still changes myArray.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You want slice:

Returns a one-level deep copy of a portion of an array.

So if you

a = ['one', 'two', 'three' ];
b = a.slice(1, 3);

Then a will still be ['one', 'two', 'three'] and b will be ['two', 'three']. Take care with the second argument to slice though, it is one more than the last index that you want to slice out:

Zero-based index at which to end extraction. slice extracts up to but not including end.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...