function.length
此函数校验参数个数
function __matchArgs__(fn) {
return function(...args){
if (args.length !== fn.length){
throw RangeError('Arguments not match!');
}
return fn.apply(this,args);
}
}
var add= __matchArgs__((a,b,c) => a+b+c );
console.log(add(1,2,3));
console.log(add(1,2));
可变参数与arguments
function add() {
let args = Array.from(arguments);
return args.reduce((a,b) => a+b);
}
console.log(add(1,23,1));
//JavaScript 函数设计中经常会让参数允许有不同的类型
function setStyle(el,property,value) {
if (typeof el ==='string') {
el = document.querySelector(el);
}
if (typeof property === 'object') {
for (var key in property) {
setStyle(el,key,property[key]);
}
}else{
el.style[property] = value;
}
}
console.log(setStyle.length);
setStyle('div',color,'red');
setStyle('div',{
'fontSize':'32px',
'backgroundColor':'white'
});