Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

js. splice returns removed item?

Tags:

javascript

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.

like image 853
Micah Avatar asked Feb 26 '13 06:02

Micah


People also ask

Does splice return the removed element?

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.

What does splice method return JavaScript?

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.

Is splice destructive JavaScript?

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).

How do you remove an element using splice?

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.


3 Answers

.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!

like image 103
Explosion Pills Avatar answered Oct 28 '22 10:10

Explosion Pills


.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"]
like image 37
Blender Avatar answered Oct 28 '22 11:10

Blender


var a = ["1","2","3"]
a.splice(1,1) && a
a=["1","3"]
like image 24
Lam Huu Hanh Nguyen Avatar answered Oct 28 '22 11:10

Lam Huu Hanh Nguyen