ES6的基础知识(一)

发布时间:2019-08-09 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了ES6的基础知识(一)脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

github上面的demo

let&const

  • let不支持变量提升

     console.LOG(a); // 此处报错
     let a = "a";
    
  • let不能重复声明

     let a = "a";
     let a = "abc"; // 报错
    
  • let支持块级作用域

     if (true) {
       let a = "a";
     }
     console.log(a) // 报错
    
     for (let i = 0; i < 5; i++) {
       setTimeout(() => {
         console.log(i); // 0 1 2 3 4
       });
     }
    
  • const除了let的功能,还不能更改声明后的值,不过可以对声明的对象增加属性和更改属性值

     const PI = 3.14;
     PI = 3.141; // 报错
    
     const obj = {
       name: '小张'
     };
     obj.name = '小红';
     obj.age = 25;
    

解构

{
  // 数组解构赋值
  let [a, b, c] = [123, "abc", { name: "xiaohong" }];
  console.log(a, b, c); // 123 'abc' { name: 'xiaohong' }
}

{
  // 对象解构赋值
  let { name, age } = {
    name: "xiaohong",
    age: 25
  };

  console.log(name, age); // xiaohong 25
}

{
  // 对解构赋值的值自定义名称
  let { name: myname, age: myage } = {
    name: "xiaohong",
    age: 25
  };

  console.log(myname, myage); // xiaohong 25
}

{
  // 默认赋值,若是给age赋值将覆盖默认值
  let { name, age = 19 } = {
    name: "xiaohong"
  };

  console.log(name, age); // xiaohong 19
}

{
  // 省略赋值
  let [, , a] = [1, 2, 3];
  console.log(a); // 3
}

展开运算

  • 函数中使用展开运算符

     function test(a, b, c) {}
     let arr = [1, 2, 3];
     test(...arr);
  • 数组中函数中使用展开运算符

     let [a, b, ...c] = [1, 2, 3, 4, 5];
     console.log(a, b, c); // 1 2 [ 3, 4, 5 ]
    
     let arr1 = [1, 2, 3];
     let arr2 = [...arr1, 4, 5];
     console.log(arr2); // [ 1, 2, 3, 4, 5 ]
  • 数组变量转成数组

    function test(a, b, c) {
       console.log([...arguments]);
     }
     test(1, 2, 4); // [1 2 4]
    

字符串

  • 模板字符串:在这之前字符串拼接用+号来完成,现在用``和S{}即可代替字符串的拼接

     let name = 'xiaohong', age = 25;
     let str = `我叫:${name},今年${age}岁了`;
     console.log(str); // 我叫:xiaohong,今年25岁了   
    
    {
     // 自定义模板字符串的返回值
     let name = "xiaohong",
       age = 25;
     // ...rest作为参数只是放在最后
     function desc(string, ...rest) {
       let str = "";
       for (let i = 0, len = rest.length; i < len; i++) {
         str += string[i] + rest[i];
       }
       str += string[string.length - 1];
       return str.toLocaleUpperCase();
     }
     let str = desc`我叫:${name},今年${age}岁了`;
     console.log(str); // 我叫:XIAOHONG,今年25岁了
    }
  • 判断字符串以某个字符串开头

     let str = "hello world!";
     console.log(str.startsWith('h')); // true
  • 判断字符串以某个字符串结尾

     let str = "hello world!";
     console.log(str.endsWith('!')); // true
  • 判断字符创是否包含某个字符串

     let str = "hello world!";
     console.log(str.includes('hello')); // true
  • 将字符串重复生成

     let str = "hello world!";
     console.log(str.repeat(3)); // hello world!hello world!hello world!   

脚本宝典总结

以上是脚本宝典为你收集整理的ES6的基础知识(一)全部内容,希望文章能够帮你解决ES6的基础知识(一)所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。