Function parameters (arguments)
arguments is not an array, but is similar to an array. In addition to having the length property, arguments does not have all the properties and methods of the array. Use arguments to implement an accumulative function.
function sum(){ var total = 0; for(var i=0; i<arguments.length; i++){ // arguments.length返回sum函数调用时传递参数的个数 total += arguments[i]; } return total; } alert("sum: " + sum(1, 3, 2, 4));
Function return value (return)
When a function is called, it is usually executed from { to } of the function. If you want to end the execution of the function early, you can use the return statement. At this time, all statements following the return statement will never be executed. For example:
function test(){ alert("first"); return; alert("second"); // 该语句永远被不会执行 } test(); // 一个函数总是会返回值,如果没有使用return返回值,默认返回undefined。如: function test(){ alert("first"); } alert(test()); // 输出:undefined // 如果函数前使用new方式调用,且返回值不是一个对象,则返回this(新对象)。如: function test(){ alert("first"); } var t = new test(); alert(typeof t); // 输出:‘object' alert(t instanceof test); // 输出:true
Exception
An exception is an abnormal accident (maybe intentional) that interferes with the normal flow of the program. When such an incident is detected, an exception should be thrown. Such as:
function add(a, b){ // 定义一个加法函数 // 如果传递的参数不是数字类型,则抛出一个异常信息 if(typeof a != 'number' || typeof b != 'number'){ throw { 'name' : "typeError", // 属性是自定义的,名字可以任意取 'message': "add方法必须使用数字作为参数" }; } return a + b; } (function(){ // 捕获add方法可能产生的异常 try{ add(10, ""); } catch(e){ // 一个try语句只有一个catch语句,如果要处理多个异常,则通过异常的name属性来区别 // 判断异常的类型 if(e.name === "typeError"){ alert(e.message); } } })();
The above is the detailed content of Detailed explanation of JavaScript function parameters, return values and exception codes. For more information, please follow other related articles on the PHP Chinese website!