繁体   English   中英

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

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

您好,我的功能遇到此问题

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

在最终结果中,我想获得“ ABC”

你需要做两件事

  • 在不带x acc上应用concat()
  • 通过将acc初始值传递为reduce()第二个参数来将其设置为''
  • 您可以使用+代替contat()

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

您也可以使用map()join()

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

看起来您想要一个字符串? join()到字符串, .toUpperCase()是直接而简单的。 使用reduce()是过大的。

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

您没有将concat()与累加器acc字符串一起使用,也没有传递其初始值,该初始值应为空字符串"" (否则,结果字符串的第一个字符将为小写字母,因为不会应用toUpperCase()对此)。

了解有关Array#reduce更多信息,此函数将累加器作为第一个参数,并将数组的元素作为第二个参数和其他两个可选参数。

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

你有两个错过。

  • 它应该是acc.concat(x.toUpperCase())
  • 你错过了initial value在reudce。 否则不会将第first字符更改为大写

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

附带说明:-您可以简单地使用+代替concat

暂无
暂无

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

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