在全局范围内分配“var location”会重定向到不存在的文件

Assigning `var location` in global scope redirects to non-existent file

我有一个 HTML 文件 test.html,其中有两个变量都命名为 location,一个是全局的,一个是局部的。但是当我在浏览器中打开它时,它只显示 Your file was not found,并且地址栏显示 file://Los%20Angeles 而不是预期的 file://test.html。为什么?

<html>
<body>
<script type="text/javascript">
var location = "Los Angeles"
function showLocation() {
    var location = "San Francisco"
    document.write(location)
}
</script>
<input type="button" onclick="showLocation()" value="Show Location"/>
</body>
</html>

'location' 是 javascript 中的保留关键字。只需将您的变量名称更改为其他名称即可。 有关保留字的更多信息:https://www.w3schools.com/js/js_reserved.asp

设置全局 location 会导致浏览器转到那个 url。它不是保留字——它是在 window 对象上定义的变量。这里有一个更好的保留字列表:

https://docs.microsoft.com/en-us/scripting/javascript/reference/javascript-reserved-words

在您的示例中,您将全局 location 设置为 'Los Angeles',这会导致 window 导航到它,就好像它是一个相对 URL 一样。

在函数内部设置 var location = "San Francisco" 对 window 对象没有影响,因为函数变量有自己的作用域。

所以你可以这样做:

function showLocation() {
    var location = "San Francisco"
    document.write(location)
}

它会按预期工作。它会将字符串 'San Francisco' 写入文档。

如果您使用的是现代浏览器,您可以通过尝试将 'location' 设置为 'let':

来查看发生了什么
let location = "los angeles"

现在您将收到类似以下内容的错误:

SyntaxError: Can't create duplicate variable that shadows a global property: 'location'