joedborg
joedborg

Reputation: 18353

Javascript splice not working

I may be wrong on what I think .splice() is meant to do, but I thought it removed one element of an array. All I want to do here is remove "pears", but it doesn't work:

var my_array = ["apples","pears","bananas","oranges"];

my_array.splice($.inArray("pears",my_array));

$.each(my_array, function(k,v) {
    document.write(v+"<br>");
});

Also at http://jsfiddle.net/jdb1991/nV95v/

Upvotes: 2

Views: 3868

Answers (7)

sod
sod

Reputation: 3928

this works for me: http://jsfiddle.net/HbjHV/

var my_array = ["apples","pears","bananas","oranges"];

var pos = $.inArray("pears", my_array);
pos !== -1 && my_array.splice(pos, 1);

$.each(my_array, function(k,v) {
    document.write(v+"<br>");
});

Upvotes: 2

Lekensteyn
Lekensteyn

Reputation: 66405

You're missing two arguments:

  • $.inArray wants the second argument to be the subject array
  • splice accepts a second argument to specify the number of elements to be deleted

The code becomes:

var my_array = ["apples","pears","bananas","oranges"];

my_array.splice($.inArray("pears", my_array), 1);

$.each(my_array, function(k,v) {
    document.write(v+"<br>");
});

Live example

Upvotes: 7

Abdul Munim
Abdul Munim

Reputation: 19217

Try this

my_array.splice($.inArray("pears", my_array), 1);

Upvotes: 1

Richard Dalton
Richard Dalton

Reputation: 35793

You need to pass the array to $.inArray and also pass the number of elements to remove into array.splice:

var my_array = ["apples","pears","bananas","oranges"];

my_array.splice($.inArray("pears", my_array), 1);

$.each(my_array, function(k,v) {
    document.write(v+"<br>");
});

http://jsfiddle.net/infernalbadger/nV95v/3/

Upvotes: 1

Pavel S.
Pavel S.

Reputation: 1027

Please look what arguments .splice() method does recieve!

Upvotes: 0

Dogbert
Dogbert

Reputation: 222108

var my_array = ["apples","pears","bananas","oranges"];

my_array.splice($.inArray("pears", my_array), 1);

$.each(my_array, function(k,v) {
    document.write(v+"<br>");
});

Upvotes: 4

Frias
Frias

Reputation: 11281

You fogot the array:

$.inArray("pears",my_array)

Docs: http://api.jquery.com/jQuery.inArray/

Upvotes: 0

Related Questions