一:ES6的一些数组方法
1、foreach
对于一个数组
var colors=["red","green","blue"];
//ES5
for(var i=0;i
//ES6
colors.forEach(function(color){
console.log(color);
})
遍历数组中的值并计算总和
var numbers=[1,2,3,4,5];
var sum=0;
function adder(number){
sum+=number;
}
numbers.forEach(adder);
console.log(sum);//15
2、map
map需要返回值,如果不返回,默认undefined,map返回的是一个新的数组。
假定一个数值数组A,将数组中的值以两倍形式放到B中
var numbers=[1,2,3];
var doubleNumbers=[];
//ES5
for(var i=0;i
//ES6
var double=numbers.map(function(number){
return number*2;
})
console.log(double);
假定一个对象数组A,将A中对象某个属性的值存到B中
var cars=[
{model:"Buick",price:"cheap"},
{model:"BMW",price:"expensive"}
];
var prices=cars.map(function(car){
return car.price;
})
console.log(prices);// ["cheap", "expensive"]
3、filter(过滤)
假定一个数组对象A,获取数组中指定类型的对象放到B数组中
var products=[
{name:"cucumber",type:"vegetable"},
{name:"banner",type:"fruit"},
{name:"celery",type:"vegetable"},
{name:"apple",type:"fruit"}
];
//ES5
var filtered=[];
for(var i=0;i
//ES6 filter
var filtered=products.filter(function(product){
return product.type==="fruit";
})
console.log(filtered);
假定一个对象数组A,过滤掉不满足条件的对象
条件:蔬菜数量大于0,价格小于10
var products=[
{name:"cucumber",type:"vegetable",num:0,price:20},
{name:"banner",type:"fruit",num:10,price:1},
{name:"celery",type:"vegetable",num:20,price:2},
{name:"apple",type:"fruit",num:20,price:20}
];
var filtered=products.filter(function(product){
return product.type==="vegetable"
&&product.num>0
&&product.price<10
})
console.log(filtered);
假定数组A、B,根据A中的ID,过滤到B中不符合的数据
var posts=[
{id:4,title:"java"},
{id:1,title:"linux"},
{id:2,title:"js"},
{id:4,title:"jquery"}
];
var comments={id:4,title:"vue.js"};
function commentsforposts(posts,comments){
return posts.filter(function(post){
return post.id===comments.id;
})
}
console.log(commentsforposts(posts,comments));//posts中的id为4的会被打印出来
4、find(只会找到第一个就停止了)
假定一个数组A,找到符合条件的对象
var users=[
{name:"JIll"},
{name:"Alex"},
{name:"Bill"}
];
//ES5
var user;
for(var i=0;i
//ES6
var user=users.find(function(user){
return user.name==="Alex";
})
console.log(user);
假定对象数组A,根据指定对象的条件找到数组中符合条件的对象
var posts=[
{id:1,title:"node.js"},
{id:2,title:"vue.js"}
];
var comment={postId:1,content:"Hello World!"};
function postforcomment(posts,comment){
return posts.find(function(post){
return post.id===comment.postId;
});
}
console.log(postforcomment(posts,comment));
5、every&&some
计算对象数组中每个电脑的操作系统是否可用,大于16位的操作系统表示可用,否则不可用
var computers=[
{name:"Apple",ram:16},
{name:"IBM",ram:4},
{name:"Acer",ram:32}
];
//ES5
var everycomputersCanRun=true;//所有都满足条件才为true
var somecomputersCanRun=false;//只要有一个满足条件就为true
for(var i=0;i
//ES6 every
var every=computers.every(function(computer){
return computer.ram>16;
})
console.log(every);
//ES6 some
var some=computers.some(function(computer){
return computer.ram>16;
})
console.log(some);
假定有一个注册页面,判断所有input内容长度是否为0
function Filed(value){
this.value=value;
}
Filed.prototype.validate=function(){
return this.value.length>0;
}
var username=new Filed("");
var password=new Filed("123")
//ES5
// console.log(username.validate()&&password.validate());
//ES6
var fileds=[username,password];
var formisValid=fileds.every(function(filed){
return filed.validate();
})
console.log(formisValid);
if(formisValid){
//允许注册
}else{
//报空
}
6、reduce
计算数组中所有值的总和
var numbers=[10,20,30];
var sum=0;
//ES5
for(var i=0;i
将数组中对象的某个属性抽到另一个数组中
var primarycolor=[
{color:"red"},
{color:"yellow"},
{color:"blue"}
];
var colors= primarycolor.reduce(function(pre,color){
pre.push(color.color);
return pre;
},[]);//初始化一个数组
console.log(colors);//["red","yellow","blue"]
判断字符串中字符串是否对称
function balance(string){
return !string.split("").reduce(function(pre,char){
if(pre<0){
return pre;
}//字符串第一个不能为")",否则返回false
if(char=="("){
return ++pre;
}
if(char==")"){
return --pre;
}
return pre;
},0);
}
console.log(balance(")(((())))"));//不对称返回false,对称返回true
二:var&&let&&const
let声明的变量有作用域的概念,更严谨;const声明常量,不能改变,但是数组能添加值
for(var i=0;i<10;i++){
console.log(i);//0-9
}
console.log(i);//0-10
for(let i=0;i<10;i++){
console.log(i);//0-9
}
console.log(i);//报错
三:模版字符串
let name="Herry";
function makeUppercase(word){
return word.toUpperCase();
}
let temp=`谢谢${name},${makeUppercase('haha')}
`;//ES6
let aa='欢迎欢迎
'+
'啦啦啦
';//字符串拼接
document.getElementById('temp').innerHTML=temp;
document.getElementById('team').innerHTML=aa;
四:箭头函数(1、缩减代码 2、改变this指向)
如图,缩减了很多代码
var double=function(number){
return number*2;
}
var double2=(number)=>{
return number*2;
}
var double3=number=>number*2;
var double4=(number,number2)=>number+number2;
console.log(double4(20,2));
还有this指向问题
const team={
members:["Henry","Elyse"],
teamName:"es6",
teamSummary:function(){
return this.members.map(function(member){
//当前this指向不明确了
return `${member}隶属于${this.teamName}小组`;
})
}
}
console.log(team.teamSummary());//${this.teamName}为undefined
通常ES5有两种解决办法
第一种解决办法
const team={
members:["Henry","Elyse"],
teamName:"es6",
teamSummary:function(){
let self=this;//外部存储指向
return this.members.map(function(member){
return `${member}隶属于${self.teamName}小组`;
})
}
}
console.log(team.teamSummary());
第二种解决办法
const team={
members:["Henry","Elyse"],
teamName:"es6",
teamSummary:function(){
return this.members.map(function(member){
return `${member}隶属于${this.teamName}小组`;
}.bind(this));//bind把this绑定到函数
}
}
console.log(team.teamSummary());
箭头函数解决了this指向
const team={
members:["Henry","Elyse"],
teamName:"es6",
teamSummary:function(){
return this.members.map((member )=>{
return `${member}隶属于${this.teamName}小组`;
})
}
}//this指向team函数
console.log(team.teamSummary());
五:增强对象字面量(缩减代码)
// new Object();{}
// new Array();[]
function createBookShop(inventory){
return{
inventory,//inventory:inventory
inventoryValue(){
return this.inventory.reduce((total,book)=>total+book.price,0);
},
priceForTitle(title){
return this.inventory.find(book=>book.title===title.price);
}
}
}
const inventory=[
{title:"Vue",price:10},
{title:"Angular",price:15}
]
// const bookShop=createBookShop(inventory);
// console.log(bookShop.inventoryValue("Vue"));
function saveFile(url,data){
$.ajax({
method:"POST",
url,//url:url
data//data:data
});
}
const url="http://fileupload.com";
const data={color:"red"};
saveFile(url,data);
六:默认参数(优化代码)
两种默认参数
function makeAjaxRequest(url,method){
if(!method){
method="GET";
}
return method;
}
console.log(makeAjaxRequest("google.com"));
console.log(makeAjaxRequest("google.com","POST"));
//---------------------------------------------------
function makeAjaxRequest(url,method="GET"){
return method;
}
console.log(makeAjaxRequest("google.com"));
console.log(makeAjaxRequest("google.com","POST"));
一个实例
function User(id){
this.id=id;
}
// console.log(new User(1));
function randomId(){
return Math.random()*999999;
}
// console.log(new User(randomId()));
function createAdminUser(user=new User(randomId())){
user.admin=true;
return user;
}
console.log(createAdminUser());//不传参时为一个随机值
七:展开运算符(spread operator)
function addNumbersn(numbers){
return numbers.reduce((sum,number)=>{
return sum+number;
},0)
}
const numbers=[1,2,3,4,5];
console.log(addNumbersn(numbers));
function addNumbersn(a,b,c,d,e){
var numbers=[a,b,c,d,e];
return numbers.reduce((sum,number)=>{
return sum+number;
},0)
}
console.log(addNumbersn(1,2,3,4,5));
function addNumbersn(...numbers){
return numbers.reduce((sum,number)=>{
return sum+number;
},0)
}
console.log(addNumbersn(1,2,3,4,5,6));//这可以随便几个参数
var defaultColors=["red","green"];
var favouriteColor=["orange","yellow"];
// var defaultColors=defaultColors.concat(favouriteColor);
// console.log(defaultColors);
console.log([...defaultColors,...favouriteColor]);//数组拼接
八:解构(更快,更便捷)
var expense={
type:"es6",
amount:"45"
}
// var type=expense.type;
// var amount=expense.amount;
const{type,amount}=expense;//解构写法,名字和属性必须一致
console.log(type,amount);
//es5
var savefiled={
extension:"jpg",
name:"girl",
size:14040
};
function fileSammary(file){
return `${file.name}.${file.extension}的总大小${file.size}`
}
console.log(fileSammary(savefiled));
//es6
var savefiled={
extension:"jpg",
name:"girl",
size:14040
};
function fileSammary({name,extension,size}){
return `${name}.${extension}的总大小${size}`
}
console.log(fileSammary(savefiled));
const names=["Henry","Bucky","Emily"];
// 解构
const[name1,name2,name3]=names;
console.log(name1,name2,name3);
// 返回数组个数
const {length}=names;
console.log(length);
// 结合展开运算符
const[name,...rest]=names;
console.log(rest);
let a,b;
[a,b]=[100,200];
console.log(b);
//对象数组
const people=[
{name:"Henry",age:20},
{name:"Bucky",age:25},
{name:"Emily",age:30}
];
//es5
var age=people[0].age;
console.log(age);//20
//es6解构
const[age]=people;
console.log(age);//第一个对象
const[{age}]=people;
console.log(age);//20
将数组转化为对象
const points=[
[4,5],
[10,1],
[0,40]
];
//期望数据格式
// [
// {x:4,y:5},
// {x:10,y:1},
// {x:0,y:40}
// ]
//es6
let newPoints=points.map(pair=>{
const x=pair[0];
const y=pair[1];
return{x,x};
})
console.log(newPoints);
//---------------------------------
let newPoints=points.map(pair=>{
const[x,y]=pair;
return{x,x};
})
console.log(newPoints);
//----------------------------------
let newPoints=points.map(([x,y])=>{
return{x,y};
});
console.log(newPoints);
九:类class
function Car(option){
this.title=option.title;
}
Car.prototype.drive=function(){
return "Vroom";
}
const car=new Car({title:"BMW"});
console.log(car);
console.log(car.drive());
// es5继承
function Toyota(option){
Car.call(this,option);//加上这个就能拿到title了
this.color=option.color;
}
Toyota.prototype=Object.create(Car.prototype);
Toyota.prototype.constructor=Toyota;
const toyota=new Toyota({color:"red",title:"Focus"});
console.log(toyota);//只能拿到color
console.log(toyota.drive());//继承到了drive方法
//es6 继承
class Car{
constructor({title}){
this.title=title;
}
drive(){
return 'vroom';
}
}
const car=new Car({title:"BMW"});
console.log(car);
console.log(car.drive());
class Toyota extends Car{
constructor(options){
super(options);
this.color=options.color;
}
}
const toyota=new Toyota({color:"red",title:"Focus"});
console.log(toyota);
console.log(toyota.drive());
十、generator生成器(返回多次值的函数)
//斐波那契数列
function fib(max){
var a=0,b=1,arr=[0,1];
while(arr.length
//genertor生成器
function* fib(max){
var a=0,b=1,n=0;
while(n
//迭代器还原生成器结构
function nameIterator(names){
let nextIndex=0;
return{
next:function(){
return nextIndex
//id自增(es6生成器)
function* createIds(){
let index=1;
while(true){
yield index++;
}
}
const gen=createIds();
for(var i=0;i<10;i++){
console.log(gen.next().value);
}
十一、新的数组结构(map)
const map1=new Map();
const key1='some string',key2={},key3=function(){};
map1.set(key1,'Value of key1');
map1.set(key2,'Value of key2');
map1.set(key3,'Value of key3');
//获取对应value
console.log(map1.get(key1),map1.get(key2),map1.get(key3));
//获取value的个数
console.log(map1.size);
//for of遍历map1
for(let[key,value] of map1){
console.log(`${key}=${value}`);
}
//only key
for(let key of map1.keys()){
console.log(key);
}
//only value
for(let value of map1.values()){
console.log(value);
}
//foreach遍历
map1.forEach((value,key)=>{
console.log(`${key}=${value}`);
})
//map1转化为数组
const keyValueArray=Array.from(map1);
console.log(keyValueArray);
//map1中的key转化为数组
const keyArray=Array.from(map1.keys());
console.log(keyArray);
//map1中的value转化为数组
const valueArray=Array.from(map1.values());
console.log(valueArray);
十二、新的数据类型(set,集合,都可以存储任何数据类型,但是唯一)
const set1=new Set();
//往set1中添加数据
set1.add(100);
set1.add("A String");
set1.add({name:"Henry"});
set1.add(true);
set1.add(100);//不显示,不可以重复添加
console.log(set1);
const set2=new Set([1,true,'string']);//初始化
console.log(set2);
// //计算set1中的数据个数
console.log(set1.size);
//检查set中是否拥有对应的值
console.log(set1.has(100));
console.log(set1.has(50+50));
console.log(set1.has({name:"Henry"}));//匹配的不是值,是地址,所以打印为false
//删除set中的内容
set1.delete(100);
console.log(set1);
//for of 遍历set
for(let item of set1){
console.log(item);
}
//foreach遍历
set1.forEach((value)=>{
console.log(value);
})
//将set转换为array
const setArray=Array.from(set1);
console.log(setArray);
十三、Promise(构造函数)
promise有三种状态
unresolved 等待任务完成
resolved 任务完成并且没有任何问题
rejected 任务完成,但是出现问题
resolved==>then
rejected==>catch
var promise=new Promise((resolve,reject)=>{
resolve();//Promise {: undefined}
reject();//Promise {: undefined}
});
console.log(promise);
var promise=new Promise((resolve,reject)=>{
// resolve();//只能调用then方法
reject();//只能调用catch方法
})
promise
.then(()=>console.log("成功,没有任何问题!"))
.then(()=>console.log("成功,可以无限调用.then方法!"))
.catch(()=>console.log("uh oh,出现了重大问题!"))
十四、新的http请求方法(fetch)
//3秒后执行then方法
let promise=new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve();
},3000)
})
// promise
// .then(()=>console.log("成功,没有问题"))
let url="http://jsonplaceholder.typicode.com/posts";//正确地址
let url1="http://jsonplaceholder.typicode.com111/posts";
// console.log(fetch(url));
fetch(url)
.then(response=>response.json())
.then(data=>console.log(data))
fetch(url1)
.catch(err=>console.log("error:"+err))
fetch请求text、json、api
//fetch三种数据格式
document.getElementById('button1').addEventListener('click',getText);
document.getElementById('button2').addEventListener('click',getJson);
document.getElementById('button3').addEventListener('click',getExternal);
function getText(){
fetch("test.txt")
.then((res)=>res.text())
.then(data=>{
console.log(data);
document.getElementById('output').innerHTML=data;
})
.catch(err=>console.log(err))
}
function getJson(){
fetch("posts.json")
.then((res)=>res.json())
.then(data=>{
console.log(data);
let output='';
data.forEach((post)=>{
output+=`${post.title} `;
})
document.getElementById('output').innerHTML=output;
})
.catch(err=>console.log(err))
}
//请求网络api
function getExternal(){
fetch("https://api.github.com/users")
.then((res)=>res.json())
.then(data=>{
console.log(data);
let output='';
data.forEach((user)=>{
output+=`${user.login} `;
})
document.getElementById('output').innerHTML=output;
})
.catch(err=>console.log(err))
}
封装了fetch库(增删改查)
class Easyhttp{
get(url){
return new Promise((resolve,reject)=>{
fetch(url)
.then(res=>res.json())
.then(data=>resolve(data))
.catch(err=>reject(err))
})
}
//post
post(url,data){
return new Promise((resolve,reject)=>{
fetch(url,{
method:"POST",
headers:{
'Content-type':'application/json'
},
body:JSON.stringify(data)
})
.then(res=>res.json())
.then(data=>resolve(data))
.catch(err=>reject(err))
})
}
//put
put(url,data){
return new Promise((resolve,reject)=>{
fetch(url,{
method:"PUT",
headers:{
'Content-type':'application/json'
},
body:JSON.stringify(data)
})
.then(res=>res.json())
.then(data=>resolve(data))
.catch(err=>reject(err))
})
}
delete(url){
return new Promise((resolve,reject)=>{
fetch(url,{
method:"DELETE",
headers:{
'Content-type':'application/json'
},
body:JSON.stringify(data)
})
.then(res=>res.json())
.then(data=>resolve('数据删除成功'))
.catch(err=>reject(err))
})
}
}
实现这个库
const http=new Easyhttp;
//get
const users=http.get("http://jsonplaceholder.typicode.com/users")
.then((data)=>{
console.log(data);
})
.catch(err=>console.log(err))
//传输数据
const data={
name:"Henry",
username:"Mrs吴",
email:"[email protected]"
};
//post
http.post("http://jsonplaceholder.typicode.com/users",data)
.then(data=>console.log(data))
.catch(err=>console.log(err))
//update user
http.put("http://jsonplaceholder.typicode.com/users/2",data)
.then(data=>console.log(data))
.catch(err=>console.log(err))
//delete user
http.delete("http://jsonplaceholder.typicode.com/users/1")
.then(data=>console.log(data))
.catch(err=>console.log(err))