简体   繁体   English

javascript array.splice() 不删除数组中的元素?

[英]javascript array.splice() does not remove element in the array?

I have a remove[] array which has all the index positions of all the element with 0 in the data array (as below).我有一个 remove[] 数组,它包含数据数组中所有元素的所有索引位置(如下所示)。

data array:数据数组:

Retail,1,Utilities,1,Food & Restaurant,3,No Data,4,Construction,0,Non-profit,1,Financial Services,12,Technology,2,Law,3,Religion,3,Retired,2,Insurance,0,Real Estate,2,Audit,3,Business Organizations,3,Media & Marketing,0,Education,3,Transportation,0,Manufacturing,0,Entertainment & Sports,0,Architecture & Engineering,0,Cultural Institutions,0,Government,0,Banking,0,Health Care,0,Business Services,0

my javascript我的 JavaScript

   var remove =  [];          
    $.each(options.series[0].data, function(index, item) {
    if (options.series[0].data[index][1] == 0)
    {                    
        //options.series[0].data.splice(index,1);  
        remove[index] = index;                                      

    }

    for (i=0; i<=remove.length; i++)
    {
    //alert(remove);                
    if (remove[i] != undefined)
        options.series[0].data.splice(remove[i],1);

    }   

data array after splice(). splice() 后的数据数组。 A lot of elements with 0 are still there.许多为 0 的元素仍然存在。

Retail,1,Utilities,1,Food & Restaurant,3,No Data,4,Non-profit,1,Financial Services,12,Technology,2,Law,3,Religion,3,Retired,2,Insurance,0,Audit,3,Business Organizations,3,Media & Marketing,0,Education,3,Manufacturing,0,Entertainment & Sports,0,Cultural Institutions,0,Banking,0,Business Services,0

if i changed the splice to include replacement element如果我将拼接更改为包含替换元素

options.series[0].data.splice(remove[i],1,'removed');

All 0 elements are removed from the data array.从数据数组中删除所有 0 元素。 huh?嗯?

Retail,1,Utilities,1,Food & Restaurant,3,No Data,4,removed,Non-profit,1,Financial Services,12,Technology,2,Law,3,Religion,3,Retired,2,removed,Real Estate,2,Audit,3,Business Organizations,3,removed,Education,3,removed,removed,removed,removed,removed,removed,removed,removed,removed

How do I remove all the 0 elements in my data array?如何删除数据数组中的所有 0 元素?

Every time you remove one, you're making any further cached indices obsolete because the array from that point forward is reindexed.每次删除一个索引时,您都会使任何进一步缓存的索引过时,因为从那时起的数组将被重新索引。

As a result, you're removing the wrong items after the first.结果,您在第一个之后删除了错误的项目。

You should iterate the remove array in reverse instead.您应该反向迭代remove数组。

var i = remove.length;
while (i--) {
    if (remove[i] != undefined)
        options.series[0].data.splice(remove[i],1);
}   

Additionally, you can improve the performance and get rid of the undefined test if you simply .push() each index into the remove array...此外,如果您只需将.push()每个索引放入remove数组中,您就可以提高性能并摆脱undefined测试......

remove.push(index);

I think you can do it pretty fast this way:我认为你可以通过这种方式快速完成:

var dataArr = ["Retail",1,"Utilities",1,"Food & Restaurant",3,"No Data",4,"Construction",0,"Non-profit",1,"Financial Services",12,"Technology",2,"Law",3,"Religion",3,"Retired",2,"Insurance",0,"Real Estate",2,"Audit",3,"Business Organizations",3,"Media & Marketing",0,"Education",3,"Transportation",0,"Manufacturing",0,"Entertainment & Sports",0,"Architecture & Engineering",0,"Cultural Institutions",0,"Government",0,"Banking",0,"Health Care",0,"Business Services",0];

var item = 0; // value of the item to remove

while (dataArr.indexOf(item) > -1) {
 dataArr.splice(dataArr.indexOf(item), 1);
}

console.log(dataArr);

My problem was that splice was removing the wrong element from the array.我的问题是 splice 从数组中删除了错误的元素。 I saw the answer with the while loop but the solution that I made is :我在 while 循环中看到了答案,但我提出的解决方案是:

var index = jQuery.inArray(element, arr);
arr.splice(index,1);

I use a library called DevBox.Linq.JS我使用一个名为 DevBox.Linq.JS 的库

It basically adds Linq type functionality to Javascript Arrays.它基本上将 Linq 类型功能添加到 Javascript 数组。 For example, it adds "Remove":例如,它添加了“删除”:

   Array.prototype.Remove = function (condition) {
    if (condition == undefined) {
        console.error('Informe a expressão para executar a tarefa.')
        return;
    }

    for (var i = 0 ; i < this.length ; i++) {
        if (condition(this[i]))
            this.splice(i, 1);
    }
}

This way you can use it with a lambda like this:通过这种方式,您可以将它与这样的 lambda 一起使用:

myArray.remove(i=>i=="valueToDelete");

Hope it helps, It already has all the functionality so you don't have to deal with that pesky splice.希望它有所帮助,它已经拥有所有功能,因此您不必处理那个讨厌的拼接。

If you look at your original array and the first result array, you'll notice that non-0 elements ARE being removed.如果您查看原始数组和第一个结果数组,您会注意到非 0 元素正在被删除。 The problem from what I can tell is that your array remove is looking for indices that have since been shifted over one to the left upon the removal of previous ones.我所知道的问题是,您的数组remove正在寻找在删除以前的索引后已向左移动的索引。 You will need to add a correcting adjustment for this in your final for loop, or approach this another way.您需要在最终的for循环中为此添加更正调整,或以另一种方式进行处理。

If you want to remove all the elements from an array, it's better don't use splice but length :如果要从数组中删除所有元素,最好不要使用splice而是使用length

options.series[0].data.length = 0;

See: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/length请参阅: https : //developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/length

Update:更新:

I misunderstood the question.我误解了这个问题。 In your case I will probably filter out the elements that are zero, instead of makes two loop (one for collect them, and one for remove them).在您的情况下,我可能会过滤掉为零的元素,而不是进行两个循环(一个用于收集它们,一个用于删除它们)。 So, something like:所以,像这样:

function isNotZero(item) {return item[1] !== 0}

var filtered = options.series[0].data.filter(isNotZero);

options.series[0].data = filtered;

See: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter请参阅: https : //developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter

If the browser you want to support doesn't implement ES5, I will suggest to you to use a shim for all the es5 methods (in that page there is one for filter), or library like underscore如果你想支持的浏览器没有实现 ES5,我会建议你对所有 es5 方法使用 shim(在该页面中有一个用于过滤器),或者像下划线这样的库

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

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