Javascript 试图将字符串数组中的第一个字符大写,为什么这不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7743582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:24:44  来源:igfitidea点击:

Trying to capitalize the first character in array of strings, why this is not working?

javascriptarraysstringcharactercapitalization

提问by Rafael Adel

I'm a beginner at Javascript. I'm trying to write a function that converts for example list-style-imageto listStyleImage.

我是 Javascript 的初学者。我想编写一个函数,转换,例如list-style-imagelistStyleImage

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

回答by Pointy

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.

“toUpperCase()”函数返回新字符串但不修改原始字符串。

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.

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

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

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

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

回答by martinkzn

Here is my solution with ES6. This is an example where I store the days of the week in my array and I uppercase them with for... ofloop.

这是我使用 ES6 的解决方案。这是一个示例,我将星期几存储在数组中,并使用for... of循环将它们大写。

const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];

for (let day of days) {
    day = day.charAt(0).toUpperCase() + day.substr(1);
    console.log(day);
}

Here is a link to the documentation: for... of loop documentation

这是文档的链接:for... of loop documentation

回答by RoccoC5

In your forloop, you need to replace the value of newArr[i]instead of simply evaluating it:

在您的for循环中,您需要替换的值newArr[i]而不是简单地评估它:

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

回答by afxentios

Since JavaScript ES6 you can achieve the "camelization" of an array of strings with a single line:

从 JavaScript ES6 开始,您可以通过一行实现字符串数组的“骆驼化”:

let newArrCamel= newArr.map(item=> item.charAt(0).toUpperCase() + item.substr(1).toLowerCase())

回答by kennebec

You don't need the array to replace a hyphen and a lowercase letter with the uppercase-

您不需要数组用大写字母替换连字符和小写字母 -

function camelCase(s){
    var rx=  /\-([a-z])/g;
    if(s=== s.toUpperCase()) s= s.toLowerCase();
    return s.replace(rx, function(a, b){
        return b.toUpperCase();
    });
}

camelCase("list-style-image")

/*  returned value: (String)
listStyleImage
*/

回答by Vivek Viswanathan

you need to store the capitalized letter back in the array. Please refer the modified loop below,

您需要将大写字母存储回数组中。请参考下面修改后的循环,

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

回答by Jmorazano

A little bit longer but it gets the job done basically playing with arrays:

稍长一点,但它完成了工作,基本上是使用数组:

function titleCase(str) {
  var arr = [];
  var arr2 = [];
  var strLower = "";
  var strLower2 = "";
  var i;
  arr = str.split(' ');

  for (i=0; i < arr.length; i++) {

    arr[i] = arr[i].toLowerCase();
    strLower = arr[i];
    arr2 = strLower.split('');
    arr2[0] = arr2[0].toUpperCase();
    strLower2 = arr2.join('');
    arr[i] = strLower2;
  }

  str = arr.join(' ');

  return str;
}

titleCase("I'm a little tea pot");

回答by Julius Omwanza

The substr()method returns the part of a string between the start index and a number of characters after it. Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr

substr()方法返回字符串的起始索引和它后面的一些字符之间的部分。来源:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr

const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
for (let day of days) {
  day = day.substr(0, 1).toUpperCase() + day.substr(1);
  console.log(day);
}

回答by Mostafa Elhusseiny

const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];

days.map( a => a.charAt(0).toUpperCase() + a.substr(1) );

回答by Pre Vizsla

function titleCase(str){    // my codelooks like Jmorazano but i only use 4 var.
var array1 = [];
var array2 = []; 
var array3 = "";
var i;
array1 = str.split(" ");
for (i=0; i < array1.length; i++) {
array1[i]= array1[i].toLowerCase();
array2=array1[i].split("");
array2[0]=array2[0].toUpperCase();
array3 = array2.join("");
array1[i] = array3;}

str = array1.join(' ');
return str;}
titleCase("I AM WhO i aM"); //Output:I Am Who I Am
// my 1st post.