• 12.【原创】ES6常用的新语法


    一、变量声明let、const

    /**
     * @变量声明
     */
    "use strict"
    // 1.变量越域
    {
        var a = 1;
        let b = 2;
    }
    console.log(a);// 1
    console.log(b);// b is not defined
    
    // 2.不可多次声明同一变量
    var x = 0;
    var x = 1;
    
    let y = 2;
    let y = 3;
    console.log(x);// Identifier 'y' has already been declared
    
    // 3.var变量提升
    console.log(m);
    var m = 10;// undefined
    console.log(n); // Cannot access 'n' before initialization
    let n = 10;
    
    // 4.常量const,必须初始化,且不可改值
    const k = 5;
    k = 6;// Assignment to constant variable.
    

      

    二、解构表达式

    /**
     * @解构表达式、字符串
     */
    "use strict"
    // 1.数组解构
    let arr = [1, 2, 3];
    let [a, b, c] = arr;
    console.log(a, b, c);// 1 2 3
    
    // 2.对象解构
    let person = {
        name: "nick",
        age: 27,
        sex: 1
    };
    
    let {name: abc, age: age1, sex } = person;
    console.log(abc, age1, sex);
    
    // 3.新增字符串方法
    let str = "hello.vue";
    // 开头
    console.log(str.startsWith("hello"));//true
    // 后缀
    console.log(str.endsWith(".vue"));//true
    // 包含
    console.log(str.includes("e"));//true
    console.log(str.includes("hello"));//true
    
    //4.1字符串模板
    let ss = `<div>
                   <span>hello world<span>
              </div>`;
    console.log(ss);// hello world
    // 4.2字符串插入变量和表达式。变量名写在 ${} 中,${} 中可以放入 JavaScript 表达式。
    let name = 'cici'; let age = 2;
    function fun()
    {
        return "这是一个函数"
    }
    
    let info = `我是${name},今年${age + 10}了, 我想说: ${fun()}`;
    console.log(info);

    三、函数优化

    /*
     * @函数
     */
    "use strict"
    // 1.箭头函数
    function say (name, cb) {
        cb(`I am ${name}`);
    }
    
    say('小胖', (res) => {
        console.log(res);
    });
    
    // 2.参数赋默认值
    let sum = (a, b = 1) =>
    {
        return a * b;
    }
    
    console.log(sum(9));// 9
    
    // 3.不定参数
    function show(...val)
    {
        for (let i = 0; i < val.length; i++)
        {
            console.log(val[i]);
        }
    }
    
    show(1, 2, 3);
    show('我', '爱', '你');
    
    // 4.箭头函数+解构
    const person = {
        name: 'tommy',
        weight: '100kg'
    }
    
    let sayHello = ({name}) => {
        console.log('hello~:' + name);
    }
    
    sayHello(person);// hello~:tommy

    四、对象优化

    /**
     * @对象
     */
    "use strict"
    // 1.新增方法
    var person = {
        name: "jack",
        age: 21,
        language: ['java', 'js', 'css']
    }
    
    console.log(Object.keys(person));// 非新增;[ 'name', 'age', 'language' ]
    console.log(Object.values(person));//["jack", 21, Array(3)]
    console.log(Object.entries(person));//[Array(2), Array(2), Array(2)]:把各个key对应值打成数组
    
    // 2.对象拷贝合并
    const target = { a: 1 };
    const source1 = { b: 2 };
    const source2 = { c: 3 };
    
    let mergeObj = Object.assign(target, source1, source2);// 合并
    let mergeObj2 = {...target, ...source1, ...source2};// 拷贝
    console.log(target);// {a:1,b:2,c:3}
    console.log(mergeObj);// {a:1,b:2,c:3}
    console.log(mergeObj2);// {a:1,b:2,c:3}
    
    // 3、声明对象简写
    const age = 23;
    const name = "张三";
    
    const person2 = { age, name }
    console.log(person2);// { age: 23, name: '张三' }
    
    // 4.对象的函数属性简写
    let person = {
        showName: function (name) { console.log('my name is:' + name) },
        showAge: (age) => { console.log('myage is:' + age) },
        showSex(sex) { console.log('I am a:' + sex) }
    }
    person.showName('nick');
    person.showAge(27);
    person.showSex('boy');

     四、数组

    // 1.map():接收一个函数,将原数组中的所有元素用这个函数处理后放入新数组返回。
    let arr = ['1', '20', '-5', '3'];
    arr = arr.map(item => item * 2);
    console.log(arr);// [ 2, 40, -10, 6 ]
    
    // 2.reduce()
    var numbers = [1, 2, 3, 4];
    // total:统计返回的值 num:元素
    function getSum(total, num)
    {
        return total + num;
    }
    
    console.log(numbers.reduce(getSum));// 10

    五、Promise

    // 1、Promise可以封装异步操作
    const promise = new Promise((resolve, reject) =>
    {
        //模拟发送http请求
        var request = require("request");
    
        //get请求
        request('http://www.baidu.com', function (error, response, body)
        {
            if (!error && response.statusCode == 200)
            {
                resolve(response.statusCode);
            }
            else
            {
                reject(response.statusCode);
            }
        });
    
    });
    
    let promise2 = promise.then((statusCode) =>
    {
        if (200 == statusCode)
        {
            return new Promise(function (resolve, reject)
            {
                resolve(statusCode);
            });
        }
        else
        {
            console.log('返回状态错误!');
        }
    
    }, function (error)
    {
        console.log('网络请求异常!');
    });
    
    promise2.then(function (body)
    {
        console.log('执行成功了!');
    }, function (error)
    {
        console.log('继续进入错误逻辑!'); // 继续进入错误逻辑!
    });
  • 相关阅读:
    Vue学习笔记
    用vue-cli3搭建vue项目
    Vue 封装可向左向右查看图片列表的组件
    css修改整个项目的滚动条样式
    Vue 可输入可下拉组件的封装
    es6 实现数组的操作
    JS 实现兼容IE浏览器报警提示声音
    SPRINGBOOT9--AOP的使用(本例展示统一处理Web请求日志)
    SPRINGBOOT8--log4j日志记录
    SPRINGBOOT7--使用@Async实现异步调用
  • 原文地址:https://www.cnblogs.com/Nick-Hu/p/13386603.html
Copyright © 2020-2023  润新知