Hike News

js添加新函数

正常是这样写的

printFarmInventory(cows,chickens){
1
2
3
4
5
6
7
8
9
10
var cowString=String(cows);
while(cowString.length<3)
cowString="0"+cowString;
console.log(cowString+"Cows");
var chickenString=String(chickens);
while (chickenString.length<3)
chickenString="0"+chickenString;
console.log(chickenString+"Chickens");
}
printFarmInventory(7,11);

如果要加入一只pig的话,把重复的代码,提取成为一个函数。

printZeroPaddedWithLable(number,label){
1
2
3
4
5
6
7
8
9
10
11
var numberString=String(number);
while (numberString.length<3)
numberString="0"+numberString;
console.log(numberString+""+label);
}
function printFarmInventory(cows,chickens,pigs){
printZeroPaddedWithLable(cows,"Cows");
printZeroPaddedWithLable(chickens,"Chickens");
printZeroPaddedWithLable(pigs,"pigs");
}
printFarmInventory(7,11,3);

不再将重复的代码提取为函数,而是提取其中一项操作。

zeroPad(number,width){
1
2
3
4
5
6
7
8
9
10
11
var string=String(number);
while(string.length<width)
string="0"+string;
return string;
}
function printFarmInventory(cows,chickens,pigs){
console.log(zeroPad(cows,3)+"Cows");
console.log(zeroPad(chickens,3)+"Chickens");
console.log(zeroPad(pigs,3)+"Pigs");
}
printFarmInventory(7,16,3);