How to define between array elements undefined and empty slots?

Suppose I am a custom script developer and I have no control over the inline javascript. The page creates arrays with random lengths, filling them with random values ​​(including false ones, for example undefined ). Not every element is assigned a value, so there may be empty slots.

Simplified example (Firefox console):

 var arr = new Array(3); arr[0] = null; arr[1] = undefined; console.log(arr); \\ Array [ null, undefined, <1 empty slot> ] console.log(arr[1]); \\ undefined console.log(arr[2]); \\ undefined console.log(arr[1] === arr[2]); \\ true console.log(typeof arr[1]); \\ undefined console.log(typeof arr[2]); \\ undefined 

As we can see, Firefox displays undefined and empty slots differently, whereas for javascript they seem the same.

Now suppose I want to clear such an array by removing all empty slots, but leaving the undefined elements intact. How to do it?

+11
source share
2 answers

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

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

Note that you cannot distinguish between empty slots and slots beyond the end of the array using this, but if you know the length of the array, then you already know that 3 not part of it, so you do not need to test 3 in arr .

You can also filter out empty slots as follows:

 arr = arr.filter( function ( _, i ) { return i in arr } ); 
+15
source

You can use Array#forEach , which skips 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; } 
+3
source

Source: https://habr.com/ru/post/1266429/


All Articles