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

Advantages and Disadvantages of Using JSON as a Function Parameter

I have not understood JSON very well, and recently I have read some introductions and found that this thing is very useful. Below, I will introduce it to everyone

1, we can add a function/Deleting parameters or adding new parameters at any parameter position will not require writing in the prescribed order as traditional parameters. Moreover, every time a parameter is added or deleted from a function, the function content needs to be modified. Using JSON as a parameter does not require considering the order of parameters.
See the following code demonstration:

<script type="text/javascript">
 <!--
 //Normal Method
 function commonArg(name,age,desc){
  var userinfo="name: "+name+","+"age: "+age+"\ndescription: "+desc;
  alert(userinfo);
 }
 commonArg("yemoo",22,"a boy!")//Each call must be written in the prescribed order of parameters. If it is written as commonArg(22,"yemoo","desc") will return incorrect information. Each time, it is necessary to remember the meaning and order of each parameter
 //JSON Parameter Method
 function jsonArg(info){
  var userinfo="name: "+info.name+"\tage: "+info.age+"\ndescription: "+info.desc;
  alert(userinfo);
 }
 jsonArg({name:"blue",age:22,desc:"a gril"63;"});
 jsonArg({desc:"not a people!",name:"sss",age:0});
 //The position of the parameters can be written arbitrarily
 //-->
 </script>

The disadvantages of the normal function are very obvious: it is necessary to remember the meaning and order of the parameters. While using the JSON method, this is not necessary.

2The usage of the function is very convenient, especially when only a few or one parameter needs to be passed in.
See the following code demonstration:

<script type="text/javascript">
 <!--
 //Normal Method
 function commonArg(name,age,desc){
  var userinfo="name: "+(name||"empty")+"\tage: "+(age||0)+"\ndescription: "+desc||"empty";
  alert(userinfo);
 }
 //When only the parameters after need to be set, each parameter before needs to be set to null
 commonArg("tempUser");
 commonArg(null,null,"a boy!");
 commonArg(null,20);
 //JSON Parameter Method
 function jsonArg(info){
  var userinfo="name: "+(info.name||"empty")+"\tage: "+(info.age||0)+"\ndescription: "+(info.desc||"empty");
  alert(userinfo);
 }
 //Each time, only the parameters that need to be set need to be set
 jsonArg({name:"tempUser"});
 jsonArg({desc:"a boy!"});
 jsonArg({age:20});
 //-->
 </script>

The advantages of JSON methods are very obvious: you only need to pass in the required parameters each time, without considering other parameters.
JSON is a very useful thing. Whether it is used in AJAX or other aspects of JavaScript, it reflects its convenient and flexible characteristics. It is indeed necessary to explore and learn JSON thoroughly.

You May Also Like