按位置从javascript数组中删除元素

时间:2015-04-15 16:56:28

标签: javascript arrays

我有一个javascript数组

var countries = ["India","USA","China","Canada","China"];

我想删除"中国"仅从第2位开始,并返回

var countries = ["India","USA","Canada","China"];

类似于java linkedlist.remove(index)

的东西

我已阅读以下问题,但如果数组中存在重复元素,我就不知道如何使用它。 How do I remove a particular element from an array in JavaScript?

4 个答案:

答案 0 :(得分:1)

您可以混合使用array.indexOfarray.splice

var countries = ["India","USA","China","Canada","China"];
var first_china = countries.indexOf("China");

if(first_china > -1){
    countries.splice(first_china , 1);
}

您链接的问题也有相同的答案(https://stackoverflow.com/a/5767357)。 indexOf会返回找到的第一个匹配的索引。因此,如果有重复项,它仍然只会删除第一个。

答案 1 :(得分:0)

尝试splice():

countries.splice(2,1);

这里,第一个参数是位置,第二个参数是要删除的元素数。

要获取索引,请使用indexOf(),如果未找到,则返回-1:

countries.indexOf("China");

所以你有:

var i = countries.indexOf("China");
if(-1 !== i) {
    countries.splice(i, 1);
}

答案 2 :(得分:0)

您可以使用JavaScript Array splice()方法。

var countries = ["India", "USA", "China", "Canada", "China"];
document.getElementById("demo").innerHTML = countries;

function myFunction() {
  countries.splice(2, 1);
  document.getElementById("demo").innerHTML = countries;
}
<button onclick="myFunction()">SPLICE!</button>
<p id="demo"></p>

答案 3 :(得分:0)

var c = ["India","USA","China","Canada","China"];
// provide the index you want to remove here (2)
var c2 = c.filter(function(item, idx) {if(idx != 2) return item;});

console.log(c2);

DEMO http://jsfiddle.net/kf8epwnh/