2015-02-06 27 views
4

我试图检查在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算法的元素。

+0

什么'一个[1] === undefined'或'(则为a.length> = 2)&&(A [ 1] === undefined)'? – collapsar 2015-02-06 12:59:34

+1

'(a [1] === a [2])'它工作正常'undefined == undefined' – 2015-02-06 13:03:03

+0

@collapsar我不知道整个数组,因为JSON.stringify不通过它。 – EnZo 2015-02-06 13:11:15

回答

3

一种方式找出分配(不一定定义)索引在一个阵列是一个迭代函数,像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)

1

JSON.stringify()replacer parameter有以下几点:

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


一些值得突出显示代码注释中提到的,您必须谨慎返回来自回调的。由于MDN文章中,我挂在顶部状态:

注:不能使用替代品功能从数组中删除值。如果您返回未定义或函数,则使用null。

这就是为什么调试片断显示为空数组项1和2

相关问题