别让undefined摧毁你的前端代码

孕育

undefined是一个特殊的值,它代表没有。嗯,不是说真的没有,它就像小强一样无所不在,但你又抓不住它,因为它是没有。。。

卑微的出生

数组溢出
var arr = [1, 2, 3];

console.log(arr[4]); // undefined

初始变量
var a;

console.log(a); // undefined

未传实参
function callMe(name) {
  return name;
}

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

无返回值
function callMe(name) {
  // do nothing
}

console.log(callMe('原罪')); // undefined

虚构属性
var def = {hello: "world"};

console.log(def.hi); // undefined

偷梁换柱

堆内存和栈内存的千丝万缕

function doYouLikeMe(You) {
  delete You.amPower;

  return 'no';
}

var I = {name: "原罪", amPower: 'yes'};

console.log(I.amPower);        // 'yes'
console.log(doYouLikeMe(I));   // 'no'

console.log(I.amPower);        // undefined

偷上瘾了

亚当和夏娃偷吃禁果,犯了原罪

function whatAboutAdam(eve) {
  eve.pop();

  return '无罪释放';
}

var eve = ['夏', '娃', '的', '原', '罪'];

console.log(eve[4]);               // '罪'
console.log(whatAboutAdam(eve));   // '无罪释放'

console.log(eve[4]);               // undefined

类型推断
var a;

console.log(typeof a);              // "undefined"
console.log(typeof undefined);      // "undefined"
console.log(typeof notDefinedKey);  // "undefined"

残酷的竞争

队友,可以用 === 对比

// void后面加上任何值都会 全等于 undefined

void 0 === undefined       // true
void 1 === undefined       // true
void '原罪' === undefined   // true
void true === undefined    // true
void {} === undefined      // true

敌人,可以用 == 对比:

null ==  undefined // true

null === undefined // false

敌人的敌人,需要取反对比:


!false === !undefined // true
!"" === !undefined // true
!0 === !undefined // true

false == undefined // false
"" == undefined // false
0 == undefined // false

克隆者入侵

undefined不是保留字,es5之后,全局undefined无法被覆盖

undefined = 2;

console.log(undefined); // undefined

严格模式下,覆盖全局undefined将直接抛错

"use strict";
undefined = 2;

console.log(undefined); // throw new TypeError();

但局部undefined还可以被覆盖(包括严格模式)

var undefined = 2;

console.log(undefined); // 2

灭霸响指

  • 覆盖undefined的值是危险动作,请勿模仿。
  • 可以用 void 0 代替 undefined,压缩插件就是这么做的
  • 有条件的看官请用typescript,给每个undefined都发通行证
  • 写js尽量用 ===,两个等于号的就忘了它吧
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值