LoginSignup
1
0

More than 3 years have passed since last update.

【初心者向け】関数を使って増税してみた /map,forEach,Math.round

Posted at

概要

関数勉強後のoutputとして、商品の値段に消費税の10%を乗せる計算をしてみました。
私と同じ初学者の方に取っては、いいエクササイズになると思うので是非やってみてください。

流れ

Q.増税後の値段を四捨五入して出す

A.
1.配列で値段を定義する
2.mapで1.1倍する
3.forEachで展開する
4.Math.roundで四捨五入する

慣れれば仕組みがすっと入ってきます!それではやってみよう!

1.配列で値段を定義する

tax.js
const prices = [132, 222, 444];

こんな端数が出そうな数字選んでるのはわざとです笑

2.mapで1.1倍する

tax.js
const afterPrices = prices.map((price) => {
    return (price *= 1.1);
});

3-4.forEachで展開しつつ、Math.roundで四捨五入する

tax.js
//3.forEachで展開する
afterPrices.forEach((net, i) => {
    //4.Math.roundで四捨五入する
    const fixedPrices = Math.round(net);
    console.log(`増税後は${i + 1}番目の商品が${fixedPrices}円です`);
  });

:point_down_tone2:
[consol]
"増税後は1番目の商品が145円です"
"増税後は2番目の商品が244円です"
"増税後は3番目の商品が488円です"

いやあ、自分はこれを0→1で組み立てて完成するまで1時間以上かかってしまいました笑
まだまだ道のりは険しいですね、一緒に頑張りましょう。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0