首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

null跟undefined有什么区别

2013-09-23 
null和undefined有什么区别?下面的例子中var messagealert(message)//”undefined”alert(age)//causes a

null和undefined有什么区别?
下面的例子中
var message;  
alert(message);  //”undefined”
alert(age);   //causes an error
但是如果用typeof来看的话,那么:
两个都是'undefined',alert和typeof差异怎么这么大?

[解决办法]

引用:
下面的例子中
var message;  
alert(message);  //”undefined”
alert(age);   //causes an error
但是如果用typeof来看的话,那么:
两个都是'undefined',alert和typeof差异怎么这么大?

有区别:运行下面代码看看区别

var TestVar;
alert(TestVar); //shows undefined
alert(typeof TestVar); //shows undefined



var TestVar = null;
alert(TestVar); //shows null
alert(typeof TestVar); //shows object

[解决办法]
下面是一段英文对话,来说明区别的

You: What is name?
JavaScript: name? What's a name? I don't know what you're talking about. You haven't ever mentioned any name before. Are you seeing some other scripting language on the (client-)side?

name = null;
You: What is name?
JavaScript: I don't know.
In short; undefined is where no notion of the thing exists; it has no type, and it's never been referenced before in that scope; null is where the thing is known to exist, but it's not known what the value is.
One thing to remember is that null is not, conceptually, the same as false or "" or such, even if they equate after type casting, i.e.

name = false;
You: What is name?
JavaScript: Boolean false.

name = '';
You: What is name?
JavaScript: Empty string


http://stackoverflow.com/questions/801032/why-is-null-an-object-and-whats-the-difference-compared-to-undefined


[解决办法]
var message;  // 定义变量 message 未初始化
alert(message);  //获取变量的值 ”undefined”
alert(age);   //获取变量的值 age 未定义,报错 causes an error
但是如果用typeof来看的话,那么:
两个都是'undefined',alert和typeof差异怎么这么大?

typeof // 获取变量的 数据类型
[解决办法]
这个跟null和undefined没有关系吧,主要是:

alert时,获取的是变量的值,如果变量未声明的话,就会报error

typeof,获取的是变量的数据类型,任何情况,都不可能报error

热点排行
Bad Request.