LoginSignup
1
1

More than 5 years have passed since last update.

複数の数値が定義されている配列dataから、「各数値」と「40未満の数値がいくつあるか」を表示するプログラムを作成

Posted at

3つの方法を考えてみた

①オーソドックス?

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>4_10</title>
    <script>
        var data = [59, 39, 100, 2, 15, 40, 84, 97];
        for(var i = 0;i<data.length;i++) {
            document.write(data[i]+'<br>'); // 配列データの表示
        }

        var count=0; //countの箱に0を代入
        for(var j= 0;j<data.length;j++) {//データの数だけ入れていく
            if(data[j]<40) {
                count++;
            }
        }

        document.write('<p>40点未満の人は' + count + '人です</p>'); // 40未満の数値の個数表示
    </script>
</head>
<body>
</body>
</html>

②配列の結合を利用

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>4_10</title>
    <script>
        var data = [59, 39, 100, 2, 15, 40, 84, 97];
        var count = [];//40未満の数字が入る変数を作りたい
        for (var i = 0; i < data.length; i++) {
            document.write(data[i]+ '<br>'); 
            if (data[i] < 40 ){
                count.push(data[i]);
            }
        }
        document.write('<p>40点未満の人は' + count.length + '人です</p>'); 
    </script>
</head>
<body>
</body>
</html>

③上級者向け

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>4_10</title>
    <script>
        var datas = [59, 39, 100, 2, 15, 40, 84, 97];
        for (var i = 0; i < datas.length; i++) {
            document.write(datas[i]+ '<br>'); 
        }

        document.write ('<p>40点未満の人は' + 
            datas.filter(
                function(data){
                    return (data<40);
                }
            ).length + '人です</p>'); 

    </script>
</head>
<body>
</body>
</html>
1
1
1

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
1