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

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

问题描述

我在JavaScript中的初学者。我试图写一个转换例如函数列表样式图片 listStyleImage

我想出了一个功能,但似乎不工作。任何人都可以点我在这里的问题?

  VAR myStr中=名单样式图象功能camelize(STR){
    变种中newstr =;
    变种newArr = [];
    如果(str.indexOf( - )!= - 1){
        newArr = str.split( - );
        对于(VAR I = 1; I< newArr.length;我++){
            newArr [I] .charAt(0).toUpperCase();
        }
        中newstr = newArr.join();
    }
    返回中newstr;
}的console.log(camelize(myStr中));


解决方案

您有实际重新分配数组元素:

 为(VAR I = 1; I< newArr.length;我++){
        newArr [I] = newArr [I] .charAt(0).toUpperCase();
    }

在与toUpperCase()函数返回新的字符串,但不修改原来的。

您可能要检查,以确保 newArr [I] 是空字符串第一,如果你连续用两个破折号输入字符串。

修改的—指出SO贡献者@lonesomeday正确地指出,你还需要重新粘上每个字符串的其余部分:

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

I'm a beginner at Javascript. 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();
    }       

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

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.

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天全站免登陆