js语句简写大全_js判断简写

35 阅读2分钟

a|0


* 取整(四舍五入)



a+.5|0


* 布尔值



!0 // true

!!0 // false


* 字符串连接



''.concat(a, b, c)


* 展平数组(在使用嵌套数组时,这是一项非常有用的技术)



const flattenedArray = [].concat(...array);


* 日期转数值



let time = +new Date();


* 条件判断给变量赋布尔值



if (name === 'XX') { flag = true; } else { flag = false; }

// 等价于 flag = name === 'XX';


* 三元表达式



if (name === 'XX') { age = 20; } else { age = 18; }

// 等价于 age = name === 'XX' ? 20 : 18;


* 判断长度不为0



if (arr.length !== 0) {}

// 等价于 if (arr.length) {}


* 判断长度为0



if (arr.length === 0) {}

// 等价于 if (!arr.length) {}


* includes简化同一条件多种结果判断(个人比较喜欢用)



if (a === 1 || a === 2 || a === 3 || a === 4) {}

// 等价于 if ([1, 2, 3, 4].includes(a)) {}


* || 短路运算符设置默认值



let name = person.name || 'XX'


* && 短路运算符防止对象不存在报错



let name = person && person.name;

// 等价于 let name = person?.name;


* 结构赋初始值



function setData({ a, b = 2 }) { this.a = a; this.b = b; }


* Object.keys()获取对象键名



let obj = { a: 1, b: 2 };

let keys = Object.keys(obj); // ['a', 'b']


* Object.values()获取对象键值



let obj = { a: 1, b: 2 };

let keys = Object.values(obj); // [1, 2]


* forEach()方法遍历数组,不返回新数组



arr.forEach((item, index) => { item.name = 'XX'; });


* filter()过滤数组,返回新数组



let newArr = arr.filter((item, index) => index > 2);


* map()对数组中的所有元素批量处理,返回新数组



let newArr = arr.map(item => { return Object.assign({}, item, { name: 'XX' }); })


* some()是否有满足条件的元素,返回布尔值



let flag = arr.some((item, index) => item.name === 'XX');


* every()数组中的每项是否都满足条件,返回布尔值



let flag = arr.every((item, index) => !!item.name);


* reduce()对数组中的每一项执行提供的reducer函数,最后返回汇总结果



let sum = [1, 2, 3, 4, 5].reduce((acc, current) => { return acc + current; }, 0);


* 条件判断语句



// before method if (color === 'red') { switchRedColor(); } else if (color === 'grey') { switchGreyColor(); } else if (color === 'yello') { switchYellowColor(); } else if(color === 'white') { switchWhiteColor(); }

// after method1 switch(color) { case 'red': switchRedColor(); break; case 'grey': switchGreyColor(); break; case 'yello': switchYellowColor(); break; case 'white': switchWhiteColor(); break; }

// after method2 const colors = { 'red': switchRedColor, 'grey': switchGreyColor, 'yellow': switchYellowColor, 'white': switchWhiteColor };

for (color in colors) { colorscolor; }

// after method3 const colors = new Map([ ['red', switchRedColor], ['grey', switchGreyColor], ['yellow', switchYellowColor], ['white', switchWhiteColor] ]);

for (color in colors) { colorscolor; }