#js常见的运算符的使用方法
-
经典问题之typeof运算符判断的类型有哪些
用typeof可以判断出来的类型有:'undefined'、'object'、'number'、'string'、'function'、'symbol'
用typeof来判断数组出现的结果let a = []; console.log(typeof a);//object几种常见的数组类型判断方法
1、es5中定义的方法Array.isArray(), 返回值true\false
let a = []; Array.isArray(a);//true2、instanceof, 判断Array的prototype属性是否在判断对象上
let a = []; a instanceof Array // true3、判断对象constructor
let a = []; a.constructor === Array //true注意,当数组的对象内容是iframe,每个iframe都有一套自己的执行环境,因此前面两种方法并不适用
4、Object.prototype.toString()的方法
let a = []; Object.prototype.toString.call(a); // "[object Array]" -
常见的隐式类型转换
1、字符串和数字相加
1 + 'a'; // '1a'2、使用 == or ===
一般情况下推荐使用 ===来判断较为靠谱,当同时需要判断undefined和null,推荐写法,a == nullundefined == null; // true undefined !== null; //true 0 == '0'; // true; -
巧用运算符简化代码量
1、&&、||、三元运算符,简化代码
let a = []; if (a.length === 0) { a.push(1); }; // 简化过后 a.length === 0 && a.push(1); // 给一个变量一个默认值 let a = b || 2; // 简化判断的方式 let a = a > 0 ? 1 : 0;2、! 、& 优化代码
// 常见的代码风格 if (a) { // ...... // } else { handleError(); } // 避免代码嵌套过深 if (!a) handleError(); // ...... //// 判断奇偶数的妙招 let a = 3; console.log(a & 1); // 打印出0 代表偶数,1代表奇数3、拓展运算符的常见使用
//数组去重 let a = [...new Set([0,1,1,2,2,3])]; // 0,1,2,3 //简单数组深拷贝赋值 let a = [0,1,2,...b]; // 相当于 a = a.concat(b) // 结构赋值的结合 let [a,...b] = [0,1,2,3,4,5]// a = 0,b = [1,2,3,4,5] // 拓展思考,vuex中,对状态的引入,...mapState(['a','b']);