ES13中实用的新JavaScript特性

102 阅读3分钟

1.从数组末尾查找元素

当我们希望从数组中找到满足一定条件的元素时,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})

image.png 查找到元素,查找时间用了73毫秒,这个用时算是很久了。

幸运的是,从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})

image.png

2.更容易为类设置私有变量成员

class Person{
    constructor(){
        this.age = 30;
        this.name = 'jia yi';
    }
    showInfo(key){
        console.log(this[key]);
    }
}
const p1 = new Person()
p1.showInfo('name') //jia yi;
p1.showInfo('age') //30;

现在通过以下方式,这种方式更加方便

class Person {  
   age = 30  
   name = 'jia yi'
   showInfo (key) {
   console.log(this[ key ])  
}}
const p1 = new Person()
p1.showInfo('name') //jia yi
p1.showInfo('age') // 30

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

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

class Person{
    constructor(name){
        this._ticket = 'app'
        this.name = 'name';
    }
    get ticket(){
        return this._ticket;
    }
    set ticket(ticket){
        this._ticket = ticket;
    }
    showMoney(){
        console.log(this._ticket);
    }
}
const p1 = new Person('jia yi');
console.log(p1._ticket); //app
console.log(p1.ticket) //app

p1._ticket = h5;
console.log(p1._ticket); //h5
console.log(p1.ticket) //h5

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

class Person{
 #ticket = 'app'
    constructor(name){
        this.name = 'name';
    }
    get ticket(){
        return this.#ticket;
    }
    set ticket(ticket){
        this.#ticket = ticket;
    }
    showMoney(){
        console.log(this.#ticket);
    }
}
const p1 = new Person('jia yi');
console.log(p1.ticket) //app
p1.ticket = 'h5';
console.log(p1.ticket)//h5
console.log(p1.#ticket) // Uncaught SyntaxError: Private field '#ticket

4.Object.hasOwn

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

   const Person = function(age){
       this.age = age;
   }
   Person.prototype.name = 'Li jia yi';
   const p1 = new Person(30);
   console.log('age' in p1) //true
   console.log('name' in p1) //true

hasOwnPeoperty方法返回一个布尔值,指示对象是否具有指定的属性作为其自身的属性

 const Person = function(age){
       this.age = age;
   }
   Person.prototype.name = 'Li jia yi';
   const p1 = new Person(30);
   console.log(p1.hasOwnProperty('age')) //true
   console.log(p1.hasOwnProperty('name')) //false

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

Object.create(null).hasOwnProperty('name') //Uncaught typeError

不用担心,我们可以使用Object.hasOwn来规避这两个问题,相比较Obj.hasOwnProperty也更加安全

let object = {age:30}
Object.hasOwn(object,'age') //true

let object2 = Object.create({ age: 24 })
Object.hasOwn(object2,'age') //false the 'age' attribute exists on prototype

let object3 = Object.create(null)
Object.hasOwn(object3, 'age') // false an object that does not inherit

5.at操作符

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

const array = [ 'li', 'jia', 'yi', 'wu', 'hao' ]
console.log(array[ 1 ], array[ 0 ]) // jia li

如果我们想获取数组的最后第N个元素,我们会怎么做呢?

const array = [ 'li', 'jia', 'yi', 'wu', 'hao' ]
const len = array.length
console.log(array[len - 1 ]) //hao
console.log(array[len - 2 ]) //wu
console.log(array[len - 3 ]) //yi

这看起来不是很优雅,我们试图寻找使用更加优雅的方式来做这件事,以后可以使用数组的at方法,它使您更像高级开发人员

const array = [ 'li', 'jia', 'yi', 'wu', 'hao' ]
console.log(array.at(-1)) // hao
console.log(array.at(-2)) // wu
console.log(array.at(-3)) // yi

6.可以在模块顶部使用await

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

const getUserInfo = ()=>{
    return new Promise((res)=>{
        setTimeout(()=>{
        res({
           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);

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

const getUserInfo = ()=>{
    return new Promise((res)=>{
        setTimeout(()=>{
        res({
           name:'fatfish'
          })
        },2000)
    })
}
  const userInfo = await getUserInfo();
  console.log('userInfo',userInfo)

image.png