30 個(gè)鮮為人知的 JavaScript 技巧,讓你的代碼更具可讀性
在今天這篇文章中,我們?yōu)榇蠹揖恼砹?0個(gè) JavaScript 技巧合集,它將幫助你優(yōu)化代碼,使其更具可讀性,提升工作效率,并節(jié)省你的時(shí)間。
現(xiàn)在,就讓我們開(kāi)始吧。
1 、使用 !! 轉(zhuǎn)換為布爾值
使用雙重否定快速將任何值轉(zhuǎn)換為布爾值。
let truthyValue = !!1; // true
let falsyValue = !!0; // false
2 、 默認(rèn)函數(shù)參數(shù)
設(shè)置函數(shù)參數(shù)的默認(rèn)值以避免定義錯(cuò)誤。
function greet(name = "Guest") {
return `Hello, ${name}!`;
}
3 、 短 If-Else 的三元運(yùn)算符
if-else 語(yǔ)句的簡(jiǎn)寫。
let price = 100;
let message = price > 50 ? "Expensive" : "Cheap";
4 、動(dòng)態(tài)字符串的模板文字
使用模板文字將表達(dá)式嵌入字符串中。
let item = "coffee";
let price = 15;
console.log(`One ${item} costs $${price}.`);
5 、解構(gòu)賦值
輕松從對(duì)象或數(shù)組中提取屬性。
let [x, y] = [1, 2];
let {name, age} = {name: "Alice", age: 30};
6 、用于數(shù)組和對(duì)象克隆的擴(kuò)展運(yùn)算符
克隆數(shù)組或?qū)ο蠖灰迷紝?duì)象。
let originalArray = [1, 2, 3];
let clonedArray = [...originalArray];
7 、短路求值
使用邏輯運(yùn)算符進(jìn)行條件執(zhí)行。
let isValid = true;
isValid && console.log("Valid!");
8 、可選鏈接 (?.)
如果引用為空,則安全地訪問(wèn)嵌套對(duì)象屬性而不會(huì)出現(xiàn)錯(cuò)誤。
let user = {name: "John", address: {city: "New York"}};
console.log(user?.address?.city); // "New York"
9 、空值合并運(yùn)算符 (??)
使用 ?? 為空或未定義提供默認(rèn)值。
let username = null;
console.log(username ?? "Guest"); // "Guest"
10 、使用 map、filter 和 reduce 進(jìn)行數(shù)組操作
無(wú)需傳統(tǒng)循環(huán)即可優(yōu)雅地處理數(shù)組。
// Map
let numbers = [1, 2, 3, 4];
let doubled = numbers.map(x => x * 2);
// Filter
const evens = numbers.filter(x => x % 2 === 0);
// Reduce
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
11 、標(biāo)記模板文字
使用模板文字進(jìn)行函數(shù)調(diào)用,以進(jìn)行自定義字符串處理。
function highlight(strings, ...values) {
return strings.reduce((prev, current, i) => `${prev}${current}${values[i] || ''}`, '');
}
let price = 10;
console.log(highlight`The price is ${price} dollars.`);
12 、使用 Object.entries() 和 Object.fromEntries()
將對(duì)象轉(zhuǎn)換為數(shù)組并轉(zhuǎn)換回來(lái),以便于操作。
let person = {name: "Alice", age: 25};
let entries = Object.entries(person);
let newPerson = Object.fromEntries(entries);
13 、 用于唯一元素的 Set 對(duì)象
使用 Set 存儲(chǔ)任何類型的唯一值。
let numbers = [1, 1, 2, 3, 4, 4];
let uniqueNumbers = [...new Set(numbers)];
14 、 對(duì)象中的動(dòng)態(tài)屬性名稱
在對(duì)象文字表示法中使用方括號(hào)來(lái)創(chuàng)建動(dòng)態(tài)屬性名稱。
let dynamicKey = 'name';
let person = {[dynamicKey]: "Alice"};
15 、使用 bind() 進(jìn)行函數(shù)柯里化
創(chuàng)建一個(gè)新函數(shù),當(dāng)調(diào)用該函數(shù)時(shí),將其 this 關(guān)鍵字設(shè)置為提供的值。
function multiply(a, b) {
return a * b;
}
let double = multiply.bind(null, 2);
console.log(double(5)); // 10
16 、使用 Array.from() 從類似數(shù)組的對(duì)象創(chuàng)建數(shù)組
將類似數(shù)組或可迭代的對(duì)象轉(zhuǎn)換為真正的數(shù)組。
let nodeList = document.querySelectorAll('div');
let nodeArray = Array.from(nodeList);
17 、可迭代對(duì)象的 for…of 循環(huán)
直接迭代可迭代對(duì)象(包括數(shù)組、映射、集合等)。
for (let value of ['a', 'b', 'c']) {
console.log(value);
}
18 、 使用 Promise.all() 實(shí)現(xiàn)并發(fā) Promise
同時(shí)運(yùn)行多個(gè) Promise 并等待所有 Promise 完成。
let promises = [fetch(url1), fetch(url2)];
Promise.all(promises)
.then(responses => console.log('All done'));
19 、函數(shù)參數(shù)的 Rest 參數(shù)
將任意數(shù)量的參數(shù)捕獲到數(shù)組中。
function sum(...nums) {
return nums.reduce((acc, current) => acc + current, 0);
}
20 、用于性能優(yōu)化的記憶化
存儲(chǔ)函數(shù)結(jié)果以避免冗余處理。
const memoize = (fn) => {
const cache = {};
return (...args) => {
let n = args[0]; // assuming single argument for simplicity
if (n in cache) {
console.log('Fetching from cache');
return cache[n];
} else {
console.log('Calculating result');
let result = fn(n);
cache[n] = result;
return result;
}
};
};
21 、使用 ^ 交換值
使用 XOR 按位運(yùn)算符交換兩個(gè)變量的值,無(wú)需臨時(shí)變量。
let a = 1, b = 2;
a ^= b; b ^= a; a ^= b; // a = 2, b = 1
22 、使用 flat() 展平數(shù)組
使用 flat() 方法輕松展平嵌套數(shù)組,展平深度作為可選參數(shù)。
let nestedArray = [1, [2, [3, [4]]]];
let flatArray = nestedArray.flat(Infinity);
23 、使用一元加法轉(zhuǎn)換為數(shù)字
使用一元加法運(yùn)算符快速將字符串或其他值轉(zhuǎn)換為數(shù)字。
let str = "123";
let num = +str; // 123 as a number
24 、 HTML 片段的模板字符串
使用模板字符串創(chuàng)建 HTML 片段,使動(dòng)態(tài) HTML 生成更清晰。
let items = ['apple', 'orange', 'banana'];
let html = `<ul>${items.map(item => `<li>${item}</li>`).join('')}</ul>`;
25 、使用 Object.assign() 合并對(duì)象
將多個(gè)源對(duì)象合并為目標(biāo)對(duì)象,有效地組合它們的屬性。
let items = ['apple', 'orange', 'banana'];
let html = `<ul>${items.map(item => `<li>${item}</li>`).join('')}</ul>`;
26 、短路默認(rèn)值
處理可能未定義或?yàn)榭盏淖兞繒r(shí),利用邏輯運(yùn)算符分配默認(rèn)值。
let options = userOptions || defaultOptions;
27 、 使用括號(hào)表示法動(dòng)態(tài)訪問(wèn)對(duì)象屬性
使用括號(hào)表示法動(dòng)態(tài)訪問(wèn)對(duì)象的屬性,當(dāng)屬性名稱存儲(chǔ)在變量中時(shí)很有用。
let property = "name";
let value = person[property]; // Equivalent to person.name
28 、 使用 Array.includes() 進(jìn)行存在性檢查
使用 includes() 檢查數(shù)組是否包含某個(gè)值,這是 indexOf 的更清晰的替代方案。
if (myArray.includes("value")) {
// Do something
}
29 、 Function.prototype.bind() 的強(qiáng)大功能
將函數(shù)綁定到上下文(此值)并部分應(yīng)用參數(shù),創(chuàng)建更可重用和模塊化的代碼。
const greet = function(greeting, punctuation) {
return `${greeting}, ${this.name}${punctuation}`;
};
const greetJohn = greet.bind({name: 'John'}, 'Hello');
console.log(greetJohn('!')); // "Hello, John!"
30 、防止對(duì)象修改
使用 Object.freeze() 防止對(duì)對(duì)象的修改,使其不可變。為了實(shí)現(xiàn)更深層次的不變性,請(qǐng)考慮更徹底地實(shí)施不變性的庫(kù)。
let obj = { name: "Immutable" };
Object.freeze(obj);
obj.name = "Mutable"; // Fails silently in non-strict mod
總結(jié)
以上就是我們今天跟你分享的30個(gè)JavaScript代碼技巧,希望這些技巧能夠?qū)δ阌兴鶐椭?/span>