函数参数 不定参数,和 默认参数
生活随笔
收集整理的這篇文章主要介紹了
函数参数 不定参数,和 默认参数
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
實現(xiàn)查找一個字符串中是否包含若干“子串” function containsAll(haystack) { for (var i=1; i<arguments.length; i++){ var needle = arguments[i]; if(haystack.indexOf(needle) === -1) { return false } } return true }
console.log(animalSentence()); console.log(animalSentence('elephants')); console.log(animalSentence('elephants','whales'));
function animalSentenceFancy(animals2="tigers",animals3=(animals2=="bears")? "sealions" : "bears"){ return `Lions and ${animals2} and ${animals3}! Oh my!`; } console.log(animalSentenceFancy('bears'));
?
console.log(containsAll('banana','b','nan')); 這種寫法無法確定參數個數,并且若是haystack前后有其余參數的話,初始索引值要改變 不定參數用法 function containsAll(haystack,...needles){ for(var needle of needles){ if(haystack.indexOf(needle) === -1){ return false } } return true } console.log(containsAll('banana','c','nan')); haystack以外的其余參數放到數組needles中,數組就可以用for-of循環(huán)遍歷 默認參數自左向右求值 示例 function animalSentence(animals2="tigers",animals3="bears"){ return `Lions and ${animals2} and ${animals3}! Oh my!`; }console.log(animalSentence()); console.log(animalSentence('elephants')); console.log(animalSentence('elephants','whales'));
function animalSentenceFancy(animals2="tigers",animals3=(animals2=="bears")? "sealions" : "bears"){ return `Lions and ${animals2} and ${animals3}! Oh my!`; } console.log(animalSentenceFancy('bears'));
轉載于:https://www.cnblogs.com/tu-front-end/p/11071657.html
總結
以上是生活随笔為你收集整理的函数参数 不定参数,和 默认参数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android Studio 3.0+
- 下一篇: Linux后台运行和关闭程序、查看后台任