下载babel
npm install --save-dev @babel/core
函数扩展
javascript
<script>
// // 新的函数方法,可以直接传参,没有传入新参时,显示原来的,传入新参时,显示新参数
// function fn(x = 0,z="缺省值"){
// console.log(x)
// console.log(z)
// }
// fn(100,"哈哈")
// function fn2(){
// console.log(arguments);
// }
// fn2(1,2,3,4)
// 出现arguments类,可以写出下面这样
function fn2(...values){
for(let v of values){
console.log(v);
}
}
fn2(1,2,3,4)
</script>
箭头函数
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 箭头函数
var fn5 = function(name,age){
if (name == 'ivy'){
return '主人'
}else{
return '客人'
}
}
// 改写为箭头函数
// 箭头前面表示的是需要传入的参数,后面表示需要做的操作
var fn5 = (name,age) => {
if (name == 'ivy'){
return '主人'
}else{
return '客人'
}
}
// 匿名函数
console.log(fn5('ivy',20))
var arr = [1,2,3,4]
arr.map(function(element,index){
console.log(element)
})
// 改写
arr.map((element,index) => {
console.log(element);
})
</script>
</body>
</html>
promise对象
javascript
<script>
// 写法一
const promise = new Promise((resolve,reject) => {
if("成功"){
resolve(data)
}else{
reject(error)
}
})
// 写法二
promise.then(data => {
return console.log('成功')
})
.catch(error => {
console.log("失败")
})
</script>
网络请求promise
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function getJSON(url){
const promise = new Promise((resolve,reject) => {
// 网络请求
const handler = function(){
if(this.readyState != 4){
return
}
if (this.status == 200){
resolve(this.response);
}else{
reject(new Error("资源错误"));
}
}
const client = new XMLHttpRequest();
client.open("GET",url);
client.onreadystatechange = handler;
client.responseType = 'json';
client.setRequestHeader("Accept","application/json");
client.send();
});
return promise;
}
getJSON("baidu.com")
.then(res => {
console.log(res);
})
.catch(error => {
console.log(error)
})
</script>
</body>
</html>