Reputation: 4560
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.
Upvotes: 10
Views: 15401
Reputation: 8513
If you find splice
's return behavior annoying, as many do, and have to use it often enough within one program, you might consider adding one of the following two custom prototype functions to use instead.
There is the popular spliced
option, which behaves as you expected splice
to 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));
The other option is one that can be used in a variety of situations. It will perform any array function specified using the parameters after it, and will always return the 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));
Doing the same thing in one line without a custom function is also possible with inline variable assignment, for the truly bold.
value = "c, a, b"
value = ((arr = value.split(',')).splice(1, 1), arr.join(','))
alert(value);
Upvotes: 3
Reputation: 298364
.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"]
Upvotes: 10
Reputation: 191779
.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!
Upvotes: 21