实例函数中第2个与第3个参数为可选参数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| function example( err, optionalA, optionalB, callback ) { var args = new Array(arguments.length); for(var i = 0; i < args.length; ++i) { args[i] = arguments[i]; }; err = args.shift();
if (typeof args[args.length-1] === 'function') { callback = args.pop(); } if (args.length > 0) optionalA = args.shift(); else optionalA = null; if (args.length > 0) optionalB = args.shift(); else optionalB = null;
if (err) { return callback && callback(err); } console.log('optionalA:', optionalA); console.log('optionalB:', optionalB); console.log('callback:', callback);
}
function example(...args) { const err = args.shift(); const callback = (typeof args[args.length-1] === 'function') ? args.pop() : null;
const optionalA = (args.length > 0) ? args.shift() : null; const optionalB = (args.length > 0) ? args.shift() : null;
if (err && callback) return callback(err);
}
example(null, 'AA');
example(null, function (err) { });
example(null, 'AA', function (err) {});
example(null, 'AAAA', 'BBBB', function (err) {});
|
如何保证optionalA和optionalB是预期的值?
设计你的函数,使其在接收optionalB时optionalA为必选参数。