0
点赞
收藏
分享

微信扫一扫

【ES6】

穆熙沐 2022-04-14 阅读 216
es6

ES6

ES是什么:全称EcmaScript,脚本语言的规范,而平时经常编写JavaScript,是EcmaScript的一种实现,所以ES新特性其实指的就是JavaScript的新特性

  • 变量
    let:

1.声明变量

let a ;
let a=1,b=[]

2.变量不能重复声明
3.块级作用域

{
	let girl='小红'
}

let相当于var有个优点:当在循环中,在var中会直接执行完毕获得最后执行的结果,而let会获得当前执行的值(例子如下)

for (var i=0;i<items.length;i++){
	items[i].onclick=function(){
		items[i].style.background='pink'//没有一个元素的背景色为粉色
		console.log(i)//3---由于变量是var所以会得到最终结果
		//var的解决办法:
		let that = this
		that.style.background='pink'
	}
}
//对比let
for (let i=0;i<items.length;i++){
	items[i].onclick=function(){
		items[i].style.background='pink'//let执行的就可以
	}
}

const:

1.声明变量

 const SCHOOL= '学校'//const由于是常量,声明变量最好用大写名称命名

2.一定要赋初始值
3.常量的值不能修改
4.块级作用域

{
	 const SCHOOL= '学校'
}

5.对于数组和对象的元素修改,不算对常量修改,不会报错

  • 结构赋值
    ES6允许按照一定模式从数组和对象中提取值,对变量进行赋值,这就称之为结构赋值

1.数组的结构赋值

 const arr =[1,2,3,4]
 let [one,two,three,fore] = arr
 console.log(one,two,three,fore)

2.对象的结构赋值

const obj = {
				one:1,
				two:2,
				three:3,
				fn:function(){
				}
			}
let {one,two,three,fn} = obj
  • 模板字符串
    ES6引入新的声明字符串的方式``

1.声明

let str = `hello world`

2.内容中可以直接出现换行符

let = `
	<div></div>
	<div></div>`

3.变量拼接

let str = 'hello world'
let str1 = `${str}js`
  • 简化对象的写法
    ES6允许大括号里面,直接写入变量和函数,作为对象的属性和方法
let name = '小红'
let change = function(){
	console.log(1111)
}
const school = {
	name,
	change,
	improve(){
		console.log(111)
	}
}
  • 箭头函数
    ES6允许使用{箭头}(=>)定义函数

1.声明一个函数

//普通函数
let fn = function(){}
//箭头函数
let fn = (a,b)=>{return a+b}

2.调用函数

let result =fn(1,2)
console.log(result)

3.不能作为构造实例化对象

let Person = (name,age)=>{
	this.name=name
	this.age=age
}
let me = new Person('xiaohong',12)
console.log(me)

3.不能使用arguments变量

let fn = ()=>{
	console.log(arguments)
}
fn(1,2,3)

4.箭头函数的简洁
省略小括号,当形参有且只有一个的时候

let add = m =>{
	return m+m
}
console.log(add(5))

省略花括号,当代码体只有一条语句的时候,此时return必须省略,而且语句的执行结果就是函数的返回值

let add = m => m+m
console.log(add(5))
  • 函数的参数默认值
    ES6允许给函数参数值初始值
function add(a,b=44,c){
	return a+b+c
}
console.log(result)
//与结构赋值结合
function add({a=1,b,c,d}){
	console.log(a,b,c,d)
}
add({
	a:2,
	b:3,
	c:5,
	d:6
})
  • rest参数
    ES6引入rest参数,用于获取函数的实参,用来代替arguments
//ES5获取实参的方式
function date(){
	console.log(arguments)
}
date(1,2,3)
//rest
function date(...args){
	cnsole.log(args)
}
date(1,2,3)
  • 拓展运算符
    [...]拓展运算符能将【数组】转换为逗号分隔的【参数序列】
//1.数组的合并
const arr=[1,2,3,4]
const arr1 = [5,6,7]
const arr3 = [...arr,...arr1]
//2.数组的克隆
const arr=[1,2,3]
const arr1 = [...arr]
//3.将伪数组转换为真正的数组
const div=['假设这是个伪数组']
const divArr = [...div]
  • Symbol
//创建Symobl
let s = Symobl()
let s2 = Symobl('小红')
let s3 = Symobl('小红')
console.log(s2==s3)//false
//Symobl.for创建
let s4 = Symobl('小红')
let s5 = Symobl('小红')
console.log(s3==s4)//true

Symobl内置属性

class Person{
	static [Symbol.hasInstance](params){
		console.log(params)
		return false
	}
}
let o ={}
console.log(o instanceof Person)

const arr = [1,2,3]
const arr2 = [4,5,6]
arr2[Symbol.isConcatSpredale]=false
arr2[Symbol.isConcatSpreadable] = false
console.log(arr.concat(arr2))

function getUers(){
	setTimeout(()=>{
		let data ='用户数据'
		iterator.next(data)
	},1000)
}
function * gen(){
	let users = yield getUers()
	console.log(users)
}
//调用生成器函数
let iterator = gen()
iterator.next()

1.Symbol.hasInstance:当其他对象使用instanceof运算符,判断是否为该对象的实例时,会调用这个方法
2.Symbol.isConcatSpreadable:对象的Symbol.isConcatSpreadable属性等于的是一个布尔值。表示该对象用于Array.prototype.concat()时,是否可以展开
3.Symbol.unscopables:该对象制定了使用with关键字,哪些属性会被with环境排除
4.Symbol.match:当执行str.match[myObject]时。如果该属性存在,会调用它,返回该方法返回值
5.Symbol.replace:当该对象被str.replace[myObject]方法调用时,会返回该方法的返回值
6.Symbol.search:当该对象被str.search[myObject]方法调用时,会返回该方法的返回值
7.Symbol.split:当该对象str.split(myObject)方法调用时,会返回该方法的返回值
8.Symbol.iterator:对象进行for…of循环时,会调用Symbol.iterator方法。会返回该方法的返回值
9.Symbol.toStringTag:在该对象上面调用tostring方法时,返回该方法的返回值
10.Symbol.species:创建衍生对象时,会使用该属性

  • promise
    promise是ES6引入的异步编程的新解决方案,语法上promise是一个构造函数,用来封装异步操作并可以获取其成功或失败的结果
//实例化promise对象
const p = new promise(function(resolve,reject){
	setTimeout(function(){
		let err = '数据读取失败'
		reject(err)
	},1000)
})
//调用promise对象的then方法
p.then(function(value){
	console.log(value)
},function(reason){
console.log(reson)
})
//正常获取fs
const fs = require("fs")
fs.readFile('./resource.txt',(err,data)=>{
	fs.readFile('./resource1.txt',(err,data1)=>{
		fs.readFile('./resource2.txt',(err,data2)=>{
			let result = data1+data2+data3
			console.log(result)
		})
	})
})
//用promise封装
const fs = require("fs")
const p = new Promise(function(resolve,reject){
	fs.readFile("./resource.txt",(err,data)=>{
		resolve(data)
	})
})
p.then(function(value){
	return new Promise(function(resolve,reject){
		fs.readFile("./resource1.txt",(err,data)=>{
			resolve(data)
		})
	})
}).then(value){
	return new Promise(function(resolve,reject){
		fs.readFile("./resource2.txt",(err,data)=>{
			value.push(data)
			resolve(data)
		})
	})
}).then(value){
	return new Promise(function(resolve,reject){
		fs.readFile("./resource3.txt",(err,data)=>{
			console.log(value)
			resolve(data)
		})
	})
})
//正常写ajax
//1.创建对象
const xhr = new XMLHTTPRequest()
//2.初始化
xhr.open('GET','URL')
//3.发送
xhr.send()
//4.绑定事件,处理响应结果
xhr.onreadystatechange=function(){
	if(xhr.readyState===4){
		if(xhr.status>=200&&xhr.status<300){
			console.log(xhr.response)//成功
		}else{//失败
			console.log(xhr.status)
		}
	}
}
//用promise封装
const p = new Promise((resolve,reject)=>{
	//1.创建对象
	const xhr = new XMLHTTPRequest()
	//2.初始化
	xhr.open('GET','URL')
	//3.发送
	xhr.send()
	//4.绑定事件,处理响应结果
	xhr.onreadystatechange=function(){
		if(xhr.readyState===4){
			if(xhr.status>=200&&xhr.status<300){
				resolve(xhr.response)//成功
			}else{//失败
				reject(xhr.response)
			}
		}
	}
})
p.then(function(value){
},function(reason){
	console.log(reason)
})

调用then方法 then方法的返回结果是Promise对象,对象状态由回调函数的执行结果决定。如果回调函数中返回的结果是 非promise类型的属性,状态为成功,返回值为对象的成功的值

  • set
    ES6提供了新的数据结构set(集合)。它类似于数组,但成员的值都是唯一的,集合实现;额iterator接口,所以可以使用【拓展运算符】和【for...of】进行遍历,集合的属性和方法。
let s = new Set()
let s2 = new Set([1,2,3,4])
console.log(s2.size)
s2.add('5')
s2.delete('3')
console.log(s2.has('1'))//true
for(let item of s2){
	console.log(item)
}
//set实践
//数组去重
let arr = [1,2,3,4,5,6,2,3,5,9]
let result = [...new Set(arr)]
//交集
let arr2 = [4,5,6,7]
let result = [...new Set(arr)].filter(item=>{
	let s2 = new Set(arr2)
	if(s2.has(item)){
		return true
	}else{
		return false
	}
})
//简写
let result = [...new Set(arr)].filter(item=>new Set(arr2).has(item))
//并集
let union = [...new Set([...arr,...arr2])]
console.log(union)
//差集
let diff = [...new Set(arr)].filter(item=>new Set(arr2).has(item))
console.log(diff)
  • Map
    ES6提供了Map数据结构,它类似于对象,也是键值对的集合,但是“键”的范围不限于字符串,各种类型的值(包括对象)都可以当做键。Map也实现了iterator接口,所以可以使用了【扩展运算符】和【for...of】进行遍历。Map的属性和方法。
let m = new Map()
//添加元素
m.set('name','xiaohong')
m.set('change',function(){
	console.log(111)
})
let key={
	school:'1'
}
m.set(key,[1,2,3])
console.log(m.size)
console.log(m.get('change'))
console.log(m.get(key))
m.clear()

//遍历
for(let v of m){
	console.log(v)
}
  • class类
    ES6提供了更接近传统语言的写法,引入了class(类)这个概念,作为对象的模板,通过class关键字,可以定义类。基本上,ES6的class可以看做只是一个语法糖,他的绝大部分功能,ES5都可以做到,行的class写法只是让对象原型的写法更加清晰,更像面向对象编程的语法而已。
function Phone(brand,price){
	this.brand = brand
	this.price = price
}
Phone.prototype.call = function(){
	console.log('11')
}
//实例化对象
let Iphone = new Phone('name','666')
Iphone .call()
console.log(Iphone)

//class
class Shouji{
	constructor(brand,price){
		this.brand = brand
		this.price = price
	}
	//方法必须使用该语法,不能使用ED5的对象完整形式
	call(){
		console.log('111')
	}
}
let onePlus = new Shouji('1+',1111)
console.log(onePlus )
//静态成员
function Phone(){}
Phone.name = 'shouji'
Phone.change = function(){
	console.log(111)
}
Phone.prototype.size = '5555'
let nokia = new Phone()
console.log(nokia.name) 
//class
//static---属于类不属于实例对象
class Phone{
	static name = 'shouji'
	static change(){
		console.log('555')
	}
}
let nokia = new Phone()
console.log(nokia.name) //undefined
console.log(Phone.name) //shouji
//对象继承
function Phone(brand,price){
	this.brand = brand
	this,price = price
}
Phone.prototype.call = function(){
	console.log(111)
}
function SmartPhone(brand,price,color,size){
	Phone.call(this,brand,price)
	this.color=color
	this.size = size
}
//设置了构造函数的原型
SmartPhone.prototype.phone = function(){
	console.log(111)
}
SmartPhone.prototype.playGame = function(){
	console.log(222)
}
const chuizi = new SmartPhone('锤子',2499,'黑色','wsw')
console.log(chuizi )

//class
constructor(brand,price){
	this.brand = brand
	this.price=price
	//父类成员的属性
	call(){
		console.log('1111')
	}
}
class SmartPhone extends Phone{
	constructor(brand,price,color,size){
		super(brand,price)
		this.color=color
		this.size=size
	}
	photo(){
		console.log(111)
	}
	playGame(){
		console.log(222)
	}
	//如果子类写了与父类的函数名一样,相当于重写,子类把父类方法给覆盖了
	call(){
		console.log('5555')
	}
}
const xiaomi = new SmartPhone ('小米',799,'黑色','5wef')
console.log(xiaomi)
xiaomi.call()
xiaomi.photo()
xiaomi.playGame()
//get和set
//set当被修改的时候才会被调用
class Phone(){
	get price(){
		console.log('111')
	}
	set price(newValue){
		console.log('555')
	}
}
//实例化对象
let s = new Phone()
s.price = 'free'
  • 数值扩展
    Number.EPSILON是JavaScript表示的最小精度
function equal(a,b){
	if(Math.abs(a-b)<Number.EPSILON){
		return true
	}else{
		return false
	}
}
console.log(0.1+0.2===0.3)//false
console.log(equal(0.1+0.2,0.3))//true

1.二进制和八进制

let b = 0b1010
let o = 0o777
let d = 100
let x = 0xff

2.Number.isNaN检测一个数字是否为NaN

console.log(Number.isNaN(123))

3.Number.isFinite检测一个数字是否为有限数

console.log(Number.isFinite(100))

4.Number.parseInt Number.parseFloat字符串转整数

console.log(Number.parseInt(462.46))

5.Number.isInteger判断一个数是否为整数

console.log(Number.isInteger(5))

6.Math.trunc将数字的小数部分抹掉

console.log(Math.trunc(3.5))

7.Math.sign判断一个数到底为正数、负数、还是零

console.log(Math.sign(100))
  • 对象方法拓展
    1.Object.is判断两个值是否完全相等
console.log(Object.is(120,120))

2.Object.assign对象的合并

const obj = {
	name:'xiaohong',
	age:18
}
const obj2 = {
	name:'xioaming',
	age:17
}
console.log(Object.assign(obj,obj2))

3.Object.setPrototype设置原型对象 Object.getPrototypeof

const school = {
	name:'xuexiao'
}
const cities = {
	city:['上海','北京','广州','深圳']
}
Object.setPrototype(school ,cities )
console.log(school )
console.log(Object.getProptotypeof(school))
  • 模块化
    模块化是指将一个大的程序文件,拆分成许多小的文件,然后将小文件组合起来
  1. export命令用于规定模块的对外接口
  2. important命令用于输入其他模块提供的功能
export let school = 'xuexiao'
export function teach(){
}
//通用导入形式
import * as m1 from './src/js/m1.js'
//解构赋值的形式
import {school,teach} from './src/js/m1.js'
import {school as xuexiao,findJob} from './src/js/m2.js'
//as--是用来修改名字的  不能名字一样,所以用as修改名字

  • babel
    官网:https://babel.docschina.org/
    http://www.ruanyifeng.com/blog/2016/01/babel.html
举报

相关推荐

0 条评论