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

f0fec82622d3e5491288e5e1f714168c.png

英文 | https://javascript.plainenglish.io/12-useful-javascript-snippets-for-everyday-problems-4f08ee1ab5e

翻译 | 杨小爱

在本文中,我将分享 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

总结

我真的希望您觉得这篇文章对您有所帮助,并且可以在您的开发过程中使用其中的一些片段。如果您也有很酷的 JavaScript 片段,请随时在评论并与其他开发人员分享它们。

最后,祝您编程快乐。

学习更多技能

请点击下方公众号

99eddc35b510f00267a3653cc062da37.gif

1db79e81188307f7d114440b0cedccf7.png

4a329084a0fff7b60d609ad3297e1d34.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值