2011-11-10 116 views
2

我認爲.splice()可能會出錯,但我認爲它刪除了數組中的一個元素。所有我想在這裏做的是去除 「梨」,但它不工作:Javascript拼接不起作用

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

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

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

此外,在http://jsfiddle.net/jdb1991/nV95v/

回答

8

您缺少兩個參數:

  • $.inArray希望的第二個參數是受試者陣列
  • 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>"); 
}); 

Live example

4
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>"); 
}); 
1

您需要將數組傳遞給$ .inArray也通過元素的數量刪除到方法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/

1

試試這個

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

這適用於我: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>"); 
});