自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

20 個超級有用的 JavaScript 技巧,讓你的工作更輕松

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

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

我們現(xiàn)在開始吧。

1. 多條件 if 語句

將多個值放入一個數(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. 簡化 if true...else 條件表達式


// 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)建一個新變量時,有時我們想檢查引用的變量是否是一個假值,例如 null 或 undefined 或空字符串。JavaScript 確實為這種檢查提供了一個很好的快捷方式——邏輯 OR 運算符 (||)

|| 僅當(dāng)左側(cè)為空或 NaN 或 null 或 undefined 或 false 時,如果左側(cè)操作數(shù)為假,則將返回右側(cè)操作數(shù),邏輯或運算符 (||) 將返回右側(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. 獲取列表中的最后一項

在其他語言中,此功能被制成可以在數(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. 使用可選的鏈接運算符 -?。

? 也稱為鏈判斷運算,它允許開發(fā)人員讀取深度嵌套在對象鏈中的屬性值,而無需驗證每個引用,當(dāng)引用為空時,表達式停止計算并返回 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. 多個條件的 && 運算符

要僅在變量為真時調(diào)用函數(shù),請使用 && 運算符。


// bad
if (test) {
callMethod();
}

// better
test && callMethod();

當(dāng)你想在 React 中有條件地渲染組件時,這對于使用 (&&) 進行短路很有用。例如:

<div> {this.state.isLoading && <Loading />} </div>

9.開關(guān)簡化

我們可以將條件存儲在鍵值對象中,并根據(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. 條件查找簡化

如果我們想根據(jù)不同的類型調(diào)用不同的方法,我們可以使用多個 else if 語句或開關(guān),但是還有比這更好的簡化技巧嗎?其實和之前的switch簡化是一樣的。


// 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. 對象屬性賦值

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. 模板字符串

如果你厭倦了使用 + 將多個變量連接成一個字符串,這個簡化技巧會讓你頭疼。


// 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的按位化簡

在數(shù)組中查找某個值時,我們可以使用 indexOf() 方法。但是還有更好的方法,我們來看這個例子。

// 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ù)字。我們也可以簡單地通過在字符串前面提供一元運算符 (+) 來做到這一點。


// bad
let total = parseInt("583");
let average = parseFloat("32.5");

// better
let total = +"583";
let average = +"32.5";

18. 按順序執(zhí)行 Promise

如果你有一堆異步或普通函數(shù)都返回要求你一個一個執(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ù),包裝到一個新的 Promise 實例中。在所有這些參數(shù)實例都返回結(jié)果(已完成或已拒絕)之前,包裝器實例不會結(jié)束。

有時候,我們并不關(guān)心異步請求的結(jié)果,我們只關(guān)心是否所有請求都結(jié)束了。這時候,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. 帶范圍的隨機數(shù)生成器

有時你需要生成隨機數(shù),但又希望數(shù)字在一定范圍內(nèi),則可以使用此工具。

function randomNumber(max = 1, min = 0) {
if (min >= max) {
return max;
}

return Math.floor(Math.random() * (max - min) + min);
}

生成隨機顏色

function getRandomColor() {
const colorAngle = Math.floor(Math.random() * 360);
return `hsla(${colorAngle},100%,50%,1)`;
}

到這里,我要跟你分享的20 個 JavaScript 的小技巧就結(jié)束了,希望這些小技巧對你有用。

寫在最后

在前面我也跟大家分享過很多這樣的小技巧,不知道大家是否學(xué)會了沒有?如果你沒有學(xué)會的話,請記得多看看,暫時用不上的一些技巧,可以自行收藏起來。

同時,也要整理一份屬于自己的使用技巧筆記。

如果你覺得我今天跟你分享的內(nèi)容有幫助的話,請記得點贊我,關(guān)注我,并將其分享給你的開發(fā)者朋友,也許能夠幫助到他。

以上就是我今天跟你分享的全部內(nèi)容,感謝你的閱讀,編程愉快!

責(zé)任編輯:華軒 來源: web前端開發(fā)
相關(guān)推薦

2023-07-18 07:56:31

工具reduce業(yè)務(wù)

2023-06-28 00:02:40

2011-07-19 10:16:55

2023-06-29 15:08:21

JavaScrip開發(fā)

2024-09-18 15:58:05

2022-10-18 16:35:51

JavaScrip數(shù)組參數(shù)

2024-10-11 13:17:16

Linux命令行快捷導(dǎo)航

2023-07-04 13:35:00

Monorepos工具管理

2010-12-23 15:55:00

上網(wǎng)行為管理

2011-04-02 10:13:36

Linux系統(tǒng)管理

2023-06-02 15:53:38

工具Python開發(fā)

2022-12-22 14:44:06

JavaScript技巧

2022-12-25 16:03:31

JavaScript技巧

2015-11-05 08:59:19

編程Visual Stud擴展

2019-11-25 10:20:54

CSS代碼javascript

2022-12-19 15:23:51

JavaScrip開發(fā)語言

2023-05-30 15:11:16

JavaScrip開發(fā)功能

2023-12-28 10:01:05

ChatGPT技巧信息

2023-08-18 15:12:00

JavaScript開發(fā)

2020-06-21 13:57:21

JavaScript開發(fā)代碼
點贊
收藏

51CTO技術(shù)棧公眾號