资讯专栏INFORMATION COLUMN

项目中常用的ES6

Stardustsky / 786人阅读

摘要:看代码及注释就懂了把代码转换为代码解构赋值字符串反引号代替引号代替了正则表达式匹配数组展开符利用的实现对象对象属性有属性有值集合和添加元素,但是不会添加相同的元素,利用这个特性实现数组去重元素数量是否有指定元素删除元

看代码及注释就懂了

把ES6(es2015)代码转换为ES5代码

$ npm install -g babel-cli

$ npm install babel-preset-env --save

$ babel ./src/es6.js -w --out-file ./dist/es5.js --presets env

解构赋值
const breakfast = () => ["cake", "coffee", "apple"]
let [dessert, drink, fruit] = breakfast()
console.info(dessert, drink, fruit) // "cake" "coffee" "apple"
const breakfast = () => {
    return {
        dessert: "cake",
        drink: "coffee",
        fruit: "apple"
    }
}
let {dessert, drink, fruit} = breakfast()
console.info(dessert, drink, fruit) // "cake" "coffee" "apple"
字符串

反引号代替引号:`some content ${variable} some content`

str.includes()、str.startsWidth()、str.endsWith() 代替了正则表达式匹配

数组展开符
// 利用 Array 的 concat() 实现
let breakfast = ["cake", "coffee", "apple"]
let food = ["rice", ...breakfast]
console.info(...breakfast, food) // "cake" "coffee" "apple", ["rice", "cake", "coffee", "apple"]
对象
// 对象属性
let food = {}
let drink = "hot drink"
food[drink] = "milk"
console.log(food["hot drink"]) // "milk"
let food = {}
let drink = "hot drink"
food[drink] = "milk"

let dessert = "cake"
food.fruit = "banane"

let breakfast = Object.assign({}, {dessert}, food) // {dessert} 有属性有值
console.log(breakfast) // {dessert: "cake", hot drink: "milk", fruit: "banane"}
集合 Set 和 Map
let fruit = new Set(["apple", "banane", "orange"])
/* 添加元素,但是不会添加相同的元素,利用这个特性实现数组去重:[...new Set(arr)] */
fruit.add("pear")
/* 元素数量 */
console.log(fruit.size) // 4
/* 是否有指定元素 */
console.log(fruit.has("apple")) // true
/* 删除元素 */
fruit.delete("banana") 

console.log(fruit) // Set(4) {"apple", "banane", "orange", "pear"}
/* 遍历 */
fruit.forEach(item => {
    console.log(item)
})
/* 清空 */
fruit.clear()

console.log(fruit) // Set(0) {}
let food = new Map()
let fruit = {}, cook = function(){}, dessert = "甜点"
food.set(fruit, "apple")
food.set(cook, "knife")
food.set(dessert, "cake")

console.log(food, food.size) // Map(3) {{…} => "apple", ƒ => "knife", "甜点" => "cake"} 3

console.log(food.get(fruit)) // "apple"
console.log(food.get(dessert)) // "cake"

food.delete(dessert)
console.log(food.has(dessert)) // false

food.forEach((value, key) => {
    console.log(`${key} = ${value}`) // [object Object] = apple    function(){} = knife
})

food.clear()
console.log(food) // Map(0) {}
Generator
function* calc(num){
    yield num+1
    yield num-2
    yield num*3
    yield num/4
    return num
}
let cal = calc(4)
console.info(
    cal.next(), // {value: 5, done: false}
    cal.next(), // {value: 2, done: false}
    cal.next(), // {value: 12, done: false}
    cal.next(), // {value: 1, done: false}
    cal.next(), // {value: 4, done: true} 遍历完了后 done:true
    cal.next() // {value: undefined, done: true}
)
class Chef{
    constructor(food){
        this.food = food;
        this.dish = [];
    }
    get menu(){ // 不得有参数(Getter must not have any formal parameters.)
        console.log("getter 取值")
        console.log(this.dish)
        return this.dish
    }
    set menu(dish){ // 必须有一个参数(Setter must have exactly one formal parameter.)
        console.log("setter 存值")
        this.dish.push(dish)
    }
    cook(){
        console.log(this.food)
    }
}
let Gu = new Chef("vegetables");
Gu.cook() // "vegetables"
console.log(Gu.menu) // "get 取值" []

Gu.menu = "egg" // "setter 存值"
Gu.menu = "fish" // "setter 存值"

console.log(Gu.menu); // "getter 取值" ["egg", "fish"]
class Person {
    constructor(name, birth){
        this.name = name
        this.birth = birth
    }
    intro(){
        return `${this.name}的生日是${this.birth}`
    }
}

class One extends Person {
    constructor(name, birth){
        super(name, birth)
    }
}

let z = new Person("zz", "01-09")
let x = new One("xx", "01-09")

console.log(z.intro(), x.intro()) // "zz的生日是01-09" "xx的生日是01-09"
// 转化为ES5的代码大概就是
/* function Person(name, birth) {
    this.name = name;
    this.birth = birth;
}
Person.prototype.intro = function () {
    return this.name + "u7684u751Fu65E5u662F" + this.birth;
};
function One(name, birth) {
    Person.apply(this, arguments);
}
One.prototype = new Person();
var z = new Person("zz", "01-09");
var x = new One("xx", "01-09");

console.log(z.intro(), x.intro()); // "zz的生日是01-09" "xx的生日是01-09" */
Promise

回调地狱

function ajax(fn){
    setTimeout(()=>{
        console.log("执行业务")
        fn()
    },1000)
}
ajax(()=>{
    ajax(()=>{
        ajax(()=>{
            ajax(()=>{
                console.log("执行结束4")
            })
            console.log("执行结束3")
        })
        console.log("执行结束2")
    })
    console.log("执行结束1")
})
/*
    效果:
        1s: 执行业务 执行结束1
        2s:  执行业务 执行结束2
        3s: 执行业务 执行结束3
        4s:  执行业务 执行结束4
*/

Promise 这样写

function delay(word){
    return new Promise((reslove,reject) => {
        setTimeout(()=>{
            console.log("执行业务")
            reslove(word)
        },1000)
    })
}
delay("执行业务1")
    .then(word=>{
        console.log(word)
        return delay("执行业务2")
    })
    .then(word=>{
        console.log(word)
        return delay("执行业务3")
    })
    .then(word=>{
        console.log(word)
        return delay("执行业务4")
    })
    .then(word=>{
        console.log(word)
    })
    .catch()

async + await

function delay(word){
    return new Promise((reslove, reject) => {
        setTimeout(()=>{
            console.log("执行业务")
            reslove(word)
        },1000)
    })
}

const start = async () => {
    const word1 = await delay("执行业务1")
    console.log(word1)

    const word2 = await delay("执行业务2")
    console.log(word2)

    const word3 = await delay("执行业务3")
    console.log(word3)
    
    const word4 = await delay("执行业务4")
    console.log(word4)
}

start()

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/98664.html

相关文章

  • ES6-7

    摘要:的翻译文档由的维护很多人说,阮老师已经有一本关于的书了入门,觉得看看这本书就足够了。前端的异步解决方案之和异步编程模式在前端开发过程中,显得越来越重要。为了让编程更美好,我们就需要引入来降低异步编程的复杂性。 JavaScript Promise 迷你书(中文版) 超详细介绍promise的gitbook,看完再不会promise...... 本书的目的是以目前还在制定中的ECMASc...

    mudiyouyou 评论0 收藏0
  • ES6常用语法整合

    摘要:说到肯定是先介绍了,据阮一峰老师介绍到,是一个广泛使用的转码器,可以将代码转为代码,从而在现有环境执行。输出其他还有等可以查看阮一峰的入门 ES6也出来有一会时间了,他新增的语法糖也的确大大提高了开发者的效率,今天就总结一些自己用到最多的。 说到ES6肯定是先介绍Babel了,据阮一峰老师介绍到,Babel是一个广泛使用的转码器,可以将ES6代码转为ES5代码,从而在现有环境执行。这意...

    张迁 评论0 收藏0
  • React项目出现频率较高ES6语法

    摘要:学习过程中,发现无论是上的还是相关文档,语法都有大量的使用。如下使用语法来定义一个组件有几个注意点使用了的继承语法,关键字这里使用了上面说的语法方法名的简写,注意方法之间不加是构造函数,可以替代。内需要调用父类的构造函数即,否则就会报错。 学习React过程中,发现无论是github上的Demo还是React相关文档,ES6语法都有大量的使用。如果不了解一些ES6语法,很难学习下去。如...

    ZHAO_ 评论0 收藏0
  • 《从零构建前后分离web项目》:前端了解过关了吗?

    摘要:前端基础架构和硬核介绍技术栈的选择首先我们构建前端架构需要对前端生态圈有一切了解,并且最好带有一定的技术前瞻性,好的技术架构可能日后会方便的扩展,减少重构的次数,即使重构也不需要大动干戈,我通常选型技术栈会参考以下三点一提出自身业务的需求是 # 前端基础架构和硬核介绍 showImg(https://segmentfault.com/img/remote/146000001626972...

    lbool 评论0 收藏0
  • 《从零构建前后分离web项目》:前端了解过关了吗?

    摘要:前端基础架构和硬核介绍技术栈的选择首先我们构建前端架构需要对前端生态圈有一切了解,并且最好带有一定的技术前瞻性,好的技术架构可能日后会方便的扩展,减少重构的次数,即使重构也不需要大动干戈,我通常选型技术栈会参考以下三点一提出自身业务的需求是 # 前端基础架构和硬核介绍 showImg(https://segmentfault.com/img/remote/146000001626972...

    cgspine 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<