undefined与null有什么区别?

siugwan 2005-03-04 09:15:07
真是烦死了,公司里的机器居然有部份IE6出现undefined的错误,大部份都是正常的,好像是IE脚本库的问题。但把undefined改为null就没事了。

请问一下undefined与null有什么区别吗?
...全文
107 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
vivianfdlpw 2005-03-04
  • 打赏
  • 举报
回复
Null Data Type
The null data type has only one value in JScript: null. The null keyword cannot be used as the name of a function or variable.

A variable that contains null contains "no value" or "no object." In other words, it holds no valid number, string, Boolean, array, or object. You can erase the contents of a variable (without deleting the variable) by assigning it the null value.

Notice that in JScript, null is not the same as 0 (as it is in C and C++). Also note that the typeof operator in JScript will report null values as being of type Object, not of type null. This potentially confusing behavior is for backwards compatibility.

Undefined Data Type
The undefined value is returned when you use:

an object property that does not exist,
a variable that has been declared, but has never had a value assigned to it.
Notice that you cannot test to see if a variable exists by comparing it to undefined, although you can check if its type is "undefined". In the following code example, assume that the programmer is trying to test if the variable x has been declared:

// This method will not work
if (x == undefined)
// do something

// This method also won't work - you must check for
// the string "undefined"
if (typeof(x) == undefined)
// do something

// This method will work
if (typeof(x) == "undefined")
// do something
Consider comparing the undefined value to null.

someObject.prop == null;
This comparison is true,

if the property someObject.prop contains the value null,
if the property someObject.prop does not exist.
To check if an object property exists, you can use the new in operator:

if ("prop" in someObject)
// someObject has the property 'prop'
siugwan 2005-03-04
  • 打赏
  • 举报
回复
那undefined与null一般情况下可以通用么?
meizz 2005-03-04
  • 打赏
  • 举报
回复
undefined 是指变量未赋任何类型的值
null 变量是一个空的 object
handsomemouse 2005-03-04
  • 打赏
  • 举报
回复
undefined是未定义,null是空

87,921

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧