试图将字符串数组中的第一个字符大写,为什么这不起作用? [英] Trying to capitalize the first character in array of strings, why this is not working?

查看:22
本文介绍了试图将字符串数组中的第一个字符大写,为什么这不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数,例如将 list-style-image 转换为 listStyleImage.

I'm trying to write a function that converts for example list-style-image to listStyleImage.

我想出了一个函数,但它似乎不起作用.有人能指出我这里的问题吗?

I came up with a function but it seems not working. Can anybody point me to the problem here ?

var myStr = "list-style-image";

function camelize(str){
    var newStr = "";    
    var newArr = [];
    if(str.indexOf("-") != -1){
        newArr = str.split("-");
        for(var i = 1 ; i < newArr.length ; i++){
            newArr[i].charAt(0).toUpperCase();
        }       
        newStr = newArr.join("");
    }
    return newStr;
}

console.log(camelize(myStr));

推荐答案

你必须真正重新分配数组元素:

You have to actually re-assign the array element:

    for(var i = 1 ; i < newArr.length ; i++){
        newArr[i] = newArr[i].charAt(0).toUpperCase();
    }       

toUpperCase()"函数返回新字符串但不修改原始字符串.

The "toUpperCase()" function returns the new string but does not modify the original.

您可能需要先检查以确保 newArr[i] 是空字符串,以防您获得带有两个连续破折号的输入字符串.

You might want to check to make sure that newArr[i] is the empty string first, in case you get an input string with two consecutive dashes.

编辑 —注意到 SO 贡献者@lonesomeday 正确地指出,您还需要将每个字符串的其余部分粘回去:

edit — noted SO contributor @lonesomeday correctly points out that you also need to glue the rest of each string back on:

         newArr[i] = newArr[i].charAt(0).toUpperCase() + newArr[i].substr(1);

这篇关于试图将字符串数组中的第一个字符大写,为什么这不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆