创建Javascript函数时遇到错误

时间:2020-11-02 17:09:48

标签: javascript

我正在尝试编写一个函数,以将用Snake Case编写的字符串更改为Camel Case,但是遇到错误。

function snakeToCamel(string) {
    arr = [...string];
    for (i of arr) {
        if (i === "_") {
            let upperCaseLetter = arr[i+1].toUpperCase();
            arr.splice(i+1,1,upperCaseLetter);
            arr.splice(i,1)
        }
    };
    return arr;
}

错误为here。我在错误中指出的行中找不到错误。发生了什么事?

snakeToCamel("you_dont_know")
snake-to-camel.js:5 Uncaught TypeError: Cannot read property 'toUpperCase' of undefined
    at snakeToCamel (snake-to-camel.js:5)
    at <anonymous>:1:1

4 个答案:

答案 0 :(得分:2)

for-of循环中,控制变量是数组元素,而不是索引。因此,您示例中的i是一个字符串。因此,arr[i+1].toUpperCase();将进行字符串连接,并尝试查找名称类似于s1而不是1的属性。

如果您要使用索引,则需要for循环或forEach调用(甚至是map,因为这是您的工作),而不是for-of循环。

其他一些注意事项:

  • 您需要确保声明变量;现在,您的代码已沦为我所谓的The Horror of Implicit Globals的牺牲品,从而创建了一个名为arr的全局代码。在const之前添加letarr

  • 您不要将;放在控制流语句所附的块之后。 (您可以 将它们放在此处,因为允许使用空语句,但不应将它们放在那里。)

例如,使用for循环:

function snakeToCamel(string) {
    // `const` because we never reassign `arr`
    const arr = [...string];
    // Traditional `for` so we have the index
    for (let i = 0, len = arr.length; i < len; ++i) {
        const ch = arr[i];
        if (ch === "_") {
            if (i === len - 1) {
                // Trailing _, just remove it
                arr.splice(i, 1);
                --i;
                --len;
            } else {
                let upperCaseLetter = arr[i + 1].toUpperCase();
                // You can remove the _ and the lowr case letter
                // in a single `splice` rather than multiple ones
                arr.splice(i, 2, upperCaseLetter);
                --i; // Need to do this to allow for multiple `_` in a row
                --len;
            }
        }
    };
    return arr;
}
console.log(snakeToCamel("one_two__three_"));

或使用map

function snakeToCamel(string) {
    let lastWasUnderscore = false;
    const result = [...string]
        .map(ch => {
            const thisIsUnderscore = ch === "_";
            if (lastWasUnderscore && !thisIsUnderscore) {
                lastWasUnderscore = false;
                return ch.toUpperCase(); // or `.toLocaleUpperCase()`
            }
            lastWasUnderscore = thisIsUnderscore;
            return thisIsUnderscore ? null : ch;
        })
        .filter(ch => ch !== null);
    return result;
}
console.log(snakeToCamel("one_two__three_"));

答案 1 :(得分:0)

您实际上已经很接近解决方案了!

我建议您使用普通的for循环,而不要使用for-of循环。 这样,您可以访问索引i

function snakeToCamel(string) {
    const arr = [...string];
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] === "_") {
            let upperCaseLetter = arr[i+1].toUpperCase();
            arr.splice(i+1,1,upperCaseLetter);
            arr.splice(i,1)
        }
    }
    return arr.join("");
}

答案 2 :(得分:0)

这是我编写的代码。 (需要根据DRY原理进行完善)

convert image -bordercolor white -border 0x20 result

我只是添加到字符串而不是数组。我还删除了下划线。告诉我是否可行。

答案 3 :(得分:0)

signup_form.errors.as_json()