window.location= 和 window.location.replace() 有什么区别?

发布于 2024-08-13 09:11:38 字数 131 浏览 3 评论 0原文

这两条线有区别吗?

var url = "http://www.google.com/";
window.location = url;
window.location.replace(url);

Is there a difference between these two lines?

var url = "http://www.google.com/";
window.location = url;
window.location.replace(url);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

只想待在家 2024-08-20 09:11:38

window.location 将一个项目添加到您的历史记录中,您可以(或应该能够)单击“后退”并返回到当前页面。

window.location.replace 替换当前历史记录项,这样您就无法返回到它。

请参阅window.location

assign(url):加载文档于
提供的 URL。

replace(url):替换当前的
所提供的文件
网址。与的区别
assign() 方法是使用后
replace() 当前页面不会
保存在会话历史记录中,这意味着
用户将无法使用后退
按钮导航到它。

哦,一般来说:

window.location.href = url;

优于:

window.location = url;

window.location adds an item to your history in that you can (or should be able to) click "Back" and go back to the current page.

window.location.replace replaces the current history item so you can't go back to it.

See window.location:

assign(url): Load the document at
the provided URL.

replace(url):Replace the current
document with the one at the provided
URL. The difference from the
assign() method is that after using
replace() the current page will not
be saved in session history, meaning
the user won't be able to use the Back
button to navigate to it.

Oh and generally speaking:

window.location.href = url;

is favoured over:

window.location = url;
苏佲洛 2024-08-20 09:11:38

太长了;

使用 location.href 或更好地使用 window.location.href

但是,如果您阅读本文,您将获得不可否认的证据。

事实是它很好用,但为什么要做一些有问题的事情呢?你应该走更高的道路,并按照可能应该做的方式去做。

location = "#/mypath/otherside"
var sections = location.split('/')

这段代码在语法、逻辑、类型上都是完全正确的
你知道它唯一的问题吗?

它有 location 而不是 location.href

那么

var mystring = location = "#/some/spa/route"

mystring 的值是多少?有人不做测试就真的知道吗?没有人知道这里到底会发生什么。天哪,我刚刚写了这个,但我什至不知道它是做什么的。 location 是一个对象,但我分配一个字符串,它会传递字符串还是传递位置对象。假设对于如何实现这一点有一些答案。你能保证所有浏览器都会做同样的事情吗?

我几乎可以猜测所有浏览器都会处理相同的情况。

var mystring = location.href = "#/some/spa/route"

如果你把它放入打字稿中,它会崩溃吗,因为类型编译器会说它应该是一个对象?

然而,这个对话比 location 对象要深入得多。这个转换是关于你想成为什么样的程序员?

如果你走这条捷径,是的,今天可能会好,明天可能会好,见鬼,可能永远都好,但你先生现在是一个糟糕的程序员。这对你来说不会有什么好处,而且会让你失败。

将会有更多的对象。将会有新的语法。

你可能会定义一个只接受一个字符串但返回一个对象的 getter,最糟糕的是你会认为你正在做正确的事情,你可能会认为你很擅长这种聪明的方法,因为这里的人可耻地将你引入歧途。

var Person.name = {first:"John":last:"Doe"}
console.log(Person.name) // "John Doe"

对于 getter 和 setter,这段代码实际上可以工作,但仅仅因为它可以完成并不意味着这样做是“明智的”。

大多数编程人员都喜欢编程并且喜欢变得更好。在过去的几年里,我取得了很大的进步,也学到了很多东西。我现在知道的最重要的事情,尤其是当你编写库时,是一致性和可预测性。

做你能持续做的事情。

+"2" <-- 这里将字符串解析为数字。你应该使用它吗?
或者你应该使用parseInt("2")

var num ==+"2" 怎么样?

从你所了解到的情况来看,从 stackoverflow 的角度来看,我不太抱有希望。

如果你开始遵循这两个词:一致且可预测。您将知道 stackoverflow 上大量问题的正确答案。

让我向您展示这将如何带来回报。
通常我将 ; 放在我编写的每一行 javascript 上。我知道这样更有表现力。我知道这样更清楚了。我遵守了我的规则。有一天我决定不这样做。为什么?因为很多人告诉我不再需要它了,JavaScript 可以不需要它。所以我决定这样做。现在,因为我已经确信自己是一名程序员(因为你应该享受掌握一门语言的成果),所以我写了一些非常简单的东西,但我没有检查它。我删除了一个逗号,我认为我不需要重新测试删除一个逗号这样简单的事情。

我在 es6 和 babel 中写了类似的东西

var a = "hello world"
(async function(){
  //do work
})()

这段代码失败了并且花了很长时间才弄清楚。
由于某种原因,它所看到的内容隐藏

var a = "hello world"(async function(){})()

在源代码深处,它告诉我“hello world”不是一个函数。

为了更有趣,节点不显示转译代码的源映射。

浪费了那么多愚蠢的时间。我也向某人展示了 ES6 的出色之处,然后我必须开始调试并演示 ES6 是如何轻松且更好。没有说服力是吧。

我希望这能回答你的问题。这是一个老问题,更多的是对于仍在学习的下一代人来说。

当人们说无论哪种方式都没关系时提出疑问。一个更明智、更有经验的人很可能会告诉你其他明智的事情。

如果有人覆盖位置对象怎么办?他们将为旧版浏览器做一个垫片。它将获得一些需要调整的新功能,并且您的 3 年旧代码将失败。

我最后要思考的一点。

编写干净、清晰、有目的的代码对你的代码所做的事情是无法用正确或错误来回答的。它的作用是使您的代码成为推动者。

您可以使用更多插件、库,而不必担心代码之间的中断。

记录在案。使用

window.location.href

TLDR;

use location.href or better use window.location.href;

However if you read this you will gain undeniable proof.

The truth is it's fine to use but why do things that are questionable. You should take the higher road and just do it the way that it probably should be done.

location = "#/mypath/otherside"
var sections = location.split('/')

This code is perfectly correct syntax-wise, logic wise, type-wise
you know the only thing wrong with it?

it has location instead of location.href

what about this

var mystring = location = "#/some/spa/route"

what is the value of mystring? does anyone really know without doing some test. No one knows what exactly will happen here. Hell I just wrote this and I don't even know what it does. location is an object but I am assigning a string will it pass the string or pass the location object. Lets say there is some answer to how this should be implemented. Can you guarantee all browsers will do the same thing?

This i can pretty much guess all browsers will handle the same.

var mystring = location.href = "#/some/spa/route"

What about if you place this into typescript will it break because the type compiler will say this is suppose to be an object?

This conversation is so much deeper than just the location object however. What this conversion is about what kind of programmer you want to be?

If you take this short-cut, yea it might be okay today, ye it might be okay tomorrow, hell it might be okay forever, but you sir are now a bad programmer. It won't be okay for you and it will fail you.

There will be more objects. There will be new syntax.

You might define a getter that takes only a string but returns an object and the worst part is you will think you are doing something correct, you might think you are brilliant for this clever method because people here have shamefully led you astray.

var Person.name = {first:"John":last:"Doe"}
console.log(Person.name) // "John Doe"

With getters and setters this code would actually work, but just because it can be done doesn't mean it's 'WISE' to do so.

Most people who are programming love to program and love to get better. Over the last few years I have gotten quite good and learn a lot. The most important thing I know now especially when you write Libraries is consistency and predictability.

Do the things that you can consistently do.

+"2" <-- this right here parses the string to a number. should you use it?
or should you use parseInt("2")?

what about var num =+"2"?

From what you have learn, from the minds of stackoverflow i am not too hopefully.

If you start following these 2 words consistent and predictable. You will know the right answer to a ton of questions on stackoverflow.

Let me show you how this pays off.
Normally I place ; on every line of javascript i write. I know it's more expressive. I know it's more clear. I have followed my rules. One day i decided not to. Why? Because so many people are telling me that it is not needed anymore and JavaScript can do without it. So what i decided to do this. Now because I have become sure of my self as a programmer (as you should enjoy the fruit of mastering a language) i wrote something very simple and i didn't check it. I erased one comma and I didn't think I needed to re-test for such a simple thing as removing one comma.

I wrote something similar to this in es6 and babel

var a = "hello world"
(async function(){
  //do work
})()

This code fail and took forever to figure out.
For some reason what it saw was

var a = "hello world"(async function(){})()

hidden deep within the source code it was telling me "hello world" is not a function.

For more fun node doesn't show the source maps of transpiled code.

Wasted so much stupid time. I was presenting to someone as well about how ES6 is brilliant and then I had to start debugging and demonstrate how headache free and better ES6 is. Not convincing is it.

I hope this answered your question. This being an old question it's more for the future generation, people who are still learning.

Question when people say it doesn't matter either way works. Chances are a wiser more experienced person will tell you other wise.

what if someone overwrite the location object. They will do a shim for older browsers. It will get some new feature that needs to be shimmed and your 3 year old code will fail.

My last note to ponder upon.

Writing clean, clear purposeful code does something for your code that can't be answer with right or wrong. What it does is it make your code an enabler.

You can use more things plugins, Libraries with out fear of interruption between the codes.

for the record. use

window.location.href

青衫负雪 2024-08-20 09:11:38

起源与 解决方案

问题的

这两行有区别吗?
window.location = "http://www.google.com/";
window.location.replace("http://www.google.com/");

简短回答

是的。

背景事实

首先,您需要知道:

window.location = "https://stackoverflow.com"window.location.href = "https://stackoverflow.com" 的别名。 com" 因此具有相同的功能。

window.location VS window.location.replace

window.location:

在这里,我在其上下文中处理 window.location = "https://website.com"window.location.href = "https://website.com"

  • location 对象上的 href 属性存储当前网页的 URL。
  • 更改 href 属性时,用户将被导航到新的 URL。
  • 项目添加到历史列表中
  • 这会在移至下一页后将 ,用户可以单击“后退”按钮
    浏览器返回此页面

window.location.replace:

  • 替换功能用于导航到新的 URL,而不向历史记录添加记录。
  • 此函数将覆盖最顶层的条目并将其从历史堆栈中替换。
  • 点击“后退”按钮后,您将无法返回到重定向之前访问的最后一个页面

结论:

回答问题:

是的,我们的两个主题之间存在差异,主要是 window.location 使您能够在浏览器历史记录中返回window.location.replace() 不允许您返回浏览器历史记录,从而从浏览器历史记录中删除以前的 URL 记录。

奖励:哪个更快?

当您使用以下内容时: window.location = "http://www.google.com/"; 您将直接更新 href 属性,这在性能上会更快比使用 window.location.replace("http://www.google.com/"); 因为更新函数比直接更新属性慢。

有关 window.location 的更多信息

window.location 返回 Location 对象,其内部如下所示:

console.log(window.location);

// This is how the Location object that returns from window.location looks like
{
    "ancestorOrigins": {},
    "href": "https://stackoverflow.com/",
    "origin": "https://stackoverflow.com",
    "protocol": "https:",
    "host": "stackoverflow.com",
    "hostname": "stackoverflow.com",
    "port": "",
    "pathname": "/",
    "search": "",
    "hash": ""
}

Location 对象还具有以下方法(函数):

Location.assign()
在参数中提供的 URL 处加载资源。

Location.reload()
重新加载当前 URL,如“刷新”按钮。

Location.toString()
返回包含整个 URL 的字符串。它是 Location.href 的同义词,
但是,它不能用于修改值。

Origins & a Solution

The Question

Is there a difference between these two lines?
window.location = "http://www.google.com/";
window.location.replace("http://www.google.com/");

Short Answer

Yes.

Background Facts

First, you want to know that:

window.location = "https://stackoverflow.com" is an alias of window.location.href = "https://stackoverflow.com" thus has the same functionality.

window.location VS window.location.replace

window.location:

Here, I am addressing window.location = "https://website.com" in its context as window.location.href = "https://website.com"

  • The href property on the location object stores the URL of the current webpage.
  • On changing the href property, a user will be navigated to a new URL.
  • This adds an item to the history list
  • after moving to the next page, the user can click the "Back" button in
    the browser to return to this page
    .

window.location.replace:

  • The replace function is used to navigate to a new URL without adding a record to the history.
  • This function is overwriting the topmost entry and replaces it from the history stack.
  • By clicking the "Back" button, you will not be able to return to the last page you visited before the redirect after moving to the next page.

Conclusion:

To answer the question:

Yes, there is a difference between our 2 subjects and mostly in the fact that window.location enables you to go back in the browser history while window.location.replace() doesn't let you go back in browser history, thus removing the previous URL record from the browser history.

Bonus: Which is faster?

When you are using this: window.location = "http://www.google.com/"; you are updating the href property directly, this is faster by performance than using window.location.replace("http://www.google.com/"); because updating a function is slower than updating a property directly.

More about window.location

window.location returns the Location object that looks like this inside:

console.log(window.location);

// This is how the Location object that returns from window.location looks like
{
    "ancestorOrigins": {},
    "href": "https://stackoverflow.com/",
    "origin": "https://stackoverflow.com",
    "protocol": "https:",
    "host": "stackoverflow.com",
    "hostname": "stackoverflow.com",
    "port": "",
    "pathname": "/",
    "search": "",
    "hash": ""
}

The Location object also has the following methods (functions):

Location.assign()
Loads the resource at the URL provided in parameter.

Location.reload()
Reloads the current URL, like the Refresh button.

Location.toString()
Returns a String containing the whole URL. It is a synonym for Location.href,
though, it can't be used to modify the value.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文