简体   繁体   English

以下代码段中的最小更改是什么,以便输出为“ ABC”?

[英]What is the smallest change in the following code snippet so that the output is “ABC”?

Hello I had this issue with my function 您好,我的功能遇到此问题

const string = ['a', 'b', 'c'].reduce((acc, x) => x.concat(x.toUpperCase()));
console.log(string );

And in the final result I want to get "ABC" 在最终结果中,我想获得“ ABC”

You need to do two things 你需要做两件事

  • apply concat() on acc not with x 在不带x acc上应用concat()
  • Set initial value of acc to '' by passing it as second parameter of reduce() 通过将acc初始值传递为reduce()第二个参数来将其设置为''
  • You can use + instead of contat() 您可以使用+代替contat()

 const string = ['a', 'b', 'c'].reduce((acc, x) => acc+x.toUpperCase(),''); console.log(string ); 

You can also do it using map() and join() 您也可以使用map()join()

 const string = ['a', 'b', 'c'].map(x=>x.toUpperCase()).join('') console.log(string ); 

It looks like you want a string? 看起来您想要一个字符串? join() to a string and .toUpperCase() is the direct and simple. join()到字符串, .toUpperCase()是直接而简单的。 Using reduce() is overkill. 使用reduce()是过大的。

 const string = ['a', 'b', 'c'].join('').toUpperCase(); console.log(string); 

You are not using concat() with the accumulator acc string and also not passing the initial value of it which should be an empty string "" (otherwise the first character of the resulting string would be lowercase as toUpperCase() won't be applied to it). 您没有将concat()与累加器acc字符串一起使用,也没有传递其初始值,该初始值应为空字符串"" (否则,结果字符串的第一个字符将为小写字母,因为不会应用toUpperCase()对此)。

Learn more about Array#reduce , this function takes the accumulator as the first param and the elements of the array as a second param and two other optional params. 了解有关Array#reduce更多信息,此函数将累加器作为第一个参数,并将数组的元素作为第二个参数和其他两个可选参数。

 const string = ['a', 'b', 'c'].reduce((acc, x) => acc.concat(x.toUpperCase()), ""); console.log(string ); 

You have two misses. 你有两个错过。

  • it should be acc.concat(x.toUpperCase()) 它应该是acc.concat(x.toUpperCase())
  • You missed initial value in reudce. 你错过了initial value在reudce。 else it will not change the first character to upper-case 否则不会将第first字符更改为大写

 const string = ['a', 'b', 'c'].reduce((acc, x) => acc.concat(x.toUpperCase()),''); console.log(string ); 

On side note:- You can simply use + instead of concat 附带说明:-您可以简单地使用+代替concat

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM