你對 JavaScript 了解多少?您知道如何充分發(fā)揮其潛力并避免常見的陷阱嗎?您知道如何編寫易于閱讀、維護(hù)和調(diào)試的代碼嗎?你知道如何使用 JavaScript 最新最酷的特性嗎?
如果您想提高 JavaScript 技能并成為更好的開發(fā)人員,那么本文適合您。本文將教您 11 個(gè)專業(yè)技巧,幫助您編寫更好的 JavaScript 代碼,你還在等什么?一起來學(xué)習(xí)吧。

1. 使用 XOR 運(yùn)算符比較數(shù)字
按位異或運(yùn)算符 (^) 對兩個(gè)操作數(shù)執(zhí)行按位異或運(yùn)算。這意味著如果位不同則返回 1,如果相同則返回 0。
const a = 1337;
const b = 69;
// nooby
a !== 69 ? console.log('Unequal') : console.log("Equal"); // Unequal
b !== 69 ? console.log('Unequal') : console.log("Equal"); // Equal
// pro
a ^ 69 ? console.log('Unequal') : console.log("Equal"); // Unequal
b ^ 69 ? console.log('Unequal') : console.log("Equal"); // Equal
2. 用數(shù)據(jù)即時(shí)創(chuàng)建和填充數(shù)組
// nooby
const array = new Array(3);
for(let i=0; i < array.length; i++){
array[i] = i;
}
console.log(array) // [ 0, 1, 2 ]
// pro
const filledArray = new Array(3).fill(null).map((_, i)=> (i));
console.log(filledArray) // [ 0, 1, 2 ]
3. 使用對象中的動(dòng)態(tài)屬性
// nooby
let propertyName = "body";
let paragraph = {
id: 1,
};
paragraph[propertyName] = "other stringy";
// { id: 1, body: 'other stringy' }
console.log(paragraph)
// pro
let propertyName = "body";
let paragraph = {
id: 1,
[propertyName] : "other stringy"
};
// { id: 1, body: 'other stringy' }
console.log(paragraph)
4. 輕松消除數(shù)組中的重復(fù)值
您可以使用集合消除數(shù)組中的重復(fù)值。
// nooby
let answers = [7, 13, 31, 13, 31, 7, 42];
let leftAnswers = [];
let flag = false;
for (i = 0; i< answers.length; i++) {
for (j = 0; j < leftAnswers.length; j++) {
if (answers[i] === leftAnswers[j]) {
flag = true;
}
}
if (flag === false) {
leftAnswers.push(answers[i]);
}
flag = false;
}
//[ 7, 13, 31, 42 ]
console.log(leftAnswers)
// pro
let answers = [7, 13, 31, 13, 31, 7, 42];
let leftAnswers = Array.from(new Set(answers));
// [ 7, 13, 31, 42 ]
console.log(leftAnswers)
5. 輕松地將對象轉(zhuǎn)換為數(shù)組
您可以使用展開運(yùn)算符將數(shù)組轉(zhuǎn)換為對象。
// nooby
let arr = ["v1", "v2", "v3"];
let objFromArray = {};
for (let i = 0; i < arr.length; ++i) {
if (arr[i] !== undefined) {
objFromArray[i] = arr[i];
}
}
// { '0': 'v1', '1': 'v2', '2': 'v3' }
console.log(objFromArray)
// pro
let objFromArrayPro = {...arr};
// { '0': 'v1', '1': 'v2', '2': 'v3' }
console.log(objFromArrayPro)
6. 使用邏輯運(yùn)算符進(jìn)行短路評估
您可以使用邏輯運(yùn)算符進(jìn)行短路評估,方法是使用 && 運(yùn)算符返回表達(dá)式鏈中的第一個(gè)假值或最后一個(gè)真值,或者使用 || 運(yùn)算符返回表達(dá)式鏈中的第一個(gè)真值或最后一個(gè)假值。
const dogs = true;
// nooby
if (dogs) {
runAway();
}
// pro
dogs && runAway()
function runAway(){
console.log('You run!');
}
7. 對象鍵維護(hù)它們的插入順序
對象鍵通過遵循一個(gè)簡單的規(guī)則來維護(hù)它們的插入順序:類整數(shù)鍵按數(shù)字升序排序,而非類整數(shù)鍵根據(jù)它們的創(chuàng)建時(shí)間排序。
const character = {
name: "Arthas",
age: 27,
class: "Paladin",
profession: "Lichking",
};
// name age class profession
console.log(Object.keys(character));
8. 創(chuàng)建并填充指定大小的數(shù)組
您可以使用帶有兩個(gè)參數(shù)的 Array() 構(gòu)造函數(shù)來創(chuàng)建和填充指定大小和值的數(shù)組:大小和值,或者對空數(shù)組使用 Array.fill() 方法。
// nooby
const size = 5;
const defaultValue = 0;
const arr = []
for(let i = 0; i < size; i++){
arr.push(defaultValue)
}
console.log(arr);
// pro
const size = 5;
const defaultValue = 0;
const arr = Array(size).fill(defaultValue);
console.log(arr); // [0, 0, 0, 0, 0]
9. 理解 JavaScript 中的 Truthy 和 Falsy 值
在布爾上下文中使用時(shí),Truthy 和 Falsy 值會(huì)隱式轉(zhuǎn)換為 true 或 false。
虛假值 => false, 0, ""(空字符串), null, undefined, &NaN
真值 => "Values", "0", {}(空對象),&[](空數(shù)組)
// pro
if(![].length){
console.log("There is no Array...");
} else {
console.log("There is an Array, Hooray!");
}
if(!""){
console.log("There is no content in this string...");
} else {
console.log("There is content in this string, Hooray!");
}
10. 用更好的參數(shù)改進(jìn)函數(shù)
不要使用單個(gè)多個(gè)參數(shù),而是使用參數(shù)對象。在函數(shù)定義中解構(gòu)它以獲得所需的屬性。
// nooby
function upload(user, resourceId, auth, files) {}
upload(...); // need to remember the order
// pro
function upload(
{ user, resourceId, auth, files } = {}
) {}
const uploadObj = {
user: 'me',
resourceId: uuid(),
auth: 'token',
files: []
}
upload(uploadObj);
11. Null 和 Undefined 在 JavaScript 中是不同的
Null 和 undefined 是兩個(gè)不同的值,表示沒有值。
- null => 是的,這是一個(gè)值。Undefined 不是
- 將 null 想象成在一個(gè)空盒子前面
- 把 undefined 想象成在沒有盒子的前面
const fnExpression = (s = 'default stringy') => console.log(s);
fnExpression(undefined); // default stringy
fnExpression(); // default stringy
fnExpression(null); // null
總結(jié)
以上就是我今天想與您分享的11個(gè)關(guān)于JavaScript的專業(yè)技巧,希望您能從中學(xué)到新東西。