@songying
2019-10-07T05:48:56.000000Z
字数 1240
阅读 1355
JavaScript
typeof操作符能够获取对象的类型,它总是返回一个字符串。
typeof 123; // 'number'typeof NaN; // 'number'typeof 'str'; // 'string'typeof true; // 'boolean'typeof undefined; // 'undefined'typeof Math.abs; // 'function'typeof null; // 'object'typeof []; // 'object'typeof {}; // 'object'
var n = new Number(123);var b = new Boolean(true);var s = new String('str');
不要使用 new Number()、new Boolean()、new String()创建包装对象;
用 parseInt() 或 parseFloat()来转换任意类型到number;
用 String() 来转换任意类型到string,或者直接调用某个对象的toString()方法;
通常不必把任意类型转换为boolean再判断,因为可以直接写if (myVar) {...};
typeof操作符可以判断出number、boolean、string、function和undefined;
判断Array要使用Array.isArray(arr);
判断null请使用 myVar === null;
判断某个全局变量是否存在用 typeof window.myVar === 'undefined';
函数内部判断某个变量是否存在用 typeof myVar === 'undefined'
| 函数 | 说明 |
|---|---|
| var now = new Date(时间戳) | 返回系统当前时间 |
| now.getFullYear() | 年份 |
| now.getMonth() | 月份 |
| now.getDate() | 几号 |
| now.getDay() | 星期几 |
| now.getHours() | 小时 |
| now.getMinutes() | 分钟 |
| now.getSeconds() | 秒数 |
| now.getMilliSeconds() | 毫秒 |
| now.getTime() | 以 number形式表示的时间数 |
| now.toLocalString() | 返回本地时间 |
| now.toUTCString() | 返回 UTC 时间 |
var d = Date.parse('2015-06-24T19:49:22.875+08:00') |
解析字符串 |
JS 有两种方式创建正则
/正则表达式/new RegExp('正则表达式')创建一个RegExp对象
var re1 = /ABC\-001/;var re2 = new RegExp('ABC\\-001');
| 函数 | 说明 |
|---|---|
| JSON.stringify(js对象) | 序列化,返回json 字符串 |
| JSON.parse(json字符串) | 反序列化,返回js对象 |
