Javascript, var name = 1, "typeof name" 给出 "string"?

Javascript, var name = 1, "typeof name" gives "string"?

当我编写如下 Javascript 代码时,我发现了这个奇怪的问题:

var name = 1;
alert(typeof name); // this will alert "string"
var b = 1;
alert(typeof b); // this will alert "number"

"typeof name"得到了"string","typeof b"得到了"number",但是,我认为它们都应该是"number"

而且此代码也不会 运行:

var name = 1;
if (name === 1) {
    alert("ok")
}

它不会发出警报,因为名称的类型是 "string" !

我在 Chrome 和 Safari 中测试了上面的代码,它们都给出了相同的结果,那么为什么在这种情况下 "typeof name" 是 "string"?为什么变量名"name"这么特别?

这是浏览器的一种行为,其中 window 对象的某些属性(如名称和状态)将仅采用字符串值,如果您分配任何其他类型的值,则该对象的 toString() 值为分配给它

var name = 1;
console.log(typeof name); // this will alert "string"

var status  = 1;
console.log(status, typeof status); //gives '1` and string

var status = {};
console.log(status, typeof status);//gives value of status as [object Object] since that is the toString() implementation of object

var b = 1;
console.log(typeof b); //

演示:Fiddle


如果您使用局部变量...即函数中的变量,则此行为不适用

function test(){
    var name = 1;
    console.log(typeof name); // this will alert "string"

    var status  = 1;
    console.log(status, typeof status); //gives '1` and string

    var status = {};
    console.log(status, typeof status);//gives value of status as [object Object] since that is the toString() implementation of object

    var b = 1;
    console.log(typeof b); //

}

test()

演示:Fiddle

原因是window下有个属性叫name(window.name)而且已经定义为字符串

当您声明一个没有作用域的变量时,它的作用域在 window 下。

查看有关 window.name 的更多信息。