function.length
此函數(shù)校驗(yàn)參數(shù)個(gè)數(shù)
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));
可變參數(shù)與arguments
function add() {
let args = Array.from(arguments);
return args.reduce((a,b) => a+b);
}
console.log(add(1,23,1));
//JavaScript 函數(shù)設(shè)計(jì)中經(jīng)常會(huì)讓參數(shù)允許有不同的類型
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'
});