Discussion on the Default Value of function Parameters in js

  • 2021-07-22 08:37:33
  • OfStack

func (string1, url, flag, icon), and then call it func (a, b) in another asp. What are the values of flag and icon, and how to define the default values? Thank you!

--Default should be undefined

The default number in the function can be arguments [i]

i is the position of your parameter, and the first one is 0

So to set the default value of flag, you can write this


function func(string1,url,flag,icon){
 if(!arguments[2]) flag = "123";
 if(!arguments[3]) icon = "456";
}

If you try, it should be like this

Today encountered a problem, need to call an JS function, want to give it a default parameter in the function, as in other languages.


<script>
function test(id=0){
 alert(id);
}
</script>
<input type="button" value="test" onclick="test()">

Operation results reported error, JS can not be transmitted in this way the default parameters, online check 1, you can use the arguments real parameter group, refer to the following example:


<script> 
function test(a){ 
var b=arguments[1]?arguments[1]:50 
return a+':'+b 
} 
alert(test(5)) 
alert(test(5,9)) 
</script> 

One small difference from other languages. .

--var b = arguments [1]? arguments [1]: 50 can also be written as: var b = arguments [1] 50;

I especially like this feature.

--var b = arguments [1] 50; This method is quite concise.


Related articles: