How to tell between undefined array elements and empty slots?

后端 未结 2 1885
一个人的身影
一个人的身影 2020-12-06 04:53

Suppose I am a user script developer and I don\'t have control over the on-page javascript. The page creates arrays with random lengths, filling them with random values (inc

相关标签:
2条回答
  • 2020-12-06 05:31

    You could use Array#forEach, which omits sparse elements.

    var arr = new Array(3);
    arr[0] = null;
    arr[1] = undefined;
    console.log(arr); 
    
    var withoutSparse = [];
    
    arr.forEach(function (a, i) {
        console.log(i);
        withoutSparse.push(a);
    });
    console.log(withoutSparse);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    0 讨论(0)
  • 2020-12-06 05:48

    You can use the in operator to check if the array has a key. It will return false for empty slots, but true for slots with values, including the value undefined:

    var arr = new Array(3);
    arr[0] = null;
    arr[1] = undefined;
    
    1 in arr; // true
    2 in arr; // false
    

    Note that you can't distinguish between empty slots and slots past the end of the array using that, but if you know the length of the array, then you already know that 3 isn't part of it, so you don't need to test 3 in arr.

    You can also filter out the empty slots like this:

    arr = arr.filter( ( _, i ) => i in arr );
    
    0 讨论(0)
提交回复
热议问题