Home  >  Article  >  Web Front-end  >  How to use sum function in javascript to sum

How to use sum function in javascript to sum

醉折花枝作酒筹
醉折花枝作酒筹Original
2021-04-22 18:49:299654browse

Method: 1. Use object arguments with the sum function, the syntax is "sum(parameter){return arguments[subscript] arguments[subscript]}"; 2. Use " " directly in the sum function, the syntax is " sum(parameter list){return parameter 1 parameter 2}".

How to use sum function in javascript to sum

The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, Dell G3 computer.

Method 1: In JavaScript, functions provide access to the argument object arguments, which provides access to the actual parameters passed to the function. This allows us to use the length attribute to determine the length passed to the function at runtime. The number of parameters.

function sum(x){
    if(arguments.length == 2){
        return arguments[0]+arguments[1];
    }
    else{
        return function(y){return x+y;}
    }
}

Method 2: If the number of parameters passed is less than the number of parameters in the function definition, the missing parameters will have undefined values ​​when referenced within the function.

function sum(x,y){
    if(y!==undefined){
        return x+y;
    }
    else{
        return function(y){return x+y;}
    }
}

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to use sum function in javascript to sum. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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