undefined

145 阅读2分钟

一:描述

1. undefined既是一个原始数据类型,也是一个原始值数据。

系统会给一个未赋值的变量自动赋值为undefined,类型也是undefined

var a;
console.log(a); //undefined
console.log(typeof a); //undefined

2. undefined是全局对象的一个属性(window.undefined)。

console.log(window.undefined); // undefined

undefined 属性的属性特性:

  • 不可写:writable: false
  • 不可配置:configurable: false
  • 不可枚举:enumerable: false
  • 不可重新定义
// 不可写
window.undefined = 1;
console.log(window.undefined); // undefined

// 不可配置
delete window.undefined;
console.log(window.undefined); // undefined

// 不可枚举
for(let key in window){
  if(key === undefined){
    console.log(key); // 没打印
  }
}

// 不可重新定义
Object.defineProperty(window, 'undefined', {
  writable: true,
  configurable: true,
  enumerable: true,
}); // Uncaught TypeError: Cannot redefine property: undefined

3. 如果方法或者是语句中操作的变量没有被赋值,则会返回undefined

function test(a) {
  console.log(a); // undefined
  console.log(typeof a); // undefined
  return a;
}
console.log(test()); // undefined

4. 一个函数如果没有使用return语句指定返回值,就会返回一个undefined值。

function test() {
  console.log('test');
}
console.log(test()); // undefined

5. undefined 不是 JS 的关键字和保留字

全局作用域给 undefined 赋值无用。非全局作用域下给 undefined 赋值可以成功(无论是否严格模式);

// 全局
var undefined = 1;
console.log(window.undefined); //undefined

// 函数
function test() {
  'use strict';
  var undefined = 1;
  console.log(undefined); // 1
}
test();

6. 如何判断一个值是否是 undefined ?

  • 使用全等操作符;
  • 使用 typeof(未被声明的变量 typeof 也返回 undefined);
  • 使用 in 操作符
// 使用全等操作符
var a;
if(a === undefined){
  console.log(true);
}

// typeof
var a;
if(typeof a === "undefined"){
  console.log(true);
}
//未被声明的变量
console.log(typeof b); // undefined

// in
var a;
if('a' in window){
  console.log(true); // 打印
}

7. void操作符

对给定的表达式进行求值,然后返回 undefined

var a, b, c;
a = void(b = 1, c = 2);
console.log(a, b, c); //undefined 1 2

console.log(void(0) === window.undefined); //true

// 当函数作用域中修改了undefined值;
// 判断是否跟window.undefined相等时,可以使用void(0)。减少获取window属性。
function test() {
  var undefined = 1;
  console.log(undefined); //1
  console.log(window.undefined === void(0)); //true
  console.log(undefined === void(0)); // false
}
test();