掌握这20个JS技巧,做一个不加班的前端人

掌握这20个JS技巧,做一个不加班的前端人
最新回答
夜见树

2021-02-19 01:48:22

掌握以下20个JavaScript技巧可显著提升开发效率,帮助前端开发者更高效地完成编码任务并减少加班时间

1. 声明和初始化数组
  • 一维数组:使用Array(n).fill(value)快速初始化固定大小的数组。const array = Array(5).fill(''); // 输出: ["", "", "", "", ""]
  • 二维数组/矩阵:结合fill和map方法初始化多维数组。const matrix = Array(5).fill(0).map(() => Array(5).fill(0));
2. 快速计算总和、最小值和最大值
  • 使用reduce方法简化数学运算:const array = [5, 4, 7, 8, 9, 2];const sum = array.reduce((a, b) => a + b); // 输出: 35const max = array.reduce((a, b) => a > b ? a : b); // 输出: 9const min = array.reduce((a, b) => a < b ? a : b); // 输出: 2
3. 数组排序技巧
  • 字符串数组:直接使用sort()和reverse()。const stringArr = ["Joe", "Kapil", "Steve", "Musk"];stringArr.sort(); // 升序stringArr.reverse(); // 降序
  • 数字数组:通过比较函数实现升序或降序。const numArray = [40, 100, 1, 5, 25, 10];numArray.sort((a, b) => a - b); // 升序numArray.sort((a, b) => b - a); // 降序
  • 对象数组:使用localeCompare对特定属性排序。const objectArr = [{ first_name: 'Lazslo' }, { first_name: 'Pig' }];objectArr.sort((a, b) => a.first_name.localeCompare(b.first_name));
4. 过滤虚假值
  • 使用filter(Boolean)快速移除数组中的0、undefined、null、false、""等虚假值。const array = [3, 0, 6, 7, '', false];const filteredArray = array.filter(Boolean); // 输出: [3, 6, 7]
5. 简化条件判断
  • 使用逻辑运算符&&和||替代简单的if-else语句。function doSomething(arg1) { arg1 = arg1 || 10; // 默认值设置 return arg1;}foo === 10 && doSomething(); // 等价于 if (foo === 10) doSomething();foo === 5 || doSomething(); // 等价于 if (foo !== 5) doSomething();
6. 删除重复值
  • 使用Set或filter结合indexOf快速去重。const array = [5, 4, 7, 8, 9, 2, 7, 5];const uniqueArray = array.filter((item, idx, arr) => arr.indexOf(item) === idx);// 或const uniqueArray = [...new Set(array)]; // 输出: [5, 4, 7, 8, 9, 2]
7. 创建计数器对象或映射
  • 普通对象:遍历字符串并统计字符出现次数。let string = 'kapilalipak';const table = {};for (let char of string) { table[char] = table[char] + 1 || 1;} // 输出: {k: 2, a: 3, p: 2, i: 2, l: 2}
  • Map对象:使用Map实现更高效的计数。const countMap = new Map();for (let char of string) { countMap.set(char, (countMap.get(char) || 0) + 1);} // 输出: Map(5) {"k" => 2, "a" => 3, ...}
8. 三元运算符简化嵌套条件
  • 使用三元运算符替代多层if-else语句。function Fever(temp) { return temp > 97 ? 'Visit Doctor!' : temp < 97 ? 'Go Out and Play!!' : 'Take Some Rest!';}
9. 选择高效的循环方式
  • for循环:性能最优,适合处理大型数组。
  • for...in:遍历对象属性,但会包含原型链上的属性,需配合hasOwnProperty使用。
  • forEach/for...of:直接获取元素,但无法使用break或continue。
10. 合并多个对象
  • 使用展开运算符...快速合并对象。const user = { name: 'Kapil' };const college = { primary: 'Mani Primary School' };const summary = { ...user, ...college }; // 输出: { name: 'Kapil', primary: 'Mani Primary School' }
11. 箭头函数简化代码
  • 箭头函数具有词法作用域,适合简化回调函数。const person = { name: 'Kapil', sayName: () => console.log(this.name) // 注意:箭头函数中的this指向外层作用域};
12. 可选链操作符?.
  • 安全访问嵌套对象属性,避免TypeError。const user = { employee: { name: "Kapil" } };console.log(user.employee?.name); // 输出: "Kapil"console.log(user.employ?.name); // 输出: undefined
13. 打乱数组顺序
  • 利用Math.random()结合sort实现随机排序。const list = [1, 2, 3, 4, 5];list.sort(() => Math.random() - 0.5); // 输出: 随机顺序的数组
14. 空合并运算符??
  • 当左侧操作数为null或undefined时返回右侧操作数。const foo = null ?? 'my school'; // 输出: "my school"const baz = 0 ?? 42; // 输出: 0
15. Rest与Spread运算符
  • Rest参数:收集剩余参数为数组。function myFun(a, b, ...manyMoreArgs) { return manyMoreArgs.length; // 输出: 剩余参数的数量}
  • Spread运算符:展开数组或对象。const parts = ['shoulders', 'knees'];const lyrics = ['head', ...parts, 'and', 'toes']; // 输出: ["head", "shoulders", ...]
16. 默认参数
  • 为函数参数设置默认值,避免手动判断。const search = (arr, low = 0, high = arr.length - 1) => high;search([1, 2, 3]); // 输出: 2
17. 进制转换
  • 使用toString(radix)将数字转换为不同进制字符串。const num = 10;num.toString(2); // 输出: "1010"(二进制)num.toString(16); // 输出: "a"(十六进制)
18. 交换变量值
  • 使用解构赋值快速交换两个变量的值。let a = 5, b = 8;[a, b] = [b, a]; // 输出: a = 8, b = 5
19. 单行回文检查
  • 通过字符串反转判断是否为回文。function checkPalindrome(str) { return str === str.split('').reverse().join('');}checkPalindrome('naman'); // 输出: true
20. 对象属性转换
  • 使用Object.entries()、Object.keys()和Object.values()快速获取对象属性。const obj = { a: 1, b: 2 };Object.entries(obj); // 输出: [["a", 1], ["b", 2]]Object.keys(obj); // 输出: ["a", "b"]Object.values(obj); // 输出: [1, 2]

总结:以上技巧覆盖了数组操作、对象处理、条件判断、函数优化等常见场景,合理运用可显著提升代码效率和可读性,从而减少开发时间和加班需求。