检查数组位置是否真的未定义

Check if an array position is really undefined or not

本文关键字:真的 未定义 是否 位置 数组 检查      更新时间:2023-09-26

我正在尝试检查JSON.stringify(obj, callback)回调中给定的值是否真的未定义。它的问题是尚未定义数组值。

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

有什么想法可以检测位置[1]是否已定义?因为数组有3个元素用于JSON.stringify算法。

找出数组中分配的(不一定是定义的)索引的一种方法是迭代器函数,如forEach,它忽略空槽:

var a = new Array(3);
a[0] = true;
a[2] = undefined;
defined = []
a.forEach(function(_, n) { defined.push(n) })
alert(defined)

因此,您可以使用伪迭代器只返回已分配的项:

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)

JSON.stringify()中的replacer参数具有以下内容:

  • 参数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>

这意味着您可以访问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>


正如我在代码注释中提到的,需要强调的是,您必须小心从回调返回undefined。正如我在顶部链接的MDN文章所述:

注意:不能使用replacer函数从数组中删除值。如果返回undefined或函数,则使用null。

这就是调试代码段显示数组条目1和2为null的原因。