Function parameters uncertain parameters, and default parameters

 
Implement a lookup string contains a plurality of "substring"
 
 
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(containsAll('banana','b','nan'));
The wording of the number of parameters can not be determined, and if there is, then the rest of the parameters before and after the haystack, the initial index value to be changed
 
Variable parameter usage
 
function containsAll(haystack,...needles){
for(var needle of needles){
if(haystack.indexOf(needle) === -1){
return false
}
}
return true
}
console.log(containsAll('banana','c','nan'));
 
The remaining parameters other than the haystack needles into an array, the array can be used for-of loop iterates
 
 
 
 
 
The default parameters are evaluated from left to right
Examples
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'));
 

Guess you like

Origin www.cnblogs.com/tu-front-end/p/11071657.html