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

后端 未结 6 1864
轮回少年
轮回少年 2021-01-14 06:51

I have a remove[] array which has all the index positions of all the element with 0 in the data array (as below).

data array:

Retail,1,Utilities,1,Fo         


        
6条回答
  •  深忆病人
    2021-01-14 07:15

    If you want to remove all the elements from an array, it's better don't use splice but length:

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

    See: 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

    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

提交回复
热议问题