名为“status”的变量的奇怪行为在javascript中 [英] strange behaviour of variable named "status" in javascript

查看:93
本文介绍了名为“status”的变量的奇怪行为在javascript中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<!DOCTYPE html>
<html>
<body>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
var status = [true,false,true,false,true,false,true,false,true,false];
var status1 = [true,false,true,false,true,false,true,false,true,false];

document.getElementById("demo1").innerHTML = status[2];
document.getElementById("demo2").innerHTML = status1[2];
</script>

</body>
</html>

https://jsfiddle.net/vdr2r38r/

为什么对于具有不同名称的相同变量,行为是否不同?

Why is the behavior different for identical variables with different names?

推荐答案

这是因为您在全局上下文中运行代码! var 绑定变量绑定到函数范围。如果您没有任何功能,那么您处于全局环境中,这意味着在浏览器中您位于窗口对象。

It's because you run your code in global context! var bound variables are bound to the function scope. If you have no function you are in global context, which means in a browser you are on the window object.

此代码将记录演示

<script>
  var foo = "Demo";
  console.log(window.foo);
</script>






现在您的代码中断因为 window.status 保留

一个简单的解决方法是通过函数包围代码,为变量提供新的上下文,这总是很好的做法。

An easy fix is to surround your code by a function to provide a new context for your variables, which is always good practice.

<script>
    (function() {
        var status = [true,false,true,false,true,false,true,false,true,false];
        var status1 = [true,false,true,false,true,false,true,false,true,false];

        document.getElementById("demo1").innerHTML = status[2];
        document.getElementById("demo2").innerHTML = status1[2];
    })();
</script>

这篇关于名为“status”的变量的奇怪行为在javascript中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆