Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 每个字母一次大写_Javascript_Arrays_String_Ecmascript 6 - Fatal编程技术网

Javascript 每个字母一次大写

Javascript 每个字母一次大写,javascript,arrays,string,ecmascript-6,Javascript,Arrays,String,Ecmascript 6,javascript函数,该函数返回一个字符串数组,该数组包含输入字符串的所有可能的大写字母,一次一个 大写(“hello”)➞ [“你好”、“你好”、“你好”、“你好”、“你好”] 我试过的是 const helloCapital=(str)=>{ 设a=[]; 为了(让我进来){ a、 push(str[i].toUpperCase()+str.slice(1)); } 返回a; }; 但它给出了奇怪的结果 ['Hello','Eello','Lello','Lello','Oello'

javascript函数,该函数返回一个字符串数组,该数组包含输入字符串的所有可能的大写字母,一次一个

大写(“hello”)➞ [“你好”、“你好”、“你好”、“你好”、“你好”]
我试过的是

const helloCapital=(str)=>{
设a=[];
为了(让我进来){
a、 push(str[i].toUpperCase()+str.slice(1));
}
返回a;
};
但它给出了奇怪的结果

['Hello','Eello','Lello','Lello','Oello']

这看起来像是课程或挑战网站的挑战

如果是这样的话,来这里问这个答案真的很不酷

但是,既然我已经在这里了,这里有一个有效的解决方案

const capitals=s=>Array.from(s,(u,i)=>s.slice(0,i)+u.toUpperCase()+s.slice(i+1))
更新:解释代码

Array.from
适用于iterable对象,例如字符串、数组和ArrayLike对象

它调用您作为iterable每个元素的第一个参数传递的函数,在本例中为字符串

函数接收iterable的1个元素(The)和该元素的位置(Thei

因此,该函数将返回3项内容的串联: *从0到i的原始字符串的子字符串 *iterable的当前元素或当前字符toUpperCase()
*从i+1到字符串末尾的原始字符串的子字符串。

您的逻辑是错误的,要工作,您需要使用大写字母和字母后的切片对字母前的切片进行合并

function capitalizeEachLetter (text) {
  return Array.from(text, (letter, index) =>
    text.slice(0, index) + letter.toUpperCase() + text.slice(index + 1)
  );
}
使用数组映射

var str=“你好”;
var capitals=Array.from(str).map((e,i,ar)=>{
设r=[…ar];
r[i]=ar[i].toUpperCase();
返回r.join(“”);
});

console.log(大写)
str.slice(1)在您的示例中始终是“ello”。哦..对…如何修复并获得结果
str[i]。slice(1)
这是一次竞争性考试,但昨天已经结束。我从昨天开始就在尝试,但什么也不去,所以…这个可以处理单个或两个字符长度的字符串吗?对代码的一点解释会很有用,先生…谢谢advance@MohammadUsman,是的,它将使用单字符或双字符strings@gunal,我已经添加了解释