夯實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信息更多哦,你的⭐是我最大的支持。查看詳情,對象