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 更多