Check if array position is undefined or not

I am trying to check if the value specified in the callback is JSON.stringify(obj, callback)really undefined or not. The problem is when the value of the array is not yet defined.

var a = new Array(3);
a[0] = true;
a[2] = undefined;

a.length;             // 3
a.hasOwnProperty(0); // true
a.hasOwnProperty(1); // false
a.hasOwnProperty(2); // true
a.hasOwnProperty(3); // false
(a[1] === a[2])      // true

Any ideas to determine if a position has been [1]determined? Since the array has 3 elements for the JSON.stringify algorithm.

+4
source share
2 answers

One way to determine the assigned (not necessarily defined) indexes in an array is through an iterator function, for example forEach, that ignores empty slots:

var a = new Array(3);
a[0] = true;
a[2] = undefined;


defined = []
a.forEach(function(_, n) { defined.push(n) })
alert(defined)
Run codeHide result

, :

a = []
a[1] = 11
a[2] = 22
a[3] = undefined
a[5] = 55
a[99] = 99
s = JSON.stringify(a, function(key, value) {
  if(Array.isArray(value))
    return value.filter(function() { return 1 });
  return value;
});

alert(s)
Hide result
+3

replacer JSON.stringify() :

  • key -
  • value -
  • this - , ,

"" :

var a = new Array(3);
a[0] = true;
a[2] = undefined;

JSON.stringify(a, function(key, value) {
    var s = '\n-----------'
    s += '\nkey: ' + JSON.stringify(key);
    s += '\nvalue: ' + JSON.stringify(value);
    s += '\nthis: ' + JSON.stringify(this);
    document.getElementById('result').innerHTML += s;
    return value;
});
<pre id="result"></pre>
Hide result

, this.


hasOwnProperty , , , :

var a = new Array(3);
a[0] = true;
a[2] = undefined;

var result = JSON.stringify(a, function(key, value) {
    // value is undefined, either explicitly or really not set
    if(typeof value === "undefined") {
        // property not set at all
        if(!this.hasOwnProperty(key)) {
            return "really undefined";
        }
        else {
            // returning undefined from the callback will set the value to null,
            // so I give another value here to demonstrate the check
            return "explicitly undefined";
        }
    }
    
    // has an actual value so just return it
    return value;
}, " ");

document.getElementById('result').innerHTML = result;
<pre id="result"></pre>
Hide result

- , , undefined . MDN, , :

.. replacer . undefined , null.

1 2.

+1

All Articles