0

How detect «empty slot» in array? «empty slot» not 'undefined'!

<script type="text/javascript">
    const has = [1, 2, /*empty slot*/, 4, undefined, 6, /*empty slot*/];
    console.log(has[2] === undefined); // true - but, is <empty slot>!!!
    console.log(has[4] === undefined); // true - needle.
</script>

Thanks!)

MaxQNEI
  • 3
  • 4

1 Answers1

1

You'd use the in operator, or the hasOwnProperty method:

const has = [1, 2, /*empty slot*/, 4, undefined, 6, /*empty slot*/];
console.log(2 in has);              // No property called 2
console.log(has.hasOwnProperty(2)); // No property called 2
console.log(4 in has);              // There is one called 4
console.log(has.hasOwnProperty(4)); // There is one called 4

in checks the object and its prototypes for the property. hasOwnProperty just checks the object itself, not its prototypes. Since Array.prototype doesn't have any properties with names like 2 and 4 defined (and never will), either works. (One will be faster than the other, but which is which may vary from JavaScript engine to JavaScript engine, and it's unlikely to matter anyway...)

These are defined in terms of objects, rather than specifically arrays, but you can use them here because standard arrays in JavaScript are objects, they just give special treatment to a class of properties (ones whose names are strings in the form defined for array indexes [see spec]), a special length property, and that inherit from Array.prototype. More in my blog post A Myth of Arrays.

If you want to find the next empty slot given an index n, then:

var emptySlot = -1;
while (n < array.length) {
    if (!(n in array)) { // or `if (!array.hasOwnProperty(n)) {`
        emptySlot = n;
        break;
    }
    ++n;
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875