[英]Unexpected behavior in JSON.parse Reviver function, deleting the object and not the key properties
JSBin鏈接,以便您可以快速運行代碼。
問題出在注釋中,但是從文檔中可以得知齊磊器(該名稱很糟糕)的工作方式,如果不返回值或返回undefined
,則應從對象中刪除該屬性。 如果返回未轉換的值,則它保持不變。
但是,當我對其進行測試時,似乎整個對象都被刪除了。 第一個示例工作正常,偶數轉換為負數,奇數不變。
但是在第二個示例中,我什至沒有得到對象,只是未定義。 所以我是看文檔了還是其他問題?
在第二個示例中,結果只是未定義。
var obj = {
one: 1,
innerObj: {
two: 2,
four: 4
},
two: 2,
three: 3,
four: 4
},
b = {},
json = JSON.stringify(obj);
/**
* This works as expected.
*/
b = JSON.parse(json, function (name, value) {
if (value % 2 === 0) {
return -value;
}
return value;
});
console.log(b);
/**
[object Object] {
four: -4,
innerObj: [object Object] {
four: -4,
two: -2
},
one: 1,
three: 3,
two: -2
}
*/
obj = {
one: 1,
innerObj: {
two: 2,
four: 4
},
two: 2,
three: 3,
four: 4
};
b = {};
json = JSON.stringify(obj);
/**
* This does not work as expected, instead of deleting the property on the object, the entire object returns undefined.
*/
b = JSON.parse(json, function (name, value) {
if (value % 2 === 0) {
return -value;
}
});
console.log(b);
// undefined
您的第二個示例保留了return value;
關。
但是即使您這樣做很艱難,它也應該只刪除了返回undefined
為值的屬性,而我認為您發現了一個錯誤(可能是?)。
從一個MDN
JSON.parse
示例中,它說當調用JSON.parse
時最后一個鍵是""
我設法重現了帶有undefined
錯誤的代碼,似乎如果您返回""
鍵的值,例如
if (name == "") {
return value;
}
它似乎按預期工作。
obj = {
one: 1,
innerObj: {
two: 2,
four: 4
},
two: 2,
three: 3,
four: 4
};
b = {};
json = JSON.stringify(obj);
/**
* This does not work as expected, instead of deleting the property on the object, the entire object returns undefined.
*/
b = JSON.parse(json, function (name, value) {
if (value % 2 === 0) {
return -value;
}
if (name == "") {
return value;
}
});
console.log(b);
// { two: -2, four: -4 }
編輯:
因此,閱讀ECAMScript JSON.parse(text [,reviver])規范 ,似乎這是預期的行為。 當描述調用reviver
函數的行為時,調用所有DefineOwnProperty
項目之后的最后一步是
返回調用抽象操作Walk,傳遞root和空String的結果。
因此,當您沒有在reviver函數中返回''
name的值時,它將理解應該刪除該值,即代表要返回的整個對象,從而導致JSON.parse
return的值undefined
。
這說明了MDN文檔上的擔憂
確保按原樣返回所有未轉換的值
但是,我同意應該更明確地說明這些細微差別。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.