AVt天堂网 手机版,亚洲va久久久噜噜噜久久4399,天天综合亚洲色在线精品,亚洲一级Av无码毛片久久精品

當前位置:首頁 > 科技  > 軟件

45 個開發(fā)人員都應(yīng)該知道的 JavaScript 超級實用技巧

來源: 責(zé)編: 時間:2024-09-10 09:49:06 97觀看
導(dǎo)讀JavaScript 是一種功能強大的語言,對于現(xiàn)代 Web 開發(fā)至關(guān)重要。今天我將分享一些超級實用的JavaScript技巧,它們將使你成為更高效、更有效的 JavaScript 開發(fā)人員,每個技巧都有詳細的解釋和示例。1. 使用 `let` 和 `cons

JavaScript 是一種功能強大的語言,對于現(xiàn)代 Web 開發(fā)至關(guān)重要。今天我將分享一些超級實用的JavaScript技巧,它們將使你成為更高效、更有效的 JavaScript 開發(fā)人員,每個技巧都有詳細的解釋和示例。iQ228資訊網(wǎng)——每日最新資訊28at.com

1. 使用 `let` 和 `const` 代替 `var`

問題:`var` 具有函數(shù)作用域,這可能導(dǎo)致錯誤和不可預(yù)測的行為。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用具有塊作用域的 `let` 和 `const`。iQ228資訊網(wǎng)——每日最新資訊28at.com

let count = 0;const PI = 3.14;

使用 `let` 和 `const` 有助于防止與作用域相關(guān)的錯誤,因為它確保變量只能在定義的塊內(nèi)訪問。iQ228資訊網(wǎng)——每日最新資訊28at.com

2. 默認參數(shù)

問題:如果沒有提供參數(shù),函數(shù)可能會失敗。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用默認參數(shù)設(shè)置后備值。iQ228資訊網(wǎng)——每日最新資訊28at.com

function greet(name = 'Guest') {return `Hello, ${name}!`;}console.log(greet()); // "Hello, Guest!"

默認參數(shù)確保函數(shù)具有合理的默認值,從而防止錯誤并使代碼更加健壯。iQ228資訊網(wǎng)——每日最新資訊28at.com

3. 模板文字

問題:字符串連接可能很麻煩且容易出錯。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用模板文字進行更清晰、更易讀的字符串插值。iQ228資訊網(wǎng)——每日最新資訊28at.com

const name = 'John';const greeting = `Hello, ${name}!`;console.log(greeting); // "Hello, John!"

模板文字使創(chuàng)建帶有嵌入表達式和多行字符串的字符串變得更加容易。iQ228資訊網(wǎng)——每日最新資訊28at.com

4. 解構(gòu)賦值

問題:從對象和數(shù)組中提取值可能非常冗長。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用解構(gòu)賦值更簡潔地提取值。iQ228資訊網(wǎng)——每日最新資訊28at.com

const user = { name: 'Jane', age: 25 };const { name, age } = user;console.log(name, age); // "Jane" 25

解構(gòu)賦值允許你輕松地將對象中的屬性和數(shù)組中的元素提取到不同的變量中。iQ228資訊網(wǎng)——每日最新資訊28at.com

5. 箭頭函數(shù)

問題:傳統(tǒng)函數(shù)表達式可能很冗長,并且不會在詞匯上綁定“this”。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用箭頭函數(shù)來實現(xiàn)更短的語法和詞匯“this”。iQ228資訊網(wǎng)——每日最新資訊28at.com

const add = (a, b) => a + b;console.log(add(2, 3)); // 5

箭頭函數(shù)為函數(shù)表達式提供了簡潔的語法,并確保 `this` 在詞匯上是綁定的。iQ228資訊網(wǎng)——每日最新資訊28at.com

6. 擴展運算符

問題:組合數(shù)組或?qū)ο罂赡芎苈闊?/span>iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用擴展運算符可以輕松組合數(shù)組和對象。iQ228資訊網(wǎng)——每日最新資訊28at.com

const arr1 = [1, 2, 3];const arr2 = [4, 5, 6];const combined = […arr1, …arr2];console.log(combined); // [1, 2, 3, 4, 5, 6]

擴展運算符允許你將一個數(shù)組或?qū)ο蟮脑財U展到另一個數(shù)組或?qū)ο笾小?/span>iQ228資訊網(wǎng)——每日最新資訊28at.com

7. 剩余參數(shù)

問題:處理可變數(shù)量的函數(shù)參數(shù)可能很棘手。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用剩余參數(shù)捕獲數(shù)組中的所有參數(shù)。iQ228資訊網(wǎng)——每日最新資訊28at.com

function sum(…args) {return args.reduce((total, num) => total + num, 0);}console.log(sum(1, 2, 3, 4)); // 10

剩余參數(shù)允許你將無限數(shù)量的參數(shù)作為數(shù)組處理,從而使你的函數(shù)更加靈活。iQ228資訊網(wǎng)——每日最新資訊28at.com

8. 短路求值

問題:編寫條件語句可能很冗長。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用短路求值編寫簡潔的條件。iQ228資訊網(wǎng)——每日最新資訊28at.com

const isLoggedIn = true;const user = isLoggedIn && { name: 'Jane', age: 25 };console.log(user); // { name: 'Jane', age: 25 }

短路求值使用邏輯運算符 `&&` 和 `||` 來簡化條件表達式。iQ228資訊網(wǎng)——每日最新資訊28at.com

9. 可選鏈

問題:如果鏈中的任何部分為 `null` 或 `undefined`,則訪問深層嵌套的屬性可能會導(dǎo)致錯誤。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用可選鏈安全地訪問嵌套屬性。iQ228資訊網(wǎng)——每日最新資訊28at.com

const user = { profile: { name: 'Jane' } };const userName = user?.profile?.name;console.log(userName); // "Jane"

可選鏈式連接允許你安全地訪問嵌套屬性,而無需明確檢查鏈式連接的每一級是否為 `null` 或 `undefined`。iQ228資訊網(wǎng)——每日最新資訊28at.com

10. 空值合并

問題:如果值為 `0` 或 `””`,則使用 `||` 提供默認值可能會產(chǎn)生意外結(jié)果。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:僅在 `null` 或 `undefined` 時使用空值合并 (`??`) 提供默認值。iQ228資訊網(wǎng)——每日最新資訊28at.com

const user = { name: '', age: 0 };const userName = user.name ?? 'Anonymous';const userAge = user.age ?? 18;console.log(userName); // ""console.log(userAge); // 0

空值合并僅允許在左側(cè)為“null”或“undefined”時提供默認值。iQ228資訊網(wǎng)——每日最新資訊28at.com

11. 對象屬性簡寫

問題:將變量分配給對象屬性可能會重復(fù)。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用屬性簡寫來簡化對象創(chuàng)建。iQ228資訊網(wǎng)——每日最新資訊28at.com

const name = 'Jane';const age = 25;const user = { name, age };console.log(user); // { name: 'Jane', age: 25 }

屬性簡寫允許你在屬性名稱與變量名稱匹配時省略屬性名稱,從而使代碼更簡潔。iQ228資訊網(wǎng)——每日最新資訊28at.com

12. 動態(tài)屬性名稱

問題:使用動態(tài)屬性名稱創(chuàng)建對象可能很冗長。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用計算屬性名稱動態(tài)創(chuàng)建對象屬性。iQ228資訊網(wǎng)——每日最新資訊28at.com

const propName = 'age';const user = { name: 'Jane', [propName]: 25 };console.log(user); // { name: 'Jane', age: 25 }

計算屬性名稱允許你動態(tài)創(chuàng)建對象屬性,使用表達式的值作為屬性名稱。iQ228資訊網(wǎng)——每日最新資訊28at.com

13. 數(shù)組 `map()`、`filter()` 和 `reduce()`

問題:迭代數(shù)組以轉(zhuǎn)換、過濾或累積值可能會重復(fù)。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用 `map()`、`filter()` 和 `reduce()` 進行常見的數(shù)組操作。iQ228資訊網(wǎng)——每日最新資訊28at.com

const numbers = [1, 2, 3, 4, 5];const doubled = numbers.map(num => num * 2);console.log(doubled); // [2, 4, 6, 8, 10]const evens = numbers.filter(num => num % 2 === 0);console.log(evens); // [2, 4]const sum = numbers.reduce((total, num) => total + num, 0);console.log(sum); // 15

這些數(shù)組方法提供了一種轉(zhuǎn)換、過濾和減少數(shù)組的函數(shù)式方法,使你的代碼更具表現(xiàn)力和簡潔性。iQ228資訊網(wǎng)——每日最新資訊28at.com

14. 字符串 `includes()`、`startsWith()` 和 `endsWith()`

問題:檢查字符串是否包含、以子字符串開頭或以子字符串結(jié)尾可能很冗長。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用 `includes()`、`startsWith()` 和 `endsWith()` 進行更簡單的字符串檢查。iQ228資訊網(wǎng)——每日最新資訊28at.com

const str = 'Hello, world!';console.log(str.includes('world')); // trueconsole.log(str.startsWith('Hello')); // trueconsole.log(str.endsWith('!')); // true

這些字符串方法提供了一種簡單易讀的方法來檢查子字符串的存在、開始或結(jié)束。iQ228資訊網(wǎng)——每日最新資訊28at.com

15. 函數(shù)參數(shù)中的數(shù)組和對象解構(gòu)

問題:從作為函數(shù)參數(shù)傳遞的數(shù)組或?qū)ο笾刑崛≈悼赡芎苋唛L。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:在函數(shù)參數(shù)中使用解構(gòu)來直接提取值。iQ228資訊網(wǎng)——每日最新資訊28at.com

const user = { name: 'Jane', age: 25 };function greet({ name, age }) {return `Hello, ${name}! You are ${age} years old.`;}console.log(greet(user)); // "Hello, Jane! You are 25 years old."

函數(shù)參數(shù)中的解構(gòu)允許你直接從傳遞給函數(shù)的對象或數(shù)組中提取值,從而使代碼更簡潔、更易讀。iQ228資訊網(wǎng)——每日最新資訊28at.com

16. 解構(gòu)中的默認值

問題:解構(gòu)對象時處理缺失的屬性可能很麻煩。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:在解構(gòu)中使用默認值來提供后備值。iQ228資訊網(wǎng)——每日最新資訊28at.com

const user = { name: 'Jane' };const { name, age = 18 } = user;console.log(name); // "Jane"console.log(age); // 18

解構(gòu)中的默認值允許你為可能缺失的屬性提供后備值,從而使你的代碼更加健壯。iQ228資訊網(wǎng)——每日最新資訊28at.com

17. 對象 `assign()`

問題:克隆或合并對象可能很冗長且容易出錯。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用 `Object.assign()` 克隆或合并對象。iQ228資訊網(wǎng)——每日最新資訊28at.com

const target = { a: 1 };const source = { b: 2 };const merged = Object.assign(target, source);console.log(merged); // { a: 1, b: 2 }

`Object.assign()` 允許你高效地克隆或合并對象,從而減少手動復(fù)制的需要。iQ228資訊網(wǎng)——每日最新資訊28at.com

18. 數(shù)組 `find()` 和 `findIndex()`

問題:使用循環(huán)在數(shù)組中查找元素或其索引可能很麻煩。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用 `find()` 和 `findIndex()` 使代碼更易讀。iQ228資訊網(wǎng)——每日最新資訊28at.com

const users = [{ id: 1, name: 'Jane' },{ id: 2, name: 'John' },];const user = users.find(u => u.id === 1);console.log(user); // { id: 1, name: 'Jane' }const index = users.findIndex(u => u.id === 1);console.log(index); // 0

這些數(shù)組方法提供了一種根據(jù)條件查找元素或其索引的簡單方法,從而提高了代碼的可讀性。iQ228資訊網(wǎng)——每日最新資訊28at.com

19. 數(shù)組 `some()` 和 `every()`

問題:檢查數(shù)組中的部分或全部元素是否滿足條件可能會很冗長。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用 `some()` 和 `every()` 來獲得更簡潔的代碼。iQ228資訊網(wǎng)——每日最新資訊28at.com

const numbers = [1, 2, 3, 4, 5];const hasEven = numbers.some(num => num % 2 === 0);console.log(hasEven); // trueconst allEven = numbers.every(num => num % 2 === 0);console.log(allEven); // false

這些數(shù)組方法允許你以簡潔的方式檢查數(shù)組中的部分或全部元素是否滿足條件。iQ228資訊網(wǎng)——每日最新資訊28at.com

20. 數(shù)組 `flat()` 和 `flatMap()`

問題:展平嵌套數(shù)組或映射和展平數(shù)組可能很麻煩。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用 `flat()` 和 `flatMap()` 使代碼更易讀。iQ228資訊網(wǎng)——每日最新資訊28at.com

const nested = [1, [2, [3, [4]]]];const flat = nested.flat(2);console.log(flat); // [1, 2, 3, [4]]const mapped = [1, 2, 3].flatMap(x => [x, x * 2]);console.log(mapped); // [1, 2, 2, 4, 3, 6]

這些數(shù)組方法提供了一種簡單的方法來展平嵌套數(shù)組,并在一個步驟中映射和展平。iQ228資訊網(wǎng)——每日最新資訊28at.com

21. 數(shù)組 `from()` 和 `of()`

問題:從可迭代對象或參數(shù)創(chuàng)建數(shù)組可能很冗長。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用 `Array.from()` 和 `Array.of()` 獲得更簡潔的代碼。iQ228資訊網(wǎng)——每日最新資訊28at.com

const set = new Set([1, 2, 3]);const arrFromSet = Array.from(set);console.log(arrFromSet); // [1, 2, 3]const arrOfNumbers = Array.of(1, 2, 3);console.log(arrOfNumbers); // [1, 2, 3]

`Array.from()` 允許你從可迭代對象創(chuàng)建數(shù)組,而 `Array.of()` 允許你從參數(shù)列表創(chuàng)建數(shù)組。iQ228資訊網(wǎng)——每日最新資訊28at.com

22. 回調(diào)中的參數(shù)解構(gòu)

問題:訪問傳遞給回調(diào)的對象的屬性可能很冗長。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:在回調(diào)參數(shù)中使用解構(gòu)以獲得更簡潔的代碼。iQ228資訊網(wǎng)——每日最新資訊28at.com

const users = [{ id: 1, name: 'Jane' },{ id: 2, name: 'John' },];users.forEach(({ id, name }) => {console.log(`User ID: ${id}, User Name: ${name}`);});

回調(diào)參數(shù)中的解構(gòu)允許你直接訪問傳遞給回調(diào)的對象的屬性,從而使代碼更簡潔。iQ228資訊網(wǎng)——每日最新資訊28at.com

23. 可選回調(diào)函數(shù)

問題:處理可選回調(diào)函數(shù)可能很麻煩。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用短路求值來調(diào)用可選回調(diào)。iQ228資訊網(wǎng)——每日最新資訊28at.com

function fetchData(url, callback) {fetch(url).then(response => response.json()).then(data => {callback && callback(data);});}

短路求值允許您僅在提供可選回調(diào)函數(shù)時才調(diào)用該函數(shù),從而使代碼更加健壯。iQ228資訊網(wǎng)——每日最新資訊28at.com

24. Promisify 回調(diào)

問題:將基于回調(diào)的函數(shù)轉(zhuǎn)換為promises可能很麻煩。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用實用函數(shù)來 promisify 回調(diào)。iQ228資訊網(wǎng)——每日最新資訊28at.com

function promisify(fn) {return function (…args) {return new Promise((resolve, reject) => {fn(…args, (err, result) => {if (err) reject(err);else resolve(result);});});};}const readFile = promisify(require('fs').readFile);readFile('path/to/file.txt', 'utf8').then(data => console.log(data)).catch(err => console.error(err));

Promisifying 允許你將基于回調(diào)的函數(shù)轉(zhuǎn)換為promises,從而更輕松地使用 async/await 語法。iQ228資訊網(wǎng)——每日最新資訊28at.com

25. 用于類似同步代碼的 Async/Await

問題:使用promises編寫異步代碼可能冗長且難以閱讀。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用 async/await 以同步風(fēng)格編寫異步代碼。iQ228資訊網(wǎng)——每日最新資訊28at.com

async function fetchData(url) {try {const response = await fetch(url);const data = await response.json();console.log(data);} catch (error) {console.error('Error fetching data:', error);}}fetchData('https://api.example.com/data');

Async/await 提供了一種編寫外觀和行為都像同步代碼的異步代碼的方法,從而提高了可讀性和可維護性。iQ228資訊網(wǎng)——每日最新資訊28at.com

26. 鏈接承諾

問題:按順序處理多個異步操作可能很麻煩。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:鏈式承諾處理多個異步操作。iQ228資訊網(wǎng)——每日最新資訊28at.com

fetch('https://api.example.com/data').then(response => response.json()).then(data => {console.log('Data:', data);return fetch('https://api.example.com/more-data');}).then(response => response.json()).then(moreData => {console.log('More Data:', moreData);}).catch(error => {console.error('Error:', error);});

鏈接 Promise 可讓你按順序處理多個異步操作,從而提高可讀性和可維護性。iQ228資訊網(wǎng)——每日最新資訊28at.com

27. Promise.all 用于并發(fā)執(zhí)行

問題:同時處理多個異步操作可能具有挑戰(zhàn)性。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用 `Promise.all` 來處理并發(fā)異步操作。iQ228資訊網(wǎng)——每日最新資訊28at.com

const fetchData1 = fetch('https://api.example.com/data1').then(response => response.json());const fetchData2 = fetch('https://api.example.com/data2').then(response => response.json());Promise.all([fetchData1, fetchData2]).then(([data1, data2]) => {console.log('Data 1:', data1);console.log('Data 2:', data2);}).catch(error => {console.error('Error:', error);});

`Promise.all` 允許你同時處理多個異步操作,并在所有操作完成后繼續(xù)執(zhí)行。iQ228資訊網(wǎng)——每日最新資訊28at.com

28. 防抖動函數(shù)

問題:頻繁的函數(shù)調(diào)用(例如在窗口調(diào)整大小事件期間)會降低性能。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用防抖動函數(shù)來限制函數(shù)執(zhí)行的速率。iQ228資訊網(wǎng)——每日最新資訊28at.com

function debounce(func, wait) {let timeout;return function (…args) {clearTimeout(timeout);timeout = setTimeout(() => func.apply(this, args), wait);};}window.addEventListener('resize', debounce(() => {console.log('Window resized');}, 200));

防抖動函數(shù)可確保函數(shù)僅在一段時間不活動后才被調(diào)用,從而提高性能。iQ228資訊網(wǎng)——每日最新資訊28at.com

29. 節(jié)流閥函數(shù)

問題:限制頻繁觸發(fā)的事件(如滾動或調(diào)整大?。┑暮瘮?shù)執(zhí)行速率。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用節(jié)流閥函數(shù)來限制函數(shù)的執(zhí)行速率。iQ228資訊網(wǎng)——每日最新資訊28at.com

function throttle(func, limit) {let lastFunc;let lastRan;return function (…args) {if (!lastRan) {func.apply(this, args);lastRan = Date.now();} else {clearTimeout(lastFunc);lastFunc = setTimeout(() => {if (Date.now() - lastRan >= limit) {func.apply(this, args);lastRan = Date.now();}}, limit - (Date.now() - lastRan));}};}window.addEventListener('scroll', throttle(() => {console.log('Window scrolled');}, 200));

節(jié)流函數(shù)可確保在指定時間段內(nèi)最多只調(diào)用一次函數(shù),從而提高頻繁觸發(fā)事件的性能。iQ228資訊網(wǎng)——每日最新資訊28at.com

30. 深度克隆對象

問題:克隆嵌套對象可能很棘手且容易出錯。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用結(jié)構(gòu)化克隆或 Lodash 等庫來深度克隆對象。iQ228資訊網(wǎng)——每日最新資訊28at.com

const obj = { a: 1, b: { c: 2 } };const deepClone = JSON.parse(JSON.stringify(obj));console.log(deepClone); // { a: 1, b: { c: 2 } }

深度克隆確保嵌套對象按值復(fù)制,而不是按引用復(fù)制,從而防止對原始對象進行意外修改。iQ228資訊網(wǎng)——每日最新資訊28at.com

31. 記憶化

問題:反復(fù)調(diào)用昂貴的函數(shù)會降低性能。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用記憶化來緩存昂貴的函數(shù)調(diào)用的結(jié)果。iQ228資訊網(wǎng)——每日最新資訊28at.com

function memoize(func) {const cache = new Map();return function (…args) {const key = JSON.stringify(args);if (cache.has(key)) {return cache.get(key);}const result = func.apply(this, args);cache.set(key, result);return result;};}const expensiveFunction = memoize((num) => {console.log('Computing…');return num * 2;});console.log(expensiveFunction(2)); // "Computing…" 4console.log(expensiveFunction(2)); // 4

記憶化通過緩存昂貴的函數(shù)調(diào)用結(jié)果并返回緩存的結(jié)果以供后續(xù)具有相同參數(shù)的調(diào)用來提高性能。iQ228資訊網(wǎng)——每日最新資訊28at.com

32. 柯里化函數(shù)

問題:創(chuàng)建具有多個參數(shù)的函數(shù)可能很麻煩。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用柯里化創(chuàng)建具有部分應(yīng)用參數(shù)的函數(shù)。iQ228資訊網(wǎng)——每日最新資訊28at.com

function curry(func) {return function curried(…args) {if (args.length >= func.length) {return func.apply(this, args);}return function (…nextArgs) {return curried.apply(this, args.concat(nextArgs));};};}const sum = (a, b, c) => a + b + c;const curriedSum = curry(sum);console.log(curriedSum(1)(2)(3)); // 6console.log(curriedSum(1, 2)(3)); // 6

通過柯里化,你可以創(chuàng)建可以用較少參數(shù)調(diào)用的函數(shù),并返回接受其余參數(shù)的新函數(shù)。iQ228資訊網(wǎng)——每日最新資訊28at.com

33. 部分應(yīng)用

問題:調(diào)用帶有重復(fù)參數(shù)的函數(shù)可能很繁瑣。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用部分應(yīng)用將一些參數(shù)預(yù)先應(yīng)用于函數(shù)。iQ228資訊網(wǎng)——每日最新資訊28at.com

function partial(func, …presetArgs) {return function (…laterArgs) {return func(…presetArgs, …laterArgs);};}const multiply = (a, b, c) => a * b * c;const double = partial(multiply, 2);console.log(double(3, 4)); // 24

部分應(yīng)用允許你通過預(yù)先應(yīng)用一些參數(shù)來創(chuàng)建新函數(shù),從而使你的代碼更加靈活和可重用。iQ228資訊網(wǎng)——每日最新資訊28at.com

34. 函數(shù)組合

問題:將多個函數(shù)組合成一個操作可能很麻煩。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用函數(shù)組合來組合多個函數(shù)。iQ228資訊網(wǎng)——每日最新資訊28at.com

const compose = (…funcs) => (arg) =>funcs.reduceRight((prev, fn) => fn(prev), arg);const add = (x) => x + 1;const multiply = (x) => x * 2;const addThenMultiply = compose(multiply, add);console.log(addThenMultiply(5)); // 12

函數(shù)組合允許你通過組合多個函數(shù)來創(chuàng)建新函數(shù),從而使你的代碼更加模塊化和可重用。iQ228資訊網(wǎng)——每日最新資訊28at.com

35. 函數(shù)流水線

問題:將一系列函數(shù)應(yīng)用于一個值可能會很冗長。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用函數(shù)流水線按順序應(yīng)用一系列函數(shù)。iQ228資訊網(wǎng)——每日最新資訊28at.com

const pipe = (…funcs) => (arg) =>funcs.reduce((prev, fn) => fn(prev), arg);const add = (x) => x + 1;const multiply = (x) => x * 2;const addThenMultiply = pipe(add, multiply);console.log(addThenMultiply(5)); // 12

函數(shù)流水線允許你按順序?qū)⒁幌盗泻瘮?shù)應(yīng)用于一個值,從而提高代碼的可讀性和可維護性。iQ228資訊網(wǎng)——每日最新資訊28at.com

36. 自調(diào)用函數(shù)

問題:定義后立即執(zhí)行函數(shù)可能很麻煩。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用立即調(diào)用函數(shù)表達式 (IIFE)。iQ228資訊網(wǎng)——每日最新資訊28at.com

(function () {console.log('This runs immediately!');})();

IIFE 允許你在定義后立即執(zhí)行函數(shù),這對于創(chuàng)建隔離范圍和避免污染全局命名空間非常有用。iQ228資訊網(wǎng)——每日最新資訊28at.com

37. 避免使用全局變量

問題:全局變量可能導(dǎo)致沖突和意外的副作用。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用局部變量和模塊來避免污染全局命名空間。iQ228資訊網(wǎng)——每日最新資訊28at.com

// Using local variablesfunction doSomething() {let localVariable = 'This is local';console.log(localVariable);}// Using modulesconst myModule = (function () {let privateVariable = 'This is private';return {publicMethod() {console.log(privateVariable);},};})();myModule.publicMethod(); // "This is private"

避免使用全局變量有助于防止沖突和意外副作用,從而使你的代碼更加模塊化和易于維護。iQ228資訊網(wǎng)——每日最新資訊28at.com

38. 使用閉包進行封裝

問題:暴露函數(shù)的內(nèi)部細節(jié)可能會導(dǎo)致誤用。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用閉包封裝內(nèi)部細節(jié)。iQ228資訊網(wǎng)——每日最新資訊28at.com

function createCounter() {let count = 0;return {increment() {count++;return count;},decrement() {count - ;return count;},};}const counter = createCounter();console.log(counter.increment()); // 1console.log(counter.increment()); // 2console.log(counter.decrement()); // 1

閉包允許你封裝內(nèi)部細節(jié)并僅公開必要的功能,從而提高代碼的安全性和可維護性。iQ228資訊網(wǎng)——每日最新資訊28at.com

39. 模塊模式

問題:將代碼組織成可重用的模塊可能具有挑戰(zhàn)性。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用模塊模式創(chuàng)建可重用和封裝的代碼。iQ228資訊網(wǎng)——每日最新資訊28at.com

const myModule = (function () {let privateVariable = 'This is private';function privateMethod() {console.log(privateVariable);}return {publicMethod() {privateMethod();},};})();myModule.publicMethod(); // "This is private"

模塊模式允許你創(chuàng)建可重用和封裝的代碼,從而改善代碼組織和可維護性。iQ228資訊網(wǎng)——每日最新資訊28at.com

40. 單例模式

問題:確保只創(chuàng)建一個類的實例可能具有挑戰(zhàn)性。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用單例模式創(chuàng)建單個實例。iQ228資訊網(wǎng)——每日最新資訊28at.com

const singleton = (function () {let instance;function createInstance() {return {name: 'Singleton Instance',};}return {getInstance() {if (!instance) {instance = createInstance();}return instance;},};})();const instance1 = singleton.getInstance();const instance2 = singleton.getInstance();console.log(instance1 === instance2); // true

單例模式確保只創(chuàng)建一個類的實例,這對于管理共享資源或配置很有用。iQ228資訊網(wǎng)——每日最新資訊28at.com

41. 工廠模式

問題:創(chuàng)建具有復(fù)雜初始化的對象可能很麻煩。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用工廠模式創(chuàng)建對象。iQ228資訊網(wǎng)——每日最新資訊28at.com

function createUser(name, role) {return {name,role,sayHello() {console.log(`Hello, my name is ${this.name} and I am a ${this.role}`);},};}const admin = createUser('Alice', 'admin');const user = createUser('Bob', 'user');admin.sayHello(); // "Hello, my name is Alice and I am an admin"user.sayHello(); // "Hello, my name is Bob and I am a user"

工廠模式允許你以靈活且可重用的方式創(chuàng)建具有復(fù)雜初始化的對象。iQ228資訊網(wǎng)——每日最新資訊28at.com

42. 觀察者模式

問題:管理狀態(tài)變化和通知多個組件可能具有挑戰(zhàn)性。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用觀察者模式來管理狀態(tài)變化并通知觀察者。iQ228資訊網(wǎng)——每日最新資訊28at.com

function Subject() {this.observers = [];}Subject.prototype = {subscribe(observer) {this.observers.push(observer);},unsubscribe(observer) {this.observers = this.observers.filter((obs) => obs !== observer);},notify(data) {this.observers.forEach((observer) => observer.update(data));},};function Observer(name) {this.name = name;}Observer.prototype.update = function (data) {console.log(`${this.name} received data: ${data}`);};const subject = new Subject();const observer1 = new Observer('Observer 1');const observer2 = new Observer('Observer 2');subject.subscribe(observer1);subject.subscribe(observer2);subject.notify('New data available'); // "Observer 1 received data: New data available" "Observer 2 received data: New data available"

觀察者模式允許你管理狀態(tài)變化并通知多個觀察者,從而改善代碼組織和可維護性。iQ228資訊網(wǎng)——每日最新資訊28at.com

43. 事件委托

問題:向多個元素添加事件監(jiān)聽器會降低性能。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用事件委托有效地管理事件。iQ228資訊網(wǎng)——每日最新資訊28at.com

document.getElementById('parent').addEventListener('click', (event) => {if (event.target && event.target.matches('button.className')) {console.log('Button clicked:', event.target.textContent);}});

事件委托允許你通過向公共父元素添加單個事件偵聽器并處理多個子元素的事件來有效地管理事件。iQ228資訊網(wǎng)——每日最新資訊28at.com

44. 避免使用 `eval()`

問題:使用 `eval()` 可能導(dǎo)致安全漏洞和性能問題。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:避免使用 `eval()` 并使用更安全的替代方案。iQ228資訊網(wǎng)——每日最新資訊28at.com

// Avoidconst code = 'console.log("Hello, world!")';eval(code); // "Hello, world!"http:// Use safer alternativesconst func = new Function('console.log("Hello, world!")');func(); // "Hello, world!"

避免使用 `eval()` 有助于防止安全漏洞和性能問題,從而使你的代碼更安全、更高效。iQ228資訊網(wǎng)——每日最新資訊28at.com

45. 使用 `for…of` 進行迭代

問題:使用 `for…in` 迭代數(shù)組容易出錯。iQ228資訊網(wǎng)——每日最新資訊28at.com

解決方案:使用 `for…of` 迭代數(shù)組和其他可迭代對象。iQ228資訊網(wǎng)——每日最新資訊28at.com

const arr = [1, 2, 3, 4, 5];for (const value of arr) {console.log(value);}// 1// 2// 3// 4// 5

`for…of` 提供了一種簡單而安全的方法iQ228資訊網(wǎng)——每日最新資訊28at.com

總結(jié)

無論你是想要提升技能的經(jīng)驗豐富的開發(fā)人員,還是渴望學(xué)習(xí)基礎(chǔ)知識的新手,今天內(nèi)容,我想都能滿足你的需求。深入了解并像專業(yè)人士一樣掌握 JavaScript 的秘訣!”iQ228資訊網(wǎng)——每日最新資訊28at.com

本文鏈接:http://www.tebozhan.com/showinfo-26-112743-0.html45 個開發(fā)人員都應(yīng)該知道的 JavaScript 超級實用技巧

聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: 20 個 Python 高效字符串處理技巧

下一篇: 阿里限流神器 Sentinel 17 問?

標簽:
  • 熱門焦點
  • 6月安卓手機性價比榜:Note 12 Turbo斷層式碾壓

    6月份有一個618,雖然這是京東周年慶的日子,但別的電商也都不約而同的跟進了,反正促銷沒壞處,廠商和用戶都能滿意。618期間一些產(chǎn)品也出現(xiàn)了歷史低價,那么各個價位段的產(chǎn)品性價比
  • 如何通過Python線程池實現(xiàn)異步編程?

    線程池的概念和基本原理線程池是一種并發(fā)處理機制,它可以在程序啟動時創(chuàng)建一組線程,并將它們置于等待任務(wù)的狀態(tài)。當任務(wù)到達時,線程池中的某個線程會被喚醒并執(zhí)行任務(wù),執(zhí)行完任
  • 深度探索 Elasticsearch 8.X:function_score 參數(shù)解讀與實戰(zhàn)案例分析

    在 Elasticsearch 中,function_score 可以讓我們在查詢的同時對搜索結(jié)果進行自定義評分。function_score 提供了一系列的參數(shù)和函數(shù)讓我們可以根據(jù)需求靈活地進行設(shè)置。近期
  • 使用LLM插件從命令行訪問Llama 2

    最近的一個大新聞是Meta AI推出了新的開源授權(quán)的大型語言模型Llama 2。這是一項非常重要的進展:Llama 2可免費用于研究和商業(yè)用途。(幾小時前,swyy發(fā)現(xiàn)它已從LLaMA 2更名為Lla
  • 從零到英雄:高并發(fā)與性能優(yōu)化的神奇之旅

    作者 | 波哥審校 | 重樓作為公司的架構(gòu)師或者程序員,你是否曾經(jīng)為公司的系統(tǒng)在面對高并發(fā)和性能瓶頸時感到手足無措或者焦頭爛額呢?筆者在出道那會為此是吃盡了苦頭的,不過也得
  • 微軟邀請 Microsoft 365 商業(yè)用戶,測試視頻編輯器 Clipchamp

    8 月 1 日消息,微軟近日宣布即將面向 Microsoft 365 商業(yè)用戶,開放 Clipchamp 應(yīng)用,邀請用戶通過該應(yīng)用來編輯視頻。微軟于 2021 年收購 Clipchamp,隨后開始逐步整合到 Microsof
  • 破圈是B站頭上的緊箍咒

    來源 | 光子星球撰文 | 吳坤諺編輯 | 吳先之每年的暑期檔都少不了瞄準追劇女孩們的古偶劇集,2021年有優(yōu)酷的《山河令》,2022年有愛奇藝的《蒼蘭訣》,今年卻輪到小破站抓住了追
  • 花7萬退貨退款無門:誰在縱容淘寶珠寶商家造假?

    來源:極點商業(yè)作者:楊銘在淘寶購買珠寶玉石后,因為保證金不夠賠付,店鋪關(guān)閉,退貨退款難、維權(quán)無門的比比皆是。“提供相關(guān)產(chǎn)品鑒定證書,支持全國復(fù)檢,可以30天無理由退換貨。&
  • OPPO、vivo、小米等國內(nèi)廠商Q2在印度智能手機市場份額依舊高達55%

    7月20日消息,據(jù)外媒報道,研究機構(gòu)的報告顯示,在全球智能手機出貨量同比仍在下滑的大背景下,印度這一有潛力的市場也未能幸免,出貨量同比也有下滑,多家廠
Top