JavaScript 中null,undefined 的区别?什么状况下会返回 undefined 值?

1、null,undefined 的区别?

null: 表示一个对象被定义了,值为“空值”; undefined 表示不存在这个值markdown

typeof undefined //"undefined"
复制代码

undefined: :是一个表示"无"的原始值或者说表示"缺乏值",就是此处应该有一个值,但尚未定义。当尝试读取时会返回 undefined;例如:变量被声明了,但没有赋值时,就等于 undefinedapp

typeof null //"object"
复制代码

null : 是一个对象(空对象, 没有任何属性和方法);例如做为函数的参数,表示该函数的参数不是对象;ide

注意:

在验证 null 时,必定要使用=== ,由于 == 没法分别 null 和 undefined函数

undefined的典型用法是:

  1. 变量被声明了,但没有赋值时,就等于 undefined
  2. 调用函数时,应该提供的参数没有提供,该参数等于 undefined

3.对象没有赋值的属性,该属性的值为 undefined 4.函数没有返回值时,默认返回 undefinedui

null的典型用法是:

  1. 做为函数的参数,表示该函数的参数不是对象
  2. 做为对象原型链的终点

2、JavaScript 中什么状况下会返回 undefined 值?

一、访问声明,可是没有初始化的变量lua

var aaa;
console.log(aaa); // undefined
复制代码

二、访问不存在的属性url

var aaa = {};

console.log(aaa.c);
复制代码

三、访问函数的参数没有被显式的传递值spa

(function (b){

console.log(b); // undefined

})();
复制代码

四、访问任何被设置为 undefined 值的变量3d

var aaa = undefined;console.log(aaa); // undefined
复制代码

五、没有定义 return 的函数隐式返回code

function aaa(){}console.log(aaa()); // undefined
复制代码

六、函数 return 没有显式的返回任何内容

function aaa(){

return;

}
console.log(aaa()); // undefined
复制代码
相关文章
相关标签/搜索