這篇文章要為大家分享一些經常在專案中使用一些技巧,JavaScript 有很多很酷的特性,大多數初學者和中級開發人員都不知道。希望對大家有幫助。
1. 有條件地在物件上新增屬性
我們可以使用展開運算符號(. ..)來有條件地快速地向JS 物件添加屬性。
const condition = true; const person = { id: 1, name: 'John Doe', ...(condition && { age: 16 }), };
如果每個運算元的值都為 true,則 && 運算子傳回最後一個求值運算式。因此傳回一個物件{age: 16},然後將其擴展為person物件的一部分。
如果condition 為false,JavaScript 會做這樣的事情:
const person = { id: 1, name: '前端小智', ...(false), }; // 展开 `false` 对对象没有影响 console.log(person); // { id: 1, name: 'John Doe' }
2.檢查屬性是否存在物件中
可以使用in 關鍵字來檢查JavaScript 物件中是否存在某個屬性。
const person = { name: '前端小智', salary: 1000 }; console.log('salary' in person); // true console.log('age' in person); // false
3.物件中的動態屬性名稱
#使用動態鍵設定物件屬性很簡單。只要使用['key name']來新增屬性:
const dynamic = 'flavour'; var item = { name: '前端小智', [dynamic]: '巧克力' } console.log(item); // { name: '前端小智', flavour: '巧克力' }
同樣的技巧也可用來使用動態鍵引用物件屬性:
const keyName = 'name'; console.log(item[keyName]); // returns '前端小智'
4. 使用動態鍵進行物件解構
我們知道在物件解構時,可以使用: 來對解構的屬性進行重新命名。但,你是否知道鍵名是動態的時,也可以解構物件的屬性?
const person = { id: 1, name: '前端小智' }; const { name: personName } = person; console.log(personName); // '前端小智'
現在,我們用動態鍵來解構屬性:
const templates = { 'hello': 'Hello there', 'bye': 'Good bye' }; const templateName = 'bye'; const { [templateName]: template } = templates; console.log(template); // Good bye
#5. 空值合併?? 運算子
當我們想要檢查一個變數是否為null 或undefined 時,??運算子很有用。當它的左側操作數為null 或 undefined時,它會傳回右側的操作數,否則傳回其左側的操作數。
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 中被認為是假的,但它不是null的或undefined的。你可能認為我們可以用||算子但這兩者之間是有區別的
你可能認為我們可以在這裡使用 || 操作符,但這兩者之間是有區別的。
const cannotBeZero = 0 || 5; console.log(cannotBeZero); // 5 const canBeZero = 0 ?? 5; console.log(canBeZero); // 0
6.可選鏈?.
#我們是不是常常遇到這樣的錯誤: TypeError: Cannot read property 'foo' of null。這對每個毅開發人員來說都是一個煩人的問題。引入可選鏈就是為了解決這個問題。一起來看看:
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
也可以使用以下函數可選鏈:
const person = { firstName: '前端', lastName: '小智', printName: function () { return `${this.firstName} ${this.lastName}`; }, }; console.log(person.printName()); // '前端 小智' console.log(persone.doesNotExist?.()); // undefined
7. 使用!! 運算子
!! 運算子可用來將表達式的結果快速轉換為布林值(true或false):
const greeting = 'Hello there!'; console.log(!!greeting) // true const noGreeting = ''; console.log(!!noGreeting); // false
8. 字串和整數轉換
#使用運算符將字串快速轉換為數字:
const stringNumer = '123'; console.log(+stringNumer); //123 console.log(typeof +stringNumer); //'number'
要將數字快速轉換為字串,也可以使用操作符,後面跟著一個空字串:
const myString = 25 + ''; console.log(myString); //'25' console.log(typeof myString); //'string'
這些型別轉換非常方便,但它們的清晰度和程式碼可讀性較差。所以實際開發,需要慎重的選擇使用。
9. 檢查陣列中的假值
#大家應該都用過陣列方法: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
以下是它的工作原理。我們知道這些陣列方法接受一個回呼函數,所以我們傳遞 Boolean 作為回呼函數。 Boolean 函數本身接受一個參數,並根據參數的真實性傳回 true 或 false。所以:
myArray.filter(val => Boolean(val));
等價於:
myArray.filter(Boolean);
10. 扁平化陣列
在原型Array 上有一個方法flat,可以從一個陣列的陣列中製作一個單一的陣列。
const myArray = [{ id: 1 }, [{ id: 2 }], [{ id: 3 }]]; const flattedArray = myArray.flat(); //[ { id: 1 }, { id: 2 }, { id: 3 } ]
你也可以定義一個深度級別,指定一個嵌套的數組結構應該被扁平化的深度。例如:
const arr = [0, 1, 2, [[[3, 4]]]]; console.log(arr.flat(2)); // returns [0, 1, 2, [3,4]]
11.Object.entries
#大多數開發人員使用 Object.keys 方法來迭代物件。此方法僅傳回物件鍵的數組,而不傳回值。我們可以使用 Object.entries 來取得鍵和值。
const person = { name: '前端小智', age: 20 }; Object.keys(person); // ['name', 'age'] Object.entries(data); // [['name', '前端小智'], ['age', 20]]
為了迭代一個對象,我們可以執行以下操作:
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
上述兩種方法都返回相同的結果,但 Object.entries 取得鍵值對更容易。
12.replaceAll 方法
#在JS 中,要將所有出現的字串替換為另一個字串,我們需要使用如下所示的正規表示式:
const str = 'Red-Green-Blue'; // 只规制第一次出现的 str.replace('-', ' '); // Red Green-Blue // 使用 RegEx 替换所有匹配项 str.replace(/\-/g, ' '); // Red Green Blue
但是在ES12 中,一個名為replaceAll 的新方法被加入到String.prototype 中,它用另一個字串值取代所有出現的字串。
str.replaceAll('-', ' '); // Red Green Blue
13.數字分隔符號
#可以使用底線作為數字分隔符,這樣可以方便計算數字中0的個數。
// 难以阅读 const billion = 1000000000; // 易于阅读 const readableBillion = 1000_000_000; console.log(readableBillion) //1000000000
下划线分隔符也可以用于BigInt数字,如下例所示
const trillion = 1000_000_000_000n; console.log(trillion); // 1000000000000
14.document.designMode
与前端的JavaScript有关,设计模式让你可以编辑页面上的任何内容。只要打开浏览器控制台,输入以下内容即可。
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 的值。
【相关推荐:javascript学习教程】
以上是總結15個JavaScript開發技巧(整理分享)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

No,youshouldn'tusemultipleIDsinthesameDOM.1)IDsmustbeuniqueperHTMLspecification,andusingduplicatescancauseinconsistentbrowserbehavior.2)Useclassesforstylingmultipleelements,attributeselectorsfortargetingbyattributes,anddescendantselectorsforstructure

html5aimstoenhancewebcapabilities,Makeitmoredynamic,互動,可及可訪問。 1)ITSupportsMultimediaElementsLikeAnd,消除innewingtheneedtheneedtheneedforplugins.2)SemanticeLelelemeneLementelementsimproveaCceccessibility inmproveAccessibility andcoderabilitile andcoderability.3)emply.3)lighteppoperable popperappoperable -poseive weepivewebappll

html5aimstoenhancewebdevelopmentanduserexperiencethroughsemantstructure,多媒體綜合和performanceimprovements.1)SemanticeLementLike like,和ImproVereAdiability and ImproVereAdabilityActibility.2)and tagsallowsemlessallowseamelesseamlessallowseamelesseamlesseamelesseamemelessmultimedimeDiaiaembediiaembedplugins.3)。 3)3)

html5isnotinerysecure,butitsfeaturescanleadtosecurityrisksifmissusedorimproperlyimplempled.1)usethesand andboxattributeIniframestoconoconoconoContoContoContoContoContoconToconToconToconToconToconTedContDedContentContentPrenerabilnerabilityLikeClickLickLickLickjAckJackJacking.2)

HTML5aimedtoenhancewebdevelopmentbyintroducingsemanticelements,nativemultimediasupport,improvedformelements,andofflinecapabilities,contrastingwiththelimitationsofHTML4andXHTML.1)Itintroducedsemantictagslike,,,improvingstructureandSEO.2)Nativeaudioand

使用ID選擇器在CSS中並非固有地不好,但應謹慎使用。 1)ID選擇器適用於唯一元素或JavaScript鉤子。 2)對於一般樣式,應使用類選擇器,因為它們更靈活和可維護。通過平衡ID和類的使用,可以實現更robust和efficient的CSS架構。

html5'sgoalsin2024focusonrefinement和optimization,notNewFeatures.1)增強performanceandeffipedroptimizedRendering.2)inviveAccessibilitywithRefinedwithRefinedTributesAndEllements.3)explityconcerns,尤其是withercercern.4.4)

html5aimedtotoimprovewebdevelopmentInfourKeyAreas:1)多中心供應,2)語義結構,3)formcapabilities.1)offlineandstorageoptions.1)html5intoryements html5introctosements introdements and toctosements and toctosements,簡化了inifyingmediaembedingmediabbeddingingandenhangingusexperience.2)newsements.2)


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。