商戶交流小程式——軟體系統設計方案
阿新 • • 發佈:2020-12-29
作業1
小明和他家人在泰國旅遊,到3個不同的飯店吃飯。賬單(bill)分別是124元,48元和268元。為了給服務員小費(tip),小明建立了一個簡單
的小費計算器函式(tipCalculator)。
a. 如果賬單小於50元,他會給賬單的20%作為小費。
b. 如果賬單在50到200元之間,他會給賬單的15%作為小費。
c. 如果賬單超過200元,他會給賬單的10%作為小費。
小明想要2個數組:
1.一個數組包含所有三個小費(每個賬單一個)。
2.一個數組包含所有三個最終支付的金額(賬單+小費)。
最後把這2個數組輸出到控制檯。
//1.
function tipCalculator(bill) {
let percentage;
if(bill < 50) {
percentage = 0.2;
}else if(bill >= 50 && bill < 200) {
percentage = 0.15;
}else {
percentage = 0.1;
}
return percentage * bill;
}
console.log('The tip is $'+tipCalculator(10));//測試函式
const bills = [124,48,268];//賬單陣列
//將賬單陣列的值傳入函式得出小費
const tips = [tipCalculator(bills[0]),tipCalculator(bills[1]),tipCalculator(bills[2])];
const cost = [bills[0] + tips[0],bills[1] + tips[1],bills[2] + tips[2]];//賬單和消費相加得出最終支付的金額
console.log('The tip is '+ tips,'The cost is ' + cost);//兩個陣列輸出到控制檯
//2.
const tipCalculator = bills => {
const tips = [ ];
const costs = [];
bills.forEach(bill => {
let tip;
if(bill < 50) {
tip = bill * 0.2;
}else if(bill >= 50 && bill < 200) {
tip = bill * 0.15;
}else {
tip = bill * 0.1;
}
const cost = bill +tip;
tips.push(tip);
costs.push(cost);
})
console.log('The tip is '+ tips);
console.log('The cost is ' + costs);
}
tipCalculator([124,48,268]);
輸出結果
作業2
假設有三個數a、b、c,求這三個數的平均值的函式為∶
function mean(a, b, c) {
return (a + b + c) / 3;
}
1.如果要求任意個數的數字的平均值,該如何改進這個函式呢?
請編寫改進的mean1()函式,讓該函式可以計算任意個數的數字的平均值。
提示:使用擴充套件運算子
2.請編寫函式mean2(),使用陣列的reduce()函式改寫mean1(),讓程式碼更加精簡。
3.請在第二步的基礎上編寫函式mean3(),實現只對陣列中的偶數求平均值。
提示:使用回撥函式和map()
// 1.
const mean1 = function(...arguments) {
let sum = 0;
for (var i=0;i<arguments.length;i++){
sum += arguments[i];
}
return sum/arguments.length;
}
avg = mean1(5,9,5,21);
console.log("The average is " + avg);
// 2.
const mean2 = (...array) => array.reduce((acc,val) => acc + val,0) / array.length;//累計求和除長度
console.log("The average is " + mean2(...[5,9,10,28]));
// 3.
const oArray1 = [8,10,21,8,10];
const oArray2 = oArray1.filter((x) => x%2===0);//取餘 偶數
console.log(oArray2);
const mean3 = oArray2.reduce(
(acc,x) => acc + x)/ oArray2.length//回撥
console.log("The average is " + mean3);
輸出結果