函数,放在对象里面叫做方法,但实际上是一样的。
定义函数
方式一:
// 绝对值函数
function abs(x) {
if (x >= 0) {
return x;
} else {
return -x;
}
}
一旦执行到 return 代表函数结束,返回结果!
如果没有执行 return ,函数执行完也会返回结果,结果就是 undefined。
方式二:
var abs = function(x) {
if (x >= 0) {
return x;
} else {
return -x;
}
}
function(x) { ... } 是一个匿名函数,但是可以把结果赋给 abs,通过 abs 就可以调用函数!
调用函数
方法名(参数);
参数问题:JavaScript 可以传递任意个参数,也可以不传递参数。
对于参数类型进行规避,手动抛出异常
var abs = function(x) {
// 手动抛出异常来判断
if (typeof x !== 'number') {
throw 'Not a Number';
}
if (x >= 0) {
return x;
} else {
return -x;
}
}
arguments
arguments 是一个 JavaScript 免费赠送的关键词。是一个数组,代表传递进来的所有参数。
var abs = function(x) {
console.log(arguments);
if (x >= 0) {
return x;
} else {
return -x;
}
}
abs(123, 678, 4884, 584, 55);
// 输入结果:
// Arguments(5) [123, 678, 4884, 584, 55]
// 123
问题:arguments 包含所有传递的参数,有时候只想使用多余的参数来进行附加操作,需要排除已有的参数。
rest
ES6 引入的新特性,获取除了已经定义的参数以外的所有参数。
var aaa(a, b, ...rest) {
console.log("a:" + a);
console.log("b:" + b);
console.log("rest:" + rest);
}
aaa(3);
// 输入结果:
// a:3 b:undefined rest:[]
aaa(1, 1233);
// 输入结果:
// a:1 b:1233 rest:[]
aaa(1, 1233, 45, 454, 99);
// 输入结果:
// a:1 b:1233 rest:[45, 454, 99]
注意:rest 参数必须写在参数列表的最后面,且必须用 ... 标识。