I am having problem of understanding splice and I want to have help.
Please check the jsfiddle.
http://jsfiddle.net/fantill/TbpWf/1/
value = "c, a, b"
value = value.split(',').splice(1, 1).join(',')
alert(value);
the value is supposed have return 'c, b'
.
However, it returns 'a'
;
What is wrong with this method?
Thank you very much.
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 item(s) in an array and slice() method returns the selected element(s) in an array, as a new array object. 2. The splice() method changes the original array and slice() method doesn't change the original array.
splice() method is a destructive array method, which means it modifies the array on which it is called (disclaimer: destructive methods can be risky, especially if you use the array in question elsewhere in your program, so proceed with caution).
The splice() function changes the contents of an array by removing existing elements and/or adding new elements. In splice the second argument is the number of elements to remove. splice modifies the array in place and returns a new array containing the elements that have been removed.
.splice
does return the removed item. However, it also manipulates the array internally. This prevents you from chaining anything to .splice
; you must do two separate calls:
value = value.split(',');
value.splice(1, 1);
console.log(value.join(','));
If you do value = value.splice(...)
, value
is overridden, and the array is lost!
.splice
is in-place, so just remove the value =
and it'll modify the array like you'd expect:
> var value = "c, a, b";
> value = value.split(', ');
["c", "a", "b"]
> value.splice(1, 1);
["a"]
> value
["c", "b"]
var a = ["1","2","3"]
a.splice(1,1) && a
a=["1","3"]
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