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

Bo *_*ker 2 javascript var typeof

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

var name = 1;
alert(typeof name); // this will alert "string"
var b = 1;
alert(typeof b); // this will alert "number"
Run Code Online (Sandbox Code Playgroud)

我得到了"typeof name"的"字符串",但是"typeof b"得到了"number",但是,我认为它们都应该是"数字"

此代码也不会运行:

var name = 1;
if (name === 1) {
    alert("ok")
}
Run Code Online (Sandbox Code Playgroud)

它不会警告,因为名字的类型是"字符串"!

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

Aru*_*hny 6

这是浏览器的行为,其中窗口对象的某些属性(如名称和状态)将仅采用字符串值,如果您指定任何其他类型的值,则该对象的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); //
Run Code Online (Sandbox Code Playgroud)

演示:小提琴


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

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()
Run Code Online (Sandbox Code Playgroud)

演示:小提琴