前端新老手必備的34種JavaScript簡寫優化技術
前端新老手必備的34種JavaScript簡寫優化技術
香芋妹妹 北京尚學堂科技有限公司 前端工程師開發者的生活總是在學習新的東西,跟上變化不應該比現在更難,我的動機是介紹所有 JavaScript 的最佳實踐,比如簡寫功能,作為一個前端開發者,我們必須知道,讓我們的生活在 2021 年變得更輕鬆。
你可能做了很長時間的 JavaScript 開發,但有時你可能沒有更新最新的特性,這些特性可以解決你的問題,而不需要做或編寫一些額外的程式碼。這些技術可以幫助您編寫乾淨和優化的 JavaScript 程式碼。此外,這些主題可以幫助你為 2021 年的 JavaScript 面試做準備。
1.如果有多個條件
我們可以在陣列中儲存多個值,並且可以使用陣列 include
方法。
//Longhand
if (
x === "abc" ||
x === "def" ||
x === "ghi" ||
x === "jkl"
) {
//logic
}
//Shorthand
if (["abc", "def", "ghi", "jkl"].includes(x)) {
//logic
}
2.如果為真…否則簡寫
這對於我們有 if-else
條件,裡面不包含更大的邏輯時,是一個較大的捷徑。我們可以簡單的使用三元運算子來實現這個簡寫。
// Longhand let test: boolean; if (x > 100) { test = true; } else { test = false; } // Shorthand let test = x > 10 ? true : false; //or we can use directly let test = x > 10; console.log(test);
當我們有巢狀條件時,我們可以採用這種方式。
let x = 300,
test2 =
x > 100
? "greater 100"
: x < 50
? "less 50"
: "between 50 and 100";
console.log(test2); // "greater than 100"
3.宣告變數
當我們要宣告兩個具有共同值或共同型別的變數時,可以使用此簡寫形式。
//Longhand
let test1;
let test2 = 1;
//Shorthand
let test1,
test2 = 1;
5.null 值檢查和分配預設值
let test1 = null,
test2 = test1 || "";
console.log("null check", test2); // output will be ""
6.undefined 值檢查和分配預設值
let test1 = undefined,
test2 = test1 || "";
console.log("undefined check", test2); // output will be ""
正常值檢查
let test1 = "test",
test2 = test1 || "";
console.log(test2); // output: 'test'
7.將值分配給多個變數
當我們處理多個變數並希望將不同的值分配給不同的變數時,此簡寫技術非常有用。
//Longhand
let test1, test2, test3;
test1 = 1;
test2 = 2;
test3 = 3;
//Shorthand
let [test1, test2, test3] = [1, 2, 3];
8.賦值運算子簡寫
我們在程式設計中處理很多算術運算子,這是將運算子分配給 JavaScript 變數的有用技術之一。
// Longhand
test1 = test1 + 1;
test2 = test2 - 1;
test3 = test3 * 20;
// Shorthand
test1++;
test2--;
test3 *= 20;
9.如果存在簡寫
這是我們大家都在使用的常用簡寫之一,但仍然值得一提。
// Longhand
if (test1 === true) or if (test1 !== "") or if (test1 !== null)
// Shorthand //it will check empty string,null and undefined too
if (test1)
注意:如果 test1 有任何值,它將在 if 迴圈後進入邏輯,該運算子主要用於null
或undefined
的檢查。
10.多個條件的 AND(&&)運算子
如果僅在變數為 true
的情況下才呼叫函式,則可以使用 &&
運算子。
//Longhand
if (test1) {
callMethod();
}
//Shorthand
test1 && callMethod();
11.foreach 迴圈簡寫
這是迭代的常用簡寫技術之一。
// Longhand
for (var i = 0; i < testData.length; i++)
// Shorthand
for (let i in testData) or for (let i of testData)
每個變數的陣列
function testData(element, index, array) {
console.log("test[" + index + "] = " + element);
}
[11, 24, 32].forEach(testData);
// logs: test[0] = 11, test[1] = 24, test[2] = 32
12.return 中比較
我們也可以在 return 語句中使用比較。它將避免我們的 5 行程式碼,並將它們減少到 1 行。
// Longhand
let test;
function checkReturn() {
if (!(test === undefined)) {
return test;
} else {
return callMe("test");
}
}
var data = checkReturn();
console.log(data); //output test
function callMe(val) {
console.log(val);
}
// Shorthand
function checkReturn() {
return test || callMe("test");
}
13.箭頭函式
//Longhand
function add(a, b) {
return a + b;
}
//Shorthand
const add = (a, b) => a + b;
更多示例。
function callMe(name) {
console.log("Hello", name);
}
callMe = (name) => console.log("Hello", name);
14.短函式呼叫
我們可以使用三元運算子來實現這些功能。
// Longhand
function test1() {
console.log("test1");
}
function test2() {
console.log("test2");
}
var test3 = 1;
if (test3 == 1) {
test1();
} else {
test2();
}
// Shorthand
(test3 === 1 ? test1 : test2)();
15. Switch 簡寫
我們可以將條件儲存在鍵值物件中,並可以根據條件使用。
// Longhand
switch (data) {
case 1:
test1();
break;
case 2:
test2();
break;
case 3:
test();
break;
// And so on...
}
// Shorthand
var data = {
1: test1,
2: test2,
3: test,
};
data[something] && data[something]();
16.隱式返回簡寫
使用箭頭函式,我們可以直接返回值,而不必編寫 return 語句。
//longhand
function calculate(diameter) {
return Math.PI * diameter
}
//shorthand
calculate = diameter => (
Math.PI * diameter;
)
17.小數基數指數
// Longhand
for (var i = 0; i < 10000; i++) { ... }
// Shorthand
for (var i = 0; i < 1e4; i++) {
18.預設引數值
//Longhand
function add(test1, test2) {
if (test1 === undefined) test1 = 1;
if (test2 === undefined) test2 = 2;
return test1 + test2;
}
//shorthand
add = (test1 = 1, test2 = 2) => test1 + test2;
add(); //output: 3
19.擴充套件運算子簡寫
//longhand
// joining arrays using concat
const data = [1, 2, 3];
const test = [4, 5, 6].concat(data);
//shorthand
// joining arrays
const data = [1, 2, 3];
const test = [4, 5, 6, ...data];
console.log(test); // [ 4, 5, 6, 1, 2, 3]
對於克隆,我們也可以使用擴充套件運算子。
//longhand
// cloning arrays
const test1 = [1, 2, 3];
const test2 = test1.slice();
//shorthand
// cloning arrays
const test1 = [1, 2, 3];
const test2 = [...test1];
20.模板文字
如果您厭倦了在單個字串中使用 +
來連線多個變數,那麼這種簡寫可以消除您的頭痛。
//longhand
const welcome = "Hi " + test1 + " " + test2 + ".";
//shorthand
const welcome = `Hi ${test1} ${test2}`;
21.多行字串簡寫
當我們在程式碼中處理多行字串時,可以使用以下功能:
//longhand
const data =
"abc abc abc abc abc abc\n\t" +
"test test,test test test test\n\t";
//shorthand
const data = `abc abc abc abc abc abc
test test,test test test test`;
22.物件屬性分配
let test1 = "a";
let test2 = "b";
//Longhand
let obj = { test1: test1, test2: test2 };
//Shorthand
let obj = { test1, test2 };
23.將字串轉換成數字
//Longhand
let test1 = parseInt("123");
let test2 = parseFloat("12.3");
//Shorthand
let test1 = +"123";
let test2 = +"12.3";
24.用解構簡寫
//longhand
const test1 = this.data.test1;
const test2 = this.data.test2;
const test2 = this.data.test3;
//shorthand
const { test1, test2, test3 } = this.data;
25.用 Array.find 簡寫
當我們確實有一個物件陣列並且我們想要根據物件屬性查詢特定物件時,find 方法確實很有用。
const data = [
{
type: "test1",
name: "abc",
},
{
type: "test2",
name: "cde",
},
{
type: "test1",
name: "fgh",
},
];
function findtest1(name) {
for (let i = 0; i < data.length; ++i) {
if (data[i].type === "test1" && data[i].name === name) {
return data[i];
}
}
}
//Shorthand
filteredData = data.find(
(data) => data.type === "test1" && data.name === "fgh"
);
console.log(filteredData); // { type: 'test1', name: 'fgh' }
26.查詢條件簡寫
如果我們有程式碼來檢查型別,根據型別需要呼叫不同的方法,我們可以選擇使用多個 else ifs 或者 switch,但是如果我們有比這更好的簡寫方法呢?
// Longhand
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);
}
// Shorthand
var types = {
test1: test1,
test2: test2,
test3: test3,
test4: test4,
};
var func = types[type];
!func && throw new Error("Invalid value " + type);
func();
27.按位索引簡寫
當我們遍歷陣列以查詢特定值時,我們確實使用 indexOf()
方法,如果找到更好的方法該怎麼辦?讓我們看看這個例子。
//longhand
if (arr.indexOf(item) > -1) {
// item found
}
if (arr.indexOf(item) === -1) {
// item not found
}
//shorthand
if (~arr.indexOf(item)) {
// item found
}
if (!~arr.indexOf(item)) {
// item not found
}
按位(〜
)運算子將返回除-1 以外的任何值的真實值。否定它就像做~~
一樣簡單。另外,我們也可以使用include()
函式:
if (arr.includes(item)) {
// true if the item found
}
28.Object.entries()
此函式有助於將物件轉換為物件陣列。
const data = { test1: "abc", test2: "cde", test3: "efg" };
const arr = Object.entries(data);
console.log(arr);
/** Output:
[ [ 'test1', 'abc' ],
[ 'test2', 'cde' ],
[ 'test3', 'efg' ]
]
**/
29.Object.values()
這也是 ES8 中引入的一項新功能,該功能執行與 Object.entries()
類似的功能,但沒有關鍵部分:
const data = { test1: "abc", test2: "cde" };
const arr = Object.values(data);
console.log(arr);
/** Output:
[ 'abc', 'cde']
**/
30.雙按位簡寫
雙重 NOT 按位運算子方法僅適用於 32 位整數)
// Longhand
Math.floor(1.9) === 1; // true
// Shorthand
~~1.9 === 1; // true
31.重複一個字串多次
要一次又一次地重複相同的字元,我們可以使用 for 迴圈並將它們新增到同一迴圈中,但是如果我們有一個簡寫方法呢?
//longhand
let test = "";
for (let i = 0; i < 5; i++) {
test += "test ";
}
console.log(str); // test test test test test
//shorthand
"test ".repeat(5);
32.在陣列中查詢最大值和最小值
const arr = [1, 2, 3];
Math.max(…arr); // 3
Math.min(…arr); // 1
33.從字串中獲取字元
let str = 'abc';
//Longhand
str.charAt(2); // c
//Shorthand
Note: If we know the index of the array then we can directly use index insted of character.If we are not sure about index it can throw undefined
str[2]; // c
34.數學指數冪函式的簡寫
//longhand
Math.pow(2, 3); // 8
//shorthand
2 ** 3; // 8
原文作者:程式設計師張張編輯於 2021-08-03 16:37
原文連結:新老手必備的34種JavaScript簡寫優化技術 | 程式設計師張張