【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
1、js的内置类型(7种)
1)基本类型(6种):null、undefined、number、string、boolean、symbol
2)对象(object)是引用类型,在使用过程中会遇到浅拷贝和深拷贝的问题
let a = { name: 'FE' };
let b = a;
b.name = 'EF';
console.log(a.name); // 'EF'
2、获取数据类型
1)typeof 基本类型,除了null都可以显示正确的类型
typeof 1; // 'number'
typeof 'a'; // 'string'
typeof undefined; // 'undefined'
typeof true; // 'boolean'
typeof Symbol(); // 'symbol'
typeof b; // 'undefined',b没有进行申明
typeof null; // 'object',因为在js的最初版本中,使用的是32位系统,为了性能考虑使用低位存储了变量的类型信息, 000开头代表的是对象,然而null表示为全零,所以错误的将它判断为了object
2)typeof 对象,除了函数都会显示 object
typeof []; // 'object'
typeof {}; // 'object'
typeof console.log // 'function'
3)若想要获得一个变量的正确类型,可以通过 Object.prototype.toString.call(变量xx)
Object.prototype.toString.call(1) // "[object Number]"
Object.prototype.toString.call('1') // "[object String]"
Object.prototype.toString.call(undefined) // "[object Undefined]"
Object.prototype.toString.call(true) // "[object Boolean]"
Object.prototype.toString.call(Symbol()) // "[object Symbol]"
Object.prototype.toString.call(null) // "[object Null]"
Object.prototype.toString.call([]) // "[object Array]"
Object.prototype.toString.call({}) // "[object Object]"
Object.prototype.toString.call(console.log) // "[object Function]"
4)注意:undefined的判断,在低版本的浏览器中可以对 undefined 进行赋值操作,直接进行 a === undefined 判断可能会出错
let a;
// 我们可以这样判断 undefined
a === undefined; // true
// 但是 undefined 不是一个保留值,在低版本的浏览器中可以对 undefined 进行赋值操作
let undefined = 1;
a === undefined; // false
// 此时判断就会出错,因此可使用下面的方式来判断 undefined
a === void 0; // true
// 因为 void 后面随意跟上一个一个组成表达式,返回的就是 undefined
3、类型转换
1)转Boolean:在判断时,undefined、null、false、NaN、''、0、-0 会被转换为false;其他额值都会被转换为true
2)对象转基本类型:先调用 valueof 方法,再调用 toString 方法,而且这两个方法可重写。当然也可以重写 Symbol.toPrimitive 方法,该方法在转基本类型时调用优先级最高
var a = [1, 2, 3];
a.valueof(); // [1, 2, 3]
a.toString; // '1,2,3'
// 重写 vauleof 和 toString 方法
a.valueof = function () {
return 1;
}
a.toString = function () {
return 2;
}
a.valueof(); // 1
a.toString(); // 2
// 重写 Symbol.toPrimitive 方法
a[Symbol.toPrimitive] = function () {
return 3;
}
1 + a; // 4
3)四则运算
+ 运算:其中一方为字符串类型,就会把另一方也转为字符串;
除 + 运算以外的其他运算:其中一方为数字,就会把另一方也转为数字;
注意: +1 -> 1; +'a' -> NaN
1 + '1'; // '11
2 * '2'; // 4
[1, 2] + [2, 1]; //',22,1'
// [1, 2].toString() => '1, 2';
// [2, 1].toString() => '2, 1';
// '1,2' + '2,1' => '1, 22, 1'
1 + + 1; // 2
1 + + 'a'; //NaN
'a' + + 'b'; //NaN
4)==操作符
/* 解析题目 [] == ![] // true 的步骤 */
// [] 转为true,然后取反变成false
[] == ![] // 可写成
[] == false;
// 根据第8条得出
ToPrimitive(false) => 0;
[] == false // 可写成
[] == 0;
// 根据第10条得出
ToPrimitive([]) => ''
[] == 0 // 可写成
'' == 0;
// 根据第5、6条得出
0 == 0 // true
// 因此 [] == ![] 的结果为true
5)比较运算符
如果是对象,通过 toPrimitive 转成对象;
如果是字符串,通过 unicode 自符索引来比较;
来源:oschina
链接:https://my.oschina.net/puguole/blog/3143703