javascript的ES6学习总结(第二部分)
Posted abc-x
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript的ES6学习总结(第二部分)相关的知识,希望对你有一定的参考价值。
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 东西
>如何使用?
import
使用模块:
<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>
到此先写到这,第三部分抽时间会补上。
以上是关于javascript的ES6学习总结(第二部分)的主要内容,如果未能解决你的问题,请参考以下文章
读书笔记《你不知道的JavaScript(上卷)》——第二部分 this和对象原型