基础数据类型
在 JavaScript 中,变量没有类型 -- 值才有类型。变量可以在任何时候,持有任何值。
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'
原生类型
封箱包装器
对象包装器服务于一个非常重要的目的。基本类型值没有属性或方法,所以为了访问 .length
或 .toString()
你需要这个值的对象包装器。值得庆幸的是,JS 将会自动地 封箱(也就是包装)基本类型值来满足这样的访问。
示例代码
var a = "abc";
a.length; // 3
a.toUpperCase(); // "ABC"
开箱
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
网友评论