では、「関数が複数の情報をまとめて返す」という考え方を、実際の使いどころで理解できるように、いくつか実用的な具体例を紹介します。
(全部 JavaScript 初心者でも動かせる内容です!)
例1:気温データから「最高・最低・平均」を返す関数
問題
気温データ [22, 25, 19, 27, 23] から、
- 最高気温
- 最低気温
- 平均気温
をまとめて返したい。
配列で返すパターン
function analyzeTemperature(temps) {
const max = Math.max(...temps);
const min = Math.min(...temps);
const avg = temps.reduce((sum, t) => sum + t, 0) / temps.length;
return [max, min, avg];
}
const [maxTemp, minTemp, avgTemp] = analyzeTemperature([22, 25, 19, 27, 23]);
console.log(`最高: ${maxTemp}℃, 最低: ${minTemp}℃, 平均: ${avgTemp.toFixed(1)}℃`);
JavaScript🧩 実行結果
最高: 27℃, 最低: 19℃, 平均: 23.2℃
オブジェクトで返すパターン(より読みやすい)
function analyzeTemperature(temps) {
const max = Math.max(...temps);
const min = Math.min(...temps);
const avg = temps.reduce((sum, t) => sum + t, 0) / temps.length;
return { max, min, avg };
}
const { max, min, avg } = analyzeTemperature([22, 25, 19, 27, 23]);
console.log(`最高: ${max}℃, 最低: ${min}℃, 平均: ${avg.toFixed(1)}℃`);
JavaScript💡 どっちがいい?
→ 配列でも書けますが、「どれが max / min / avg かわかりにくい」ので、
オブジェクトの方が可読性が高いです。
例2:日付情報を返す関数(配列とオブジェクトの比較)
配列パターン
function getDateInfo() {
const now = new Date();
return [now.getFullYear(), now.getMonth() + 1, now.getDate()];
}
const [year, month, day] = getDateInfo();
console.log(`${year}年${month}月${day}日`);
JavaScriptオブジェクトパターン
function getDateInfo() {
const now = new Date();
return {
year: now.getFullYear(),
month: now.getMonth() + 1,
day: now.getDate()
};
}
const { year, month, day } = getDateInfo();
console.log(`${year}年${month}月${day}日`);
JavaScript💡 使い分けポイント
- 配列:順序がはっきりしている「座標」「RGB値」「日付」などに向く
→[年, 月, 日]みたいに順番が意味を持つとき。 - オブジェクト:意味をラベルで明確にしたいとき(
{year, month, day})
例3:商品データから「合計金額」と「平均価格」を返す
function calcCartInfo(items) {
const total = items.reduce((sum, item) => sum + item.price, 0);
const average = total / items.length;
return { total, average };
}
const products = [
{ name: "ペン", price: 100 },
{ name: "ノート", price: 200 },
{ name: "ファイル", price: 300 }
];
const { total, average } = calcCartInfo(products);
console.log(`合計金額: ${total}円`);
console.log(`平均価格: ${average}円`);
JavaScript🧩 実行結果:
合計金額: 600円
平均価格: 200円
例4:座標の距離を返す関数(配列が適するパターン)
2点の座標 (x1, y1) と (x2, y2) から、
- 距離
- 中点(x, y)
を求めて返す。
function calcDistance(x1, y1, x2, y2) {
const dx = x2 - x1;
const dy = y2 - y1;
const distance = Math.sqrt(dx * dx + dy * dy);
const mid = [(x1 + x2) / 2, (y1 + y2) / 2];
return [distance, mid];
}
const [dist, [midX, midY]] = calcDistance(0, 0, 6, 8);
console.log(`距離: ${dist}, 中点: (${midX}, ${midY})`);
JavaScript🧩 実行結果:
距離: 10, 中点: (3, 4)
💡 こういう「数値の並び」は配列のほうが自然です。
「中点のX・Y座標」を [midX, midY] で分割代入できるのも便利!
例5:APIデータを整形して返す(現実的な応用)
目的
APIなどから取得した生データを、
「UI表示用に使いやすい形」にして返す関数を作る。
function formatUser(rawUser) {
const fullName = `${rawUser.firstName} ${rawUser.lastName}`;
const isAdult = rawUser.age >= 18;
return { fullName, isAdult };
}
const raw = { firstName: "Taro", lastName: "Yamada", age: 20 };
const { fullName, isAdult } = formatUser(raw);
console.log(fullName); // "Taro Yamada"
console.log(isAdult); // true
JavaScript🧩 実用ポイント:
- 関数内で複数の処理をまとめて行い、
- 必要な「複数の結果(名前・成人判定など)」を一度に返す。
まとめ
| 方法 | 向いている場面 | 特徴 |
|---|---|---|
| 配列で返す | 順番に意味があるデータ(座標、RGB、日付など) | シンプルだけど順序ミスに注意 |
| オブジェクトで返す | 名前を付けてわかりやすくしたいデータ | 可読性が高く安全 |
