你不知道的 JavaScript 中卷
- date: 20200329
- author: czhang
Plan
你不知道的 JavaScript 中卷
Notes
1. 内置类型
1. null
2. undefined
3. boolean
4. number
5. string
6. object
7. symbol
1. typeof
1. null ===> 'object'
2. undefined ===> 'undefined'
3. boolean ===> 'boolean'
4. number ===> 'number'
5. string ===> 'string'
6. object ===> 'object'
7. symbol ===> 'symbol'
8. function ===> 'function'
var a;
a; // undefined
b; // TeferenceError: b is not defined
var a;
typeof a; // "undefined"
typeof b; // "undefined" typeof 保护机制
2. 值
1.数组
数组也可以使用字符串键值作为属性,但并不计算到数组长度里面
2. 字符串
数组的成员函数可以在起原始值上进行操作,但 字符串(string)不可以,但是 string 可以借用 Array 的方法
var a = 'foo';
var b = Array.prototype.join.call(a, '-'); // f-o-o
var c = Array.prototype.map.call(a, function(v) {
return v.toUpperCase() + '.';
}); // "F.O.O."
区别: string 没有反转函数,也不可以借用 array 的反转函数 reverse
3. 数字
- number 包括 “整数” + 十进制数 但 整数 是没有小数的十进制数
- JS 中 的数字类型是基于 IEEE754 标准实现的, 为"浮点数",使用"双精度"格式(64 位二进制)
- 由于是浮点数,因此数字没有办法完全相等: 0.1 + 0.2 === 0.3 false , 因此可以使用机器精度(machine epsilon)来定义范围 Number.EPSILON = Math.pow(2,-52)
function numbersCloseEnoughToEqual(n1, n2) {
return Math.abs(n1 - n2) < Number.EPSILON;
}
- 整数的安全范围: 远小于 Number.MAX_VALUE
Number.MAX_SAFE_INTEGER = 2 ^ (53 - 1); // 整数的最大值
Number.MIN_SAFE_INTEGER = -2 ^ (53 + 1); // 整数的最小值
- 整数检测:Number.isInteger()
4. 特殊数值
- null / undefined ,在非严格模式下,可以给 undefined 赋值: undefined = 2,严格模式下加个 var 也可赋值
function foo() {
'use strict';
var undefined = 2;
console.log(undefined); // 2
}
- NaN 是一个特殊值,它和自身不想等,非自反的值: NaN != NaN
- 使用 isNaN 检查:参数是否是 NaN,不是数字
var a = 2/"foo"
bar b = "foo"
window.isNaN(a) // true
window.isNaN(b) // true !!
Number.isNaN:
if (!Number.isNaN) {
Number.isNaN = function(n) {
return typeof n === 'number' && window.isNaN(n);
};
}
// 或者利用 NaN 的不等于自身的特点:
if (!Number.isNaN) {
Number.isNaN = function(n) {
return n !== n;
};
}
无穷数:
Infinity = Number.POSITIVE_INFINITY
- Infinity = Number.NEGATIVE_INFINITY
零 : 正 0 负 0
特殊等式: Object.is() 判断两个值是否绝对相等
5. 值和引用
- 简单值:通过值的复制来赋值/传递 (null/undefined/string/number/boolean/symbol)
- 复合值:通过引用的复制来复制/传递 (object)
3. 原生函数
- 内部属性[[class]] 所有 typeof 返回 "object" 的对象,都包含一个内部属性[[class]],可以看作内部的分类,一般可以通过 Object.prototype.toString.call 来查看
Object.prototype.toString.call([1, 2, 3]); // [object Array]
Object.prototype.toString.call(/regex-literal/i); // [object RegExp]
// 基本类型都会被各自的封装对象自动包装
Object.prototype.toString.call(null); // [object Null]
Object.prototype.toString.call(undefined); // [object Undefined]
Object.prototype.toString.call('abc'); // [object String]
Object.prototype.toString.call(42); // [object Number]
Object.prototype.toString.call(true); // [object Boolean]
- 一般不推荐直接使用封装对象。
- 拆封:使用 valueOf()
var a = new String('abc');
a.valueOf(); // "abc"