[英]Given an array of strings, convert each string into: uppercase if first letter is capital lower case if first letter is small
[英]Why first letter in array of strings don't convert to upper case?
我接受輸入字符串"ZpglnRxqenU"
並且必須返回帶有該視圖的字符串"Z-Pp-Ggg-Llll-Nnnnn-Rrrrrr-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnnnnnnn-Uuuuuuuuuuu"
我幾乎完成了,但是我不知道為什么數組元素中的第一個字母不會變為大寫。
function accum(s) { let str = s.toLowerCase(); let arr = []; for(let i=0; i<str.length;i++){ arr.push(str[i].repeat(i+1)); arr[i][0].toUpperCase(); } return arr.join('-'); } console.log(accum("ZpglnRxqenU")); // must be "Z-Pp-Ggg-Llll-Nnnnn-Rrrrrr-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnnnnnnn-Uuuuuuuuuuu"
字符串是不可變的,僅使用.toUpperCase()不會更新現有字符串,為此,您可以嘗試以下代碼
function accum(s) {
let str = s.toLowerCase();
let arr = [];
for(let i=0; i<str.length;i++){
arr.push(str[i].repeat(i+1));
var [firstLetter, ...rest] = arr[i]
arr[i] = firstLetter.toUpperCase() +rest.join('')
}
return arr.join('-');
}
Javascript中的字符串是不可變的 ,因此如果要進行轉換,則必須為arr[i] = arr[i][0].toUpperCase() + arr[i].slice(1)
。
toUpperCase()
僅返回字符, 它不會操縱被調用的String 。
對於String.prototype
上的任何其他方法,例如String.replace()
。
更清楚地說:Javascript中要更改包含String的變量的唯一方法是為該變量分配一個新值 。
function accum(s) { let str = s.toLowerCase(); let arr = []; for(let i=0; i<str.length; i++){ arr.push(str[i].repeat(i+1)); arr[i] = arr[i][0].toUpperCase() + arr[i].slice(1); } return arr.join('-'); } console.log(accum("ZpglnRxqenU"));
您可以像這樣進行操作,並刪除不必要的這一行arr[i][0].toUpperCase();
function accum(s) { let str = s.toLowerCase(); let arr = []; for(let i=0; i<str.length;i++){ let gStr = str[i].repeat(i+1); arr.push(gStr[0].toUpperCase() + gStr.slice(1)); } return arr.join('-'); } console.log(accum("ZpglnRxqenU"));
字符串是不可變的。 使用toUpperCase()不會更改原始字符串。 取而代之的是,它將返回一個新字符串。 您必須將此新字符串保存在所需的位置:
arr[i][0] = arr[i][0].toUpperCase();
您可以利用Array.from
並以字符為Array.from
獲取字符串,然后將第一個大寫字符和重復的字符映射為新字符串。
最后,將所有項目連接到單個字符串。
function accum(s) { return Array .from(s.toLowerCase(), (c, i) => c.toUpperCase() + c.repeat(i)) .join('-'); } console.log(accum("ZpglnRxqenU"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.