url.toJSON()


URL 对象上调用 toJSON() 方法将返回序列化的 URL。 返回值与 url.hrefurl.toString() 的相同。

URL 对象使用 JSON.stringify() 序列化时将自动调用该方法。

const myURLs = [
  new URL('https://www.example.com'),
  new URL('https://test.example.org')
];
console.log(JSON.stringify(myURLs));
// 打印 ["https://www.example.com/","https://test.example.org/"]

The toJSON() method on the URL object returns the serialized URL. The value returned is equivalent to that of url.href and url.toString().

This method is automatically called when an URL object is serialized with JSON.stringify().

const myURLs = [
  new URL('https://www.example.com'),
  new URL('https://test.example.org')
];
console.log(JSON.stringify(myURLs));
// Prints ["https://www.example.com/","https://test.example.org/"]