Home >Web Front-end >JS Tutorial >Introduction to how to define functions in JavaScript

Introduction to how to define functions in JavaScript

零下一度
零下一度Original
2017-06-28 13:50:431261browse

This article mainly introduces JavaScriptrelated information on defining functions. Friends who need it can refer to it

In JavaScript, the way to define functions is as follows:


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

The above abs() function is defined as follows:

  • function indicates that this is a function definition;

  • abs is the name of the function;

  • (x) The parameters of the function are listed in brackets , multiple parameters are preceded by, Separation; The code between

  • ##{ ... } is the function body, which can contain several statements or even no statements.

Please note that when the statements inside the function body are executed, once return is executed, the function will be executed and the result will be returned. Therefore, very complex logic can be implemented inside the function through

conditional judgment and loops.

If there is no return statement, the result will be returned after the function is executed, but the result will be undefined.

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

So, the second way of defining a function is as follows:


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

In this way, function (x) { ... } is a

Anonymous function, it has no function name. However, this anonymous function is assigned to the variable abs, so the function can be called through the variable abs.

The above two definitions are completely equivalent. Note that the second method requires adding a ; at the end of the function body according to the complete syntax, indicating the end of the assignment statement.

Call the function

When calling the function, just pass in the parameters in order:


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

Since JavaScript allows any number of parameters to be passed in without affecting the call, there is no problem if more parameters are passed in than the defined parameters, although these parameters are not required inside the function:


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

There is no problem if there are fewer parameters passed in than the ones defined:



abs(); // 返回NaN

At this time, the parameter x of the abs(x) function will receive undefined, evaluates to NaN.

To avoid receiving 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;
  }
}

arguments

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


function foo(x) {
  alert(x); // 10
  for (var i=0; i<arguments.length; i++) {
    alert(arguments[i]); // 10, 20, 30
  }
}
foo(10, 20, 30);

Using arguments, you can get all the parameters passed in by the caller. In other words, even if the function does not define any parameters, you can still get the value of the parameter:


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

In fact, arguments are most commonly used to determine the number of parameters passed in. You may see writing like this:


// 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变为默认值
  }
  // ...
}

To change the middle parameter b into an "optional" parameter, you can only judge it through arguments, and then readjust the parameters. and assign a value.

rest parameters

Since JavaScript functions allow receiving any number of parameters, we have to use arguments to obtain all 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(&#39;a = &#39; + a);
  console.log(&#39;b = &#39; + b);
  console.log(rest);
}

In order to obtain parameters other than the defined parameters a and b, we have to use arguments, and the loop must start from index 2 to exclude the first two parameters. This way of writing is very awkward. , just to get extra rest parameters, is there a better way?

The ES6 standard introduces the rest parameter. The above function can be rewritten as:


function foo(a, b, ...rest) {
  console.log(&#39;a = &#39; + a);
  console.log(&#39;b = &#39; + 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 []

The rest parameter can only be

written at the end , It is marked with... in the front. From the running results, we can see that the incoming parameters are bound to a and b first, and the extra parameters are given to the variable rest in the form of an array. Therefore, we get all the parameters without the arguments.

If the parameters passed in are not filled with the normally defined parameters, it does not matter, the rest parameter will receive an empty array (note that it is not undefined).

Because the rest parameter is a new ES6 standard, you need to test whether the browser supports it. Please write a sum() function using the rest parameter, which receives any number of parameters and returns their sum:

Top of the form


&#39;use strict&#39;;
// 测试:
var i, args = [];
for (i=1; i<=100; i++) {
  args.push(i);
}
if (sum() !== 0) {
  alert(&#39;测试失败: sum() = &#39; + sum());
} else if (sum(1) !== 1) {
  alert(&#39;测试失败: sum(1) = &#39; + sum(1));
} else if (sum(2, 3) !== 5) {
  alert(&#39;测试失败: sum(2, 3) = &#39; + sum(2, 3));
} else if (sum.apply(null, args) !== 5050) {
  alert(&#39;测试失败: sum(1, 2, 3, ..., 100) = &#39; + sum.apply(null, args));
} else {
  alert(&#39;测试通过!&#39;);
}

Be careful with your return statement

We mentioned earlier that the JavaScript engine has a mechanism to automatically add a semicolon at the end of the line, which may cause you to fall into a big pitfall with the return statement:


function foo() {
  return { name: &#39;foo&#39; };
}
foo(); // { name: &#39;foo&#39; }

If you split the return statement into two lines:



function foo() {
  return
    { name: &#39;foo&#39; };
}
foo(); // undefined

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


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

So the correct way to write multiple lines is:

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

练习

定义一个计算圆面积的函数area_of_circle(),它有两个参数:

r: 表示圆的半径;

pi: 表示π的值,如果不传,则默认3.14

The above is the detailed content of Introduction to how to define functions in JavaScript. 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