js 中内置类型一共 7 种(包括 es6),7 种内置类型可分为两大类型:基本类型 和 引用类型(对象Object)。javascript
1.基本类型包括:null
、undefined
、string
、number
、boolean
、symbol
。java
重点说下数字类型number
:es6
NaN
也属于 number
类型,而且 NaN
不等于自身;2.对象(Object)是引用类型,在使用过程当中会遇到 浅拷贝 和 深拷贝 的问题。函数
const x = { name: 'x'};
const y = x;
y.name = 'y';
console.log(x.name); // y
复制代码
1.对于基本类型,除了 null
均可以显示正确类型post
typeof x; // 'undefined'
typeof '1'; // 'string'
typeof 1; // 'number'
typeof true; // 'boolean'
typeof Symbol(); // 'symbol'
复制代码
typeof 1
也能够写成 typeof(1)
,其余也是同样。性能
2.对于对象,除了函数都显示object
ui
typeof []; // 'object'
typeof {}; // 'object'
typeof console; // 'object'
typeof console.log; // 'function'
复制代码
3.说说 null
,一个遗留 bug,明明是基本类型,但是就显示 object
spa
typeof null ; // 'object'
复制代码
那为何会出现这种状况呢? js 最第一版本中,使用的是 32 位系统,为了性能考虑使用低位存储变量的类型信息,000
开头表示对象,而 null
表示全零,因此将它错判为 object
了。虽然如今内部类型的判断代码变了,可是这个 bug 却一直流传下来。prototype
4.正确获取变量类型可以使用 Object.prototype.toString.call(xx)
,得到相似 [object Type]
的字符串code
Object.prototype.toString.call(111)
复制代码
除了 undefined
、null
、false
、NaN
、''
、0
、-0
,其余都为 true
,包括对象。
对象转基本类型时,会调用 valueOf
、toString
两个方法,也能够重写 Symbol.toPrimitive
(优先级最高)
let p = {
valueOf(){
return 0;
},
toString(){
return '1';
},
[Symbol.toPrimitive] (){
return 2;
}
}
console.log(1 + p); // 3
console.log('1' + p); // 12
复制代码
console.log(1 + '1'); // 11
console.log(1 * '1'); // 1
console.log([1, 2] + [1, 2]); // '1, 21, 2'
// [1, 2].toString() => '1, 2'
// [1, 2].toString() => '1, 2'
// '1, 2' + '1, 2' => '1, 21, 2'
复制代码
加号有个须要主要的表达式 'a' + + 'b'
console.log('a' + + 'b'); // aNaN
// + 'b' => NaN
复制代码
==
操做符比较运算 x == y
,其中 x
和 y
是值,产生 true
或 false
:
(1).Type(x)
与 Type(y)
相同,则
Type(x)
为 undefined
,返回 true
;Type(x)
为 null
,返回 true
;Type(x)
为 number
,则
x
为 NaN
,返回 false
(NaN == NaN
);y
为 NaN
,返回 false
(NaN == NaN
);x
与 y
相等数值,返回 true
;x
为 +0
,y
为 -0
,返回 true
;x
为 -0
,y
为 +0
,返回 true
;Type(x)
为 string
,则当 x
与 y
为彻底相同的字符序列(长度相等且相同字符在相同位置)时返回 true
,不然 false
('11' == '21')。Type(x)
为 boolean
,x
与 y
同为 true
或同为 false
,返回true;(2).x
为 null
且 y
为 undefined
,返回 true
,互换也是;
(3).若 Type(x)
为 number
且 Type(y)
为 string
,返回 comparison x = toNumber(y)
的结果,互换也是;
(4).Type(x)
为 boolean
,返回 toNumber(x)
= y
( 5 > 3 == 1),互换也是;
(5).Type(x)
为 string
或 number
,且 Type(y)
为 object
,返回 x = toPrimitive(y)
的结果,互换也是;
注:toPrimitive
对象转基本类型
有个烧脑的例子:
console.log( [] == ![] ); // true
// 从右往左解析, [] => true => 取反 => false => [] = false
// 根据第(4)条,toNumber(false) => 0
// 根据第(5)条,toPrimitive([]) == 0 => [].toString() => ''
// 根据第(3)条,toNumber('') == 0 => 0 == 0
复制代码
总结:对象-布尔(字符串)-数字
toPrimitive
转为对象;unicode
字符索引来比较;