函数扩展
一、参数默认值
{
function test(x, y="world"){
console.log(x,y);
}
test("hello"); //hello world
test("hello","jack"); //hello jack
}
二、rest参数
接受多个参数进行操作。
{
function test(...arg){
for(let v of arg ){
console.log(v);
}
}
test(1,2,3,"a",4,5); //1,2,3,a,4,5
}
三、扩展运算符
可以看做rest参数逆运用
{
console.log(...[1,2,3]); // 1,2,3
}
{
console.log("a",...[1,2,3]); // a,1,2,3
}
四、箭头函数
arrow是函数名,v代表参数, =>后面是返回值
{
let arrow = v => v*2;
console.log(arrow(2)); //4
}
如果没有参数,就用一个圆括号放在参数的位置。
{
let arrow = () => 2;
console.log(arrow()); //2
}
运用箭头函数要注意this绑定,this对象就是定义时所在的对象,而不是使用时所在的对象。
五、尾调用
看函数的最后一步是不是调用另一个函数,会提升性能。
function f(x){
return g(x);
}
例
{
function tail(x){
console.log(x);
}
function fx(x){
return tail(x);
}
fx(123); //123
}