[英]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.