js新方法

4. 展开(spread)语法

在下面的示例中,Math.max 不能直接接受 arr 数组,因为它的参数不是数组类型,但可以以数组中的各个元素作为参数。展开运算符... 可用于提取数组的各个元素。

const arr = [4, 6, -1, 3, 10, 4];
const max = Math.max(...arr);
console.log(max);
// 10


5. 变长参数(rest)语法

你可以用它将传给函数的任意数量的参数放入数组中!

function myFunc(...args) {
console.log(args[0] + args[1]);
}
myFunc(1, 2, 3, 4);
//3

reduce:基于给定函数累加值。

const arr = [1, 2, 3, 4, 5, 6];
const reduced = arr.reduce((total, current) => total + current);
console.log(reduced);
// 21
11. promise

一旦你理解了 JavaScript 回调,很快就会发现自己陷入了“回调地狱”中。这个时候可以使用 promise!将异步逻辑包装在 promise 中,使用“then”来处理成功的情况,使用“catch”来处理异常。

const myPromise = new Promise(function(res, rej) {
setTimeout(function(){
if (Math.random() < 0.9) {
return res('Hooray!');
}
return rej('Oh no!');
}, 1000);
});
myPromise
.then(function(data) {
console.log('Success: ' + data);
})
.catch(function(err) {
console.log('Error: ' + err);
});

// If Math.random() returns less than 0.9 the following is logged:
// "Success: Hooray!"
// If Math.random() returns 0.9 or greater the following is logged:
// "Error: On no!"
 
 
原文地址:https://www.cnblogs.com/guidan/p/10471174.html