Javascript,var name = 1," typeof name"给出“字符串”? [英] Javascript, var name = 1, "typeof name" gives "string"?

查看:138
本文介绍了Javascript,var name = 1," typeof name"给出“字符串”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I found this weird problem, when I write Javascript code like below:

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的数字,但是,我认为它们都应该是数字

I got "string" for "typeof name", but got "number" for "typeof b", however, I think they both should be "number"

此代码也不会运行:

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

它不会提醒,因为名字的类型是字符串!

It won't alert out, since name's type is "string" !

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

I tested above code in Chrome and Safari, they both give the same result, so why "typeof name" is "string" in this case? why the variable name "name" is so special?

推荐答案

这是一个浏览器的行为,其中一些属性的window对象就像name和status将只接受字符串值,如果你指定任何其他类型的值,那么该对象的toString()值被赋值给它

It is a behavior of the browser where some properties of window object like name and status will take only string values, if you assign any other type of values then the toString() value of that object is assigned to it

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); //

演示:小提琴

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

This behavior is not applicable if you use local variables... ie variables in a function

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()

演示:小提琴

这篇关于Javascript,var name = 1," typeof name"给出“字符串”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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