Tried 👏👏👏
const bills = [22, 295, 176, 440, 37, 105, 10, 1100, 86, 52];
const tips = [];
const totals = [];
const calcTip = function (billValue) {
if (billValue >= 50 && billValue <= 300) {
return billValue * 0.15
} else {
return billValue * 0.2
}
}
for (let repetition = 0; repetition <= 9; repetition++) {
tips.push(calcTip(bills[repetition]));
totals.push(bills[repetition] + tips[repetition]);
}
console.log(tips);
console.log(totals);
Answer
const calcTip = function (billValue) {
return billValue >= 50 && billValue <= 300 ? billValue * 0.15 : billValue * 0.2;
}
const bills = [22, 295, 176, 440, 37, 105, 10, 1100, 86, 52];
const tips = [];
const totals = [];
for (let i = 0; i < bills.length; i++) {
const tip = calcTip(bills[i]);
tips.push(tip);
totals.push(tip + bills[i]);
}
console.log(bills, tips, totals);
// (10) [22, 295, 176, 440, 37, 105, 10, 1100, 86, 52] (10) [4.4, 44.25, 26.4, 88, 7.4, 15.75, 2, 220, 12.9, 7.8] (10) [26.4, 339.25, 202.4, 528, 44.4, 120.75, 12, 1320, 98.9, 59.8]
https://www.w3schools.com/jsref/jsref_push.asp
JavaScript Array push() Method
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
www.w3schools.com
Bonus 1 - sum
const calcAverage = function (arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
// sum = sum + arr[i];
sum += arr[i];
}
console.log(sum);
}
calcAverage([2, 3, 5]);
// prints 10
Bonums 2 - average
const calcAverage = function (arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
// sum = sum + arr[i];
sum += arr[i];
}
return sum / arr.length;
}
console.log(calcAverage([2, 3, 5]));
// prints 3.3333333333333335
'Programming > JavaScript' 카테고리의 다른 글
Coding Challenge #1 - Developer Skills (feat. Problem solving) (0) | 2022.11.13 |
---|---|
An High-Level Overview of JavaScript (0) | 2022.11.13 |
Looping Backwards and Loops in Loops (0) | 2022.09.19 |
The while Loop (0) | 2022.09.19 |
Looping Arrays, Breaking and Continuing (0) | 2022.09.19 |