English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

A Brief Discussion on Default Parameters of JavaScript Functions

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

--The default value should be undefined

You can preset numbers in the function with arguments[i]

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

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

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

Try it, it should be like this

I encountered a problem today, I need to call a JS function, I want to give it a default parameter in the function, thinking it is the same as other languages.

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

The runtime error reported is that you cannot pass default parameters in JavaScript, I searched online and found that you can use the arguments actual parameter array, see 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> 

A little 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.

This brief discussion on the default parameter of function in JavaScript is all that I share with you. I hope it can serve as a reference for you, and I also hope that everyone will support the Shouting Tutorial.

You May Also Like