# 函数

• 版本网址缩略名： JavaScript/Guide/Functions
• 版本标题： 函数
• 版本 id： 360319
• 创建于：
• 创建者： iwo
• 是否已审核?
• 审核于：
• 审核人： iwo
• 是否被批准？
• 是否是当前版本？
• 评论

## 定义函数

• 函数的名称。
• 封闭在括号()中，并由逗号区隔的一个函数引数（译注：实际参数）列表。
• 封闭在花括号{}中，用于定义函数功能的一些JavaScript语句。

function square(number) {
return number * number;
}

return number * number;

function myFunc(theObject) {
theObject.make = "Toyota";
}

var mycar = {make: "Honda", model: "Accord", year: 1998},
x,
y;

x = mycar.make;     // x gets the value "Honda"

myFunc(mycar);
y = mycar.make;     // y gets the value "Toyota"
// (the make property was changed by the function)

function myFunc(theObject) {
theObject = {make: "Ford", model: "Focus", year: 2006};
}

var mycar = {make: "Honda", model: "Accord", year: 1998},
x,
y;

x = mycar.make;     // x gets the value "Honda"

myFunc(mycar);
y = mycar.make;     // y still gets the value "Honda"

if (num == 0){
function myFunc(theObject) {
theObject.make = "Toyota"
}
}

var square = function(number) {return number * number};

var factorial = function fac(n) {return n<2 ? 1 : n*fac(n-1)};

print(factorial(3));

function map(f,a) {
var result = [], // Create a new Array
i;
for (i = 0; i != a.length; i++)
result[i] = f(a[i]);
return result;
}

map(function(x) {return x * x * x}, [0, 1, 2, 5, 10]);

## 调用函数

square(5);

print(square(5));
/* ... */
function square(n){return n*n}

print(square(5));
square = function (n) {
return n * n;
}

function factorial(n){
if ((n == 0) || (n == 1))
return 1;
else
return (n * factorial(n - 1));
}

var a, b, c, d, e;
a = factorial(1); // a gets the value 1
b = factorial(2); // b gets the value 2
c = factorial(3); // c gets the value 6
d = factorial(4); // d gets the value 24
e = factorial(5); // e gets the value 120

## 函数的域

// The following variables are defined in the global scope
var num1 = 20,
num2 = 3,
name = "Chamahk";

// This function is defined in the global scope
function multiply() {
return num1 * num2;
}

multiply(); // Returns 60

// A nested function example
function getScore () {
var num1 = 2,
num2 = 3;

return name + " scored " + (num1 + num2);
}

}

getScore(); // Returns "Chamahk scored 5"

## 闭包

var pet = function(name) {          // The outer function defines a variable called "name"
var getName = function() {
return name;                // The inner function has access to the "name" variable of the outer function
}

return getName;               // Return the inner function, thereby exposing it to outer scopes
},
myPet = pet("Vivie");

myPet();                            // Returns "Vivie"

var createPet = function(name) {
var sex;

return {
setName: function(newName) {
name = newName;
},

getName: function() {
return name;
},

getSex: function() {
return sex;
},

setSex: function(newSex) {
if(typeof newSex == "string" && (newSex.toLowerCase() == "male" || newSex.toLowerCase() == "female")) {
sex = newSex;
}
}
}
}

var pet = createPet("Vivie");
pet.getName();                  // Vivie

pet.setName("Oliver");
pet.setSex("male");
pet.getSex();                   // male
pet.getName();                  // Oliver

var getCode = (function(){
var secureCode = "0]Eal(eh&2";    // A code we do not want outsiders to be able to modify...

return function () {
return secureCode;
};
})();

getCode();    // Returns the secret code

var createPet = function(name) {  // Outer function defines a variable called "name"
return {
setName: function(name) {    // Enclosed function also defines a variable called "name"
name = name;               // ??? How do we access the "name" defined by the outer function ???
}
}
}

## 使用引数对象

arguments[i]

function myConcat(separator) {
var result = "", // initialize list
i;
// iterate through arguments
for (i = 1; i < arguments.length; i++) {
result += arguments[i] + separator;
}
return result;
}

// returns "red, orange, blue, "
myConcat(", ", "red", "orange", "blue");

// returns "elephant; giraffe; lion; cheetah; "
myConcat("; ", "elephant", "giraffe", "lion", "cheetah");

// returns "sage. basil. oregano. pepper. parsley. "
myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley");

## 预定义的函数

JavaScript语言有好些个顶级的预定义函数：

• {{ web.link("#parseInt_and_parseFloat_functions", "parseInt and parseFloat") }}
• {{ web.link("#Number_and_String_functions", "Number and String") }}
• {{ web.link("#escape_and_unescape_functions", "encodeURI, decodeURI, encodeURIComponent, and decodeURIComponent") }} (all available with Javascript 1.5 and later).

### eval函数

The eval function evaluates a string of JavaScript code without reference to a particular object. The syntax of eval is:

eval(expr);

where expr is a string to be evaluated.

If the string represents an expression, eval evaluates the expression. If the argument represents one or more JavaScript statements, eval performs the statements. The scope of eval code is identical to the scope of the calling code. Do not call eval to evaluate an arithmetic expression; JavaScript evaluates arithmetic expressions automatically.

### isFinite函数

The isFinite function evaluates an argument to determine whether it is a finite number. The syntax of isFinite is:

isFinite(number);

where number is the number to evaluate.

If the argument is NaN, positive infinity or negative infinity, this method returns false, otherwise it returns true.

The following code checks client input to determine whether it is a finite number.

if(isFinite(ClientInput)){
/* take specific steps */
}

### isNaN函数

The isNaN function evaluates an argument to determine if it is "NaN" (not a number). The syntax of isNaN is:

isNaN(testValue);

where testValue is the value you want to evaluate.

The parseFloat and parseInt functions return "NaN" when they evaluate a value that is not a number. isNaN returns true if passed "NaN," and false otherwise.

The following code evaluates floatValue to determine if it is a number and then calls a procedure accordingly:

var floatValue = parseFloat(toFloat);

if (isNaN(floatValue)) {
notFloat();
} else {
isFloat();
}

### parseInt和parseFloat函数

The two "parse" functions, parseInt and parseFloat, return a numeric value when given a string as an argument.

The syntax of parseFloat is

parseFloat(str);

where parseFloat parses its argument, the string str, and attempts to return a floating-point number. If it encounters a character other than a sign (+ or -), a numeral (0-9), a decimal point, or an exponent, then it returns the value up to that point and ignores that character and all succeeding characters. If the first character cannot be converted to a number, it returns "NaN" (not a number).

The syntax of parseInt is

parseInt parses its first argument, the string str, and attempts to return an integer of the specified radix (base), indicated by the second, optional argument, radix. For example, a radix of ten indicates to convert to a decimal number, eight octal, sixteen hexadecimal, and so on. For radixes above ten, the letters of the alphabet indicate numerals greater than nine. For example, for hexadecimal numbers (base 16), A through F are used.

If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. If the first character cannot be converted to a number in the specified radix, it returns "NaN." The parseInt function truncates the string to integer values.

### Number和String函数

The Number and String functions let you convert an object to a number or a string. The syntax of these functions is:

var objRef;
objRef = Number(objRef);
objRef = String(objRef);

where objRef is an object reference. Number uses the valueOf() method of the object; String uses the toString() method of the object.

The following example converts the Date object to a readable string.

var D = new Date(430054663215),
x;
x = String(D); // x equals "Thu Aug 18 04:37:43 GMT-0700 (Pacific Daylight Time) 1983"

The following example converts the String object to Number object.

var str = "12",
num;
num = Number(str);

You can check it. Use DOM method write() and JavaScript typeof operator.

var str = "12",
num;
document.write(typeof str);
document.write("<br/>");
num = Number(str);
document.write(typeof num);

### escape和unescape函数

The escape and unescape functions do not work properly for non-ASCII characters and have been deprecated. In JavaScript 1.5 and later, use encodeURI, decodeURI, encodeURIComponent, and decodeURIComponent.

The escape and unescape functions let you encode and decode strings. The escape function returns the hexadecimal encoding of an argument in the ISO Latin character set. The unescape function returns the ASCII string for the specified hexadecimal encoding value.

The syntax of these functions is:

escape(string);
unescape(string);

These functions are used primarily with server-side JavaScript to encode and decode name/value pairs in URLs.

{{ autoPreviousNext("JSGChapters") }}