亚洲最大看欧美片,亚洲图揄拍自拍另类图片,欧美精品v国产精品v呦,日本在线精品视频免费

  • 站長資訊網(wǎng)
    最全最豐富的資訊網(wǎng)站

    總結(jié)15個JavaScript開發(fā)技巧(整理分享)

    本篇文章給大家分享一些經(jīng)常在項目中使用一些技巧,JavaScript 有很多很酷的特性,大多數(shù)初學(xué)者和中級開發(fā)人員都不知道。希望對大家有幫助。

    總結(jié)15個JavaScript開發(fā)技巧(整理分享)

    1. 有條件地向?qū)ο筇砑訉傩?/span>

    我們可以使用展開運算符號(…)來有條件地向 JS 對象快速添加屬性。

    const condition = true; const person = {   id: 1,   name: 'John Doe',   ...(condition && { age: 16 }), };

    如果每個操作數(shù)的值都為 true,則 && 操作符返回最后一個求值表達(dá)式。因此返回一個對象{age: 16},然后將其擴(kuò)展為person對象的一部分。

    如果 condition 為 false,JavaScript 會做這樣的事情:

    const person = {   id: 1,   name: '前端小智',   ...(false),  }; // 展開 `false` 對對象沒有影響 console.log(person); // { id: 1, name: 'John Doe' }

    2.檢查屬性是否存在對象中

    可以使用 in 關(guān)鍵字來檢查 JavaScript 對象中是否存在某個屬性。

    const person = { name: '前端小智', salary: 1000 }; console.log('salary' in person); // true console.log('age' in person); // false

    3.對象中的動態(tài)屬性名稱

    使用動態(tài)鍵設(shè)置對象屬性很簡單。只需使用['key name']來添加屬性:

    const dynamic = 'flavour'; var item = {   name: '前端小智',   [dynamic]: '巧克力' } console.log(item); // { name: '前端小智', flavour: '巧克力' }

    同樣的技巧也可用于使用動態(tài)鍵引用對象屬性:

    const keyName = 'name'; console.log(item[keyName]); // returns '前端小智'

    4. 使用動態(tài)鍵進(jìn)行對象解構(gòu)

    我們知道在對象解構(gòu)時,可以使用 : 來對解構(gòu)的屬性進(jìn)行重命名。但,你是否知道鍵名是動態(tài)的時,也可以解構(gòu)對象的屬性?

    const person = { id: 1, name: '前端小智' }; const { name: personName } = person; console.log(personName); // '前端小智'

    現(xiàn)在,我們用動態(tài)鍵來解構(gòu)屬性:

    const templates = {   'hello': 'Hello there',   'bye': 'Good bye' }; const templateName = 'bye'; const { [templateName]: template } = templates; console.log(template); // Good bye

    5. 空值合并 ?? 操作符

    當(dāng)我們想檢查一個變量是否為 null 或 undefined 時,??操作符很有用。當(dāng)它的左側(cè)操作數(shù)為null 或 undefined時,它返回右側(cè)的操作數(shù),否則返回其左側(cè)的操作數(shù)。

    const foo = null ?? 'Hello'; console.log(foo); // 'Hello' const bar = 'Not null' ?? 'Hello'; console.log(bar); // 'Not null' const baz = 0 ?? 'Hello'; console.log(baz); // 0

    在第三個示例中,返回 0,因為即使 0 在 JS 中被認(rèn)為是假的,但它不是null的或undefined的。你可能認(rèn)為我們可以用||算子但這兩者之間是有區(qū)別的

    你可能認(rèn)為我們可以在這里使用 || 操作符,但這兩者之間是有區(qū)別的。

    const cannotBeZero = 0 || 5; console.log(cannotBeZero); // 5 const canBeZero = 0 ?? 5; console.log(canBeZero); // 0

    6.可選鏈 ?.

    我們是不是經(jīng)常遇到這樣的錯誤: TypeError: Cannot read property ‘foo’ of null。這對每一個毅開發(fā)人員來說都是一個煩人的問題。引入可選鏈就是為了解決這個問題。一起來看看:

    const book = { id:1, title: 'Title', author: null }; // 通常情況下,你會這樣做 console.log(book.author.age) // throws error console.log(book.author && book.author.age); // null // 使用可選鏈 console.log(book.author?.age); // undefined // 或深度可選鏈 console.log(book.author?.address?.city); // undefined

    還可以使用如下函數(shù)可選鏈:

    const person = {   firstName: '前端',   lastName: '小智',   printName: function () {     return `${this.firstName} ${this.lastName}`;   }, }; console.log(person.printName()); // '前端 小智' console.log(persone.doesNotExist?.()); // undefined

    7. 使用 !! 操作符

    !! 運算符可用于將表達(dá)式的結(jié)果快速轉(zhuǎn)換為布爾值(true或false):

    const greeting = 'Hello there!'; console.log(!!greeting) // true const noGreeting = ''; console.log(!!noGreeting); // false

    8. 字符串和整數(shù)轉(zhuǎn)換

    使用 + 操作符將字符串快速轉(zhuǎn)換為數(shù)字:

    const stringNumer = '123'; console.log(+stringNumer); //123 console.log(typeof +stringNumer); //'number'

    要將數(shù)字快速轉(zhuǎn)換為字符串,也可以使用 + 操作符,后面跟著一個空字符串:

    const myString = 25 + ''; console.log(myString); //'25' console.log(typeof myString); //'string'

    這些類型轉(zhuǎn)換非常方便,但它們的清晰度和代碼可讀性較差。所以實際開發(fā),需要慎重的選擇使用。

    9. 檢查數(shù)組中的假值

    大家應(yīng)該都用過數(shù)組方法:filter、some、every,這些方法可以配合 Boolean 方法來測試真假值。

    const myArray = [null, false, 'Hello', undefined, 0]; // 過濾虛值 const filtered = myArray.filter(Boolean); console.log(filtered); // ['Hello'] // 檢查至少一個值是否為真 const anyTruthy = myArray.some(Boolean); console.log(anyTruthy); // true // 檢查所有的值是否為真 const allTruthy = myArray.every(Boolean); console.log(allTruthy); // false

    下面是它的工作原理。我們知道這些數(shù)組方法接受一個回調(diào)函數(shù),所以我們傳遞 Boolean 作為回調(diào)函數(shù)。Boolean 函數(shù)本身接受一個參數(shù),并根據(jù)參數(shù)的真實性返回 true 或 false。所以:

    myArray.filter(val => Boolean(val));

    等價于:

    myArray.filter(Boolean);

    10. 扁平化數(shù)組

    在原型 Array 上有一個方法 flat,可以從一個數(shù)組的數(shù)組中制作一個單一的數(shù)組。

    const myArray = [{ id: 1 }, [{ id: 2 }], [{ id: 3 }]]; const flattedArray = myArray.flat();  //[ { id: 1 }, { id: 2 }, { id: 3 } ]

    你也可以定義一個深度級別,指定一個嵌套的數(shù)組結(jié)構(gòu)應(yīng)該被扁平化的深度。例如:

    const arr = [0, 1, 2, [[[3, 4]]]]; console.log(arr.flat(2)); // returns [0, 1, 2, [3,4]]

    11.Object.entries

    大多數(shù)開發(fā)人員使用 Object.keys 方法來迭代對象。 此方法僅返回對象鍵的數(shù)組,而不返回值。 我們可以使用 Object.entries 來獲取鍵和值。

    const person = {   name: '前端小智',   age: 20 }; Object.keys(person); // ['name', 'age'] Object.entries(data); // [['name', '前端小智'], ['age', 20]]

    為了迭代一個對象,我們可以執(zhí)行以下操作:

    Object.keys(person).forEach((key) => {   console.log(`${key} is ${person[key]}`); }); // 使用 entries 獲取鍵和值 Object.entries(person).forEach(([key, value]) => {   console.log(`${key} is ${value}`); }); // name is 前端小智 // age is 20

    上述兩種方法都返回相同的結(jié)果,但 Object.entries 獲取鍵值對更容易。

    12.replaceAll 方法

    在 JS 中,要將所有出現(xiàn)的字符串替換為另一個字符串,我們需要使用如下所示的正則表達(dá)式:

    const str = 'Red-Green-Blue'; // 只規(guī)制第一次出現(xiàn)的 str.replace('-', ' '); // Red Green-Blue // 使用 RegEx 替換所有匹配項 str.replace(/-/g, ' '); // Red Green Blue

    但是在 ES12 中,一個名為 replaceAll 的新方法被添加到 String.prototype 中,它用另一個字符串值替換所有出現(xiàn)的字符串。

    str.replaceAll('-', ' '); // Red Green Blue

    13.數(shù)字分隔符

    可以使用下劃線作為數(shù)字分隔符,這樣可以方便地計算數(shù)字中0的個數(shù)。

    // 難以閱讀 const billion = 1000000000; // 易于閱讀 const readableBillion = 1000_000_000; console.log(readableBillion) //1000000000

    下劃線分隔符也可以用于BigInt數(shù)字,如下例所示

    const trillion = 1000_000_000_000n; console.log(trillion); // 1000000000000

    14.document.designMode

    與前端的JavaScript有關(guān),設(shè)計模式讓你可以編輯頁面上的任何內(nèi)容。只要打開瀏覽器控制臺,輸入以下內(nèi)容即可。

    document.designMode = 'on';

    15.邏輯賦值運算符

    邏輯賦值運算符是由邏輯運算符&&、||、??和賦值運算符=組合而成。

    const a = 1; const b = 2; a &&= b; console.log(a); // 2 // 上面等價于 a && (a = b); // 或者 if (a) {   a = b }

    檢查a的值是否為真,如果為真,那么更新a的值。使用邏輯或 ||操作符也可以做同樣的事情。

    const a = null; const b = 3; a ||= b; console.log(a); // 3 // 上面等價于 a || (a = b);

    使用空值合并操作符 ??:

    const a = null; const b = 3; a ??= b; console.log(a); // 3 // 上面等價于 if (a === null || a === undefined) {   a = b; }

    注意:??操作符只檢查 null 或 undefined 的值。

    贊(0)
    分享到: 更多 (0)
    網(wǎng)站地圖   滬ICP備18035694號-2    滬公網(wǎng)安備31011702889846號