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.
Yes, splice returns the removed items, and the output is supposed to be a because that's what you removed.
The splice() method is a built-in method for JavaScript Array objects. It lets you change the content of your array by removing or replacing existing elements with new ones. This method modifies the original array and returns the removed elements as a new array.
The splice() method returns the removed items in an array. The slice() method returns the selected element(s) in an array, as a new array object. The splice() method changes the original array and slice() method doesn't change the original array.
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 includingend
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With