(window.location中的) host 与 hostname 的区别

陪她去流浪 桃子 2016年06月11日 阅读次数:6674

今天听 dudu 说起 host 与 hostname 的区别,查了下文档,的确是这么回事。发现自己一直没有注意到这个问题。在给函数参数取名的时候,经常混用。没办法啦,自己只是半个前端开发者。

MDN的文档说明如下:

Location.host
    Is a DOMString containing the host, that is the hostname, a ':', and the port of the URL.

Location.hostname
    Is a DOMString containing the domain of the URL.

也就是说,host 是 URL 中的 主机:端口, 而 hostname 仅是 URL 中的 主机

**注意:**如果URL中没有写端口号,则 hosthostname 是一样的。

举个例来说:

网址 https://blog.twofei.com/index.php

  • location.host 将得到 blog.twofei.com
  • location.hostname 将得到 blog.twofei.com

网址 https://blog.twofei.com:443/index.php

  • location.host 将得到 blog.twofei.com:443
  • location.hostname 将得到 blog.twofei.com

这篇文章的内容已被作者标记为“过时”/“需要更新”/“不具参考意义”。

标签:javascript · 前端