掌握这几个JS技巧,做一个不加班的前端人
文章代码转自 https://juejin.cn/post/7068853819135754253 这里,其中有一些代码错误,本文已进行更正,且一些简单技巧,没有写入本文。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <script> // 1. 声明和初始化数组 const array1 = Array(5).fill(""); console.log(array1); // ['', '', '', '', ''] const matrix = Array(5) .fill(0) .map(() => Array(5).fill(0)); console.log(matrix); // 2. 找出总和、最小值和最大值 const array2 = [5, 4, 7, 8, 9, 2]; console.log(array2.reduce((a, b) => a + b)); // 35 console.log(array2.reduce((a, b) => (a > b ? a : b))); // 9 console.log(array2.reduce((a, b) => (a > b ? b : a))); // 2 console.log(Math.max(...array2)); // 9 console.log(Math.min(...array2)); // 2 // 3. 对字符串、数字或对象数组进行排序 // 排序字符串数组 const stringArr = ["Joe", "Kapil", "Steve", "Musk"]; stringArr.sort(); // sort 会直接改变原数组 console.log(stringArr); // 按开头字母顺序排序,['Joe', 'Kapil', 'Musk', 'Steve'] stringArr.reverse(); // reverse 会直接改变原数组 console.log(stringArr); // ['Steve', 'Musk', 'Kapil', 'Joe'] // 排序数字数组 const array3 = [40, 100, 1, 5, 25, 10]; console.log(array3.sort()); // [1, 10, 100, 25, 40, 5] console.log(array3.sort((a, b) => a - b)); // [1, 5, 10, 25, 40, 100] console.log(array3.sort((a, b) => b - a)); // [100, 40, 25, 10, 5, 1]; // 对象数组排序 const objectArr = [ { first_name: "Lazslo", last_name: "Jamf" }, { first_name: "Pig", last_name: "Bodine" }, { first_name: "Pirate", last_name: "Prentice" }, ]; objectArr.sort((a, b) => a.last_name.localeCompare(b.last_name)); console.log(JSON.stringify(objectArr)); // [{"first_name":"Pig","last_name":"Bodine"},{"first_name":"Lazslo","last_name":"Jamf"},{"first_name":"Pirate","last_name":"Prentice"}] // 4. 从数组中过滤出虚假值 const array4 = [3, 0, 6, 7, "", false, undefined, null]; console.log(array4.length); // 8 console.log(array4.filter(Boolean)); // [3, 6, 7] // 5. 对各种条件使用逻辑运算符 function doSomething(arg1) { arg1 = arg1 || 10; // 如果尚未设置,则将 arg1 设置为 10 作为默认值 return arg1; } let foo = 10; console.log(foo === 10 && doSomething(666)); // 666 // is the same thing as if (foo == 10) then doSomething(); // 输出: 10 console.log(foo === 5 || doSomething()); // 10 // is the same thing as if (foo != 5) then doSomething(); // 输出: 10 // 6. 删除重复值 const array6 = [5, 4, 7, 8, 9, 2, 7, 5]; // 注意,filter 不改变原数组,返回新数组 // 以下原理为当 当前遍历到的值的索引与数组中第一次出现该值的索引相同才返回,即第二次出现同样的值(重复值)不返回 console.log(array6.filter((item, idx, arr) => arr.indexOf(item) === idx)); // [5, 4, 7, 8, 9, 2] const nonUnique = [...new Set(array6)]; console.log(nonUnique); // 7. 创建计数器对象或映射 let string = "kapilalipak"; const table = {}; for (let char of string) { table[char] = table[char] + 1 || 1; } console.log(table); // 输出 // {k: 2, a: 3, p: 2, i: 2, l: 2} const countMap = new Map(); for (let i = 0; i < string.length; i++) { if (countMap.has(string[i])) { countMap.set(string[i], countMap.get(string[i]) + 1); } else { countMap.set(string[i], 1); } } console.log(countMap); // Map(5) {"k" => 2, "a" => 3, "p" => 2, "i" => 2, "l" => 2} console.log(countMap.entries()); // MapIterator {'k' => 2, 'a' => 3, 'p' => 2, 'i' => 2, 'l' => 2} console.log(countMap.keys()); // MapIterator {'k', 'a', 'p', 'i', 'l'} console.log(countMap.values()); // MapIterator {2, 3, 2, 2, 2} console.log(countMap.size); // 5 // 8. 三元运算符很酷 function Fever(temp) { return temp > 97 ? "Visit Doctor!" : temp < 97 ? "Go Out and Play!!" : temp === 97 ? "Take Some Rest!" : ""; } console.log(Fever(97)); // "Take Some Rest!" console.log(Fever(100)); // "Visit Doctor!" // 17. 将十进制转换为二进制或十六进制 // 注意 toString 不改变原字符串 const num = 10; console.log(num.toString(2)); // 输出: "1010" console.log(num.toString(16)); // 输出: "a" console.log(num.toString(8)); // 输出: "12" const num1 = 10.2345; // toPrecision 返回数字的长度,字符串没有这个方法 console.log(num1.toPrecision(3)); // 10.2 //19.单行回文检查 function checkPalindrome(str) { return str == str.split("").reverse().join(""); } console.log(checkPalindrome("naman")); // true // 20.将Object属性转成属性数组 // 注意 这里 是对象,与map 调用对应 api 返回的数据类型不同,这里返回都是数组 const obj = { a: 1, b: 2, c: 3 }; console.log(Object.entries(obj)); console.log(Object.keys(obj)); console.log(Object.values(obj)); </script> </body> </html>
分类:
javascript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
2018-07-25 react-router实现tab页面切换,并解决选中样式首页始终选中问题