js中function參數預設值

來源:互聯網
上載者:User

標籤:參考   --   alert   cli   onclick   string   nts   數組   運行   

--在dreamweaver做網站時,函數定義是在一個*.js檔案中,其中定義了一個func,有四個參數,function func(string1,url,flag,icon),然後在另一個asp中調用它func(a,b),那flag和icon的值是什麼,怎麼定義預設值?謝謝!

--預設值應該是 undefined
在函數內預設數可以用 arguments[i]
i就是你參數的位置 第一個為0
所以要設定 flag 的預設值 則可以這麼寫
function func(string1,url,flag,icon){
  if(!arguments[2]) flag = "123";
  if(!arguments[3]) icon = "456";
}
你試試 應該是這樣

--------------------------------------------------------------------------------

今天遇到一個問題,需要調用一個JS函數,想在函數中給它一個預設參數,以為跟其他語言一樣。
<script>
function test(id=0){
    alert(id);
}
</script>
<input type="button" value="test" onclick="test()">
運行結果報錯,JS中不能這樣傳預設參數,上網查了一下,可以藉助於arguments 實參數組,參考下例:

  1. <script> 
  2. function test(a){ 
  3. var b=arguments[1]?arguments[1]:50 
  4. return a+‘:‘+b 
  5. } 
  6. alert(test(5)) 
  7. alert(test(5,9)) 
  8. </script> 

跟其他語言的一點小區別。。

--var b=arguments[1]?arguments[1]:50 還可以寫做: var b= arguments[1] || 50; 我特別喜歡它這個特性。

--var b= arguments[1] || 50; 這個方法相當精簡啊。

js中function參數預設值

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.