JS. Does splice return a deleted item?

I have a problem understanding splices and I want help.

Please check jsfiddle.

http://jsfiddle.net/fantill/TbpWf/1/

value = "c, a, b" value = value.split(',').splice(1, 1).join(',') alert(value); 

it is assumed that return 'c, b' has a value.

However, it returns 'a' ;

What is wrong with this method?

Thank you very much.

+7
source share
4 answers

.splice returns the returned item. However, it also manipulates the array inside. This does not allow you to bind anything to .splice ; You must make two separate calls:

 value = value.split(','); value.splice(1, 1); console.log(value.join(',')); 

If you do value = value.splice(...) , value overridden and the array is lost!

+15
source

.splice in place, so just delete value = and it will change the array as you expected:

 > var value = "c, a, b"; > value = value.split(', '); ["c", "a", "b"] > value.splice(1, 1); ["a"] > value ["c", "b"] 
+8
source
 var a = ["1","2","3"] a.splice(1,1) && a a=["1","3"] 
+6
source

If you find that the splice return behavior is annoying, as many do, and you have to use it often enough in the same program, you might consider adding one of the following two custom prototype functions to use instead.

There is a popular spliced option that behaves as you expected, splice will behave in your question.

 Array.prototype.spliced = function() { Array.prototype.splice.apply(this, arguments); return this; } value = "c, a, b"; value = value.split(',').spliced(1, 1).join(','); console.log(JSON.stringify(value)); 

Another option is one that can be used in various situations. It will perform any array function specified using parameters after it, and will always return an array.

 Array.prototype.arrEval = function() { var args = Array.prototype.slice.call(arguments); Array.prototype[args.shift()].apply(this, args); return this; } // splice example value = "c, a, b"; value = value.split(', ').arrEval('splice', 1, 1).join(', '); console.log(JSON.stringify(value)); // push example value = value.split(', ').arrEval('push', 'a').join(', '); console.log(JSON.stringify(value)); // unshift example value = value.split(', ').arrEval('unshift', 'f', 'e', 'd').reverse().join(', '); console.log(JSON.stringify(value)); 


You can also do the same in one line without a user-defined function using the built-in variable assignment, for really bold.

 value = "c, a, b" value = ((arr = value.split(',')).splice(1, 1), arr.join(',')) alert(value); 

+2
source

All Articles