JavaScript learning records definition and invocation of day5-functions

Source: Internet
Author: User
Tags abs

JavaScript learning records definition and invocation of day5-functions

[TOC]

1. Defining functions

In JavaScript, you define a function as follows:

function abs(x) {    if (x >= 0) {        return x;    } else {        return -x;    }}

abs()the above functions are defined as follows:

functionIndicates that this is a function definition;
absis the name of the function;
(x)The parameters of the function are listed in parentheses, and multiple parameters are , separated;
{ ... }The code between is a function body, can contain several statements, and even can not have any statements.
Note that when the statement inside the function body executes, the function executes and returns the result as soon as it is executed return . Therefore, it is possible to implement very complex logic within a function through conditional judgments and loops.

If there is no return statement, the result is returned after the function is executed, except for the result undefined .

Since the function of JavaScript is also an object, the abs() function defined above is actually a function object, and the functions name abs can be considered as a variable pointing to the function.

Therefore, the second way to define a function is as follows:

var abs = function (x) {    if (x >= 0) {        return x;    } else {        return -x;    }};

In this way, function (x) { ... } it is an anonymous function that does not have a function name. However, this anonymous function assigns a value to the variable abs , so abs the function can be called by a variable.

The two definitions are completely equivalent , and note that the second way is to add one at the end of the function body according to the complete syntax ; , indicating the end of the assignment statement.

2. Calling functions

When you call a function, you pass in the arguments sequentially:

abs(10);  // 返回10abs(-9);  // 返回9

Because JavaScript allows you to pass in any parameter without affecting the call, there is no problem with the parameters passed in that are more than the defined parameters, although they are not required inside the function:

abs(10, ‘blablabla‘);  // 返回10abs(-9, ‘haha‘, ‘hehe‘, null);  // 返回9

There is no problem with the parameters passed in that are less than defined:

abs();  // 返回NaN

At this point the ABS (x) function parameter x is received undefined and the result is computed NaN .

To avoid receipt undefined , you can check the parameters:

function abs(x) {    if (typeof x !== ‘number‘) {        throw ‘Not a number‘;    }    if (x >= 0) {        return x;    } else {        return -x;    }}
3. Arguments

JavaScript also has a free keyword arguments that works only inside the function and always points to all parameters passed in by the caller of the current function. argumentssimilar Array but it is not a Array :

‘use strict‘function foo(x) {    console.log(‘x = ‘ + x);  // 10    for (var i = 0; i < arguments.length; i++) {        console.log(‘arg ‘ + i + ‘ = ‘ + arguments[i]);  // 10, 20, 30    }}foo(10, 20, 30);

Using arguments , you can get all the parameters that the caller passed in. That is, even if the function does not define any parameters, it can get the value of the parameter:

function abs() {    if (arguments.length === 0) {        return 0;    }    var x = arguments[0];    return x >= 0 ? x : -x;}console.log(abs());  // 0console.log(abs(10));  // 10console.log(abs(-9));  // 9

In fact arguments , it is most commonly used to determine the number of incoming parameters. You may see the following notation:

// foo(a[, b], c)// 接收2~3个参数,b是可选参数,如果只传2个参数,b默认为null:function foo(a, b, c) {    if (arguments.length === 2) {        // 实际拿到的参数是a和b,c为undefined        c = b;  // 把b赋给c        b = null;  // b变为默认值    }    console.log(a, b, c);}foo(1, 2);  // 1 null 2

To change the middle parameter B to an optional parameter, you can only pass arguments judgment and then re-adjust the parameter and assign a value.

4. Reset parameter

Since JavaScript functions allow the receipt of arbitrary parameters, we have to use arguments to get all the parameters:

function foo(a, b) {    var i, rest = [];    if (arguments.length > 2) {        for (i = 2; i<arguments.length; i++) {            rest.push(arguments[i]);        }    }    console.log(‘a = ‘ + a);    console.log(‘b = ‘ + b);    console.log(rest);}foo();// 结果:// a = undefined// b = undefined// []foo(1, 2);// 结果:// []// a = 1// b = 2foo(3, 4, 5);// 结果:// a = 3// b = 4// [ 5 ]

In order to obtain a b parameters other than the defined parameters, we have to use arguments , and the loop to start from the index 2 to exclude the first two parameters, this is very awkward, just to obtain additional rest parameters, there is no better way?

The ES6 standard introduces rest parameters, the above function can be rewritten as:

function foo(a, b,...rest){    console.log(‘a = ‘ + a);    console.log(‘b = ‘ + b);    console.log(rest);}foo(1, 2, 3, 4, 5);// 结果:// a = 1// b = 2// Array [ 3, 4, 5 ]foo(1);// 结果:// a = 1// b = undefined// Array []

restParameters can only be written at the end, preceded by the ... identification, from the running results, we know that the parameters are bound first, a b and the extra parameters are given to the variable in the array form, rest so we do not need to arguments get all the parameters.

It does not matter if the passed parameter does not fill the normal defined parameters, and the rest parameter receives an empty array (note not undefined ).

Because rest the parameter is ES6 new standard, you need to test whether the browser supports it. Use rest parameters to write a sum() function that receives any arguments and returns their and:

‘use strict‘;function sum(...rest) {   var num = 0;   var x;   for (x of rest) {        num = num + x;    }    return num;}// 测试:var i, args = [];for (i=1; i<=100; i++) {    args.push(i);}if (sum() !== 0) {    console.log(‘测试失败: sum() = ‘ + sum());} else if (sum(1) !== 1) {    console.log(‘测试失败: sum(1) = ‘ + sum(1));} else if (sum(2, 3) !== 5) {    console.log(‘测试失败: sum(2, 3) = ‘ + sum(2, 3));} else if (sum.apply(null, args) !== 5050) {    console.log(‘测试失败: sum(1, 2, 3, ..., 100) = ‘ + sum.apply(null, args));} else {    console.log(‘测试通过!‘);}
5. Be careful with your return statement

We talked about the JavaScript engine that has a mechanism for automatically adding semicolons at the end of the line, which may allow you to plant return a large hole in the statement:

function foo() {    return { name: ‘foo‘ };}foo(); // { name: ‘foo‘ }

If you split the return statement into two lines:

function foo() {    return        { name: ‘foo‘ };}foo(); // undefined

Be careful, because the JavaScript engine automatically adds a semicolon mechanism at the end of the line, the code above actually becomes:

function foo() {    return; // 自动添加了分号,相当于return undefined;        { name: ‘foo‘ }; // 这行语句已经没法执行到了}

So the correct multi-line notation is:

function foo() {    return { // 这里不会自动加分号,因为{表示语句尚未结束        name: ‘foo‘    };}

Practice

    1. Defines a function that calculates the area of a circle area_of_circle() , which has two parameters:
      • R: Indicates the radius of the circle;
      • PI: The value of π, if not passed, the default 3.14
‘use strict‘;function area_of_circle(r, pi) {    // var area;    // if (arguments.length == 2) {    //     area = pi * r * r;    // } else if (arguments.length < 2){    //     pi = 3.14;    //     area = pi * r * r;    // } else {    //     console.log("arguments number must be 1 or 2.")    //     return;    // }    // return area;    return r * r * (pi || 3.14);}// 测试:if (area_of_circle(2) === 12.56 && area_of_circle(2, 3.1416) === 12.5664) {    console.log(‘测试通过‘);} else {    console.log(‘测试失败‘);}

Learning Reference Tutorial: http://www.liaoxuefeng.com

JavaScript learning records definition and invocation of day5-functions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.