你不知道的JSON对象的那些参数们

208 阅读1分钟

let obj = {
  name: 'dss',
  birth: new Date('2000-01-01'),
  toJSON: function () {
    return this.name;
  } // 加上这行后的输出变为:json: "dss"
}
console.log('obj:', obj); // obj: { name: 'dss', birth: 2000-01-01T00:00:00.000Z }
let json = JSON.stringify(obj);
console.log('json:', json); // json: {"name":"dss","birth":"2000-01-01T00:00:00.000Z"}

let objCopy = JSON.parse(json);
console.log('objCopy:', objCopy); //objCopy: { name: 'dss', birth: '2000-01-01T00:00:00.000Z' }

let objCopy2 = JSON.parse(json, function (key, value) {
  if (key === 'birth') {
    return new Date(value);
  }
  return value;
});
console.log('objCopy2:', objCopy2); //objCopy2: { name: 'dss', birth: 2000-01-01T00:00:00.000Z }

console.log('objCopy2.getFullYear():', objCopy2.birth.getFullYear()); // objCopy2.getFullYear(): 2000