夯实Javascript基础。git
基本类型有六种: null,undefined,boolean,number,string,symbol。github
基本类型的值是保存在栈内存
中的简单数据段数组
基础类型最重要的特性bash
// str 不能调用 Array的 sort 和 splice
Array.prototype.sort.call('strxyz');
// Uncaught TypeError: Cannot assign to read only property '2' of object '[object String]'
Array.prototype.splice.call('strxyz');
// Uncaught TypeError: Cannot assign to read only property 'length' of object '[object String]'
// object 能够使用 Array的sort 和 splice
Array.prototype.sort.call({x: 1, y: 2});
// {x: 1, y: 2}
Array.prototype.splice.call({x: 1, y: 2});
// []
复制代码
__proto__
没有属性
str.x = 1;
console.log(str.x); // undefined
复制代码
基本包装类型
(String、Number、Boolean)当你调用 `str.length` 时,实际过程是这样的:
- 建立String类型的一个实例
- 在实例上调用指定的方法
- 销毁这个实例
var str = 'abc';
var _str = new String(str);
var len = _str.length;
_str = null;
console.log(len);
复制代码
其余特性ui
undefined
null
false
NaN
''
0
-0
为 false,其余都为 true
1 === 1.0
var a = NaN; a !== a;
String
类型是类数组,具备iterator
typeof String('x')[Symbol.iterator] === 'function'
检测基础类型用 typeof
spa
// typeof 只适合检测 基础类型
typeof new Date() // 'object'
typeof [] // 'object'
typeof {} // 'object'
typeof console.log // 'function'
复制代码
基本类型转换时,首先会调用 valueOf
,而后调用 toString
。而且这两个方法能够重写。prototype
var a = 1;
var obj = {x: 1};
obj.toString === '[object Object]';
var arr = [2, 3];
arr.toString() === '2,3';
a + obj === '1[object Object]';
a + arr === '12,3';
复制代码
Symbol.toPrimitive
该方法在转基本类型时调用优先级最高。code
let a = {
valueOf() {
return 1;
},
toString() {
return '2';
},
[Symbol.toPrimitive]() {
return 3;
}
}
1 + a // => 4
复制代码
number
,那么会转换为字符串(toString
)进行拼接持续更新中,Github信息更多哦,你的⭐是我最大的支持。查看详情,对象