◆
JavaScript 数据类型与 null、undefined 区别
数据类型
基本数据类型
- 字符串(
string) - 数值(
number) - 布尔值(
boolean) BigInt(bigInt)- 符号(
symbol,ES6中新增)
特殊值
- 空值(
null): 表示空值,即此处的值为空。 - 未定义(
undefined)
引用数据类型(合成类型)
object:在 JS 中除了基本数据类型以外的都是对象。
内置对象
ObjectStringNumberBooleanFunctionArrayDateRegExpErrornull和undefined没有对应的构造形式,它们只有文字形式。相反,Date只有构造,没有文字形式。对于
Object、Array、Function和RegExp(正则表达式)来说,无论使用文字形式还是构造形式,它们都是对象,不是字面量。
typeof '42' === 'string'; // true
typeof 42 === 'number'; // true
typeof true === 'boolean'; // true
typeof null === 'object'; // true
typeof undefined === 'undefined'; // true
typeof 1n === 'bigint';
// ES6中新加入的类型
typeof Symbol('fx') === 'symbol'; // true
typeof { life: 42 } === 'object'; // true
typeof new Date() === 'object'; // true
null 与 undefined 区别作用
null- 代表空值,代表一个空对象指针,使用
typeof运算得到object,所以你可以认为它是一个特殊的对象值 - 转为数值时为
0 - 可作为对象原型链的终点。
- 当使用完一个比较大的对象时,需要对其进行释放内存时,设置为
null - 主动释放一个变量引用的对象,表示一个变量不再指向任何对象地址
- 代表空值,代表一个空对象指针,使用
undefined- 是一个表示"此处无定义"的原始值,转为数值时为
NaN - 是所有未赋值变量默认值。
- 变量被声明了,但没有赋值时,就等于
undefined。 - 调用函数时,应该提供的参数没有提供,该参数等于
undefined。 - 对象没有赋值的属性,该属性的值为
undefined。 - 函数没有返回值时,默认返回
undefined。
- 是一个表示"此处无定义"的原始值,转为数值时为
// "object"
typeof null;
// "undefined"
typeof undefined;
// false
null === undefined;
// true
null == undefined;
// 0
Number(null);
// NaN
Number(undefined);
undefined 应用场景
// 变量声明了,但没有赋值
var i;
i; // undefined
// 调用函数时,应该提供的参数没有提供,该参数等于 undefined
function f(x) {
return x;
}
f(); // undefined
// 对象没有赋值的属性
var o = new Object();
o.p; // undefined
// 函数没有返回值时,默认返回 undefined
function f() {}
f(); // undefined
如何判断数据类型
- 可以通过
Object.prototype.toString.call(xx)。这样我们就可以获得类似[object Type]的字符串。 instanceof可以正确的判断对象的类型,因为内部机制是通过判断对象的原型链中是不是能找到类型的prototype。
function judgeType(obj) {
let class2type = {};
'Array Date RegExp Object Error'
.split(' ')
.forEach(e => (class2type['[object ' + e + ']'] = e.toLowerCase()));
if (obj == null) return String(obj);
return typeof obj === 'object'
? class2type[Object.prototype.toString.call(obj)] || 'object'
: typeof obj;
}

还没有留言,来发表第一条吧~