今天這篇文章,我將跟大家分享21個(gè)我自己收藏使用的JavaScript技巧,希望今天這篇文章里的內(nèi)容能夠幫助到你,讓你的工作更高效!更輕松!

我們現(xiàn)在開始吧。
1. 多條件 if 語句
將多個(gè)值放入一個(gè)數(shù)組中,然后調(diào)用該數(shù)組的 include 方法。
// bad
if (x === "abc" || x === "def" || x === "ghi" || x === "jkl") {
  //logic
}
// better
if (["abc", "def", "ghi", "jkl"].includes(x)) {
  //logic
}
2. 簡(jiǎn)化 if true...else 條件表達(dá)式
// bad
let test: boolean;
if (x > 100) {
  test = true;
} else {
  test = false;
}
// better
let test = x > 10 ? true : false;
//or 
let test = x > 10;
console.log(test);
3. 假值(undefined, null, 0, false, NaN, empty string)檢查
當(dāng)我們創(chuàng)建一個(gè)新變量時(shí),有時(shí)我們想檢查引用的變量是否是一個(gè)假值,例如 null 或 undefined 或空字符串。JavaScript 確實(shí)為這種檢查提供了一個(gè)很好的快捷方式——邏輯 OR 運(yùn)算符 (||)
|| 僅當(dāng)左側(cè)為空或 NaN 或 null 或 undefined 或 false 時(shí),如果左側(cè)操作數(shù)為假,則將返回右側(cè)操作數(shù),邏輯或運(yùn)算符 (||) 將返回右側(cè)的值。
// bad
if (test1 !== null || test1 !== undefined || test1 !== "") {
  let test2 = test1;
}
// better
let test2 = test1 || "";
// bad
if (test1 === true) or if (test1 !== "") or if (test1 !== null)
// better
if (test1){
  // do some
}else{
  // do other
}
//Note: If test1 has a value, the logic after if will be executed. 
//This operator is mainly used for null, undefined, and empty string checks.
4. null/undefined 檢查和默認(rèn)賦值
//null checking and default assignmentlet test1 = null;let test2 = test1 ?? "";
console.log("null check", test2); // output empty string ""
//undefined checking and default assignmentconst test = undefined ?? "default";console.log(test);// expected output: "default"
5. 獲取列表中的最后一項(xiàng)
在其他語言中,此功能被制成可以在數(shù)組上調(diào)用的方法或函數(shù),但在 JavaScript 中,你必須自己做一些工作。
let array = [0, 1, 2, 3, 4, 5, 6, 7];
console.log(array.slice(-1)) >>> [7];
console.log(array.slice(-2)) >>> [6, 7];
console.log(array.slice(-3)) >>> [5, 6, 7];
function lastItem(list) {
  if (Array.isArray(list)) {
    return list.slice(-1)[0];
  }
  if (list instanceof Set) {
    return Array.from(list).slice(-1)[0];
  }
  if (list instanceof Map) {
    return Array.from(list.values()).slice(-1)[0];
  }
}
6.比較后返回
// bad
let test;
function checkReturn() {
  if (!(test === undefined)) {
    return test;
  } else {
    return callMe("test");
  }
}
// better
function checkReturn() {
  return test ?? callMe("test");
}
7. 使用可選的鏈接運(yùn)算符 -?。
? 也稱為鏈判斷運(yùn)算,它允許開發(fā)人員讀取深度嵌套在對(duì)象鏈中的屬性值,而無需驗(yàn)證每個(gè)引用,當(dāng)引用為空時(shí),表達(dá)式停止計(jì)算并返回 undefined。
const travelPlans = {
        destination: "DC",
        monday: {
            location: "National Mall",
            budget: 200,
        },
    };
    // bad
    const res = travelPlans && travelPlans.tuesday && travelPlans.tuesday.location && travelPlans.tuesday.location.href;
    console.log(res);  // Result: undefined
    // better
    const res1 = travelPlans?.tuesday?.location?.href;
    console.log(res1);  // Result: undefined
8. 多個(gè)條件的 && 運(yùn)算符
要僅在變量為真時(shí)調(diào)用函數(shù),請(qǐng)使用 && 運(yùn)算符。
// bad
if (test) {
  callMethod();
}
// better
test && callMethod();
當(dāng)你想在 React 中有條件地渲染組件時(shí),這對(duì)于使用 (&&) 進(jìn)行短路很有用。例如:
<div> {this.state.isLoading && <Loading />} </div>9.開關(guān)簡(jiǎn)化
我們可以將條件存儲(chǔ)在鍵值對(duì)象中,并根據(jù)條件調(diào)用它們。
// bad
switch (data) {
  case 1:
    test1();
    break;
  case 2:
    test2();
    break;
  case 3:
    test();
    break;
    // And so on...
}
// better
var data = {
  1: test1,
  2: test2,
  3: test,
};
// If type exists in data, execute the corresponding function
data[type] && data[type]();
10.默認(rèn)參數(shù)值
// bad
function add(test1, test2) {
  if (test1 === undefined) test1 = 1;
  if (test2 === undefined) test2 = 2;
  return test1 + test2;
}
// better
add = (test1 = 1, test2 = 2) => test1 + test2;
add(); //output: 3
11. 條件查找簡(jiǎn)化
如果我們想根據(jù)不同的類型調(diào)用不同的方法,我們可以使用多個(gè) else if 語句或開關(guān),但是還有比這更好的簡(jiǎn)化技巧嗎?其實(shí)和之前的switch簡(jiǎn)化是一樣的。
// bad
if (type === "test1") {
  test1();
} else if (type === "test2") {
  test2();
} else if (type === "test3") {
  test3();
} else if (type === "test4") {
  test4();
} else {
  throw new Error("Invalid value " + type);
}
// better
var types = {
  test1,
  test2,
  test3,
  test4,
};
types[type] && types[type]();
12. 對(duì)象屬性賦值
let test1 = "a";
let test2 = "b";
// bad
let obj = { test1: test1, test2: test2 };
// better
let obj = { test1, test2 };
13. 解構(gòu)賦值
// bad
const test1 = this.data.test1;
const test2 = this.data.test2;
const test2 = this.data.test3;
// better
const { test1, test2, test3 } = this.data;
14. 模板字符串
如果你厭倦了使用 + 將多個(gè)變量連接成一個(gè)字符串,這個(gè)簡(jiǎn)化技巧會(huì)讓你頭疼。
// bad
const welcome = "Hi " + test1 + " " + test2 + ".";
// better
const welcome = `Hi ${test1} ${test2}`;
15. 跨越字符串
// bad
    const data =
        "hello maxwell this is a test\n\t" + "test test,test test test test\n\t";
  
   // better
    const data = `hello maxwell this is a test
                    test test,test test test test`;
16. indexOf的按位化簡(jiǎn)
在數(shù)組中查找某個(gè)值時(shí),我們可以使用 indexOf() 方法。但是還有更好的方法,我們來看這個(gè)例子。
// bad
if (arr.indexOf(item) > -1) {
  // item found
}
if (arr.indexOf(item) === -1) {
  // item not found
}
// better
if (~arr.indexOf(item)) {
  // item found
}
if (!~arr.indexOf(item)) {
  // item not found
}
//The bitwise (~) operator will return true (except for -1), 
//the reverse operation only requires !~. Alternatively, the includes() function can be used.
if (arr.includes(item)) {
  // true if the item found
}
17. 將字符串轉(zhuǎn)換為數(shù)字
有諸如 parseInt 和 parseFloat 等內(nèi)置方法可用于將字符串轉(zhuǎn)換為數(shù)字。我們也可以簡(jiǎn)單地通過在字符串前面提供一元運(yùn)算符 (+) 來做到這一點(diǎn)。
// bad
let total = parseInt("583");
let average = parseFloat("32.5");
// better
let total = +"583";
let average = +"32.5";
18. 按順序執(zhí)行 Promise
如果你有一堆異步或普通函數(shù)都返回要求你一個(gè)一個(gè)執(zhí)行它們的Promise怎么辦?
async function getData() {
        const promises = [fetch("url1"), fetch("url2"), fetch("url3"), fetch("url4")];
        for (const item of promises) {
            // Print out the promise
            console.log(item);
        }
        // better
        for await (const item of promises) {
            // Print out the results of the request
            console.log(item);
        }
    }等待所有Promiae完成。
Promise.allSettled() 方法接受一組 Promise 實(shí)例作為參數(shù),包裝到一個(gè)新的 Promise 實(shí)例中。在所有這些參數(shù)實(shí)例都返回結(jié)果(已完成或已拒絕)之前,包裝器實(shí)例不會(huì)結(jié)束。
有時(shí)候,我們并不關(guān)心異步請(qǐng)求的結(jié)果,我們只關(guān)心是否所有請(qǐng)求都結(jié)束了。這時(shí)候,Promise.allSettled() 方法就非常有用了。
const promises = [fetch("index.html"), fetch("https://does-not-exist/")];
const results = await Promise.allSettled(promises);
// Filter out successful requests
const successfulPromises = results.filter((p) => p.status === "fulfilled");
// Filter out failed requests and output the reason
const errors = results
.filter((p) => p.status === "rejected")
.map((p) => p.reason);19.交換數(shù)組元素的位置
// bad
const swapWay = (arr, i, j) => {
  const newArr = [...arr];
  let temp = newArr[i];
  newArr[i] = list[j];
  newArr[j] = temp;
  return newArr;
};
//Since ES6, swapping values from different locations in an array has become much easier
// better
const swapWay = (arr, i, j) => {
  const newArr = [...arr];
  const [newArr[j],newArr[i]] = [newArr[i],newArr[j]];
  return newArr;
};
20. 帶范圍的隨機(jī)數(shù)生成器
有時(shí)你需要生成隨機(jī)數(shù),但又希望數(shù)字在一定范圍內(nèi),則可以使用此工具。
function randomNumber(max = 1, min = 0) {
  if (min >= max) {
    return max;
  }
  return Math.floor(Math.random() * (max - min) + min);
}生成隨機(jī)顏色
function getRandomColor() {
  const colorAngle = Math.floor(Math.random() * 360);
  return `hsla(${colorAngle},100%,50%,1)`;
}到這里,我要跟你分享的20 個(gè) JavaScript 的小技巧就結(jié)束了,希望這些小技巧對(duì)你有用。
寫在最后
在前面我也跟大家分享過很多這樣的小技巧,不知道大家是否學(xué)會(huì)了沒有?如果你沒有學(xué)會(huì)的話,請(qǐng)記得多看看,暫時(shí)用不上的一些技巧,可以自行收藏起來。
同時(shí),也要整理一份屬于自己的使用技巧筆記。
如果你覺得我今天跟你分享的內(nèi)容有幫助的話,請(qǐng)記得點(diǎn)贊我,關(guān)注我,并將其分享給你的開發(fā)者朋友,也許能夠幫助到他。
以上就是我今天跟你分享的全部?jī)?nèi)容,感謝你的閱讀,編程愉快!