箭頭函數

目的

簡化function的形式,只保留參數與函式

//ES5
function(參數){
  函式
}

//ES6
(參數) => {函式}

範例

var names=["Ian", "Moko", "Afro"];

//ES5
//names的毎筆資料會丟進function的參數
//變成全名
//陣列.map(),修改原陣列,變成新的陣列
var fullNames=names.map(
 function(name){
 return `${name} CHEN`;
 }
);
console.log(fullNames);//["Ian CHEN", "Moko CHEN", "Afro CHEN"]

//ES6
//(參數) => {函式}
var fullNames2=names.map(
 (name) => 
 {return `${name} CHEN`;});
console.log(fullNames2);//["Ian CHEN", "Moko CHEN", "Afro CHEN"]


//只有一個參數的話可以不用()
//也可以省略return,順便拿掉{}
var fullNames3=names.map(name => `${name} CHEN`);
console.log(fullNames3);//["Ian CHEN", "Moko CHEN", "Afro CHEN"]

進階:指定參數初始値

const numbers=[5,2,7,10,50];

//ES5
var total=0;
for(i=0;i<numbers.length;i++){
 total += numbers[i];
}

console.log(total) //74

//ES6
//reduce,陣列累加用法
const total2=numbers.reduce((total, number) => {
 return total += number;
},0)//←這邊的0等同於宣告total初始値=0,total從0開始累加

console.log(total2) //74

進階:多個述句(statement)

加分號結束後直接寫

button.btns click
button.btns click
button.btns click
#btnstatus
const btns=document.querySelectorAll(".btns");
btns.forEach((btn, n) => {
  btn.addEventListener("click", function(){
  btnstatus.textContent=`you clicked btn ${n+1}`;
 });
  btn.addEventListener("mousemove", function(){
  btnstatus.textContent=`you touched btn ${n+1}`;
 })
})

Display

Leave a Reply

Your email address will not be published. Required fields are marked *