gpt4 book ai didi

javascript - 带有替换函数的 JSON.stringify 中的奇怪行为

转载 作者:数据小太阳 更新时间:2023-10-29 04:17:11 24 4
gpt4 key购买 nike

考虑一下:

var object = {date: new Date()};

JSON.stringify(object, function(key, value) {
console.log('---');
console.log('key:', key);
console.log('value:', value);
console.log('value instanceof Date:', value instanceof Date);

return value;
});

作为documentation说:

The replacer parameter can be either a function or an array. As a function, it takes two parameters, the key and the value being stringified. The object in which the key was found is provided as the replacer's this parameter. Initially it gets called with an empty key representing the object being stringified, and it then gets called for each property on the object or array being stringified.

...

If you return any other object, the object is recursively stringified into the JSON string, calling the replacer function on each property, unless the object is a function, in which case nothing is added to the JSON string.

但是如果你运行代码,你会得到这个:

---
key:
value: { date: Fri Jan 10 2014 02:25:00 GMT+0100 (CET) }
value instanceof Date: false
---
key: date
value: 2014-01-10T01:25:00.262Z
value instanceof Date: false

这意味着,在调用 replacer 函数之前,日期属性已被字符串化。这是正常行为还是我遗漏了什么?如何在不覆盖默认 toJSON 方法的情况下影响 Date 字符串化的格式?

谢谢!

编辑

根据回复和接下来的研究,此时文档似乎还不清楚,toJSON 在替换函数之前被调用。根据 Pills 的回复,这段代码应该可以完成工作:

var object = {date: new Date };

JSON.stringify(object, function(key, value) {
if (typeof(value) === 'object') {
for (var k in value) {
if (value[k] instanceof Date) {
value[k] = value[k].getTime();
}
}
}
return value;
});

编辑#2

Xotic750 的解决方案比以前的要好得多。

最佳答案

它很老但只是为了完成它。

根据 this Q/AMDN JSON.stringify article ,替换器是用找到 key 的对象的实例调用的,因此无需更改原型(prototype)或做其他技巧:

function log(what) {
what = what || "";
document.getElementById("out").innerText += what + "\n";
}

function replacer(key, value) {
console.log(this);
log("Key: '" + key + "' = '" + value + "'");
log("this = " + this);
log("this[key] = " + this[key]);
log("this[key] instanceof Date = " + (this[key] instanceof Date));
log("this instanceof Date = " + (this[key] instanceof Date));

if (this[key] instanceof Date) {
return "This was a date: " + this[key].getTime();
}

return value;
}

var obj = {
d: new Date()
};

var result;
result = JSON.stringify(new Date(), replacer);
log();
log(result);
log();
result = JSON.stringify(obj, replacer);
log();
log(result);
<pre id="out"></pre>

关于javascript - 带有替换函数的 JSON.stringify 中的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21034760/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com