基礎(chǔ)數(shù)據(jù)類型
在 JavaScript 中烹棉,變量沒(méi)有類型 -- 值才有類型滥崩。變量可以在任何時(shí)候涂臣,持有任何值惨险。
null
typeof null === 'object'
這是js存在的bug羹幸。
undefined
typeof undefined === 'undefined'
boolean
let a=true;
typeof a === 'boolean'
number
let a=10;
typeof a === 'number'
string
let a='Nick';
typeof a === 'string'
object
let a={ name : 'Nick' };
typeof a === 'object'
symbol
let a=Symbol();
typeof a === 'symbol'
原生類型
封箱包裝器
對(duì)象包裝器服務(wù)于一個(gè)非常重要的目的”栌洌基本類型值沒(méi)有屬性或方法栅受,所以為了訪問(wèn) .length
或 .toString()
你需要這個(gè)值的對(duì)象包裝器。值得慶幸的是恭朗,JS 將會(huì)自動(dòng)地 封箱(也就是包裝)基本類型值來(lái)滿足這樣的訪問(wèn)屏镊。
示例代碼
var a = "abc";
a.length; // 3
a.toUpperCase(); // "ABC"
開(kāi)箱
var a = new String( "abc" );
var b = new Number( 42 );
var c = new Boolean( true );
a.valueOf(); // "abc"
b.valueOf(); // 42
c.valueOf(); // true
String
let s = new String( "Hello World!" );
console.log( s.toString() ); // "Hello World!"
let a = new String( "abc" );
typeof a; // "object" ... 不是 "String"
a instanceof String; // true
Object.prototype.toString.call( a ); // "[object String]"
Number
let a = new Number(12);
console.log(a.valueof()); // 12
Boolean
let k = new Boolean(false);
console.log(k.valueOf()); // false
Array
let l = new Array(1,2,3);
console.log(l); // [ 1, 2, 3 ]
Object
let m=new Object({name:'Nick'});
console.log(m); // { name: 'Nick' }
Function
let n = new Function("count","n", " return count+n;");
console.log(n(1,2)); // 3
RegExp
let r = new RegExp('e');
console.log(r.test("hello")); // true
console.log(r.exec("hello")); // [ 'e', index: 1, input: 'hello', groups: undefined ]
r.compile('o');
console.log(r.test('hello')); //true
console.log(r.exec('hello')); // [ 'o', index: 4, input: 'hello', groups: undefined ]
r.compile('a');
console.log(r.test('hello')); // false
console.log(r.exec('hello')); // null
Date
function format(num) {
if (num < 10) {
return `0${num}`
} else {
return `${num}`;
}
}
let date = new Date();
console.log(`${date.getFullYear()}-${format(date.getMonth() + 1)}-${ format(date.getDate())} ${format(date.getHours())}:${format(date.getMinutes())}:${format(date.getSeconds())}`); // 2018-06-06 14:23:37
Error
try {
let error = new Error('異常');
throw error;
} catch (e) {
console.log(e.message); // 異常
}
Symbol
let p = Symbol('key');
let q = Symbol('key');
console.log(p === q); // false
let s = Symbol.for('name');
let t = Symbol.for('name');
console.log(s === t); // true