JavaScript: The Definitive Guide, Sixth Editio javaScript权威指南(第6版) pdf 文字版-文字版, javascript电子书, 和javascript 有关的电子书:

8.3.1 Optional Parameters

8.3.1 Optional Parameters


When a function is invoked with fewer arguments than declared parameters, the additional parameters are set to the undefined value. It is often useful to write functions so that some arguments are optional and may be omitted when the function is invoked. To do this, you must be able to assign a reasonable default value to parameters that are omitted. Here is an example:

// Append the names of the enumerable properties of object o to the

// array a, and return a. If a is omitted, create and return a new array.

function getPropertyNames(o, /* optional */ a) {

if (a === undefined) a = []; // If undefined, use a new array

for(var property in o) a.push(property);

return a;

}

// This function can be invoked with 1 or 2 arguments: var a = getPropertyNames(o); // Get o's properties into a new array getPropertyNames(p,a); // append p's properties to that array

Instead of using an if statement in the first line of this function, you can use the || operator in this idiomatic way:

a = a || [];

Recall from §4.10.2 that the || operator returns its first argument if that argument is truthy and otherwise returns its second argument. In this case, if any object is passed as the second argument, the function will use that object. But if the second argument is omitted (or null or another falsy value is passed), a newly created empty array will be used instead.

Note that when designing functions with optional arguments, you should be sure to put the optional ones at the end of the argument list so that they can be omitted. The programmer who calls your function cannot omit the first argument and pass the second: she would have to explicitly pass undefined the first argument. Also note the use of the comment /* optional */ in the function definition to emphasize the fact that the parameter is optional.

8.3 Function Arguments and Parameters | 171

欢迎转载,转载请注明来自一手册:http://yishouce.com/book/1/31363.html
友情链接It题库(ittiku.com)| 版权归yishouce.com所有| 友链等可联系 admin#yishouce.com|粤ICP备16001685号-1