では「翻訳辞書を用意して本格的に i18n(多言語対応)する方法」を見てみましょう。
ゴール
- 言語ごとに翻訳辞書を用意する
- 関数の中で「キー」を使って文言を取り出す
- 日本語・英語以外にも簡単に拡張できる
翻訳辞書の例
const translations = {
ja: {
cart: 'カート',
items: '点',
subtotal: '合計',
taxIncluded: '税込',
noItems: '商品はありません',
others: '…他{count}件'
},
en: {
cart: 'Cart',
items: 'items',
subtotal: 'Subtotal',
taxIncluded: 'Tax incl.',
noItems: 'No items',
others: '…and {count} more'
}
};
JavaScript👉 文言を「キー」で管理することで、言語を切り替えるだけで表示を変えられる。
翻訳を取り出す関数
function t(lang, key, params = {}) {
let text = translations[lang][key] || key;
// {count} のようなプレースホルダーを置換
for (const p in params) {
text = text.replace(`{${p}}`, params[p]);
}
return text;
}
JavaScriptリスト要約関数(辞書対応)
function summarizeList(items, max = 3, lang = 'ja') {
if (items.length === 0) return t(lang, 'noItems');
if (items.length <= max) {
return items.join(', ');
} else {
const shown = items.slice(0, max).join(', ');
const remaining = items.length - max;
return t(lang, 'others', { count: remaining }).replace('…', shown + ' ');
}
}
JavaScriptカート概要関数
function cartSummary(cart, lang = 'ja', taxRate = 0.1) {
const validItems = cart.filter(item => item.quantity > 0);
const names = validItems.map(item => item.name);
const nameList = summarizeList(names, 3, lang);
const subtotal = validItems
.map(item => item.price * item.quantity)
.reduce((acc, subtotal) => acc + subtotal, 0);
const totalWithTax = Math.floor(subtotal * (1 + taxRate));
const itemCount = validItems.reduce((acc, item) => acc + item.quantity, 0);
return `${t(lang, 'cart')}: ${nameList} / ${itemCount}${t(lang, 'items')} / ${t(lang, 'subtotal')}: ${subtotal.toLocaleString()}円 (${t(lang, 'taxIncluded')} ${totalWithTax.toLocaleString()}円)`;
}
JavaScript実行例
console.log(cartSummary(cart, 'ja'));
// "カート: Tシャツ, ジーンズ, 帽子 / 4点 / 合計: 10,000円 (税込 11,000円)"
console.log(cartSummary(cart, 'en'));
// "Cart: Tシャツ, ジーンズ, 帽子 / 4items / Subtotal: 10,000円 (Tax incl. 11,000円)"
JavaScriptポイント
- 翻訳辞書を使えば 言語追加が簡単(フランス語や中国語も追加可能)
- キーで管理するので、文言が増えても整理しやすい
- 実務では i18next などのライブラリを使うとさらに便利
💡 ここまでで「多言語対応の基礎」ができました。
次の発展としては、「金額や日付のフォーマットも言語ごとに変える(Intl APIを使う)」とさらに実用的になります。


