i18n: Abbreviation for Internationalization
Simple i18n functionality using the Array.prototype.reduce() method
The reduce() method sequentially executes a reducer function provided by you for each element in the array. Each run of the reducer will pass in the calculation results of the previous elements as parameters, and finally aggregate the results into a single return value.
Implementation code:
function $translate(key) {
// 翻译字典配置选项
const options = {
greetings: {
hello: "Bonjour!",
},
};
// 使用 `key` 作为索引获取 `options` 对象的深层属性
return key.split(".").reduce((o, i) => {
console.log("o", o);
console.log("i", i);
if (o) return o[i];
}, options);
// 简写
// return key.split(".").reduce((o, i) => o && o[i], options);
}
$translate("greetings.hello");
output:
reference: