GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

No menu could be recovered. Follow the blue links in the page.

This view

  • Original page
  • New address

GeezerVison is showing ja.javascript.info — 入力値の合計

  • チュートリアル
  • JavaScript 言語
  • データ型
  • 配列
レッスンに戻る

入力値の合計

重要性: 4

次のような関数 sumInput() を書きなさい:

  • 値に関して、prompt を使ってユーザに訪ね、配列にその値を格納します。
  • ユーザが非数値、空文字、または “キャンセル” を選択したとき、数値を尋ねるのを終了します。
  • 配列のアイテムを計算し、合計を返します。

P.S. ゼロ 0 は有効な数値です。ゼロで入力をストップしないでください。

デモを実行

些細ですが重要な解法の詳細に注意してください。私たちは、prompt のあと、すぐに value を数値に変換しません。なぜなら、value = +value の後に、ゼロ(有効数字)と空の文字列(停止のサイン)を区別することができないからです。私たちは後ほど代わりにそれを行います。

function sumInput() {

  let numbers = [];

  while (true) {

    let value = prompt("A number please?", 0);

    // should we cancel?
    if (value === "" || value === null || !isFinite(value)) break;

    numbers.push(+value);
  }

  let sum = 0;
  for (let number of numbers) {
    sum += number;
  }
  return sum;
}

alert( sumInput() );
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.