12 個解決日常問題的JavaScript 代碼片段

// 1. Destructive Assignmentconst data = ["Paul", "too old", "Software Engineer"]const [name, age, job_title] = dataconsole.log(name, age, job_title) // Paul too old Software Engineer
2、在Array中查找對象
JavaScript find() 方法可用于搜索數(shù)組以查找特定對象。
// 2. Find an object in Arrayconst employess = [{name: "Paul", job_title: "Software Engineer"},{name: "Peter", job_title: "Web Developer"},{name: "Harald", job_title: "Screen Designer"},]let sen = employess.find(data => data.job_title === "Software Engineer")console.log(sen) // { name: 'Paul', job_title: 'Software Engineer' }
3、反轉字符串
以下代碼段可用于在不使用循環(huán)的情況下反轉任何字符串。
// 3. Reverse a Stringconst reverse = (input) => {return input.split("").reverse().join("");}console.log(reverse("Paul Knulst")) // tslunK luaPconsole.log(reverse("Medium is awesome")) // emosewa si muideM
4、帶有占位符的模板文字
如果您使用模板文字,您可以借助 ${} 方法在字符串中包含變量。
// 4. Placeholder in Stringslet placeholder1 = "Engineer";let placeholder2 = "Developer";console.log(`I'm a Software ${placeholder1}`); // I'm a Software Engineerconsole.log(`I'm a Software ${placeholder2}`); // I'm a Software Developer
5、單行 if-else 語句
對于 JavaScript 中的簡單 if-else 語句,您可以使用單行方法來執(zhí)行它。
// 5. One-Line if-else Statement// normalif (13 > 37) {console.log(true);} else {console.log(false)}// One liner13 > 37 ? console.log(true) : console.log(false)
6、擺脫重復
在 JavaScript 中,有一種簡單的方法可以從任何輸入數(shù)組中去除重復項。當數(shù)組中有很多元素并且可能有一些重復項時,這非常方便。
以下代碼段將展示如何使用 Set 數(shù)據(jù)類型來實現(xiàn)此目的
// 6. Get Rid of Duplicatesfunction removeDuplicates(array) {return [...new Set(array)];}const uniqueStr = removeDuplicates(["Paul", "John", "Harald", "Paul", "John"])const uniqueNr = removeDuplicates([1, 1, 2, 2, 3, 3, 4, 5, 6, 7, 7, 7, 9])console.log(uniqueStr) // [ 'Paul', 'John', 'Harald' ]console.log(uniqueNr) // [1, 2, 3, 4, 5, 6, 7, 9]
7、將字符串拆分為數(shù)組
如果您想將字符串拆分為數(shù)組,可以使用以下代碼片段
// 7. Split String to Arrayconst randomString = "Software"const newArray = [...randomString]console.log(newArray) // ['S', 'o', 'f', 't', 'w', 'a', 'r', 'e']
8、捕獲右鍵單擊
如果使用 JavaScript 并希望在用戶使用時捕獲右鍵單擊以執(zhí)行某些代碼。
// 8. Capture Right Click// only usable in HTML/JSwindow.oncontextmenu = () => {console.log("Right Click is Pressed!")}
9、遍歷鍵和值
這個有用的片段可用于迭代字典數(shù)據(jù)的鍵(或值)。為此,您可以檢索鍵/值并使用 forEach 函數(shù)。
// 9. Looping through Keys and Valuesconst programming_languages = {JavaScript: 1, Kotlin: 2, Python: 3};Object.keys(programming_languages).forEach((key) => {console.log(key);});// JavaScript// Kotlin// PythonObject.values(programming_languages).forEach((key) => {console.log(key);});// 1// 2// 3
10、智能數(shù)據(jù)過濾
使用 JavaScript 內置的 Filter 方法過濾您的數(shù)據(jù)。如果您的輸入有大量數(shù)據(jù)并且您只需要輸入數(shù)組中的特定數(shù)據(jù),這很重要。
// 10. Smart Data Filterationconst jobs = ["Frontend Developer", "Backend Developer", "Data Scientist", "Teacher"]const filtered_jobs1 = jobs.filter(data => data.length < 10)const filtered_jobs2 = jobs.filter(data => data.includes("Developer"))console.log(filtered_jobs1) // [ 'Teacher' ]console.log(filtered_jobs2) // [ 'Frontend Developer', 'Backend Developer' ]
11、空合并運算符
空合并運算符 (??) 是一個邏輯運算符,當其左側操作數(shù)為空或未定義時返回其右側操作數(shù),否則返回其左側操作數(shù)。
// 11. Nullish coalescing operatorconst foo = null ?? 'default string';const baz = 0 ?? 42;console.log(foo); // default stringconsole.log(baz); // 0
12、錯誤處理
在編程中,開發(fā)過程中總會發(fā)生錯誤。為了避免您的程序崩潰,您可以使用 try-catch 語句。這是每個編程語言中的一種眾所周知的語法,用于捕獲運行時錯誤。
// 12. Error Handlingfunction getRectArea(width, height) {if (isNaN(width) || isNaN(height)) {throw 'Parameter is not a number!';}}try {getRectArea(3, "A")} catch (err) {console.log(`There was an error: ${err}`)} finally {console.log("This code block is executed regardless of try/catch results")}// Output:// There was an error: Parameter is not a number!// This code block is executed regardless of try/catch results
總結
我真的希望您覺得這篇文章對您有所幫助,并且可以在您的開發(fā)過程中使用其中的一些片段。如果您也有很酷的 JavaScript 片段,請隨時在評論并與其他開發(fā)人員分享它們。
最后,祝您編程快樂。
學習更多技能
請點擊下方公眾號
![]()

