[英]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 你需要做两件事
concat()
on acc
not with x
x
acc
上应用concat()
acc
to ''
by passing it as second parameter of reduce()
acc
初始值传递为reduce()
第二个参数来将其设置为''
+
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. 你有两个错过。
acc.concat(x.toUpperCase())
acc.concat(x.toUpperCase())
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.