ES6介绍
1. let和const关键字
| let | let用来声明变量(可变的量) 不能重复声明 但是可以重新赋值 let只能在当前作用域中进行修改变化 作用域外边的不受影响 【以后项目声明变量都写let就可以了】 |
|---|---|
| const | const用来声明常量(不变的量) 【声明数组和对象的时候使用const】 const不能重新赋值 但是可以被修改 值不能修改的量称为常量 一定要赋初始值 一般常量使用大写(潜规则) 常量的值不能修改 也是块级作用域 对于数组和对象的元素修改,不算对常量的修改,不会报错 |
2 es6数组方法
| some |
|---|
| every |
| filter |
| map |
| find |
| findIndex |
| forEach |
3 解构赋值
4 扩展运算符
5 箭头函数
将es5语法中的function关键字变为 =>格式var 变量名=function() {// 执行代码块}箭头函数const 变量名=()=> {// 执行代码块}如果函数有参数1 只有一个参数 则当前参数外边小括号可以省略const 变量名=a=> {console.log(a)}2 如果有多个参数 则参数外层的小括号不能省略const 变量名=(b,c)=> {console.log(b,c)}3 如果当前一个函数 有返回值 并且返回值只有一个 则外层花括号和return 都可以省略const a=x=>{return x}const x=x=> x4 默认参数const a=(x=默认值1,y=默认值2)=> {console.log(x,y)}a(参数1,参数2) // 参数1 参数2a() // 如果函数在进行调用的时候乜有传递对应的参数 则会走默认的参数值 输出结果 默认值1 默认值2
6 class类
7 promise
8 axios async await
9 import export
实现cnode切换和分页
<body><ul id="tab"><li>全部</li><li>精华</li></ul><div class="content"></div><ul id="page"><li>1</li><li>2</li><li>3</li></ul><script>const content=document.querySelector(".content")const page=document.querySelector("#page")const getList=(tab='all',page=1)=> {let str=""fetch(`https://cnodejs.org/api/v1/topics?page=${page}&tab=${tab}&limit=20`).then(res=> res.json()).then(res1=> {console.log(res1)for(let i=0; i<res1.data.length; i++) {str+=`<p>${res1.data[i].title}</p>`}content.innerHTML=str}).catch(err=> {console.log(err)})}getList()document.querySelector("#tab").onclick=()=> {console.log(event.target.innerHTML)getList(event.target.innerHTML=="全部"?"all":"good")localStorage.setItem('tab',event.target.innerHTML=="全部"?"all":"good")}page.onclick=()=> {getList(localStorage.getItem("tab")?localStorage.getItem('tab'):"all", event.target.innerHTML)}</script>
数组方法 some every
| some 当一个数组中只要有一个元素能够匹配,则返回true,反之返回false 格式: 数组.some((item, index, array)=> { // item 表示数组中每一项 index下标索引 array原数组 return 条件 }) |
every 当一个数组中所有的元素都匹配,则返回true,反之返回false 格式: 数组.every((item, index, array)=> { // item 表示数组中每一项 index下标索引 array原数组 return 条件 }) |
|---|---|
<script>const arr=[3,6,9,9,12]const data=[{id: 1,name: "张三",age: 15,sex: "男"},{id: 2,name: "李四",age: 16,sex: "女"}]const result=data.every(item=> item.sex=="男")console.log(result)// arr.every((item, index, array)=> {// console.log(item, index, array)// })// const result=arr.some((item, index, array)=> {// // console.log(item, index, array)// return item==9// })// console.log(result)// const result=data.some(item=> item.sex=="男")// if(result) {// alert("正常渲染数据")// }else {// alert("不渲染数据")// }</script>
数组方法 filter map find findeIndex
| map | 根据现有数组生成一个长度相同的 新数组 格式: 数组.map((item, index, array)=> { return 条件 }) |
|---|---|
| filter | 对数组进行筛选 返回符合条件的 新数组 格式: 数组.filter((item, index, array)=> { return 条件 }) |
| find | 对当前数组进行查询 找到符合条件的元素 格式: 数组.find((item, index, array)=> { return 条件 }) |
| findIndex | 对当前数组进行查询 找到符合条件的元素下标索引 格式: 数组.findIndex((item, index, array)=> { return 条件 }) |
| forEach | 对当前数组进行循环遍历 只要for循环能够遍历的 forEach都可以 格式: 数组.forEach((item, index, array)=> { console.log(item) }) |
<script>const arr=[1,2,3]arr.forEach((item, index, array)=> {console.log(item)})// const result=arr.findIndex((item, index, array)=> {// console.log(item, index, array)// return item>=2// })// console.log(result)// const result=arr.find((item, index, array)=> {// // if(item>=2) {// // console.log(item)// // }// return item>=2// })// console.log(result)// const result=arr.filter((item, index, array)=> {// console.log(item, index, array)// return item>2// })// console.log(result)// const arr=[// {// id: 1,// name: "张三",// age: 15,// sex: "男"// },// {// id: 2,// name: "李四",// age: 16,// sex: "女"// },// {// id: 3,// name: "李华",// age: 20,// sex: "女"// }// ]// const result=arr.filter(item=> item.age>=20&&item.sex=="男")// console.log(result)// const a=arr.map((item, index, array)=> {// // console.log(item, index, array)// item.sex="女"// delete(item.age)// item.score=0// return item// })// console.log(a)</script>
解构赋值
| 解构赋值可以对数组或者是对象进行提取值 并且对变量进行赋值 这种形式我们称之为解构赋值 | |
|---|---|
| 1 数组解构 | 从数组中提取值 按照对应的位置 对变量赋值 这种写法属于模式匹配 只要等号两边的模式相同 我们就可以对等号左边的变量进行赋值 按顺序 例如 let [a,b,c]=[1,2,3] console.log(a) |
| 2 对象解构 | 对象解构与数组解构不太一样 数组中的元素是按照顺序来排列 变量的取值由它的位置决定 对象的属性没有顺序 变量必须与属性名一致 才能进行赋值 例如: let {name, age}={name: “zhangsan”, age: 15} console.log(name) console.log(age) |
| 3 字符串解构 | 字符串也可以解构赋值 这是因为 字符串被转换成了一个类似数组的对象 例如 const [a,b,c]=”123” console.log(a) console.log(b) console.log(c) |
| 4 函数参数解构 | 函数的参数可以使用解构赋值 例如 function demo([x,y]) { console.log(x,y) } demo([1,2]) |
| 5 默认值 | 解构赋值允许指定默认值 例如: let [a,b=1] = [1] console.log(b) |
<script>
let {a,b}={a:1, b:[1,2]}
console.log(a,b)
// let [a,b="zhangsan"] = [1]
// console.log(b)
// function demo([x,y]) {
// console.log(x)
// }
// demo([1,2])
// const [a,b,c]="he ll o"
// console.log(a)
// console.log(b)
// console.log(c)
// let [a, {b}, [{c,d}]]=[{name: 'zhangsan'},{b:123},[{w:123}]]
// console.log(a)
// console.log(b)
// console.log(c)
// let {age, name}={name: "zhangsan", age: 15}
// console.log(name)
// console.log(age)
// let [a,b,c]=[31,2,3]
// console.log(a)
// console.log(b)
// console.log(c)
// let [x, [y,z]]=[1, [2,3]]
// console.log(x)
// console.log(z)
// let [x,y,z]=[1,[2,3]]
// console.log(x)
// console.log(y)
// console.log(z)
// let a=1
// let b=2
// let c=3
// let d=[a,b,c]
// console.log(d,a,b)
</script>
扩展运算符
| 扩展运算符是三个点(…) 它可以将对象或者是数组外层的结构给展开 可以直接拿取对象或者是数组中的数据 |
|
|---|---|
| 数组扩展 | 格式: var arr=[1,2,3] var newArr=[4] // [4,1,2,3] […newArr, …arr] 对数组的操作 1 复制了一下数组 const a=[1,2] const b=[…a] console.log(b) 2 合并数组 const a=[1,2] const b=[3] console.log([…a,…b]) |
| 对象扩展 | es6允许在大括号里边 直接写入变量和函数 作为对象的属性和方法 例如: let age=15 let name=”zhangsan” let sex=”nan” const stus={ name, // name: name sex, age } console.log(stus) 当属姓名与属性值(变量) 名字一致的时候可以简写 只用写一个 对象扩展需要使用扩展运算符 对象的解构赋值用于从一个对象中取值 相当于将目标对象自身的所有的可遍历的 但是尚未被读取的属性 分配到指定的对象上边 所有的键和值 都会被拷贝到对应的新对象上边 例如: let z={a:1,b:2} let m={…z} console.log(m) // {a:1, b:2} |
| 合并对象 | assign() Object.assign()方法用于合并对象 将原有的对象复制到目标对象中 格式: const a={ a: 1 } const b={ b: 2 } Object.assign(a,b) 相当于将b对象复制到a对象中 console.log(a) {a:1,b:2} |
| 对象属性名 | Object.keys() 该方法返回一个对象中对应的属性的键名 格式: Object.keys(对象) 例如 const stus={ name: “张三”, age: 15 } Object.keys(stus) // [‘name’,’age’] |
| Object.values() 该方法返回是一个数组 数组里边的值为当前对象所有的属性值 格式: Object.values(对象) 例如: const stus={ name: “张三”, age: 15 } Object.values(stus) // [“张三”, 15] |
|
| 对象获取键和值 | Object.entries() 该方法可以返回一个数组 里边成员是当前对象中的属性名和属性值组成的数组 格式 Object.entries(对象) 例如: const stus={ name: “张三”, age: 15 } Object.entries(stus) // [[“name”,”张三”], [“age”, 15]] |
class类
格式:
class 类名 {
// 构造器
constructor(参数1,参数2) {
this.参数1=参数1
this.参数2=参数2
}
方法() {
// 执行代码块
}
...
}
例如
class Demo {
constructor(x,y) {
this.x=x
this.y=y
}
toString() {
return this.x
}
}
继承
子类可以继承父类中的方法和属性
格式
class 子类名 extends 父类名{
constructor(继承的属性1,继承的属性2,自定义属性) {
super(继承的属性1,继承的属性2) // 超类 写继承super必写 只能写在constructor中 使用super可以继承到父类中的属性和方法
this.自定义属性=自定义属性值
}
方法()
}
}
// 在子类中调用父类的方法 需要使用super.父类方法名()
class类中setter(存值)和getter(取值)函数
格式
class 类名{
constructor(参数1,参数2) {
this.参数1=值
this.参数2=值
}
set 函数名(value) {
// 代码块
this.参数1=value // 设置新的value值
}
get 函数名() {
// 代码块
}
}
const 常量名=new 类名()
常量名.函数名=新的value值 // 存值
常量名.函数名 // 取值
例如:
class Demo {
constructor(x,y) {
this.x=x
this.y=y
}
set a(value) {
this.x=value
}
get a() {
console.log(this.x)
}
}
const a=new Demo(1,2)
console.log(a.x) // 1
a.x=3
a.x // 3
---------------------------------------------------------------------------------------------------
<script>
// 构造函数
// function Demo(x,y) {
// this.x=x
// this.y=y
// Demo.prototype.test=function() {
// console.log(x)
// }
// }
// const a=new Demo(100,2)
// console.log(a.test())
// class Demo{
// constructor(x,y) {
// this.x=x
// this.y=y
// }
// test() {
// console.log(this.x)
// }
// }
// const a=new Demo("张三","李四")
// console.log(a.test())
// class Father{
// constructor(money,house,car) {
// this.money=money
// this.house=house
// this.car=car
// }
// run() {
// console.log("running")
// }
// }
// const father=new Father(0.2, "5M", "人力三轮车")
// console.log(father.money, father.car)
// father.run()
// class Child extends Father{
// constructor(money, house, car, cars) {
// super(money, house, car) // 继承父类中属性
// this.cars=cars
// }
// eat() {
// console.log("eating", this.car)
// return super.run // 可以使用super.父类的方法名 调用父类中对应的方法
// }
// }
// const child=new Child(10, "10m","三轮车", "电动三轮车")
// console.log(child.eat())
// setter getter函数
class Parent{
constructor(name) {
this.name=name
}
get firstName() {
return "zhang"+this.name
}
set firstName(value) {
this.name=value
}
}
const parent=new Parent("san")
parent.firstName="san feng" // 存值
console.log(parent.firstName) // 取值
</script>
promise 语法
| 是一个对象 是异步编程的一种解决方案 相当一个容器 里边保存着未来可能发生的一种结果 |
|
|---|---|
| promise 有三种状态 | pending 进行中 resolve 成功 reject 失败 |
| 生成的结果只有两种 | pending => resolve 进行中到成功 pending => reject 进行中到失败 |
| 解决了传统函数的回调地狱 方法:.then( ) .catch |
格式:
function 函数名() {
return new Promise((resolve, reject)=> {
if() {
return resolve()
}else {
return reject()
}
})
}
调用
函数名().then(()=> {
// 成功回调
}).catch(()=> {
// 失败回调
})
注意:
promise里边只要是成功写在.then函数中 失败只用写一个.catch
我们可以一直写多个then函数 但是只能有一个catch函数 catch放在最后 链式调用
基于原生promise 第三方js库
axios
---------------------------------------------------------------------------------------
<script>
function run(name) {
console.log(name+"量体温")
return new Promise((resolve, reject)=> {
setTimeout(()=> {
if(Math.random()>0.5) {
return resolve()
}else {
return reject()
}
}, 500)
})
}
run("宿管阿姨").then(()=> {
console.log("体温正常")
return run("保安小弟")
}).then(()=> {
console.log("体温正常")
return run("地铁安检")
}).then(()=> {
console.log("体温正常")
return run("商场保安")
}).then(()=> {
console.log("成功抵达二七万达")
}).catch(()=> {
console.log("滚回去")
})
</script>
axios
| 基于promise的http库 异步请求 | |
|---|---|
| 特点: | 从浏览器中创建 XMLHttpRequests 从 node.js 创建 http 请求 支持 Promise API 拦截请求和响应 转换请求数据和响应数据 取消请求 自动转换 JSON 数据 客户端支持防御 XSRF |
| 安装使用 | 1 npm安装 npm i axios 2 cdn外部引入 |
| axios请求方式 | axios.request(config) axios.get(url[, config]) axios.delete(url[, config]) axios.head(url[, config]) axios.post(url[, data[, config]]) axios.put(url[, data[, config]]) axios.patch(url[, data[, config]]) |
| 常用请求方式 | get 格式: axios.get(“url”, { params: { 参数名1: 参数值1, 参数名2: 参数值2, … } }).then(res=> { // 成功回调 }).catch(err=> { // 失败回调 }) |
| post 格式: axios.post(“url”, { 参数名1: 参数值1, 参数名2: 参数值2, … }).then(res=> { // 成功回调 }).catch(err=> { // 失败回调 }) |
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
// axios.get("https://cnodejs.org/api/v1/topics", {
// params: {
// page: 1,
// limit: 10,
// tab: "good"
// }
// }).then(res=> {
// console.log(res)
// }).catch(err=> {
// console.log(err)
// })
function rei() {
axios.post("http://localhost:3000/register", {
admin: "lisi",
password: 123456
}).then(res=> {
console.log(res)
}).catch(err=> {
console.log(err)
})
}
</script>
async await
| 数据请求 (异步请求) | 格式: async function 函数名() { try { await 函数名() await 函数名() await 函数名() … } catch { // 错误捕获 } } |
|---|---|
| 注意:await必须在async内部 两者配合使用 成对出现 | |
| 现有阶段我们所能使用异步请求 | 1 XMLHttpRequest 2 jquery中$.axjx() $.get() $.post() 3 fetch() 4 基于promise异步请求 原生 axios axios.get() axios.post() 5 async await |
<script>
function request(name) {
console.log("向"+name+"请求")
return new Promise((resolve,reject)=> {
setTimeout(()=> {
if(Math.random()>0.5) {
resolve()
}else {
reject()
}
}, 1000)
})
}
// request("妈妈").then(()=> {
// console.log("同意")
// return request("爸爸")
// }).then(()=> {
// console.log("同意")
// return request("奶奶")
// }).then(()=> {
// console.log("同意")
// return request("爷爷")
// }).catch(()=> {
// console.log("相亲失败")
// })
async function marry() {
try{
await request("妈妈")
await request("爸爸")
await request("奶奶")
await request("爷爷")
}catch{
console.log("相亲失败")
}
}
marry()
</script>
import export
| es6语法中模块导入和输出。 模块功能主要由两个命令构成:export和import。 export命令用于规定模块的对外接口,import命令用于输入其他模块提供的功能。 在一个模块中如果只需要输入一个需要使用 export default 变量或者方法。 如果一次需要输出多个需要使用 export {变量1, 变量2, …}。 |
|
|---|---|
格式:
如果需要输出的是一个变量的时候
输出文件 a.js
let a=123
let b=456
export default a;
需要使用的文件 b.js
import a from "路径"
console.log(a)
如果需要输出的是多个变量时候
a.js
export {变量1, 变量2}
b.js
import {变量1, 变量2} from "路径"
如果b.js文件中已经声明相同变量 这个时候为了避免冲突 我们可以使用as别名
import {变量1 as 新的变量名1, 变量2 as 新的变量名2} from "路径"
如果输出多个变量 但是在引入时候只要其中一个 我们可以直接在引入的文件中只写一个
for..of遍历
| for…of 可以对数组进行循环遍历 不能遍历对象 |
遍历对象一般使用 for…in 格式 var arr=[1,2,3] for(let i of arr) { console.log ( i ) // 1 2 3 } |
|---|---|
<script>
let arr=["内容一","内容二","内容三"]
// const obj={
// name: "张三",
// sex: "男"
// }
// for(let i=0; i<arr.length; i++) {
// console.log(arr[i])
// }
// arr.forEach(item=> {
// console.log(item)
// })
for(let i of arr) {
console.log(i)
}
</script>
