如何返回第一个字母为大写字母的数组的所有元素

how can I return all the elements of an array with the first letter as a capital letter

本文关键字:大写字母 数组 元素 何返回 返回 第一个      更新时间:2023-09-26

我试图让下面数组中每个元素的第一个字母返回大写字母,但似乎只能返回第二个单词

var clenk = ["ham","cheese"];
var i = 0;
for (i = 0; i < clenk.length; i++) {
var result = clenk[i].replace(/'b./g, function(m){ return m.toUpperCase(); });
}
alert(result);
var clenk = ["ham","cheese"];
var i = 0;
for (i = 0; i < clenk.length; i++) {
    var result = clenk[i].replace(/'b./g, function(m){ return m.toUpperCase(); });
    alert(result);
}

把你的alert(result)放在循环中,否则你只能得到最后一个result

Array.prototype.map在这里可能更简单:

var results = clenk.map(function (word) {
    return word.charAt(0).toUpperCase() + word.substr(1);
});
String.prototype.toUpperCaseWords = function () {
  return this.replace(/'w+/g, function(a){ 
    return a.charAt(0).toUpperCase() + a.slice(1).toLowerCase()
  })
}

并像这样使用:-

"MY LOUD STRING".toUpperCaseWords(); // Output: My Loud String
"my quiet string".toUpperCaseWords(); // Output: My Quiet String
var stringVariable = "First put into a var";
stringVariable.toUpperCaseWords(); // Output: First Put Into A Var