幫你提高開發(fā)效率的JavaScript20個技巧
減少代碼行數(shù)和加快開發(fā)的技術!
我們在開發(fā)中,經常要寫一些函數(shù),如排序、搜索、尋找唯一的值、傳遞參數(shù)、交換值等,在這里我列出了我搜集的一些技術資源,可以像高手一樣寫出這些函數(shù)!
這些方法肯定會對你有幫助:
- 減少LOC(代碼行)的數(shù)量
- 編碼競
- 黑客馬拉松
- 或者其他限時任務
這些JavaScript黑客技術大多使用ECMAScript6(ES2015)以后的技術,盡管最新版本是ECMAScript11(ES2020)。
注意:下面所有的技巧都是在谷歌瀏覽器的控制臺測試的。
1. 申明和初始化數(shù)組
可以用默認值來初始化特定大小的數(shù)組,如""、null或0。你可能已經把這些用于一維數(shù)組,但如何初始化二維數(shù)組/矩陣呢?
const array = Array(5).fill(''); // Output (5) ["", "", "", "", ""] const matrix = Array(5).fill(0).map(()=>Array(5).fill(0)); // Output (5) [Array(5), Array(5), Array(5), Array(5), Array(5)] 0: (5) [0, 0, 0, 0, 0] 1: (5) [0, 0, 0, 0, 0] 2: (5) [0, 0, 0, 0, 0] 3: (5) [0, 0, 0, 0, 0] 4: (5) [0, 0, 0, 0, 0] length: 5
2.進行求和、最小值和最大值
使用reduce方法來快速進行基本的數(shù)學運算。
const array = [5,4,7,8,9,2];
求和
array.reduce((a,b) => a+b); // Output: 35
最大值
array.reduce((a,b) => a>b?a:b); // Output: 9
最小值
array.reduce((a,b) => a<b?a:b); // Output: 2
3. 對字符串、數(shù)字或對象的數(shù)組進行排序
有內置的sort()和reverse()方法來對字符串進行排序,但對數(shù)字或對象數(shù)組的排序呢?
數(shù)字和對象的排序技巧,可以按照遞增和遞減的順序進行排序。
字符串排序
const stringArr = ["Joe", "Kapil", "Steve", "Musk"] stringArr.sort(); // Output (4) ["Joe", "Kapil", "Musk", "Steve"] stringArr.reverse(); // Output (4) ["Steve", "Musk", "Kapil", "Joe"]
數(shù)字排序
const array = [40, 100, 1, 5, 25, 10]; array.sort((a,b) => a-b); // Output (6) [1, 5, 10, 25, 40, 100] array.sort((a,b) => b-a); // Output (6) [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)); // Output (3) [{…}, {…}, {…}] 0: {first_name: "Pig", last_name: "Bodine"} 1: {first_name: "Lazslo", last_name: "Jamf"} 2: {first_name: "Pirate", last_name: "Prentice"} length: 3
4. 是否需要從一個數(shù)組中過濾掉無用的值?
像0,undefined,null,false,"",''這樣的值可以通過下面的技巧輕松過濾。
const array = [3, 0, 6, 7, '', false]; array.filter(Boolean); // Output (3) [3, 6, 7]
5. 為各種條件使用邏輯運算符
如果你想減少嵌套,比如if...else或switch,可以使用邏輯運算符AND/OR。
function doSomething(arg1){ arg1 = arg1 || 10; // set arg1 to 10 as a default if it's not already set return arg1; } let foo = 10; foo === 10 && doSomething(); // is the same thing as if (foo == 10) then doSomething(); // Output: 10 foo === 5 || doSomething(); // is the same thing as if (foo != 5) then doSomething(); // Output: 10
6. 刪除重復的值
你可能已經在for循環(huán)中使用了indexOf(),它返回第一個找到的索引,或者使用較新的includes(),它從數(shù)組中返回布爾值true/false,以找出/刪除重復的值。這里我們有兩種更快捷的方法。
const array = [5,4,7,8,9,2,7,5]; array.filter((item,idx,arr) => arr.indexOf(item) === idx); // or const nonUnique = [...new Set(array)]; // Output: [5, 4, 7, 8, 9, 2]
7. 創(chuàng)建一個計數(shù)器對象或Map
很多時候,需要通過創(chuàng)建計數(shù)器對象或Map來解決問題,該對象以變量為鍵,以其頻率/出現(xiàn)次數(shù)為值來跟蹤變量。
let string = 'kapilalipak'; const table={}; for(let char of string) { table[char]=table[char]+1 || 1; } // Output {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); } } // Output Map(5) {"k" => 2, "a" => 3, "p" => 2, "i" => 2, "l" => 2}
8. 三元運算符很酷
你可以用三元運算符避免嵌套條件if...elseif...elseif。
function Fever(temp) { return temp > 97 ? 'Visit Doctor!' : temp < 97 ? 'Go Out and Play!!' : temp === 97 ? 'Take Some Rest!'; } // Output Fever(97): "Take Some Rest!" Fever(100): "Visit Doctor!"
9. 與傳統(tǒng)的once相比,for循環(huán)更快。
for 和 for...in 默認會得到索引,但你可以使用 arr[index]。
for...in也接受非數(shù)字,所以要避免它。
forEach,for...of可以直接得到元素。
forEach也可以得到索引,但for...of不能。
10. 合并兩個對象
在日常工作中,我們經常需要合并多個對象。
const user = { name: 'Kapil Raghuwanshi', gender: 'Male' }; const college = { primary: 'Mani Primary School', secondary: 'Lass Secondary School' }; const skills = { programming: 'Extreme', swimming: 'Average', sleeping: 'Pro' }; const summary = {...user, ...college, ...skills}; // Output gender: "Male" name: "Kapil Raghuwanshi" primary: "Mani Primary School" programming: "Extreme" secondary: "Lass Secondary School" sleeping: "Pro" swimming: "Average"
11. 箭頭函數(shù)
箭頭函數(shù)表達式是傳統(tǒng)函數(shù)表達式的一個緊湊的替代方案,但它有局限性,不能在所有情況下使用。因為它們有詞法范圍(parental scope),沒有自己的this和arguments,因此它們指的是它們被定義的環(huán)境。
const person = { name: 'Kapil', sayName() { return this.name; } } person.sayName(); // Output "Kapil"
箭頭函數(shù)改寫為:
const person = { name: 'Kapil', sayName() { return this.name; } } person.sayName(); // Output "Kapil"
12. 可選鏈式
如果在?之前的值是未定義的或空的,可選鏈式?就會停止評估,并返回未定義。
const user = { employee: { name: "Kapil" } }; user.employee?.name; // Output: "Kapil" user.employ?.name; // Output: undefined user.employ.name // Output: VM21616:1 Uncaught TypeError: Cannot read property 'name' of undefined
13. 打亂一個數(shù)組
使用內置的Math.random()方法。
const list = [1, 2, 3, 4, 5, 6, 7, 8, 9]; list.sort(() => { return Math.random() - 0.5; }); // Output (9) [2, 5, 1, 6, 9, 8, 4, 3, 7] // Call it again (9) [4, 1, 7, 5, 3, 8, 2, 9, 6]
14. 空值合并運算符
空值合并運算符(??)是一個邏輯運算符,當其左側的操作數(shù)為空或未定義時,返回其右側的操作數(shù),否則返回其左側的操作數(shù)。
const foo = null ?? 'my school'; // Output: "my school" const baz = 0 ?? 42; // Output: 0
15. Rest & Spread 運算符
那些神秘的3個點...可以Rest或Spread!
function myFun(a, b, ...manyMoreArgs) { return arguments.length; } myFun("one", "two", "three", "four", "five", "six"); // Output: 6
和
const parts = ['shoulders', 'knees']; const lyrics = ['head', ...parts, 'and', 'toes']; lyrics; // Output: (5) ["head", "shoulders", "knees", "and", "toes"]
16. 缺省參數(shù)
const search = (arr, low=0,high=arr.length-1) => { return high; } search([1,2,3,4,5]); // Output: 4
17. 將十進制轉換為二進制或十六進制
我們可以使用一些內置的方法,如.toPrecision()或.toFixed()來幫助實現(xiàn)此類問題。
num.toString(2); // Output: "1010" num.toString(16); // Output: "a" num.toString(8); // Output: "12"
18. 使用解構簡單交換2個值
let a = 5; let b = 8; [a,b] = [b,a] [a,b] // Output (2) [8, 5]
19. 單行回文檢查
function checkPalindrome(str) { return str == str.split('').reverse().join(''); } checkPalindrome('naman'); // Output: true
20. 將對象的屬性變成一個數(shù)組的屬性
使用Object. entries(),Object.key()和Object.values()。
const obj = { a: 1, b: 2, c: 3 }; Object.entries(obj); // Output (3) [Array(2), Array(2), Array(2)] 0: (2) ["a", 1] 1: (2) ["b", 2] 2: (2) ["c", 3] length: 3 Object.keys(obj); (3) ["a", "b", "c"] Object.values(obj); (3) [1, 2, 3]
總結
我整理的就這些了,希望大家可以關注腳本之家其他文章!
相關文章
three.js-結合dat.gui實現(xiàn)界面可視化修改及調試詳解
這篇文章主要為大家介紹了three.js-結合dat.gui實現(xiàn)界面可視化修改及調試詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-02-02