實戰二
計算平均值
傳統寫法
const average = function () {
const nums = Array.from(arguments);
const total = nums.reduce(function (acc, val) {
return acc + val
}, 0);
console.log(total);
return total / nums.length;
}箭頭函式寫法
const average = (...num) => num.reduce((acc, val) => acc + val, 0) / num.length;console.log(average(1, 2, 3, 4, 5, 10));
reduce() = 可以與前一個回傳的值再次作運算。
參數包含以下:
· accumulator
前一個參數,如果是第一個陣列的話,值是以另外傳入或初始化的值
· currentValue 當前變數
· currentIndex 當前索引
· array 全部陣列
實戰三
物件內的 this
傳統寫法
const person = {
data: {
},
getData: function() {
const vm = this;
$.ajax({
url: 'https://randomuser.me/api/',
dataType: 'json',
success: function(data) {
console.log(data);
vm.data = data.results[0];
console.log('person.data', person.data);
}
});
}
}
person.getData();
箭頭函式寫法
const person = {
data: {
},
getData: function() {
// 註解 const vm = this;
$.ajax({
url: 'https://randomuser.me/api/',
dataType: 'json',
success: (data) => {
console.log(data);
this.data = data.results[0];
console.log('person.data', person.data);
}
});
}
}
person.getData();
在此由於 success 改成箭頭函式寫法,所以沒有自己的 this,因此向外尋找時,參考了父層 this 也就是 getData。
因此 this 將會從此開始計算,那在下方 getData 是基於在 person 所呼叫,因此 this 就會指向到 person,那麼就不會指向 getData
補充資源:
一個可以告訴你js各種小技巧的chrome擴充插件(幾乎都是用es6寫法)
https://30secondsofknowledge.com/