类型
内置类型:
null/undifined/boolean/string/number/Object/symbol
判断:
typeof()
特殊类型
undifined =>未定义
undeclared =>未声明(Javascript统一当做undifined处理)
值
1. 数组
数组也是对象=>
let arr =[]
arr[0] = 'Janus'
arr['test'] = 'test value'
arr.length ---> 1
console.log(arr.test) ---> test value
注意:当key可以被强制类型转换未十进制数字类型时,按照索引进行填充
let arr =[]
arr[0] = 'Janus'
arr['16'] = 'test value'
arr.length ---> 17
2.字符串
字符串与数组
基本上数组具有的成员函数字符串都具备,特殊情况可以“借用”,like:
let a = '123'
Array.prototype.join.call(a,'-') --->'1-2-3'
let b = 'abcd';
Array.prototype.map.call(a,(v)=>{
return v.toUpperCase();
}) --->'ABCD'
字符串不可变,所有成员函数返回的都是新的字符串,而数组的成员函数都是基于数组进行操作。
因此“借用”受限制 —— 字符串反转
let b = 'abcd';
Array.prototype.reverse.call(b)
--->
VM24810:2 Uncaught TypeError: Cannot assign to read only property '0' of object '[object String]'
at String.reverse (<anonymous>)
at <anonymous>:2:25
技巧:先分割为字符串数组,再调用reverse(),后拼接
let a = 'abcd';
a.split('').reverse().join('') ---> 'dcba'
3.数字
可省略的0
.42 ---> 0.42
42.0 ---> 42
2.330000 ---> 2.3
超大/小数 —— (科学计数法)
let a = 5E10 ---> 50000000000
let b = 5E-10 ---> 50000000000
let c = a * b ---> 25
a.toExponential() --> '5e+10'
显示位数(自动截取/补齐)
小数位数:tofixed()
let a = 4.23
a.toFixed(5) ---> 4.23000
整体位数:toPrecision()
let a = 4.23
a.toPrecision(5) ---> 4.2300
0.1 + 0.2 === 0.3 --->false!!!
原因:浮点数精度造成
解决方案:Number.EPSILON(机器精度),只要绝对值差小于机器精度,可认为相等
function isEqual(v1,v2){
return Math.abs(v1-v2)<Number.EPSILON
}
let a = 0.1+0.2;
console.log(a === 0.3) ---> false
isEqual(a,0.3) ---> true
4.特殊值
4.1 undefined/null
undefined类型只有一个值,即undefined。null类型也只有一个值,即null。它们的名称既是类型也是值。
- undefined 指从未赋值
- null 指曾赋过值,但是目前没有值
undifined可局部修改,因此判断是否为undifined建议通过void 0 获取
4.2 不是数字的数字——NaN(not a number)
不可直接比较
let a = 2/'foo';
a === NaN -- > false
NaN === NaN --> false
判断:isNaN() —— 只针对于number
let a = 2/'foo';
isNaN(a) ---> true
isNaN(NaN) ---> true
let b = 'foo'
isNaN(b) ---> true (历史bug)
解决方案:
a.Number.isNaN()
let b = 'foo'
Number.isNaN(b) ---> false!
b.NaN是JavaScript中唯一一个不等于自身的值
function isNaNPolyfill(n){
return n!==n
}
let b = 'foo';
isNaNPolyfill(b) ---> false
isNaNPolyfill(NaN) ---> true
4.3 无穷数
1/0 -> Infinity
-1/0 -> -Infinity
Infinity/Infinity -> NaN
4.4 特殊等式
Object.is()
-0 === 0 --->true
Object.is(-0,0) --->false
4.5 值和引用
基本类型通过“值传递”
复杂类型通过“引用传递”