作成ファイル・保存場所
js-basic フォルダに以下のファイルを作成してください。
| ファイル名 | 内容 |
|---|---|
| js-basic10.html | 関数定義と呼び出しの練習用HTMLファイル |
基本コード(HTML)は下記からコピー
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>JS Practice 10 関数とアロー関数</title>
</head>
<body>
<h1>関数とアロー関数の練習</h1>
<script>
// 1) 基本の関数定義と呼び出し
// 2) 引数つきの関数
// 3) 戻り値を使った関数
// 4) アロー関数で条件つきの処理({}とreturnが必要な例)
// 5) アロー関数で同じ処理(省略した書き方)
// ※ 1行だけなら {} と return を省略できます
</script>
</body>
</html>
JavaScriptは <script> タグの中に直接書きましょう(内部JS)
今回のテーマ
JavaScriptでは、関数(function) を使うことで処理をひとまとめにできます。
また、最近は =>(アロー関数)という書き方もよく使われます。
この回では、引数つきの関数、戻り値、アロー関数との違いを体験してみましょう。
目的
functionを使って処理をまとめる方法を学ぶ- 引数 を使って、関数に値を渡せるようになる
- 戻り値 (
return) を使って、関数から結果を受け取る方法を学ぶ =>(アロー関数)の書き方と使いどころを理解する
チェックポイント
function greet(name) { … }のように関数が定義できるかreturnを使って値を返せているかgreet('Taro')のように引数を渡して実行できるかconst add = (a, b) => a + b;のようにアロー関数が書けるかfunctionと=>の違い(書き方やthisの扱い)を説明できるか
解説ポイント
関数とは?
関数は「処理のかたまり」を定義し、何度でも呼び出せる仕組みです。
function hello() {
console.log('Hello!');
}
// 関数の呼び出し
hello();
引数とは?
関数に値を渡すときに使う「受け取り用の変数」です。
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet('Taro'); // Hello, Taro!
戻り値とは?
関数から結果を返すときに return を使います。
function add(a, b) {
return a + b;
}
let sum = add(3, 5);
console.log(sum); // 8
このように return を使うと、関数の「結果」を変数に代入したり、あとで使い回すことができます。
console.log() と return の違い
// 出力するだけの関数(値は返さない)
function showSum(a, b) {
console.log(a + b);
}
showSum(3, 5); // 8 と表示されるが、値は返されない
- console.log() は画面(コンソール)に表示するだけの処理です
- return は「値を関数の外に返す」ために使います。
アロー関数(=>)とは?
function を短く書ける書き方です。this の扱いが異なる点もありますが、基本は同じです。
// 普通の関数
function double(x) {
return x * 2;
}
// アロー関数(省略しない書き方)
// if文など複数行の処理を行うときは、{} と return が必要
const checkNumber = (x) => {
if (x % 2 === 0) {
return '偶数です';
} else {
return '奇数です';
}
};
console.log(double(4)); // 8
console.log(checkNumber(4)); // 偶数です
console.log(checkNumber(5)); // 奇数です
// アロー関数の省略記法(1行だけの処理に限る)
// {} と return は不要です
const double2 = x => x * 2;
console.log(double2(4)); // 8
HTML/JavaScriptトレーニング
以下のHTMLファイルを作成して、ブラウザのコンソールで動作を確認してみましょう。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>JS Practice 10 関数とアロー関数</title>
</head>
<body>
<h1>関数とアロー関数の練習</h1>
<script>
// =======================
// 1. 基本の関数定義と呼び出し
// =======================
function hello() {
console.log('Hello!');
}
hello(); // => Hello!
// =======================
// 2. 引数つきの関数
// =======================
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet('Taro'); // => Hello, Taro!
greet('Hanako'); // => Hello, Hanako!
// =======================
// 3. 戻り値を使った関数
// =======================
function add(a, b) {
return a + b;
}
let sum = add(3, 5);
console.log(`3 + 5 = ${sum}`); // => 3 + 5 = 8
// =======================
// 4. アロー関数で条件を返す
// =======================
const judge = (score) => {
if (score >= 80) {
return '合格';
} else {
return '不合格';
}
};
let result1 = judge(85);
let result2 = judge(65);
console.log(`85点の判定:${result1}`); // => 合格
console.log(`65点の判定:${result2}`); // => 不合格
// =======================
// 5. アロー関数でBMIを計算
//BMIの計算式はBMI = 体重(kg) ÷(身長(m) × 身長(m))
//身長cm を受け取り、メートルに変換 → 体重で割る必要があります。
// =======================
const calcBMI = (heightCm, weightKg) => {
const heightM = heightCm / 100; // cm → m
const bmi = weightKg / (heightM * heightM);
return Math.floor(bmi); // 小数点以下は切り捨て
};
let bmi1 = calcBMI(170, 60); // 170cm・60kg の場合
let bmi2 = calcBMI(160, 50); // 160cm・50kg の場合
console.log(`170cm・60kgのBMIは ${bmi1}`); // => 20
console.log(`160cm・50kgのBMIは ${bmi2}`); // => 19
// =======================
// 6-A. 円の面積
//ちなみに 3.14 は Math.PI()というメソッドでもOK
// =======================
const getCircleArea = (radius) => {
const pi = 3.14;
const area = Math.floor(pi * radius * radius);
return area;
};
console.log(`半径5cmの円の面積は ${getCircleArea(5)} cm²`); // → 78
console.log(`半径10cmの円の面積は ${getCircleArea(10)} cm²`); // → 314
</script>
</body>
</html>
追加トレーニング
まずは関数にする前の動きを考えて、関数化してみましょう
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>JS Practice 10 関数とアロー関数</title>
</head>
<body>
<h1>関数とアロー関数の練習</h1>
<script>
// =======================
// 1. 関数を使わずに BMI を計算してみよう
// =======================
let height = 172.5; // 身長(cm)
let weight = 66; // 体重(kg)
let height_m = height / 100; // メートルに変換
let bmi = weight / (height_m * height_m); // BMI 計算式
console.log(`身長172.5cm・体重66kgのBMIは ${Math.floor(bmi)}`);
// =======================
// 2. 同じ処理を関数にまとめてみよう(アロー関数)
// =======================
const calcBMI = (heightCm, weightKg) => {
const heightM = heightCm / 100;
const bmi = weightKg / (heightM * heightM);
return Math.floor(bmi); // 小数点以下は切り捨て
};
let bmi1 = calcBMI(170, 60);
let bmi2 = calcBMI(160, 50);
console.log(`170cm・60kgのBMIは ${bmi1}`);
console.log(`160cm・50kgのBMIは ${bmi2}`);
// =======================
// 3. 円の面積(まずは変数で)
// =======================
let radius = 10;
let pi = 3.14;
let circleArea = pi * radius * radius;
console.log(`半径10cmの円の面積は ${Math.floor(circleArea)} cm²`);
// =======================
// 4. 円の面積を関数で書こう
// =======================
const getCircleArea = (radius) => {
const pi = 3.14;
const area = pi * radius * radius;
return Math.floor(area);
};
console.log(`半径5cmの円の面積は ${getCircleArea(5)} cm²`);
console.log(`半径12cmの円の面積は ${getCircleArea(12)} cm²`);
// =======================
// 5. 台形の面積(まずは変数で)
// =======================
let topValue = 6;
let bottom = 10;
let heightT = 5;
let trapezoidArea = ((topValue + bottom) * heightT) / 2;
console.log(`上底6cm・下底10cm・高さ5cmの台形の面積は ${Math.floor(trapezoidArea)} cm²`);
// =======================
// 6. 台形の面積を関数にしてみよう
// =======================
const getTrapezoidArea = (topValue, bottom, height) => {
const area = ((topValue + bottom) * height) / 2;
return Math.floor(area);
};
console.log(`上底12cm・下底18cm・高さ7cmの台形の面積は ${getTrapezoidArea(12, 18, 7)} cm²`);
console.log(`上底5cm・下底9cm・高さ4cmの台形の面積は ${getTrapezoidArea(5, 9, 4)} cm²`);
</script>
</body>
</html>
応用トレーニング
個人別の成績計算を関数で効率化しよう!
let tanaka = [98, 75, 66, 90, 100]; let sato = [78, 85, 90, 90, 50]; let takahashi = [87, 99, 90, 50, 50];
問題1:関数を使わずに、合計点と平均点を出してみよう
- 変数
totalを用意し、for...of文を使ってtanaka配列の合計点を求めてください。 - 合計点を
console.logで表示してください。 - 平均点も計算し、表示してください。
- 同じ処理を
satoとtakahashiに対しても書いてみましょう(コードは3回繰り返すことになります)。
解答例
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>成績表示</title>
</head>
<body>
<h1>中間試験個人成績表</h1>
<script>
let tanaka = [98, 75, 66, 90, 100];
let sato = [78, 85, 90, 90, 50];
let takahashi = [87, 99, 90, 50, 50];
// tanaka
let total1 = 0;
for (let score of tanaka) {
total1 += score;
}
console.log(`tanakaさんの合計点は${total1}`);
let ave1 = Math.floor(total1 / tanaka.length);
console.log(`tanakaさんの平均点は${ave1}`);
// sato
let total2 = 0;
for (let score of sato) {
total2 += score;
}
console.log(`satoさんの合計点は${total2}`);
let ave2 = Math.floor(total2 / sato.length); // ← 修正
console.log(`satoさんの平均点は${ave2}`);
// takahashi
let total3 = 0;
for (let score of takahashi) {
total3 += score;
}
console.log(`takahashiさんの合計点は${total3}`);
let ave3 = Math.floor(total3 / takahashi.length); // ← 修正
console.log(`takahashiさんの平均点は${ave3}`);
</script>
</body>
</html>
問題2:処理を関数にまとめよう(functionバージョン)
- 合計点と平均点を計算して表示する関数
showScoreを定義してください。 - 引数は「名前(文字列)」と「点数の配列(数値配列)」の2つです。
console.logを使って「◯◯さんの合計点はXXX」「平均点はYYY」のように表示します。tanaka、sato、takahashiの3人の点数で関数を呼び出してください。
解答例
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>成績表示</title>
</head>
<body>
<h1>中間試験個人成績表</h1>
<script>
// 合計を計算する関数
function getTotal(scores) {
let total = 0;
for (let score of scores) {
total += score;
}
return total;
}
// 平均を計算する関数(小数点以下を切り捨て)
function getAverage(scores) {
let total = getTotal(scores); // 合計を計算
let ave = Math.floor(total / scores.length); // 平均(整数)を求める
return ave; // 結果を返す
}
// 表示用の関数
function showScore(name, scores) {
const total = getTotal(scores);
const average = getAverage(scores);
console.log(`${name}さんの合計点は${total}`);
console.log(`${name}さんの平均点は${average}`);
}
let tanaka = [98, 75, 66, 90, 100];
let sato = [78, 85, 90, 90, 50];
let takahashi = [87, 99, 90, 50, 50];
showScore("田中", tanaka);
showScore("佐藤", sato);
showScore("高橋", takahashi);
</script>
</body>
</html>
アロー関数に書き換えよう
- 上で作成した
showScore関数を「アロー関数」に書き換えてみましょう。 - 書き方が少し変わりますが、処理内容はまったく同じにします。
解答例
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>成績表示</title>
</head>
<body>
<h1>中間試験個人成績表(アロー関数版)</h1>
<script>
// 合計点を計算するアロー関数(ブロック構文)
const getTotal = (scores) => {
let total = 0;
for (let score of scores) {
total += score;
}
return total;
};
// 平均点を計算するアロー関数(ブロック構文・変数に代入・整数化)
const getAverage = (scores) => {
const total = getTotal(scores); // 合計を取得
const average = Math.floor(total / scores.length); // 平均を整数にして代入
return average; // 平均を返す
};
// 表示用のアロー関数(ブロック構文)
const showScore = (name, scores) => {
const total = getTotal(scores);
const average = getAverage(scores);
console.log(`${name}さんの合計点は${total}`);
console.log(`${name}さんの平均点は${average}`);
};
// データと関数の呼び出し
const tanaka = [98, 75, 66, 90, 100];
const sato = [78, 85, 90, 90, 50];
const takahashi = [87, 99, 90, 50, 50];
//表示する名前は漢字で表示もできます
showScore("田中", tanaka);
showScore("佐藤", sato);
showScore("高橋", takahashi);
</script>
</body>
</html>
