以下是20个JavaScript缩写技巧的后10个,涵盖位运算、ES6特性及循环优化等高效写法:
11. 双非运算符(~~)替代Math.floor()- 功能:对数字向下取整,效果等同于Math.floor()。
- 传统写法:const floor = Math.floor(6.8); // 6
- 简化写法:const floor = ~~6.8; // 6
- 限制:仅适用于32位整数范围(-2147483648到2147483647),超出范围需用Math.floor()。
12. 对象属性缩写(ES6)- 功能:变量名与对象键名相同时,省略重复赋值。
- 传统写法:const name = '微信公众号:web前端开发';const age = 18;const person = { name: name, age: age };
- 简化写法:const name = 'Yangxiaoai';const age = 30;const person = { name, age };
13. 箭头函数简化- 功能:缩短函数声明,支持隐式返回。
- 传统写法:function sayHello(name) { console.log('Hello', name); }setTimeout(function() { console.log('Loaded'); }, 2000);list.forEach(function(item) { console.log(item); });
- 简化写法:sayHello = name => console.log('Hello', name);setTimeout(() => console.log('Loaded'), 2000);list.forEach(item => console.log(item));
- 隐式返回:单语句箭头函数自动返回结果,省略return。// 传统function calcCircumference(diameter) { return Math.PI * diameter; }// 简化calcCircumference = diameter => Math.PI * diameter;
14. 参数解构- 功能:快速提取对象或数组中的值。
- 传统写法:const store = this.props.store;const form = this.props.form;const loading = this.props.loading;
- 简化写法:const { store, form, loading } = this.props;// 重命名变量const { entity: contact } = this.props;
15. 扩展运算符(...)- 功能:合并数组、克隆数组、合并对象等。
- 合并数组:// 传统const nums = [2, 4, 6].concat(odd);// 简化const nums = [2, 4, 6, ...odd];
- 克隆数组:// 传统const arr2 = arr.slice();// 简化const arr2 = [...arr];
- 插入数组:const nums = [2, ...odd, 4, 6];
- 对象解构剩余值:const { a, b, ...z } = { a: 1, b: 2, c: 3 }; // z: { c: 3 }
- 合并对象:// 传统let full_names = Object.assign(fname, lname);// 简化let full_names = { ...fname, ...lname };
16. 强制参数- 功能:通过默认值抛出错误,确保参数有效。
- 传统写法:function foo(bar) { if (bar === undefined) throw new Error('Missing parameter!'); return bar;}
- 简化写法:const mandatory = () => { throw new Error('Missing parameter!'); };foo = (bar = mandatory()) => bar;
17. 双逻辑NOT(!!)转布尔值- 功能:快速将任意值转为布尔类型。
- 示例:!!23; // true!!""; // false!!0; // false!!{}; // true
18. 变量交换(数组解构)- 功能:无需临时变量交换值。
- 传统写法:let a = 5, b = 10;const temp = a; a = b; b = temp;
- 简化写法:let a = 5, b = 10;[a, b] = [b, a];
19. 变量声明合并- 功能:简化多变量声明。
- 传统写法:let x; let y; let z = 3;
- 简化写法:let x, y, z = 3;// 多变量赋相同值let a = b = c = 100;
- 注意:合并声明可能降低可读性,需谨慎使用。
20. For循环优化- 功能:提供多种遍历方式。
- 传统写法:for (let i = 0; i < arr.length; i++) console.log(arr[i]);
- 简化写法:
for...of(遍历值):
for (let str of arr) console.log(str);forEach(带回调):
arr.forEach(str => console.log(str));for...in(遍历对象键):
const obj = { a: 1, b: 3 };for (let key in obj) console.log(key, obj[key]);
总结:这些技巧通过ES6特性(如箭头函数、解构、扩展运算符)和位运算优化代码,提升可读性与执行效率。实际应用中需权衡缩写与可维护性,避免过度简化导致调试困难。