92~123(ES6简介+ES6的新增语法+ES6的内置对象扩展)

1 ES6简介

1.1 什么是ES6?

ES6的全程是ECMAScript,它是由ECMA国际标准化组织,制定的一项脚本语言的标准化规范

在这里插入图片描述

ES6实际上是一个泛指,泛指ES2015及后续的版本

1.2 为什么使用ES6?

每一次标准的诞生都意味着语言的完善,功能的加强。JavaScript语言本身也有一些令人不满意的地方。

  • 变量提升特性增加了程序运行时的不可预测性
  • 语法过于松散, 实现相同的功能,不同的人可能会写出不同的代码

2 ES6的新增语法

2.1 let

ES6中新增的用于声明变量的关键字

  • let声明的变量只在所处于的块级有效
if (true) {
    let a = 10;
}
console.log(a); // a is not defined
  • 不存在变量提升
console.log(a); // a is not defined
let a = 10;
  • 暂时性死区
var tmp = 123;
if (true) {
    tmp = 'abc';
    let tmp;
}

eg:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script type="text/javascript">
        // let 关键字就是用来声明变量的 使用let关键字生命的变量具有块级作用域
        // let a = 10;
        // console.log(a);
        // if (true) {
        //     let b = 20;
        //     console.log(b);
        //     if (true) {
        //         let c = 30;
        //     }
        //     console.log(c);
        // }
        // console.log(b);
        
        // 在一个大括号中 使用let关键字声明的变量才具有块级作用域 var关键字是不具备这个特点的
        // if (true) {
        //     let num = 100;
        //     var abc = 200;
        // }
        // console.log(abc);
        // console.log(num);
        
        // 防止循环变量变成全局变量
        // for (let i = 0; i < 2; i ++ ) {

        // }
        // console.log(i);

        // 使用let关键字声明的变量没有变量提升
        // console.log(a);
        // let a = 100;

        // 使用let关键字声明的变量具有暂时性死区
        var num = 10;
        if (true) {
            console.log(num);
            let num = 20;
        }
    </script>
</body>
</html>
经典面试题
var arr = [];
    for (var i = 0; i < 2; i ++ ) {
        arr[i] = function() {
            console.log(i);
        }
    }
    arr[0]();
    arr[1]();

在这里插入图片描述

经典面试题图解:此题的关键点在于变量i是全局的,函数执行时输出的都是全局作用域下的值

两次输出的都是2

let arr = [];
    for (var i = 0; i < 2; i ++ ) {
        arr[i] = function() {
            console.log(i);
        }
    }
    arr[0]();
    arr[1]();

在这里插入图片描述

经典面试题图解:此题的关键点在于每次循环都会产生一个块级作用域,每个块级作用域中的变量都是不同的函数执行时输出的是自己上一级(循环产生的块级作用域)作用域下的i值.

输出为1 2

2.2 const

作用:声明常量,常量就是值(内存地址)不能变化的量

  • 具有块级作用域
if (true) {
    const a = 10;
}
console.log(a); // a is not defined
  • 声明常量时必须赋值
const PI; // Missing initializer in const declaration
  • 常量赋值后,值不能修改
const PI = 3.14;
PI = 100; // Assigment to constant variable
const ary = [100, 200];
ary[0] = 'a';
ary[1] = 'b';
console.log(ary); // ['a', 'b'];
ary = ['a', 'b']; // Assigment to constant variable

eg:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>使用const关键字声明常量</title>
</head>
<body>
    <script type="text/javascript">
        // 使用const关键字声明的常量具有块级作用域
        // if (true) {
        //     const a = 10;
        //     console.log(a);
        //     if (true) {
        //         const a = 20;
        //         console.log(a);
        //     }
        // }
        // console.log(a);

        // 使用const关键字声明的常量必须赋初值
        // const PI = 3.14;

        // 常量声明后值不能更改
        const PI = 3.14;
        // PI = 100;
        const ary = [100, 200];
        ary[0] = 123;
        ary = [1, 2]; // 不被允许
        console.log(ary);
    </script>
</body>
</html>

2.3 let const var的区别

  1. 使用var声明的变量,其作用域为该语句所在的函数内,且存在变量提升现象。
  2. 使用let声明的变量,其作用域为该语句所在的代码块内,不存在变量提升。
  3. 使用const声明的是常量,在后面出现的代码中不能再修改该常量的值。

在这里插入图片描述

2.4 解构赋值

ES6中允许从数组中提取值,按照对应位置,对变量赋值,对象也可以实现解构

2.4.1 数组解构

let [a, b, c] = [1, 2, 3];
console.log(a);
console.log(b);
console.log(c);

如果解构不成功,变量的值为undefined

let [foo] = [];
let [bar, foo] = [1];
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script type="text/javascript">
        // 数组解构允许我们按照一一对应的关系提取值 然后将值赋值给变量
        let ary = [1, 2, 3];
        let [a, b, c] = ary;
        console.log(a);
        console.log(b);
        console.log(c);
    </script>
</body>
</html>

2.4.2 对象解构

let person = { name: 'zhangsan', age: 20};
let { name, age } = person;
console.log(name); // 'zhangsan'
console.log(age); // 20
let { name: myName, age: myAge } = person; // myName myAge 属于别名
console.log(myName); // 'zhangsan'
console.log(myAge); // 20

eg:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script type="text/javascript">
        // 对象解构允许我们使用变量的名字匹配对象的属性 匹配成功 将对象属性的值赋值给变量
        let person = { name: 'yaya', age: 30, sex: '男' };
        // let { name, age, sex } = person;
        // console.log(name);
        // console.log(age);
        // console.log(sex);
        let { name: myName } = person;
        console.log(myName);
    </script>
</body>
</html>

2.5 箭头函数

ES6新增的定义函数的方式

() => {}
const fn = () => {}

函数体中只有一句代码,且代码的执行结果就是返回值,可以省略大括号

function sum(num1, num2) {
    return num1 + num2;
}
const sum = (num1, num2) => num1 + num2;

如果形参只有一个,可以省略小括号

function fn(v) {
    return v;
}
const fn = v => v;

箭头函数不绑定this关键字,箭头函数中的this,指向的是函数定义位置的上下文this

const obj = { name: '张三' }
function fn() {
    console.log(this);
    return () => {
        console.log(this);
    }
}
const resFn = fn.call(obj);
resFn();

eg:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>箭头函数</title>
</head>
<body>
    <script type="text/javascript">
        // 箭头函数是用来简化函数定义语法的
        // const fn = () => {
        //     console.log(123);
        // }
        // fn();

        // 在箭头函数中,如果函数体中只有一句代码 并且代码的执行结果就是函数的返回值 函数体大括号可以省略
        // const sum = (n1, n2) => n1 + n2;
        // const result = sum(10, 20);
        // console.log(result);

        // 在箭头函数中 如果形参外侧的小括号也是可以省略的
        // const fn = v => alert(v);
        // fn(20);

        // 箭头函数不绑定this 箭头函数没有自己的this关键字 如果在箭头函数中使用this this关键字将指向箭头函数定义位置中的this
        function fn() {
            console.log(this); 
            return () => {
                console.log(this);
            }
        }
        const obj = {name: 'zhangsan'};
        const resFn = fn.call(obj);
        resFn();
    </script>
</body>
</html>
箭头函数面试题
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>箭头函数面试题</title>
</head>
<body>
    <script type="text/javascript">
        var age = 100;
        var obj = {
            age: 20,
            say: () => {
                alert(this.age); // 弹出的是window下的age
            }
        }
        obj.say();
    </script>
</body>
</html>

对象是不能产生作用域的,say()实际是被定义在全局作用域下,say()方法中的this指向的是window,所以弹出的是window下的age

2.6 剩余参数

剩余参数语法允许我们将一个不定数量的参数表示为一个数组

function sum (first, ...args) {
    console.log(first); // 10
    console.log(args); // [20, 30]
}
sum(10, 20, 30);

剩余参数和解构配合使用

let students = ['wangwu', 'zhangsan', 'lisi'];
let [s1, ...s2] = students;
console.log(s1); // 'wangwu'
console.log(s2); // ['zhangsan', 'lisi']

eg:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>剩余参数</title>
</head>
<body>
    <script type="text/javascript">
        // const sum = (...args) => {
        //     let total = 0;
        //     args.forEach(item => total += item);
        //     return total;
        // };
        // console.log(sum(10, 20));
        // console.log(sum(10, 20, 30));
        let ary1 = ['张三', '李四', '王五'];
        let [s1, ...s2] = ary1;
        console.log(s1);
        console.log(s2);
    </script>
</body>
</html>

3 ES6的内置对象扩展

3.1 Array的扩展方法

扩展运算符(展开语法)
  1. 扩展运算符可以将数组或者对象转为逗号分隔的参数序列
let ary = [1, 2, 3];
...ary // 1, 2, 3
console.log(...ary); // 1 2 3
  1. 扩展运算符可以应用于合并数组
// 方法一
let ary1 = [1, 2, 3];
let ary2 = [3, 4, 5];
let ary3 = [...ary1, ...ary2];
// 方法二
ary1.push(...ary2);
  1. 将类数组或可遍历对象转换为真正的数组
let oDivs = document.getElementsByName('div');
oDivs = [...oDivs];

eg:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
    <div>6</div>
    <script>
        // 扩展运算符可以将数组拆成以逗号分割的参数序列
        // let ary = ["a", "b", "c"];
        // ...ary // "a", "b", "c"
        // console.log(...ary);
        // console.log("a", "b", "c");

        // 扩展运算符应用于数组合并
        // let ary1 = [1, 2, 3];
        // let ary2 = [4, 5, 6];
        // // ...ary1 // 1, 2, 3
        // // ...ary2 // 4, 5, 6
        // let ary3 = [...ary1, ...ary2];
        // console.log(ary3);

        // 合并数组的第二种方法
        // let ary1 = [1, 2, 3];
        // let ary2 = [4, 5, 6];
        // ary1.push(...ary2);
        // console.log(ary1);

        // 利用扩展运算符将伪数组转换为真正的数组
        var oDivs = document.getElementsByTagName('div');
        console.log(oDivs);
        var ary = [...oDivs];
        ary.push('a');
        console.log(ary);
    </script>
</body>
</html>
构造函数方法:Array.from()

将类数组或可遍历对象转换为真正的数组

let arrayLike = {
    '0': 'a',
    '1': 'b',
    '2': 'c',
    length: 3
};
let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']

方法还可以接受第二个参数,作用类似于数组的map方法,用来对每个元素进行处理,将处理后的值放入返回的数组

let arrayLike = {
    "0": 1,
    "1": 2,
    "length": 2
}
let newAry = Array.from(arrayLike, item => item * 2);

eg:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        // var arrayLike = {
        //     "0": "张三", 
        //     "1": "李四",
        //     "2": "王五",
        //     "length": 3
        // }
        // var ary = Array.from(arrayLike);
        // console.log(ary);

        var arrayLike = {
            "0": "1", 
            "1": "2",
            "length": 2
        }
        var ary = Array.from(arrayLike, item => item * 2);
        console.log(ary);
    </script>
</body>
</html>
实例方法:find()

用于找出第一个符合条件的数组成员,如果没有找到返回undefined

let ary = [{
    id: 1,
    name: '张三'
}, {
    id: 2,
    name: '李四'
}];
let target = ary.find((item, index) => item.id == 2);

eg:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      let ary = [
        {
          id: 1,
          name: "张三",
        },
        {
          id: 2,
          name: "李四",
        },
      ];
      let target = ary.find(item => item.id == 3);
      console.log(target);
    </script>
  </body>
</html>
实例方法:findIndex()

用于找出第一个符合条件的数组成员的位置,如果没有找到返回-1

let ary = [1, 5, 10, 15];
let index = ary.findIndex((value, index) => value > 9);

eg:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        let ary = [10, 20, 50];
        let index = ary.findIndex(item => item > 15);
        console.log(index);
    </script>
</body>
</html>
实例方法:includes()

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

[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false

eg:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>includes方法</title>
</head>
<body>
    <script>
        let ary = ["a", "b", "c"];
        let result = ary.includes('a'); 
        console.log(result); // true
        result = ary.includes('a'); 
        console.log(result); // false
    </script>
</body>
</html>

3.2 String的扩展方法

模板字符串

ES6新增的创建字符串的方式,使用反引号定义

let name = `zhangsan`;
  1. 模板字符串中可以解析变量
let name = '张三';
let sayHello = `hello, my name is ${name}`; // hello, my name is zhangsan
  1. 模板字符串中可以换行
let result = {
    name: 'zhangsan',
    age: 20,
    sex: '男'
}
let html = `<div>
<span>${result.name}</span>
<span>${result.age}</span>
<span>${result.sex}</span>
</div>`;
  1. 在模板字符串中可以调用函数
const sayHello = function() {
    return '哈哈哈哈 追不到我吧 我就是这么强大';
};
let greet = `${ sayHello() } 哈哈哈哈`;
console.log(greet); // 哈哈哈哈 追不到我吧 我就是这么强大 哈哈哈哈

eg:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>模板字符串</title>
</head>
<body>
    <script>
        // let name = `yaya`;
        // let sayHello = `Hello, 我的名字叫${name}`;
        // console.log(sayHello);
        // let result = {
        //     name: "zhangsan",
        //     age: 20
        // };

        // let html = `
        //     <div>
        //         <span>${result.name}</span>
        //         <span>${result.age}</span>
        //     </div>
        // `;
        // console.log(html);
        const fn = () => {
            return '我是fn函数';
        }
        let html = `我是模板字符串 ${fn()}`;
        console.log(html);
    </script>
</body>
</html>
  1. 实例方法: startWith()和endsWith()
  • startWith():表示参数字符串是否在原字符串的头部,返回布尔值
  • endsWith(): 表示参数字符串是否在原字符串的尾部,返回布尔值
let str = 'Hello world!';
str.startWith('Hello'); // true
str.endsWith('!'); // true

eg:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        let str = 'Hello ECMAScript 2015';
        let r1 = str.startsWith('Hello');
        console.log(r1); // true
        let r2 = str.endsWith('2016');
        console.log(r2); // false
    </script>
</body>
</html>
  1. 实例方法:repeat()
    repeat方法表示将原字符串重复n次,返回一个新字符串
'x'.repeat(3) // 'xxx'
'hello'.repeat(2) // 'hellohello'

3.3 Set数据结构

ES6提供了新的数据结构Set。它类似于数组,但是成员的值都是唯一的,没有重复的值。

  1. Set本身是一个构造函数,用来生成Set数据结构。
const s = new Set();
  1. Set函数可以接受一个数组作为参数,来初始化。
const set = new Set([1, 23, 4, 4]) ;
  1. 可以实现数组去重
    eg:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        const s1 = new Set();
        console.log(s1.size);

        const s2 = new Set(["a", "b"]);
        console.log(s2.size);

        const s3 = new Set(["a", "a", "b", "b"]);
        console.log(s3.size);
        const ary = [...s3];
        console.log(ary); // ["a", "b"]
    </script>
</body>
</html>
  1. 实例方法
  • add(value):添加某个值,返回Set结构本身
  • delete(value):删除某个值,返回一个布尔值,表示删除是否成功
  • has(value):返回一个布尔值,示该值是否为Set的成员
  • clear():清除所有成员,没有返回值
const s = new Set();
s.add(1).add(2).add(3); // 向set结构中添加值
s.delete(2); // 删除set结构中的2值
s.has(1); // 表示set结构中是否有1这个值 返回布尔值
s.clear() // 清除set结构中的所有值
  1. 遍历
    Set结构的实例与数组一样,也拥有forEach方法,用于对每个成员执行某种操作,没有返回值
s.forEach(value => console.log(value))

eg:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        // const s1 = new Set();
        // console.log(s1.size);

        // const s2 = new Set(["a", "b"]);
        // console.log(s2.size);

        // const s3 = new Set(["a", "a", "b", "b"]);
        // console.log(s3.size);
        // const ary = [...s3];
        // console.log(ary);

        // const s4 = new Set();
        // // 向set结构中添加值 使用add方法
        // s4.add('a').add('b');
        // console.log(s4.size);
        // // 从set结构中删除值 用到的方法是delete
        // const r1 = s4.delete('a');
        // console.log(s4.size);
        // console.log(r1);
        // // 判断某一个值是否是set数据结构中的成员 使用has
        // const r2 = s4.has('a');
        // console.log(r2);
        // // 清空set数据结构中的值
        // s4.clear();
        // console.log(s4.size);

        // 遍历Set数据结构 从中取值
        const s5 = new Set(['a', 'b', 'c']);
        s5.forEach(value => {
            console.log(value);
        })
    </script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值