分享 6 个关于ES13 中非常实用的新特性

948fe4fde7ef3a7eac30acf27960eed3.jpeg

英文 | https://javascript.plainenglish.io/6-amazing-and-useful-new-javascript-features-in-es13-b0719dfa0541

1. at

当我们想要获取数组的第 N 个元素时,我们通常使用 [] 来获取。

const array = [ 'fatfish', 'medium', 'blog', 'fat', 'fish' ]


console.log(array[ 1 ], array[ 0 ]) // medium fatfish

哦,这似乎不是什么稀罕事。但是请朋友们帮我回忆一下,如果我们想得到数组的最后第N个元素,我们会怎么做呢?

const array = [ 'fatfish', 'medium', 'blog', 'fat', 'fish' ]
const len = array.length


console.log(array[ len - 1 ]) // fish
console.log(array[ len - 2 ]) // fat
console.log(array[ len - 3 ]) // blog

这看起来很难看,我们应该寻求一种更优雅的方式来做这件事。是的,以后请使用数组的at方法!

它使您看起来像高级开发人员。

const array = [ 'fatfish', 'medium', 'blog', 'fat', 'fish' ]


console.log(array.at(-1)) // fish
console.log(array.at(-2)) // fat
console.log(array.at(-3)) // blog

2.Object.hasOwn

是的,通常有两种方式,它们有什么区别呢?

  • 对象中的“名称”

  • obj.hasOwnProperty('名称')

“in”运算符

如果指定属性在指定对象或其原型链中,则 in 运算符返回 true。

const Person = function (age) {
  this.age = age
}


Person.prototype.name = 'fatfish'


const p1 = new Person(24)


console.log('age' in p1) // true 
console.log('name' in p1) // true  pay attention here

obj.hasOwnProperty

hasOwnProperty 方法返回一个布尔值,指示对象是否具有指定的属性作为其自身的属性(而不是继承它)。

使用上面相同的例子

const Person = function (age) {
  this.age = age
}


Person.prototype.name = 'fatfish'


const p1 = new Person(24)


console.log(p1.hasOwnProperty('age')) // true 
console.log(p1.hasOwnProperty('name')) // fasle  pay attention here

也许“obj.hasOwnProperty”已经可以过滤掉原型链上的属性,但在某些情况下并不安全,会导致程序失败。

Object.create(null).hasOwnProperty('name')
// Uncaught TypeError: Object.create(...).hasOwnProperty is not a function

Object.hasOwn

不用担心,我们可以使用“Object.hasOwn”来规避这两个问题,比“obj.hasOwnProperty”方法更方便也更安全。

let object = { age: 24 }


Object.hasOwn(object, 'age') // true


let object2 = Object.create({ age: 24 })


Object.hasOwn(object2, 'age') // false  The 'age' attribute exists on the prototype


let object3 = Object.create(null)


Object.hasOwn(object3, 'age') // false an object that does not inherit from "Object.prototype"

3.在模块的顶层使用“await”

来自 mdn 的 await 操作符用于等待一个 Promise 并获取它的 fulfillment 值。

const getUserInfo = () => {
  return new Promise((rs) => {
    setTimeout(() => {
      rs({
        name: 'fatfish'
      })
    }, 2000)
  })
}
// If you want to use await, you must use the async function.
const fetch = async () => {
  const userInfo = await getUserInfo()
  console.log('userInfo', userInfo)
}


fetch()
// SyntaxError: await is only valid in async functions
const userInfo = await getUserInfo()
console.log('userInfo', userInfo)

3ac9552c29b8c2ddf8746b350afd7a4d.png

事实上,在 ES13 之后,我们可以在模块的顶层使用 await,这对于开发者来说是一个非常令人高兴的新特性。那太棒了。

const getUserInfo = () => {
  return new Promise((rs) => {
    setTimeout(() => {
      rs({
        name: 'fatfish'
      })
    }, 2000)
  })
}


const userInfo = await getUserInfo()
console.log('userInfo', userInfo)

3e94f21e616840f022a45c7fffbdc842.png

4.使用“#”声明私有属性

以前我们用“_”来表示私有属性,但是不安全,仍然有可能被外部修改。

class Person {
  constructor (name) {
    this._money = 1
    this.name = name
  }


  get money () {
    return this._money
  }


  set money (money) {
    this._money = money
  }


  showMoney () {
    console.log(this._money)
  }
}


const p1 = new Person('fatfish')


console.log(p1.money) // 1
console.log(p1._money) // 1


p1._money = 2 // Modify private property _money from outside


console.log(p1.money) // 2


console.log(p1._money) // 2

我们可以使用“#”来实现真正安全的私有属性

class Person {
  #money=1


  constructor (name) {
    this.name = name
  }


  get money () {
    return this.#money
  }


  set money (money) {
    this.#money = money
  }


  showMoney () {
    console.log(this.#money)
  }
}


const p1 = new Person('fatfish')


console.log(p1.money) // 1


// p1.#money = 2 // We cannot modify #money in this way
p1.money = 2


console.log(p1.money) // 2


console.log(p1.#money) // Uncaught SyntaxError: Private field '#money' must be declared in an enclosing class

5. 更容易为类设置成员变量

除了通过“#”为类设置私有属性外,我们还可以通过一种新的方式设置类的成员变量。

class Person {
  constructor () {
    this.age = 1000
    this.name = 'fatfish'
  }


  showInfo (key) {
    console.log(this[ key ])
  }
}


const p1 = new Person()


p1.showInfo('name') // fatfish
p1.showInfo('age') // 1000

现在你可以使用下面的方式,使用起来确实更加方便。

class Person {
  age = 1000
  name = 'fatfish'


  showInfo (key) {
    console.log(this[ key ])
  }
}


const p1 = new Person()


p1.showInfo('name') // fatfish
p1.showInfo('age') // 1000

6.从数组末尾查找元素

当我们想从数组中找到满足一定条件的元素时,find 和 findIndex 都是不错的选择。

const array = Array(10000000).fill(1)


array.push(2)


const d1 = Date.now()
const el = array.find((el) => el >= 2)
const d2 = Date.now()


console.log({ el, time: d2 - d1 })

9e64a7019cb8aeb29df54718cdcb39b9.png

得到2,查找时间用了84毫秒,这是一个很恐怖的数字,而且耗时太长了。

幸运的是,从 ES13 开始,如果你之前指定目标元素更靠近尾部,使用 findLast 将大大减少其查找时间。

const array = Array(10000000).fill(1)


array.push(2)


const d1 = Date.now()
const el = array.findLast((el) => el >= 2)
const d2 = Date.now()


console.log({ el, time: d2 - d1 })

d85ea0904878cc7ce9fbf2a4cd0e7274.png

总结

学习更多技能

请点击下方公众号

a4ed2874d14ba976f234193f1ea23c42.gif

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值