ES6语法新特性2

数组扩展

Array.from

Array.from方法用于将两类对象转为真正的数组:

类似数组的对象(array-like object)和可遍历(iterable)的对象(包括 ES6 新增的数据结构 Set 和 Map)

function add(){
    // [1, 2, 3]  获取参数转化为数组
    console.log([].slice.call(arguments)); // es5
    console.log(Array.from(arguments))    // es6 
}
add(1,2,3);

// 实际使用
let items = document.getElementsByTagName('li');
Array.from(items).forEach(ele =>{
    console.log(ele); 
})

//from()还可以接受第二个参数,用来对每个元素进行处理
let li = Array.from(items,ele => ele.textContent);
console.log(li);

Array.of

将一组值,转换成数组

console.log(Array.of(3, 11, 20)); // 输出 [3, 11, 20]

find()findIndex()

//find()找出第一个符合条件的数组成员
let num = [1, 2, -10, 8, 2].find((n) => {
    return n < 0;
})
console.log(num); // 输出 -10

//findIndex()找出第一个符合条件的数组成员的索引
let numIndex = [1, 2, -10, 8, 2].findIndex((n) => {
    return n < 0;
})
console.log(numIndex);// 输出 2

迭代器、生成器

迭代器

//使用Symbol.iterator创建一个迭代器
const it = items[Symbol.iterator]();
console.log(it);
//调用next方法向下迭代,next方法会返回当前的位置
const nextEle = it.next();

//可迭代的数据结构
// Array String MaSet    

生成器

Generator函数,可以通过yield关键字,把函数的执行流挂起

为改变执行流程提供了可能,从而也为了异步编程提供了解决方案

它跟普通函数的区分:

  1. 在function后面,函数名之前有个*

  2. 函数内部有yield(产出)表达式

function* add() {
    console.log('start');
    var x = yield '2';
    console.log('x:' + x);
    var y = yield '3';
    console.log('y:' + y);
}
var it = add();
console.log(it.next());     // 输出 start         ;{value: '2', done: false}
console.log(it.next())      // 输出 x:undefined ;{value: '3', done: false}
//传递参数
console.log(it.next(999))   // 输出 y:999       ;{value: undefined, done: true}

//总结:
//Generator函数是分段执行的,yield语句是暂停执行,而next方法可以恢复执行
//return 方法返回给定值,并结束遍历Generator函数
//提供参数返回该参数,不提供则返回undefined

应用

 function getdata(){
     setTimeout(()=>{
         console.log('数据加载完成.....')
         j.next()
     },2000)
 }
function* load(){
    console.log('开启遮罩层.....')
    yield getdata()
    console.log('关闭遮罩层.......')
}
let j = load();
j.next()  
//输出 开启遮罩层.....;数据加载完成.....;关闭遮罩层.......

Promise对象

Promise 它其实就是一个容器,里面保存着某个未来才会结束的事件(异步操作)的结果

Promise接收一个函数作为参数,默认的relove和reject分别是两个函数

let pro = new Promise(function(resolved,rejected){
    //...执行异步任务
	let res = {code:200,data:{name:'admin'},error:'失败了'};
    setTimeout(()=>{
        if (res.code ==200){
            resolved(res.data)
        }else{
            rejected(res.error)
        }
    },2000)
})
pro.then((val)=>{
    console.log(val) 
}).catch(err =>{
    console.log(err);
})

传参

function timeout(ms){
    return new Promise((resolved,rejected)=>{
        setTimeout(()=>{
            resolved('hello,promise!')
        },ms)
    })
};
timeout(2000).then((val)=>{console.log(val)})
//Promise的all方法提供了并行执行异步操作的能力,并且在所有异步操作执行完后才执行回调
let Promise1 = new Promise(function (resolve, reject) {})
let Promise2 = new Promise(function (resolve, reject) {})
let Promise3 = new Promise(function (resolve, reject) {})
let p3 = Promise.all([Promise1, Promise2, Promise3])
p3.then(() => {
    // 三个都成功 则成功
}).catch(err => {
    // 只要有失败,都失败
})
// 应用场景:所有的都加载完后,我们再进行页面的初始化。
//race的应用场景:比如我们可以用race给某个异步请求设置超时时间,并且在超时后执行相应的操作
//finally()不管返回对错,都会执行

async函数

其实是Generator函数和promise的语法糖

async函数返回一个Promise对象,可以使用then方法添加回调函数,

但函数执行的时候,一旦遇到await就会先返回,等到异步操作完成,再接着执行函数体内后面的语句

async function f(){
    if (true){return 'hello' } ;  //return语句返回的值,会成为then方法回调函数的参数。
    throw new Error('出错了');     //Promise对象变为reject状态,抛出的错误对象会被catch方法回调函数接收到
}

f().then(v => console.log(v)).catch(e => console.log(e,'err'))

await命令

await命令后面是一个 Promise 对象。如果不是,会被转成一个立即resolve的 Promise 对象

async function f() {
    return await 123;
}
// 只要一个await语句后面的 Promise 变为reject,那么整个async函数都会中断执行。
async function f() {
    await Promise.reject('错误');
    await Promise.resolve('hello world'); // 不会执行
}
// 使用try...catch捕获异步失败
async function f() {
    try{
        await Promise.reject('错误');
    }catch(e){
        console.log(e)
    }  // 也可以写成 await Promise.reject('错误').catch(e => console.log(e));
    return await Promise.resolve('hello world'); // 会执行
}  

class类

class Person {
    // 类的实例属性
    myPro = 32;
    // 类的静态属性
    static yourPro = 45;
    // constructor方法 是类的默认方法,通过new命令生成对象实例时,自动调用该方法,
    //一个类必须有constructor方法,如果没有定义,会被默认添加
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    sayName(){
        return this.name;
    }
    // 公有方法
    say(a) {
        return this[name](a);
    }
    // 私有方法
    [name](a) {
        return a;
    }
    // 静态方法 不能通过实例去调用,只能通过类本身去调用
    static create() {
        return new Person('admin',123);
    }
}
//继承 extends
class woman extends Person {
    constructor(name,age,color){
        super(name,age);
        this.color = color;
    }
    //重写父类的方法
    sayName(){
        return this.name+'hi';
    }
}
let d1 = new Person('admin',18);
console.log(d1 instanceof Person);//属性是否出现在对象的原型链中

模块

import and export

例子

<script type="module">
    import man,{name,sayHi,data,Person} from './mybag.js'
    console.log({name,sayHi,data,Person})
    console.log(name);
    sayHi()
    console.log(data);
    let n = new Person();
    n.sayname();
    console.log(man);
</script>

//mybag.js

export let name ='小马';
export let data = {name:'admin'}
export function sayHi(){
    console.log('hi');
}
export class Person{
    constructor(){
    }
    sayname(){
        console.log('hi');
    }
}
let man = 123
export default man;
posted @ 2023-10-11 10:58  嘚惹  阅读(10)  评论(0编辑  收藏  举报