欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

javascript的ES6学习总结(第二部分)

程序员文章站 2022-05-29 12:03:48
1.数组循环 介绍数组循环之前,先回顾一下ES5数组的循环 (1)数组遍历(代替普通的for):arr.forEach(callback(val,index,arr){todo}) //val是数组的当前项,index是数组的键名(下标),arr是整个数组 (2)数组映射:arr.map(callb ......

1.数组循环

介绍数组循环之前,先回顾一下es5数组的循环

(1)数组遍历(代替普通的for):arr.foreach(callback(val,index,arr){todo}) //val是数组的当前项,index是数组的键名(下标),arr是整个数组

let arr = ['today','tomorrow','the day after tommrrow','three days from now'];
arr.foreach(function(val,index,arr){
    console.log(val,index,arr);//today 0 (4) ["today", "tomorrow", "the day after tommrrow", "three days from now"]...
});

(2)数组映射:arr.map(callback(item,index,arr){todo... 正常情况下,需要配合return,返回的是一个新数组,若没有return,相当于foreach,一般用于在有return的情况下}) //item是数组的当前项,index是数组的键名(下标),arr是整个数组

let arr = [
    {title:'aaaa',read:100,hot:true},
    {title:'bbbb',read:100,hot:true},
    {title:'cccc',read:100,hot:true},
    {title:'dddd',read:100,hot:true}
];
let newarr = arr.map((item,index,arr)=>{
    // console.log(val,index,arr);
    let json = {};
    json.t = item.title;
    json.r = item.read;
    json.h = item.hot == true && '真棒!!!';
    return json;
});
console.log(newarr);//(4) [object, object, object, object]

(3)数组过滤:arr.filter(callback(item,index,arr){todo... 正常情况下,需要配合return,返回值为true的元素,返回值为false的元素则被过滤掉}) //item是数组的当前项,index是数组的键名(下标),arr是整个数组

let arr = [
    {title:'aaaa',read:100,hot:true},
    {title:'bbbb',read:100,hot:false},
    {title:'cccc',read:100,hot:true},
    {title:'dddd',read:100,hot:false}
];
let newarr = arr.filter((item,index,arr)=>{
    // return item.hot == true;
    return item.hot;
});
console.log(newarr);//(2) [object, object]

(4)数组单项检测:arr.some(callback(item,index,arr){todo... 正常情况下,需要配合return,如果有一个值为true,则返回true,否则返回false}) //item是数组的当前项,index是数组的键名(下标),arr是整个数组

let arr = ['one','two','three','four'];
let b = arr.some((val,index,arr)=>val=='one');
console.log(b);//true

注:此方法可封装成一个检测数组中是否存在某一项的函数

let arr = ['apple','banana','orange'];
function findinarray(arr,item){
    return arr.some((val,index,arr)=> val == item);
}
console.log(findinarray(arr,'orange'));//true

(5)数组多项检测:arr.every(callback(item,index,arr){todo... 正常情况下,需要配合return,如果所有的值都为true,则返回true,否则返回false}) //item是数组的当前项,index是数组的键名(下标),arr是整个数组

let arr = ['one','two','three','four',6,8,2];
let b = arr.every((val,index,arr)=>val);
console.log(b);//true

(6)数组简化:arr.reduce(callback(prev,cur,index,arr){todo... 正常情况下,需要配合return,返回计算后的结果},传递给函数的初始值(可选,默认为第一项的值)) //prev是数组的前一项(如果第一次循环,则prev默认为0),cur是数组的当前项,index是数组的键名(下标),arr是整个数组;

arr.reduceright()用法和arr.reduce类似,只不过计算顺序是从右向左

//数组求和
let arr = [1,2,3,4,5];
let res = arr.reduce((prev,cur,index,arr)=>{
    return prev+cur;
},0);
console.log(res);//15//数组求积
let arr = [1,2,3,4,5];
let res = arr.reduce((prev,cur,index,arr)=>{
    return prev*cur;
},1);
console.log(res);//120
// 数组求最大值
let arr = [1,2,3,298,4,5,199];
let res = arr.reduce((prev,cur,index,arr)=>{
    return (cur>prev?cur:prev);
});
console.log(res);//298
// 求阶乘(es2017新增幂运算符**,例如math.pow(2,3)可写成2**3。)
let arr = [2,2,3];
let res = arr.reduce((prev,cur,index,arr)=>{
return math.pow(prev,cur);//也可以写成return prev**cur
});
console.log(res);//64

(7)es6新增for...of循环:

let arr = ['a','b','c','d'];
// 遍历值
for(let val of arr){
    console.log(val);
}
// 遍历下标
for(let index of arr.keys()){
    console.log(index);
}
// 遍历某一项
for(let item of arr.entries()){
    console.log(item[0],item[1]);
}
// or
for(let [key,val] of arr.entries()){
    console.log(key,val);
}

(8)es6新增array.from()方法:将类数组对象(只要有length属性就可以)转换为数组,也可以复制数组

<ul>
    <li>11</li>
    <li>22</li>
    <li>33</li>
    <li>44</li>
</ul>

<script type="text/javascript">
window.onload= function(){
    let ali = document.queryselectorall('ul li');
    // let arrli = array.from(ali);//es6方法
  // let arrli = [...ali];//es6方法 let arrli = [].slice.call(ali);//es5方法 arrli.pop(); console.log(arrli); } </script>
function show(){
    let args = array.from(arguments);
    // let args = [...arguments];//也可以用拓展运算符
    args.push(6);
    console.log(args);//[1, 2, 3, 4, 5, 6]
}
show(1,2,3,4,5);
let str = 'hello';
// let arr = str.split('');
// let arr = [...str];
let arr = array.from(str);
console.log(arr);//["h", "e", "l", "l", "o"]
let json = {
    0:'one',
    1:'two',
    2:'three',
    length:3
}
let arr = array.from(json);
console.log(arr);//["one", "two", "three"]

(9)es6新增array.of()方法:把一组值转成数组

let arr = array.of('apple','banana','orange');
console.log(arr);//["apple", "banana", "orange"]

(10)es6新增array.find()查找元素方法:查找,找出第一个符合条件的数组成员,如果没有找到返回undefined

let arr = [1,2221,344,876,55,56,78];
let res = arr.find((val,index,arr)=>{
    return val > 333;
});
console.log(res);//2221

(11)es6新增array.findindex()查找元素索引方法:查找,找出第一个符合条件的数组成员的位置,如果没有找到返回-1

let arr = [1,2221,344,876,55,56,78];
let res = arr.findindex((val,index,arr)=>{
    return val > 333;
});
console.log(res);//1

(12)es6新增array.fill()填充数组方法:array.fill(要填充的内容,开始填充的位置,结束的位置)

let arr = new array(10);
arr.fill('默认',1,3);
console.log(arr);//[undefined × 1, "默认", "默认", undefined × 7]

(13)es7(es2016)新增array.includes()查找数组中是否存在某一项方法,如果有返回true,否则返回false

let arr = [1,2,3,4];
let b = arr.includes(2);
console.log(b);//true

2.对象简洁语法及对象新增

(1)对象简洁语法

let name = 'pilot';
let age = 18;
let json = {
    name,//相当于name:name
    age//相当于age:age
}
console.log(json);//object {name: "pilot", age: 18}
let name = 'pilot';
let age = 18;
let json = {
    name,//相当于name:name
    age,//相当于age:age
    showa(){//注意:不要替换为箭头函数
        return this.name;
    },
    showb(){
        return this.age;
    }
}
console.log(json.showa(),json.showb());//pilot 18

(2)es6对象新增object.is()方法:比较两个值是否相等

console.log(nan == nan);//false
console.log(nan != nan);//true
console.log(nan === nan);//false
console.log(nan !== nan);//true
let b = object.is(nan,nan);
console.log(b);//true
console.log(+0 == -0);//true
let b = object.is(+0,-0);
console.log(b);//false
console.log(object.is('aaa','aab'));//false

(3)es6对象新增object.assign()方法:用来合并对象,object.assign(目标对象,source1,source2...),后面的值会覆盖前面的值

let json = {a:1};
let json2 = {b:2,a:2};
let json3 = {c:3};
let obj = object.assign({},json,json2,json3);
console.log(obj);//{a: 2, b: 2, c: 3}
// 复制数组
let a = [1,2,3,4];
let b = object.assign([],a);
console.log(b);//[1, 2, 3, 4]

(4)es8(es2017)新增object.keys()、object.entries()、object.values()方法

let json = {
    a:1,
    b:2,
    c:3
}
for(let key of object.keys(json)){
    console.log(key);//a,b,c
}
let {keys,values,entries} = object;//解构
let json = {
    a:1,
    b:2,
    c:3
}
for(let key of keys(json)){
    console.log(key);//a,b,c
}
for(let value of values(json)){
    console.log(value);//1,2,3
}
for(let item of entries(json)){
    console.log(item);//["a", 1],["b", 2],["c", 3]
}
for(let [key,val] of entries(json)){
console.log(key,val);//a, 1,b, 2,c, 3
}

(5)es9(es2018)新增对象的”…“运算符

let {x,y,...z} = {x:1,y:2,a:3,b:4};//在chrome最新版本测试
console.log(x,y,z);//1 2 {a: 3, b: 4}
let json = {a:3,b:4};
let json2 = {...json};//复制json对象(在chrome最新版本测试)
delete json2.b;
console.log(json);//{a: 3, b: 4}
console.log(json2);//{a: 3}

3.promise:解决异步回调问题

(1)promise.resolve('aa'):将现有的东西,转成一个promis对象,resolve状态,成功状态;

promise.reject('aa'):将现有的东西,转成一个promis对象,reject状态,失败状态;

promise.all([p1,p2,p3]):把promise打包,扔到一个数组里面,打包完还是一个promise对象,必须确保所有的promise对象,都是resolve状态,都是成功状态;

promise.race([p1,p2,p3]):把promise打包,扔到一个数组里面,打包完还是一个promise对象,只要有一个成功,就返回成功状态。

let p1 = promise.resolve('aaa');
//等价于 let p1 = new promise(resolve=>{resolve('aaa')});
p1.then(res=>{
    console.log(res);//aaa
});
let p1 = promise.reject('aaa');
//等价于 let p1 = new promise((resolve,reject)=>{reject('aaa')});
p1.then(res=>{
    console.log(res);
}).catch(err=>{
    console.log(err);//aaa
});
let p1 = promise.resolve('aaa');
let p2 = promise.resolve('bbb');
let p3 = promise.resolve('ccc');
promise.all([p1,p2,p3]).then(res=>{
    // console.log(res);//["aaa", "bbb", "ccc"]
    let [res1,res2,res3] = res;
    console.log(res1,res2,res3);//aaa bbb ccc
});
let p1 = promise.resolve('aaa');
let p2 = promise.reject('bbb');
let p3 = promise.reject('ccc');
promise.race([p1,p2,p3]).then(res=>{
    console.log(res);//aaa
});
new promise(function(resolve,reject){
    //resolve,成功调用
    //reject,失败调用
})
let a = 103;
let promise = new promise(function(resolve,reject){
    if(a == 10){
        resolve('成功');
    }else{
        reject('失败');
    }
});
// promise.then(success,fail);
promise.then(res=>{
    console.log(res);//成功
},err=>{
    console.log(err);//失败
})
let a = 103;
let promise = new promise(function(resolve,reject){
    if(a == 10){
        resolve('成功');
    }else{
        reject('失败');
    }
});
// promise.then(success,fail);
// promise.then(res=>{
//     console.log(res);//成功
// },err=>{
//     console.log(err);//失败
// });
// promise.catch(err=>{//reject,发生错误,别名
//     console.log(err);//失败
// });

// promise.then(success,fail);
promise.then(res=>{
    console.log(res);//成功
}).catch(err=>{//reject,发生错误,别名
    console.log(err);//失败
});

4.模块化

(1)在es6之前,是不支持模块化的,但是社区制定一套模块规范:

commonjs   主要服务端 nodeja require('http')

amd            requirejs,curljs

cmd            seajs

es6模块化出来后,统一服务端和客户端模块规范:

import {xx} from ddd;

(2)基本概念:

注:需要放服务器环境

>如何定义模块?  

export 东西

export const a = 12;
export{
  a as aaa,
  a as bbb
}

>如何使用?  

import

import './modules/1.js';
import {aaa as a,bbb as b} from 'xxx'

使用模块:

<script type="module">

</script>

import特点:

1.import可以是相对路径,也可以是绝对路径

import 'https://cdn.bootcss.com/jquery/2.2.2/jquery.js'

2.import模块只会导入一次,无论引入多少次

3.import './modules/1.js';如果这么用,相当于引入文件

4.有提升效果,import会自动提升到顶部,首先执行

5.导出去模块内容,如果里面有定时器更改,外面也会改动

* 6.import动态引入:

import(),类似于node里面的require,可以动态引入,默认import语法不能写到if之类的语法里

优点:

1.按需加载

2.可以写if中

3.路径也可以写动态

4.因为返回值是promise对象,所以可以用then方法

例子:

one.html

<script type="module">
import {a,b,c} from './modules/1.js';
console.log(a,b,c);//12 15 65
</script>

1.js

export const a = 12;
export const b = 15;
export let c = 65;

two.html

<script type="module">
import {aaa as a,bbb as b,ccc as c} from './modules/2.js';
console.log(a,b,c);//12 5 102
</script>

2.js

const a =12;
const b =5;
const c =102;
export {
    a as aaa,//起别名
    b as bbb,
    c as ccc
}

three.html

<script type="module">
import * as modtwo from './modules/3.js';
console.log(modtwo.aaa);//125
</script>

3.js

const a =125;
const b =25;
const c =1012;
export {
    a as aaa,//起别名
    b as bbb,
    c as ccc
}

four.html

<script type="module">
import a,{cc,dd} from './modules/4.js';
console.log(a,cc,dd);//12 21 23
</script>

4.js

export default 12;
export const cc = 21;
export const dd = 23;

five.html

<script type="module">
//import有提升效果,import会自动提升到顶部,首先执行
console.log(a,cc,dd);//12 21 23
import a,{cc,dd} from './modules/5.js';
</script>

5.js

export default 12;
export const cc = 21;
export const dd = 23;

six.html

<script type="module">
//导出去模块内容,如果里面有定时器更改,外面也会改动
import {a,b} from './modules/6.js';
console.log(a);
settimeout(() => {
    console.log(a);
}, 3000);
</script>

6.js

let a = 6;
let b = 12;
settimeout(()=>{
    a = 12345;
},2000);
export {
    a,
    b
}

seven.html

<script type="module">
//动态加载模块,按需加载,可以写if中,路径可以是动态
import('./modules/7.js').then(res=>{
    console.log(res.a+res.b);//27
});
</script>

7.js

console.log('7模块加载了');
export const a = 12;
export const b = 22;

eight.html

<script type="module">
//动态加载模块结合promise使用
promise.all([
    import('./modules/1.js'),
    import('./modules/2.js')
]).then(([mod1,mod2])=>{
    console.log(mod1);
    console.log(mod2);
})
</script>

nine.html

<script type="module">
//动态加载模块结合async、await函数使用
async function main(){
    /* 方法1 */
    const mod1 = await import('./modules/1.js');
    const mod2 = await import('./modules/2.js');
    console.log(mod1,mod2);
    /* 方法2 */
    const [m1,m2] = await promise.all([
        import('./modules/1.js'),
        import('./modules/2.js')
    ]);
    console.log(m1,m2);
}
main();
</script>

到此先写到这,第三部分抽时间会补上。