简体   繁体   English

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

[英]Remove elements from javascript array by position

I have a javascript array 我有一个JavaScript数组

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

I want to remove "China" only from 2nd position, and return 我只想从第二个位置删除“中国”,然后返回

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

Something similar to java linkedlist.remove(index) 类似于linkedlist.remove(index)

I have read following question but I don't know how to use it if there are duplicate elements in array. 我已经阅读了以下问题,但是如果数组中有重复的元素,我不知道如何使用它。 How do I remove a particular element from an array in JavaScript? 如何从JavaScript中的数组中删除特定元素?

You can use a mix of array.indexOf and array.splice . 您可以混合使用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);
}

The question you linked also has the same answer ( https://stackoverflow.com/a/5767357 ). 您链接的问题也有相同的答案( https://stackoverflow.com/a/5767357 )。 indexOf will return you the index of the first match it finds. indexOf将返回您找到的第一个匹配项的索引。 So if there are duplicates, it will still only remove the first one. 因此,如果有重复项,它将仍然仅删除第一个。

Try splice(): 尝试splice():

countries.splice(2,1);

Here, first argument is the position and second is the number of elements to remove. 在这里,第一个参数是位置,第二个参数是要删除的元素数。

To get the index use indexOf(), -1 if not found: 要获取索引,请使用indexOf(),如果未找到,则为-1:

countries.indexOf("China");

So you have: 所以你有了:

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

You can use the JavaScript Array splice() Method. 您可以使用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> 

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/ 演示http : //jsfiddle.net/kf8epwnh/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM