Removing an empty string from an array logic

This question already has an answer here:

  • Remove empty elements from an array in Javascript 36 answers

  • One problem is that Arrays and Objects are slightly different things. To iterate over an array you can use things like:

    for (var i=0; i<arr.length; i++) {
      /* code */
    }
    
    arr.forEach(function(item, index, arr) {
      /* code */
    });
    

    The for..in structure is used to iterate over the keys in an Object:

    var obj = { b : 1, c:2 }
    
    for (var key in obj) {
      console.log(key) // will output first b then c
    }
    

    The simplest way to remove empty values in an array is this:

    var arr = [ 1, '', null, 3, 0, undefined, '', 4 ];
    var filtered = arr.filter(function(item){ return item != null && item !== ''; });
    
    console.log(filtered) // [1,3,0,4]
    

    Obviously you can add more things that should be filtered out of your original array by changing the function passed to filter .


    或者使用filter方法的简单方法。

    var newArray = oldArray.filter(function(v){return v!==''});
    
    链接地址: http://www.djcxy.com/p/37742.html

    上一篇: 删除数组Javascript中的未定义索引

    下一篇: 从数组逻辑中删除空字符串