1:三点运算符
(1). rest(可变)参数
* 用来取代arguments 但比arguments灵活,只能是最后部分形参参数
function add(...values) {
let sum = 0;
for(value of values) {
sum += value;
}
return sum;
}
(2). 扩展运算符
let arr1 = [1,3,5];
let arr2 = [2,...arr1,6];
arr2.push(...arr1);
<script type="text/javascript"> function fun(...values) { console.log(arguments); // arguments.forEach(function (item, index) { // console.log(item, index); // }); console.log(values); values.forEach(function (item, index) { console.log(item, index); }) } fun(1,2,3); let arr = [2,3,4,5,6]; let arr1 = ['abc',...arr, 'fg']; console.log(arr1); </script>
2:默认形参
* 形参的默认值----当不传入参数的时候默认使用形参里的默认值
function Point(x = 1,y = 2) {
this.x = x;
this.y =
y;
}
3:Promise对象
1. 理解:
* Promise对象: 代表了未来某个将要发生的事件(通常是一个异步操作)
* 有了promise对象, 可以将异步操作以同步的流程表达出来, 避免了层层嵌套的回调函数(俗称'回调地狱')
* ES6的Promise是一个构造函数, 用来生成promise实例
2. 使用promise基本步骤(2步):
* 创建promise对象
let promise = new Promise((resolve, reject) => {
//初始化promise状态为 pending
//执行异步操作
if(异步操作成功) {
resolve(value);//修改promise的状态为fullfilled
} else {
reject(errMsg);//修改promise的状态为rejected
}
})
* 调用promise的then()
promise.then(function(
result => console.log(result),
errorMsg => alert(errorMsg)
))
3. promise对象的3个状态
* pending: 初始化状态
* fullfilled: 成功状态
* rejected: 失败状态
4. 应用:
* 使用promise实现超时处理
* 使用promise封装处理ajax请求
let request = new XMLHttpRequest();
request.onreadystatechange = function () {
}
request.responseType = 'json';
request.open("GET", url);
request.send();
-->
window.onload = function () { //回调函数 //获取新闻信息 function getNews(url) { let promise = new Promise((resolve, reject) => { let request = new XMLHttpRequest(); request.onreadystatechange = () =>{ if(request.readyState === 4 ) { if(request.status == 200){ //请求发送成功 let news = request.response; resolve(news); } else{ reject("请求失败了。。。"); } } } request.responseType = "json"; request.open("GET",url); request.send();//发送 }) return promise; } getNews("http://127.0.0.1:3000/news?id=2").then((news)=>{ console.log(news); document.write(JSON.stringify(news)); console.log('http://localhost:3000' + news.commentsUrl); return getNews('http://localhost:3000' + news.commentsUrl); },()=>{ alert(error); }). then((comments) => { console.log(comments); document.write('<br><br><br><br><br>' + JSON.stringify(comments)); }, (error) => { alert(error); }) }