利用这些技巧提升你的 JS 技能 #2

2025-05-24

利用这些技巧提升你的 JS 技能 #2

在本文中我将与您分享一些有关 JS 的新闻技巧,可以提高您的技能!

不要用来delete删除属性

delete从对象中删除属性是非常糟糕的(性能差),而且会产生很多副作用

但是如果您需要删除某个属性,您应该怎么做?

您需要使用函数式方法,创建一个不包含此属性的新对象。您可以使用类似这样的函数来实现这一点 👇

const removeProperty = (target, propertyToRemove) => {
    // We split the property to remove from the target in another object
    const { [propertyToRemove]: _, ...newTarget } = target
    return newTarget
}

const toto = { a: 55, b: 66 }
const totoWithoutB = removeProperty(toto, 'b') // { a: 55 }
Enter fullscreen mode Exit fullscreen mode

一个非常简单的片段将对你有很大帮助!

仅当属性存在时才向对象添加属性

有时我们需要为对象添加一个已定义的属性。我们可以像这样:

const toto = { name: 'toto' }
const other = { other: 'other' }
// The condition is not important
const condition = true

if (condition) {
   other.name = toto.name 
}
Enter fullscreen mode Exit fullscreen mode

❌ 无论如何,这不是很好的代码……

✅ 你可以使用更优雅的东西!👇

// The condition is not important
const condition = true

const other = {
   other: 'other',
   ...condition && { name: 'toto' }
}
Enter fullscreen mode Exit fullscreen mode

有关布尔扩展运算符的更多解释:https://dev.to/codeoz/comment/1ib4g

如果条件为真,则将属性添加到对象中(这要归功于&&运算符)

我也可以这样做👇

// The condition is not important
const condition = true
const toto = { name: 'toto' }

const other = {
   other: 'other',
   ...condition && toto
}
Enter fullscreen mode Exit fullscreen mode

使用模板字符串

当我们学习 JavaScript 中的字符串并需要将它们与变量连接起来时,我们会编写类似这样的代码👇

const toto = 'toto'
const message = 'hello from ' + toto + '!' // hello from toto!
Enter fullscreen mode Exit fullscreen mode

❌如果添加其他变量和字符串,它可能会变成垃圾!

您可以使用模板文字字符串

您只需用反引号替换单引号或双引号即可。

并将所有变量包装起来${variable}

const toto = 'toto'
const message = `hello from ${toto}!` // hello from toto!
Enter fullscreen mode Exit fullscreen mode

短路条件

如果你必须在条件为真时执行某个函数,例如👇

if(condition){
    toto()
}
Enter fullscreen mode Exit fullscreen mode

你可以像👇一样使用短路

condition && toto()
Enter fullscreen mode Exit fullscreen mode

由于&&(AND) 运算符,如果条件为真,它将执行toto函数

设置变量的默认值

如果需要为变量设置默认值

let toto

console.log(toto) //undefined

toto = toto ?? 'default value'

console.log(toto) //default value

toto = toto ?? 'new value'

console.log(toto) //default value
Enter fullscreen mode Exit fullscreen mode

得益于??(Nullish 合并)运算符,如果第一个值未定义或为空,它将在(??)之后分配默认值!

使用控制台计时器

例如,如果你需要知道某个函数的执行时间,可以使用控制台计时器。它会非常快速地返回函数执行前后的时间!

console.time()
for (i = 0; i < 100000; i++) {
  // some code
}
console.timeEnd() // x ms
Enter fullscreen mode Exit fullscreen mode

我希望你喜欢这篇文章!

🎁 如果您在TwitterUnderrated skills in javascript, make the difference上关注我并给我点赞,即可免费获得我的新书😁

或者在这里获取

🇫🇷🥖 对于法国开发者,你可以查看我的YoutubeChannel

🎁我的新闻通讯

☕️ 你可以支持我的作品🙏

🏃‍♂️ 你可以关注我 👇

🕊 推特:https://twitter.com/code__oz

👨‍💻 Github:https://github.com/Code-Oz

你也可以标记🔖这篇文章!

文章来源:https://dev.to/codeoz/improve-your-js-skills-with-theses-tips-2-3bg2
PREV
用这些技巧提高你的 JS 技能 #1
NEXT
我如何提高我的 Typescript 技能 #1:Typeguard 和 Type Utils