Removing undefined values from Array

后端 未结 13 2033
死守一世寂寞
死守一世寂寞 2020-12-02 16:52

In certain situations, it may happen that we have undefined or generally falsy values in Array structures. For instance when reading and filling data f

13条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 17:08

    The solution with Array.filter will actually keep the array unchanged and create a new array without the undesired items. If you want to clean an array without duplicating it, you can use this:

    for (var i = data.length-1; i >= 0; i--) {
        if (!data[i]) {
            data.splice(i, 1);
        }
    }
    

提交回复
热议问题