getLanguageCodeIndexPosition
函数查找语言代码在 url 标记中的位置,我想避免使用临时的 position
变量,这也许是一个更实用的解决方案。
我不知道语言标记是 en
还是 es
,所以如果找到一个返回它的位置,我会同时查找这两个
我欢迎你的建议
const languages = ["en", "es"];
const path = "http://www.app.name.local/es/compass/sample-compass/compass-temporal";
function getLanguageCodeIndexPosition() {
const tokens = path.split("/");
let position = undefined;
languages.forEach(sef => {
const index = tokens.findIndex(token => token === sef);
if (index !== -1) {
position = index;
return false;
}
});
return position;
}
const position = getLanguageCodeIndexPosition();
console.log(position);
最佳答案
修改findIndex
下的函数:
const languages = ["en", "es"];
const path = "http://www.app.name.local/es/compass/sample-compass/compass-temporal";
function getLanguageCodeIndexPosition() {
const tokens = path.split("/");
return tokens.findIndex(token => languages.includes(token));
}
console.log(getLanguageCodeIndexPosition());
关于javascript - 关于如何避免使用临时变量的建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58203589/