2015-02-06 29 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

相關問題