亚洲视频二区_亚洲欧洲日本天天堂在线观看_日韩一区二区在线观看_中文字幕不卡一区

公告:魔扣目錄網(wǎng)為廣大站長提供免費收錄網(wǎng)站服務(wù),提交前請做好本站友鏈:【 網(wǎng)站目錄:http://www.430618.com 】, 免友鏈快審服務(wù)(50元/站),

點擊這里在線咨詢客服
新站提交
  • 網(wǎng)站:51998
  • 待審:31
  • 小程序:12
  • 文章:1030137
  • 會員:747

使用現(xiàn)代速記技術(shù),技巧和竅門優(yōu)化您的JAVAScript代碼

開發(fā)人員的生活總是在學(xué)習(xí)新事物,并且跟上變化的難度不應(yīng)該比現(xiàn)在已經(jīng)難,我的動機是介紹所有JavaScript最佳實踐,例如速記和功能,我們作為前端開發(fā)人員必須知道這些使我們的生活在2021年變得更加輕松

您可能已經(jīng)進行了很長時間的JavaScript開發(fā),但是有時您可能沒有使用不需要解決或編寫一些額外代碼即可解決問題的最新功能。這些技術(shù)可以幫助您編寫干凈且優(yōu)化的JavaScript代碼。此外,這些主題可以幫助您為2021年的JavaScript采訪做好準備。

在這里,我將提供一個新系列,介紹速記技術(shù),這些速記技術(shù)可幫助您編寫更干凈和優(yōu)化的JavaScript代碼。這是您在2021年必須知道的JavaScript編碼的備忘單。

1.如果有多個條件

我們可以在數(shù)組中存儲多個值,并且可以使用數(shù)組include方法。

//longhand
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
    //logic
}
//shorthand
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
   //logic
}

2.If true … else 簡寫

當我們具有不包含更大邏輯的if-else條件時,這是一個更大的捷徑。我們可以簡單地使用三元運算符來實現(xiàn)該速記。

// 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;

4.空,未定義,空檢查

當我們確實創(chuàng)建新變量時,有時我們想檢查為其值引用的變量是否為null或未定義。JavaScript確實具有實現(xiàn)這些功能的非常好的捷徑。

// Longhand
if (test1 !== null || test1 !== undefined || test1 !== '') {
    let test2 = test1;
}
// Shorthand
let test2 = test1 || '';

5.空值檢查和分配默認值

let test1 = null,
    test2 = test1 || '';
console.log("null check", test2); // output will be ""

6.未定義值檢查和分配默認值

let test1 = undefined,
    test2 = test1 || '';
console.log("undefined check", test2); // output will be ""

正常值檢查

let test1 = 'test',
    test2 = test1 || '';
console.log(test2); // output: 'test'

(獎金:現(xiàn)在我們可以對主題4,5和6使用??運算符)

空位合并運算符

空合并運算符??如果左側(cè)為null或未定義,則返回右側(cè)的值。默認情況下,它將返回左側(cè)的值。

const test= null ?? 'default';
console.log(test);
// expected output: "default"const test1 = 0 ?? 2;
console.log(test1);
// expected output: 0

7.給多個變量賦值

當我們處理多個變量并希望將不同的值分配給不同的變量時,此速記技術(shù)非常有用。

//Longhand 
let test1, test2, test3;
test1 = 1;
test2 = 2;
test3 = 3;
//Shorthand 
let [test1, test2, test3] = [1, 2, 3];

8.賦值運算符的簡寫

我們在編程中處理很多算術(shù)運算符。這是將運算符分配給JavaScript變量的有用技術(shù)之一。

// Longhand
test1 = test1 + 1;
test2 = test2 - 1;
test3 = test3 * 20;
// Shorthand
test1++;
test2--;
test3 *= 20;

9.如果存在速記

這是我們大家都在使用的常用速記之一,但仍然值得一提。

// Longhand
if (test1 === true)

// Shorthand
if (test1)

注意:如果test1有任何值,它將在if循環(huán)后進入邏輯,該運算符通常用于null或未定義的檢查。

10.多個條件的AND(&&)運算符

如果僅在變量為true的情況下才調(diào)用函數(shù),則可以使用&&運算符。

//Longhand 
if (test1) {
 callMethod(); 
} 
//Shorthand 
test1 && callMethod();

11. foreach循環(huán)速記

這是迭代的常用速記技術(shù)之一。

// Longhand
for (var i = 0; i < testData.length; i++)

// Shorthand
for (let i in testData) or  for (let i of testData)

每個變量的數(shù)組

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語句中使用比較。它將避免我們的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.箭頭函數(shù)

//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.短函數(shù)調(diào)用

我們可以使用三元運算符來實現(xiàn)這些功能。

// 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速記

我們可以將條件保存在鍵值對象中,并可以根據(jù)條件使用。

// 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.小數(shù)基指數(shù)

// Longhand
for (var i = 0; i < 10000; i++) { ... }

// Shorthand
for (var i = 0; i < 1e4; i++) {

18.默認參數(shù)值

//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 abcnt'
    + 'test test,test test test testnt'
//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.字符串成數(shù)字

//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的簡寫

當我們確實有一個對象數(shù)組并且我們想要根據(jù)對象屬性查找特定對象時,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.查找條件速記

如果我們有代碼來檢查類型,并且基于類型需要調(diào)用不同的方法,我們可以選擇使用多個else if或進行切換,但是如果我們的速記比這更好呢?

// 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.速記按位索引

當我們迭代數(shù)組以查找特定值時,我們確實使用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()函數(shù):

if (arr.includes(item)) { 
// true if the item found
}

28. Object.entries()

此功能有助于將對象轉(zhuǎn)換為對象數(shù)組。

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中引入的一項新功能,它執(zhí)行與Object.entries()類似的功能,但沒有關(guān)鍵部分:

const data = { test1: 'abc', test2: 'cde' };
const arr = Object.values(data);
console.log(arr);
/** Output:
[ 'abc', 'cde']
**/

30. Double Bitwise簡寫

(雙重NOT按位運算符方法僅適用于32位整數(shù))

// Longhand
Math.floor(1.9) === 1 // true

// Shorthand
~~1.9 === 1 // true

31.重復(fù)一個字符串多次

要一次又一次地重復(fù)相同的字符,我們可以使用for循環(huán)并將它們添加到同一循環(huán)中,但是如果我們有一個簡寫方法呢?

//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.在數(shù)組中查找最大值和最小值

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.功率速記

數(shù)學(xué)指數(shù)冪函數(shù)的簡寫:

//longhand
Math.pow(2,3); // 8
//shorthand
2**3 // 8

 

如果您想了解JavaScript版本的最新功能,請檢查以下內(nèi)容:

ES2021 / ES12

· replaceAll():返回一個新字符串,該字符串的所有模式匹配均被新的替換詞替換。

· Promise.any():它需要Promise對象的可迭代對象,并且當一個Promise履行時,返回帶有值的單個Promise。

· 弱引用:此對象持有對另一個對象的弱引用,而不會阻止該對象被垃圾回收。

· FinalizationRegistry:讓您在垃圾回收對象時請求回調(diào)。

· 方法和訪問器的私有可見性修飾符:私有方法可以用#聲明。

· 邏輯運算符:&&和||操作員。

· 數(shù)字分隔符:啟用下劃線作為數(shù)字文字中的分隔符,以提高可讀性。

· Intl.ListFormat:此對象啟用語言敏感列表格式。

· Intl.DateTimeFormat:此對象啟用對語言敏感的日期和時間格式。

ES2020 / ES11

1. BigInt:提供了一種表示(整個)大于253–1的數(shù)字的方法

11.動態(tài)導(dǎo)入:動態(tài)導(dǎo)入提供了將JS文件作為模塊動態(tài)導(dǎo)入的選項。這將幫助您按需獲得模塊。

12.空合并運算符:如果左側(cè)為null或未定義,則返回右側(cè)的值。默認情況下,它將返回左側(cè)的值。

1. globalThis:包含全局this值,該值基本上用作全局對象。

1. Promise.allSettled():返回一個承諾,該承諾基本上包含具有每個承諾結(jié)果的對象數(shù)組。

15.可選鏈接:使用任何連接的對象或檢查方法讀取值,并檢查屬性是否存在。

1. String.prototype.matchAll():返回所有與正則表達式匹配字符串的結(jié)果的迭代器。

17.命名導(dǎo)出:使用此功能,每個文件可以有多個命名導(dǎo)出。

18.定義明確的順序:

1. import.meta:對象將特定于上下文的元數(shù)據(jù)公開給JS模塊

ES2019 / ES10

1. Array.flat():通過組合主數(shù)組中的其他數(shù)組來創(chuàng)建一個新數(shù)組。注意:我們可以設(shè)置合并數(shù)組的深度。

1. Array.flatmap:通過將回調(diào)函數(shù)應(yīng)用于數(shù)組的每個元素來創(chuàng)建一個新數(shù)組。

1. Object.fromEntries():將鍵值對列表轉(zhuǎn)換為對象。

1. String.trimStart()和String.trimEnd():方法從字符串的開頭和結(jié)尾刪除空格。

1. try…catch:語句標記要嘗試的語句塊,如果發(fā)生任何錯誤,catch將對其進行處理。

1. Function.toString():將任何方法/代碼轉(zhuǎn)換為字符串。

1. Symbol.prototype.description:返回Symbol對象的可選描述。

ES2018 / ES9

27.異步迭代:借助async和await,我們現(xiàn)在可以在for循環(huán)中運行一系列異步迭代。

1. Promise.finally():在結(jié)算或拒絕時返回承諾。這將有助于避免重復(fù)和捕獲處理程序。

1. Rest / Spread屬性:用于對象分解和數(shù)組。

30.正則表達式命名捕獲組:可以在方括號后使用符號?進行命名。

31.正則表達式s(dotAll)標志:匹配除回車符以外的任何單個字符。s標志更改了此行為,因此允許使用行終止符

32.正則表達式Unicode屬性轉(zhuǎn)義符:可以通過設(shè)置Unicode u標志以及 p {…}和 p {…}來設(shè)置Unicode屬性轉(zhuǎn)義符。

ES2017 / ES8

1. Object.entries():返回給定對象鍵和值對的數(shù)組。

1. Object.values():返回給定對象的屬性值的數(shù)組。

1. padStart():用另一個字符串填充當前字符串,直到結(jié)果字符串達到長度為止。

1. padEnd():從當前字符串的末尾開始,使用給定的字符串填充當前字符串。

1. Object.getOwnPropertyDescriptors():返回給定對象的所有自己的屬性描述符。

38.異步功能:在Promises上擴展以進行異步調(diào)用。

ES2016 / ES7

1. Array.prototype.includes():確定數(shù)組在給定值中是否包括某個值。它返回true或false。

40.求冪:返回將第一個操作數(shù)提升為第二個操作數(shù)的冪的結(jié)果。

ES2015 / ES6

41.箭頭函數(shù)表達式:在某些情況下可替代傳統(tǒng)函數(shù)表達式

42.增強的對象文字:擴展為支持設(shè)置對象構(gòu)造。

43.類:使用class關(guān)鍵字創(chuàng)建類。

44.模板文字:可以使用$ {param}在字符串中直接添加參數(shù)

45.解構(gòu)分配:幫助從數(shù)組解壓縮值或從對象解壓縮屬性。

46. Default + Rest + Spread:支持默認值,spread參數(shù)或數(shù)組作為參數(shù)。

47. Let + Const:

48. Promises:用于異步操作。

49.模塊:

50. Map + Set + WeakMap + WeakSet:

51.數(shù)學(xué)+數(shù)字+字符串+數(shù)組+對象API:

... ...

(本文由聞數(shù)起舞翻譯自rajaraodv的文章《34 JavaScript Optimization Techniques to Know in 2021》,轉(zhuǎn)載請注明出處,原文鏈接:https://medium.com/javascript-in-plain-english/34-javascript-optimization-techniques-to-know-in-2021-d561afdf73c3)

分享到:
標簽:優(yōu)化 JavaScript
用戶無頭像

網(wǎng)友整理

注冊時間:

網(wǎng)站:5 個   小程序:0 個  文章:12 篇

  • 51998

    網(wǎng)站

  • 12

    小程序

  • 1030137

    文章

  • 747

    會員

趕快注冊賬號,推廣您的網(wǎng)站吧!
最新入駐小程序

數(shù)獨大挑戰(zhàn)2018-06-03

數(shù)獨一種數(shù)學(xué)游戲,玩家需要根據(jù)9

答題星2018-06-03

您可以通過答題星輕松地創(chuàng)建試卷

全階人生考試2018-06-03

各種考試題,題庫,初中,高中,大學(xué)四六

運動步數(shù)有氧達人2018-06-03

記錄運動步數(shù),積累氧氣值。還可偷

每日養(yǎng)生app2018-06-03

每日養(yǎng)生,天天健康

體育訓(xùn)練成績評定2018-06-03

通用課目體育訓(xùn)練成績評定