Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...