Micah
Micah

Reputation: 4560

js. splice returns removed item?

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

Answers (4)

omikes
omikes

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

Lam Huu Hanh Nguyen
Lam Huu Hanh Nguyen

Reputation: 89

var a = ["1","2","3"]
a.splice(1,1) && a
a=["1","3"]

Upvotes: 8

Blender
Blender

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

Explosion Pills
Explosion Pills

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

Related Questions