12 个解决日常问题的JavaScript 代码片段

12 个解决日常问题的JavaScript 代码片段

12 个有用的 JavaScript 片段,希望通过这些代码的学习,加快开发速度并节省时间!

1、破坏赋值

在 JavaScript 中,您可以使用析构方法将数组中的值解包并将它们分配给其他变量。

// 1. Destructive Assignment
const data = ["Paul", "too old", "Software Engineer"]
const [name, age, job_title] = data

console.log(name, age, job_title) // Paul too old Software Engineer

2、在Array中查找对象

JavaScript find() 方法可用于搜索数组以查找特定对象。

// 2. Find an object in Array
const 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 String
const reverse = (input) => {
    
    
    return input.split("").reverse().join("");
}

console.log(reverse("Paul Knulst")) // tslunK luaP
console.log(reverse("Medium is awesome")) // emosewa si muideM

4、带有占位符的模板文字

如果您使用模板文字,您可以借助 ${} 方法在字符串中包含变量。

// 4. Placeholder in Strings
let placeholder1 = "Engineer";
let placeholder2 = "Developer";

console.log(`I'm a Software ${
      
      placeholder1}`); // I'm a Software Engineer
console.log(`I'm a Software ${
      
      placeholder2}`); // I'm a Software Developer

5、单行if-else语句

对于 JavaScript 中的简单 if-else 语句,您可以使用单行方法来执行它。

// 5. One-Line if-else Statement

// normal
if (13 > 37) {
    
    
    console.log(true);
} else {
    
    
    console.log(false)
}
// One liner
13 > 37 ? console.log(true) : console.log(false)

6、摆脱重复

在 JavaScript 中,有一种简单的方法可以从任何输入数组中去除重复项。当数组中有很多元素并且可能有一些重复项时,这非常方便。

以下代码段将展示如何使用 Set 数据类型来实现此目的

// 6. Get Rid of Duplicates
function 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 Array
const 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/JS
window.oncontextmenu = () => {
    
    console.log("Right Click is Pressed!")}

9、遍历键和值

这个有用的片段可用于迭代字典数据的键(或值)。为此,您可以检索键/值并使用 forEach 函数。

// 9. Looping through Keys and Values
const programming_languages = {
    
    JavaScript: 1, Kotlin: 2, Python: 3};
Object.keys(programming_languages).forEach((key) => {
    
    
    console.log(key);
});
// JavaScript
// Kotlin
// Python
Object.values(programming_languages).forEach((key) => {
    
    
    console.log(key);
});
// 1
// 2
// 3

10、智能数据过滤

使用 JavaScript 内置的 Filter 方法过滤您的数据。如果您的输入有大量数据并且您只需要输入数组中的特定数据,这很重要。

// 10. Smart Data Filteration
const 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 operator
const foo = null ?? 'default string';
const baz = 0 ?? 42;

console.log(foo); // default string
console.log(baz); // 0

12、错误处理

在编程中,开发过程中总会发生错误。为了避免您的程序崩溃,您可以使用 try-catch 语句。这是每个编程语言中的一种众所周知的语法,用于捕获运行时错误。

// 12. Error Handling
function 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

- End -

*陆荣涛前端学习交流Q群858752519
加群备注:CSDN推荐
请添加图片描述

猜你喜欢

转载自blog.csdn.net/sdasadasds/article/details/125044946