Javascript: definition of a separation array, undefined value and array value that is not defined

How can I now check if a value is defined as undefined, or if it is not really defined?
eg.

var a = []; a[0] = undefined; // a defined value that undefined typeof a[0] === "undefined"; // and a value that hasn't been defined at all typeof a[1] === "undefined"; 

Is there a way to separate these two? it is possible to use a for-in loop to traverse the array, but is there an easier way?

+4
source share
2 answers

You can use the in operator to check if a given index is present in the array, regardless of its actual value.

 var t = []; t[0] = undefined; t[5] = "bar"; console.log( 0 in t ); // true console.log( 5 in t ); // true console.log( 1 in t ); // false console.log( 6 in t ); // false if( 0 in t && t[0] === undefined ) { // the value is defined as "undefined" } if( !(1 in t) ) { // the value is not defined at all } 
+2
source

you can check if the pointer is in the given array:

 0 in a // => true 1 in a // => false 
+3
source

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


All Articles