实现说明
迭代发生在 for (const candidate of candidates) 内部——循环之外的语句只执行一遍。
各个操作都建立在顶层绑定之上:candidates、base、relative、resolved。
使用要点
- 演示输出是带标签的(
ok :、bad :、with base:),每个操作都会留下自己的一行标注。
常见问题
需要标准库之外的东西吗?
除标准库外不引入任何东西——这个示例没有依赖。 跨调用保留的状态放在这些顶层绑定里:candidates、base、relative。
核心语句
const base = 'https://docs.example.com/guide/';
const resolved = new URL(relative, base);
const relative = './auth.html#tokens';
代码示例
const candidates = [
'https://api.example.com/v2/orders?limit=5',
'//cdn.example.com/lib.js',
'mailto:[email protected]',
'not a url at all',
];
for (const candidate of candidates) {
// canParse 先验证:无效输入不会让 new URL 抛出异常
if (URL.canParse(candidate)) {
const url = new URL(candidate);
console.log('ok :', url.protocol, url.host || '(opaque)');
} else {
console.log('bad :', JSON.stringify(candidate));
}
}
// 相对地址需要 base:canParse 接受第二个参数
const base = 'https://docs.example.com/guide/';
const relative = './auth.html#tokens';
console.log('with base:', URL.canParse(relative, base));
const resolved = new URL(relative, base);
console.log('resolved :', resolved.href);
console.log('hash :', resolved.hash);