zhenguilin / javascript-note

Here are some notes for javascript
https://github.com/zhenguilin/javascript-note
0 stars 0 forks source link

函数的定义和调用 #7

Open zhenguilin opened 6 years ago

zhenguilin commented 6 years ago

避免收到undefined,可以对参数进行检查

function abs(x) {
    if (typeof x !== 'number') {
        throw 'Not a number';
    }
    if (x >= 0) {
        return x;
    } else {
        return -x;
    }
}
zhenguilin commented 6 years ago

JavaScript还有一个免费赠送的关键字arguments,它只在函数内部起作用,并且永远指向当前函数的调用者传入的所有参数。arguments类似Array但它不是一个Array

zhenguilin commented 6 years ago

arguments最常用于判断传入参数的个数。你可能会看到这样的写法

// 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变为默认值
    }
    // ...
}
zhenguilin commented 6 years ago

只是为了获得额外的rest参数,有没有更好的方法?ES6标准引入了rest参数

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