发布于 2026-01-06 1 阅读
0

5个你必须知道的JavaScript技巧和窍门

5个你必须知道的JavaScript技巧和窍门

JavaScript 不断推出各种新颖有趣的功能,有时让人难以跟上。在本文中,我将分享一些实用技巧,帮助你快速掌握 JavaScript 的最新动态,并加深你的 JavaScript 知识。

1. 使用“Set”对象创建一个包含唯一值的数组

想象一下,你有一个数组,其中包含一些重复项,而你只想筛选出唯一的项。

你可以尝试编写一个映射过滤器来实现这个功能。或者,ES6 引入了Set 对象,只需一行代码即可解决这个问题。

const arrayWithUniqueItems = [...new Set([1, 2, 3, 3,])]
// [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

现在,这个例子使用的是整数,但你也可以使用字符串和浮点数!

想要更深入了解 Set 对象,请查看Claire-Parker Jones 的这篇文章

2. 缩短你的“if”语句

这可真是一个棘手的问题。

缩短“if”语句是简化代码的好方法。

但是,如果您需要编写更复杂的语句,则绝对应该选择第一种方案。

// Instead of using this                                      
if (iAmHungry) {
   bakeAnEgg()
}

// You can use this
if (iAmHungry) bakeAnEgg()

// Or this
iAmHungry? bakeAnEgg() : 0

Enter fullscreen mode Exit fullscreen mode

记住,代码的可读性和易用性比少写几行代码更重要。

3. 使用数组的长度属性缩短数组长度

缩短数组长度的一个好方法是重新定义其 length 属性。

let array = [0, 1, 2, 3, 4, 5, 6, 6, 8, 9]
array.length = 4

// Result: [0, 1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

但需要注意的是,这是一种破坏性地修改数组的方法。这意味着你会丢失数组中原有的所有其他值。

4. 使用扩展运算符合并对象

假设你想将多个对象合并成一个包含所有这些对象的对象。

扩展运算符(…)是实现此目的的好方法!

const obj1 = {'a': 1, 'b': 2}
const obj2 = {'c': 3}
const obj3 = {'d': 4}

// Combine them using the spread operator            
const objCombined = {...obj1, ...obj2, ...obj3}

// Result: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Enter fullscreen mode Exit fullscreen mode

使用此功能时需要注意的是,无论何时更新其中一个对象,合并后的对象都不会反映这些更改。

5. 使用 window.location 对象

JavaScript 可以使用 window.location 对象访问当前 URL。这很方便,但更酷的是,这个对象还包含 URL 的某些部分。

获取协议/主机/路径名/搜索等更多信息!

// JavaScript can access the current URL in parts. For this URL:
`https://thatsanegg.com/example/index.html?s=article`

window.location.protocol == `https:`
window.location.host == `thatsanegg.com`
window.location.pathname == `/example/index.html`
window.location.search == `?s=article`
Enter fullscreen mode Exit fullscreen mode

就这样!

感谢阅读,看看你学到了多少东西😄

本文最初发表于“That's an Egg”网站。

文章来源:https://dev.to/toktoktwan/5-must-know-javascript-tips-tricks-3pm7