window.location.assign() 和 window.location.href 的主要区别:
读取和设置
window.location.href:既可以读取当前 URL,也可以通过赋值更改 URL。
window.location.assign():只能用于跳转到新的 URL,不能读取当前地址。
历史记录
window.location.assign():会生成一条新的历史记录,用户可以通过“后退”按钮返回。
window.location.href:更改 URL 时同样会生成历史记录。
语义区别
window.location.href:常用于直接赋值,更直观。
window.location.assign():更明确地表示执行跳转。
示例
// 使用 href 读取当前地址
console.log(window.location.href);
// 使用 href 进行跳转
window.location.href = 'https://example.com';
// 使用 assign 进行跳转
window.location.assign('https://example.com');
总结:
如果需要读取 URL 或简单跳转,href 更方便;如果只想执行跳转且强调跳转行为,assign() 更合适。平常用的window.location.href 更多