JavaScript 基础(一):null 和 undefined

一、前言

一直有在看 JS 基础的内容。一直也有在总结,现在是时候自己也写一些基础方面的系列。

后面会持续更新。

思来想去,就从基础数据类型开始。开始的开始就从 null 和 undefined(一生二,二生三,三生万物)

二、Undefined

undefined 是 Undefined 类型的唯一值。是当用 var let 声明了变量但是没有赋值时(未初始化),当前变量默认就是 undefined。

所以不用显示的给变量赋值为 undefined。

可以检测 undefined 类型的方法有:

const undefinedObj = undefined
console.log(typeof undefinedObj)  // undefined
console.log(undefinedObj === undefined)  // true
console.log(Object.prototype.toString.call(undefinedObj))  // [object Undefined]

三、Null

null 是 Null 类型的唯一值。标识的是一个空对象指针。从这个地方看,所以:

 console.log(typeof nullObj)
 // object

在使用 typeof 检测类型时,返回的 “object”。

从底层来看,JavaScript 中单个值在栈中是占用32位的存储单元,这32个单元又划分为:

类型标签(1-3位)、实际数据。typeof 检测就是检测的类型标签。

类型标签是:000 的,表示的 object。

null 因为其存储上全部是 0,所以用 typeof 检测返回的是 “object”。

那准确检测的方法有:

 const nullObj = null
 console.log(nullObj === null)    // true
 console.log(Object.prototype.toString.call(nullObj))    //[object Null]

四、两者使用差异

1、使用频率

现在开发中一般使用框架开发,变量声明都比较规范。现在使用 undefined 越来越少了。null 使用比较多。

2、两者相等

使用 == 进行比较两者,返回 true

console.log(null == undefined)    // true

3、string、number 是否应该赋值为 null

在开发中遇到过,对于 string、number 的是否应该赋值为 null 的情况。

一般来说,string 类型应该赋值为 ‘’,number 类型应该赋值为 0。

遇到这样的一个场景:

  Vue 中使用 axios 请求接口,当把 string 、number 赋值为 null 时,会直接不带这些参数,正好达到了想要的效果(就是不想使用这个字段查询)

  如果 string 是 ‘’,那么就不一样了,会带上该参数,而且后端还要特殊处理(特别是后端单引号和双引号字符不一样)。

出于这样的原因,应该根据实际情况确定怎么使用。

原文地址:https://www.cnblogs.com/zhurong/p/14060745.html