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

use*_*274 2 javascript

getLanguageCodeIndexPosition函数在url的令牌中找到语言代码的位置,我想避免使用临时position变量,这也许是一种更具功能性的解决方案。

我不知道该语言标记是否为enes,所以我寻找是否找到一个返回其位置的标记

我欢迎你的建议

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);
Run Code Online (Sandbox Code Playgroud)

mbo*_*jko 5

修改以下功能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());
Run Code Online (Sandbox Code Playgroud)