Home > Web Front-end > JS Tutorial > Detailed explanation of JavaScript function parameters, return values ​​and exception codes

Detailed explanation of JavaScript function parameters, return values ​​and exception codes

伊谢尔伦
Release: 2017-07-25 10:46:06
Original
1766 people have browsed it

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));
Copy after login

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&#39;
alert(t instanceof test); // 输出:true
Copy after login

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 != &#39;number&#39; || typeof b != &#39;number&#39;){
        throw {
            &#39;name&#39;  : "typeError", // 属性是自定义的,名字可以任意取
            &#39;message&#39;: "add方法必须使用数字作为参数"
        };
    }
    return a + b;
}
(function(){
    // 捕获add方法可能产生的异常
    try{
        add(10, "");
    } catch(e){ 
        // 一个try语句只有一个catch语句,如果要处理多个异常,则通过异常的name属性来区别
        // 判断异常的类型
        if(e.name === "typeError"){
            alert(e.message);
        }
    }
})();
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template