關於js中高階函數的認識

來源:互聯網
上載者:User

標籤:function   epp   數字   高階函數   black   else   console   傳回值   i+1   

Javascript中的高階函數,是我們在編程中使用的一種重要的函數式編程,它的主要形式有兩種。一種是把函數作為參數傳遞到另外一個函數中(例如:事件監聽器),另一種是把函數作為傳回值放入另外的函數中(例如:閉包函數)。

 

把函數作為參數傳遞的形式:

例:建立10個div並給每一個div中添加相應的數字

<body>

<div id="container">

 

</div>

</body>

<script>

//建立函數

function create(fn){

var  container = document.getElementById(‘container‘);

for(var i=0;i<10;i++){

var  div = document.createElement(‘div‘);

div.innerHTML = i+1;

container.appendChild(div);

if( typeof fn ==‘function‘){

 

fn(div);

}else{

console.log(‘輸入錯誤!‘)

 

}

}

}

 

 

//子項目添加樣式

//樣式一

function setStyle(div){

div.style.margin =‘0 auto‘;

div.style.width = ‘100px‘;

div.style.height = ‘100px‘;

div.style.background = ‘deeppink‘;

div.style.border = ‘1px solid black‘;

div.style.display = ‘inline-block‘;

}

 //樣式二

function setStyle1(div){

div.style.margin =‘0 auto‘;

div.style.width = ‘50px‘;

div.style.height = ‘50px‘;

div.style.background = ‘blue‘;

div.style.border = ‘1px solid black‘;

div.style.display = ‘inline-block‘;

}

 

create(setStyle);

create(setStyle1);

</script>

把函數作為傳回值形式

例:利用高階函數,實現簡單的加減乘除計算機

//計算公式

function add(a,b){

return a+b;

};

function sub(a,b){

return a-b;

};

function mul(a,b){

return a*b;

};

function div(a,b){

return a/b;

};

//高階Function Compute器

function calc(fn){

return function(){

if(typeof fn == ‘function‘){

return fn.apply(this,arguments);

}

}

};

var a = calc(add)(1,2);

var b = calc(sub)(1,2);

var c = calc(mul)(1,2);

var d = calc(div)(1,2);

console.log(a);//輸出3

console.log(b);//輸出-1

console.log(c);//輸出2

console.log(d);//輸出0.5

關於js中高階函數的認識

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.