ES6(1)

205 阅读6分钟

let和const

let

//1.let没有声明变量提升
console.log(a);//Cannot access 'a' before initialization
let a = 10;

//2.是一个块作用域
if (1 === 1) {
    let b = 10;
}
console.log(b);//b is not defined

//3.不能重复声明
let a = 1;
let a = 10;
console.log(a);//Identifier 'a' has already been declared

const

//const 声明变量 一旦被声明 无法修改 符合let的3条规则
const max = 30;
max = 40;
console.log(max);// Assignment to constant variable.
//可以修改const声明的对象中的属性
const person = {
    name: 'qaq'
}
person.name = 'aba';
console.log(person);//{name: "aba"}

//但不能用这种方式修改
const person = {
    name: 'qaq'
}
person = {
    age: 'qaq'
}
console.log(person);//Assignment to constant variable

作用:

  1. for循环例子
  2. 不会污染全局变量(声明的变量如果与window挂载的全局属性相重合,不会修改该属性)
  3. 一般情况下使用const,如果变量需要修改则用let

模板字符串

模板字符串:使用tab键上面的反引号``,插入变量时使用${}

let name = 'qaq';
let a = `name:${name}`;//这里不是'' 是``
console.log(a);//name:qaq

强大的函数

函数的默认值、剩余参数

默认值

    //默认值可以直接写在形参里
    function add(a = 10, b = 20) {
      return a + b;
    }
    console.log(add());//30
    console.log(add(50, 50));//100
    
    //默认的表达式可以是一个函数
    function add(a, b = getVal(5)) {
      return a + b;
    }

    function getVal(val) {
      return val + 5;
    }
    console.log(add(10));//20

剩余参数

    //ES5写法
    function pick(obj) {
      let result = Object.create(null);
      for (let i = 1; i < arguments.length; i++) {
        result[arguments[i]] = obj[arguments[i]];
      }
      return result;
    }
    let book = {
      title: 'es6',
      author: 'mjj',
      year: 2020
    }
    let bookData = pick(book, 'author', 'year');
    let bookData1 = pick(book, 'author', 'year', 'title');
    console.log(bookData);//{author: "mjj", year: 2020}
    console.log(bookData1);//{author: "mjj", year: 2020, title: "es6"}
    
    //es6写法
    //剩余参数:由三个点...和一个紧跟着的具名参数指定 如...keys
    function pick(obj, ...keys) {
      //解决了arguments问题
      let result = Object.create(null);
      for (let i = 0; i < keys.length; i++) {
        result[keys[i]] = obj[keys[i]];
      }
      return result;
    }
    let book = {
      title: 'es6',
      author: 'mjj',
      year: 2020
    }
    let bookData = pick(book, 'author', 'year');
    console.log(bookData);//{author: "mjj", year: 2020}

方便理解

//主要解决arguments问题
function checkArgs(...args){
    console.log(args);//(3) ["a", "b", "c"]
    console.log(arguments);
    //Arguments(3) ["a", "b", "c", callee: (...), Symbol(Symbol.iterator): ƒ]
}
checkArgs('a','b','c');

扩展运算符、箭头函数

扩展运算符:将一个数组分割,并将各个项作为分离的参数传给函数

    //处理数组中最大值
    const arr = [12, 12, 34, 654, 65, 23, 54];
    console.log(Math.max.apply(null, arr));//654
    //es6扩展运算符
    const arr = [12, 12, 34, 654, 65, 23, 54];
    console.log(Math.max(...arr));//654

箭头函数 使用=>来定义 function(){}

    let add = function(a,b){
      return a+b;
    }

等同于

    let add = (a,b) => {
      return a+b;
    }

只有一个形参可以省略括号 如只有一个形参a

    let add = a => {
      return a+10;
    }

第三段代码更简便写法

    let add = a => (a+10);

如果第三段代码函数里为return a 则可以这么写

    let add = a => a;
注意事项:
  1. 如果形参为空一定要加上小括号
  2. 箭头函数没有this指向箭头函数内部this值只能通过查找作用域链来确定。一旦使用箭头函数,当前就不存在作用域链
  3. 使用箭头函数后 不存在arguments属性
  4. 箭头函数不能使用new关键字来实例化对象

解构赋值

    //解构赋值是对赋值运算符的一种扩展
    //它针对数组和对象来进行操作
    let Person = {
      name: 'qaq',
      age: '20'
    }
    let {name, age} = Person;
    console.log(name, age);//qaq,20
    //剩余运算符
    let node = {
      a: 'aaa',
      b: [],
      c: {
        name: 12
      }
    }
    let {a,...res} = node;
    console.log(res);/*Object
                       b: []
                       c: {name: 12}*/
    //对数组解构
    let arr = [1,2,3];
    let [a,b,c] = arr;
    console.log(a,b,c);//1,2,3
    //可嵌套
    let [a,[b],c] = [1,[2],3];

拓展的对象功能

    const name = 'qaq',
          age = 21;
    const person = {
      name:name,
      age:age,
      sayName:function(){
        console.log(this.name);
      }
    }

es6写法

    const name = 'qaq',
          age = 21;
    const person = {
      name,//必须要name:name时才行
      age,
      sayName(){
        console.log(this.name);
      }
    }
    const name = 'a';
    const obj = {
        isShow:true,
        [name+'bc']:123,//如果调用外部变量需要用[]
        ['f'+name](){
            console.log(this);
        }
    }
    console.log(obj);/*Object
                        abc: 123
                        fa: ƒ ['f' + name]()
                        isShow: true*/

is() ===

比较两个值是否严格相等

console.log(NaN === NaN);//false
console.log(Object.is(NaN,NaN));//true

assign()

对象的合并

Object.assign(target,obj1,obj2...)//把obj1,obj2合并到target里

Symbol

原始数据类型Symbol,表示是独一无的值
最大的用途:用来定义对象的私有变量

const name = Symbol('name');
const name2 = Symbol('name');
console.log(name === name2);//false
//内存地址不一样

如果用Symbol定义的对象中的变量,取值时一定要用[变量名]

let s1 = Symbol('s1');
let obj = {
    [s1]:'qqq'
};
console.log(obj[s1]);//qqq
console.log(obj.s1);//undefined

for(let key in obj){
    console.log(key);//undefined
}
//Symbol定义的变量无法被遍历出来

//获取对象中Symbol声明的属性名的方法
//(1)
let s = Object.getOwnPropertySymbols(obj);
console.log(s);
//(2)
let m = Reflect.ownKeys(obj);
console.log(m);

set、map

set

集合:表示无重复值的有序列表 let set = new Set();

  1. set.add() 添加
  2. set.delete() 删除
  3. set.has() 检验某个值是否在set中
  4. set.size() 长度
  5. 将set转换成数组
let set2 = new Set([1,2,3,4,4,5,5]);
//扩展运算符
let arr = [...set2];

ps:set中对象的引用无法被释放(但是用WeakSet可以)

map

map类型是键值对的有序列表,键和值是任意类型
let map = new Map();

  1. map.set('key','value') 设置
  2. map.get('key') 获取
  3. map.has('key') 检验是否有
  4. map.delete('key') 删除
  5. map.clear(map) 清除所有

数组的扩展功能

转化为数组的es6方法

form()

  1. Array.from()
    function add() {
      let arr = Array.from(arguments);
      console.log(arr);//转化为数组
    }
    add(1, 2, 3, 4, 5);
  1. 扩展运算符 将伪数组转化为真数组
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
  </ul>
  <script>
    let list = document.getElementsByTagName('li');
    console.log(list);//HTMLCollection(4) [li, li, li, li]
    let arr = Array.from(list);
    console.log(arr);//(4) [li, li, li, li]
    let arr1 = [...list];
    console.log(arr1);//(4) [li, li, li, li]
    let arr2 = [list];
    console.log(arr2);//[HTMLCollection(4)]
  </script>
  1. Array.form()补充 还可以接受第二个参数,用来对每个元素进行处理
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
  </ul>
    <script>
    let list = document.getElementsByTagName('li');
    console.log(list);
    let arr = Array.from(list,ele=>ele.textContent);
    console.log(arr);//(4) ["1", "2", "3", "4"]
  </script>

of()

of() 将一组值转换成数组

var arr = Array.of(3,4,6,[1,2,3],{id:3});
//任意数据类型都可以转换

copyWithin()

//数组内部将制定位置的元素复制到其他位置,返回当前数组
//从3位置往后的所有数值,替换从0位置往后的三个数值
console.log([1,2,3,8,9,10].copyWithin(0,3));
//[8,9,10,8,9,10]

find() findIndex()

find()找出第一个符合条件的数组成员

console.log([1,2,-10,-20,7,5].find(n => n < 0));
//-10

findIndex()找出第一个符合条件的数组成员的索引

console.log([1,2,-10,-20,7,5].findIndex(n => n < 0));
//2

遍历器 entries() keys() values()

  1. keys() 对键名遍历
  2. values() 对值遍历
  3. entries() 对键值对遍历
    console.log(['a', 'b'].keys()); //Array Iterator {}(遍历器)
    for (let index of ['a', 'b'].keys()) {
      console.log(index);//0 1
    }
    
    for (let ele of ['a', 'b'].values()) {
      console.log(ele); //a b
    }
    
    for (let [index, ele] of ['a', 'b'].entries()) {
      console.log([index, ele]); //[0,'a'] [1,'b']
    }

includes()

返回一个布尔值 表示某个数组是否包含给定的值