ES6新增(2)

来源:互联网 发布:mac os x怎么下载 编辑:程序博客网 时间:2024/06/05 02:06

关于ES6新增的东西(2)

六、原生Promise

就是一个对象,用来传递异步操作的数据(消息)pending(等待、处理中)—> Resolve(完成、fullFilled)              —> Rejected(拒绝、失败)

ES6:

复制代码
var p1=new Promise(function(resolve,reject){    //resolve  成功了    //reject    失败了        });var p1=new Promise(function(resolve,reject){    if(异步处理成功了){        resolve(成功数据)    }else{        reject(失败原因)    }        });p1.then(成功(resolve),失败(reject))    √--------------------------------------------p1.catch——用来捕获错误
复制代码

七、新方法

1》箭头函数

根据参数个数不同,分这几种情况:
() => { … } // 零个参数用 () 表示
x => { … } // 一个参数可以省略 ()
(x, y) => { … } // 多参数不能省略 ()

eg:

复制代码
/*function show(a){return a;}var s=show(12);alert(s);*/var show=(a,b)=>a+b;var s=show(12,5);
复制代码

 2》复制数组

   arr2.from(arr)//这样不用再使用for循环了

​      arr2 = [...arr]

​ 3》for of循环

​ 4》map 、delete

八、默认参数

ES5:

复制代码
function point(x, y, isFlag){  x = x || 0;  y = y || -1;  isFlag = isFlag || true;  console.log(x,y, isFlag);}point(0, 0) // 0 -1 true point(0, 0, false) // 0 -1 true point(1) // 1 -1 truepoint() // 0 -1 true
复制代码

注意到了这里有问题,这里的默认参数先进行了布尔值的类型转换,因为undefined、0、false、null都是假。修改一下可以这样写

1
2
3
4
5
6
7
8
9
10
function point(x, y, isFlag){
  x = x || 0;
  y = typeof(y) === 'undefined' ? -1 : y;
  isFlag = typeof(isFlag) === 'undefined' ? true : isFlag;
  console.log(x,y, isFlag);
}
point(0, 0) // 0 0 true
point(0, 0, false) // 0 0 false
point(1) // 1 -1 true
point() // 0 -1 true

  

ES6:

复制代码
function point(x = 0, y = -1, isFlag = true){  console.log(x,y, isFlag);}point(0, 0) // 0 0 truepoint(0, 0, false) // 0 0 falsepoint(1) // 1 -1 truepoint() // 0 -1 true
复制代码
0 0
原创粉丝点击