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() 方法可用于搜索数组以查找特定对象。
// 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、反转字符串
以下代码段可用于在不使用循环的情况下反转任何字符串。
// 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 语句,您可以使用单行方法来执行它。
// 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 中,有一种简单的方法可以从任何输入数组中去除重复项。当数组中有很多元素并且可能有一些重复项时,这非常方便。
以下代码段将展示如何使用 Set 数据类型来实现此目的
// 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、将字符串拆分为数组
如果您想将字符串拆分为数组,可以使用以下代码片段
// 7. Split String to Arrayconst randomString = "Software"const newArray = [...randomString]console.log(newArray) // ['S', 'o', 'f', 't', 'w', 'a', 'r', 'e']
8、捕获右键单击
如果使用 JavaScript 并希望在用户使用时捕获右键单击以执行某些代码。
// 8. Capture Right Click// only usable in HTML/JSwindow.oncontextmenu = () => {console.log("Right Click is Pressed!")}
9、遍历键和值
这个有用的片段可用于迭代字典数据的键(或值)。为此,您可以检索键/值并使用 forEach 函数。
// 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、智能数据过滤
使用 JavaScript 内置的 Filter 方法过滤您的数据。如果您的输入有大量数据并且您只需要输入数组中的特定数据,这很重要。
// 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、空合并运算符
空合并运算符 (??) 是一个逻辑运算符,当其左侧操作数为空或未定义时返回其右侧操作数,否则返回其左侧操作数。
// 11. Nullish coalescing operatorconst foo = null ?? 'default string';const baz = 0 ?? 42;console.log(foo); // default stringconsole.log(baz); // 0
12、错误处理
在编程中,开发过程中总会发生错误。为了避免您的程序崩溃,您可以使用 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
总结
我真的希望您觉得这篇文章对您有所帮助,并且可以在您的开发过程中使用其中的一些片段。如果您也有很酷的 JavaScript 片段,请随时在评论并与其他开发人员分享它们。
最后,祝您编程快乐。
学习更多技能
请点击下方公众号
![]()

