Javascript 关于如何避免使用临时变量的建议

Javascript 关于如何避免使用临时变量的建议,javascript,Javascript,getLanguageCodeIndexPosition函数在url的标记中查找语言代码的位置,我希望避免使用临时position变量,这可能是一个更实用的解决方案 我不知道语言标记是en还是es,因此如果找到一个返回其位置,我会同时查找这两个标记 我欢迎你的建议 const languages = ["en", "es"]; const path = "http://www.app.name.local/es/compass/sample-compass/compass-temporal";

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);

您可以使用
map()
find()
获取第一个匹配的语言索引

const languages=[“en”,“es”];
常量路径=”http://www.app.name.local/es/compass/sample-compass/compass-temporal";
函数getLanguageCodeIndexPosition(){
const tokens=path.split(“/”);
返回语言
.map(lang=>tokens.indexOf(lang))
.find(i=>i>=0);
}
const position=getLanguageCodeIndexPosition();

控制台日志(位置)修改
findIndex
下的函数:

const languages=[“en”,“es”];
常量路径=”http://www.app.name.local/es/compass/sample-compass/compass-temporal";
函数getLanguageCodeIndexPosition(){
const tokens=path.split(“/”);
返回tokens.findIndex(token=>languages.includes(token));
}
log(getLanguageCodeIndexPosition())
您可以使用作为
.findIndex()
的谓词

const languages=[“en”,“es”];
常量路径=”http://www.app.name.local/es/compass/sample-compass/compass-temporal";
const getLanguageCodeIndexPosition=()=>path.split('/').findIndex(t=>languages.includes(t));

log(getLanguageCodeIndexPosition())map
a
filter
中,code>Nice解决方案我只会用find替换filter,只返回索引这很好。我不确定我是否理解,
es
在本例中,通过将
split
应用于path获得的令牌中,
es
的位置是3
['http:',''www.app.name.local','es','compass','sample compass','compass temporal']
@user615274 Yes,我只是想验证一下,结果你想要
3
。当您将这些片段称为“令牌”时,我原以为您希望这些片段位于URL的末尾。但我只是想确定一下。出于好奇,你打算用这个索引值做什么?它是更改网站语言的组件的一部分,当用户单击网站上提供的其中一种语言时,我需要替换url中的语言代码,此函数用于标识在调用
location.replace(newuri)