Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 760
joedborg Avatar asked Apr 30 '26 08:04

joedborg


1 Answers

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

like image 161
Lekensteyn Avatar answered May 03 '26 00:05

Lekensteyn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!