什么时候将location设置为URL字符串而不是设置location.href?

location = "http://www.stackoverflow.com";

vs

location.href = "http://www.stackoverflow.com";

Mozilla开发者网络参考


当前回答

但有一点要记住。

假设您想要使用当前URL构建某个URL。下面的代码实际上会重定向,因为它没有调用String。Location.replace:

nextUrl = window.location.replace('/step1', '/step2');

以下代码起作用:

// cast to string
nextUrl = (window.location+'').replace('/step1', '/step2');

// href property
nextUrl = window.location.href.replace('/step1', '/step2');

其他回答

但有一点要记住。

假设您想要使用当前URL构建某个URL。下面的代码实际上会重定向,因为它没有调用String。Location.replace:

nextUrl = window.location.replace('/step1', '/step2');

以下代码起作用:

// cast to string
nextUrl = (window.location+'').replace('/step1', '/step2');

// href property
nextUrl = window.location.href.replace('/step1', '/step2');

你可以直接设置location,因为它略短。如果你想要简洁,你通常可以省略窗口。了。

URL赋值给两个位置。href和location定义在JavaScript 1.0中工作,追溯到Netscape 2,并在此后的每个浏览器中实现。所以随便挑一个,用你觉得最清楚的。

澄清一下,你不能使用location.split('#'), location是一个对象,而不是字符串。但是你可以执行location. reff .split('#');因为位置。Href是一个字符串。

使用React时,请使用global.location.href。

在TypeScript中,使用window.location.href作为窗口。Location在技术上是一个包含以下内容的对象:

Properties
hash
host
hostname
href    <--- you need this
pathname (relative to the host)
port
protocol
search

设置窗口。位置将产生类型错误,而 Window.location.href的类型是字符串。