[英]I can't understand why I'm receiving this output after a .reduce javascript method
This is my code:这是我的代码:
nicknames = {'RAM' : 'Black', 'ELC': 'Mamba', 'FAD' : 'Samba', 'NOP' : 'STOP'}
const nickGet = (initials) => {
return initials.match(/.{1,3}/g).reduce((arr, trio) => {
if (!nicknames[trio]) throw new Error('Invalid trio')
return [...arr, nicknames[trio]]
})
}
I am getting the below output when I run nickGet("ELCRAM"):当我运行 nickGet("ELCRAM") 时,我得到以下 output:
["E", "L", "C", "Black"]
I know that if I want to make this work, I should set an initial value of [] to reduce.我知道如果我想让这个工作,我应该设置一个 [] 的初始值来减少。 However, I'm wondering why when I don't, I get this specific out.但是,我想知道为什么当我不这样做时,我会得到这个具体的信息。 How is ELC being divided into separate values in my array? ELC 如何在我的数组中划分为单独的值? What is the logic behind it here?这背后的逻辑是什么?
Thank you!谢谢!
EDIT, trying to do it with map function:编辑,尝试用 map function 来做:
var nicknames = { RAM: 'Black', ELC: 'Mamba', FAD: 'Samba', NOP: 'STOP' };
const nickGet = (initials) => {
var nick = initials.match(/.../g).map((trio) => {
if (!nicknames[trio]) throw new Error('Invalid trio')
return nicknames[trio]
}, []);
nick.length = nick.findIndex(element => element == "STOP");
return nick;
};
Anyway to do it so that maps just stops when it hits STOP?无论如何要这样做,以便地图在停止时停止? Not sure what to replace "nothing" with if any.如果有的话,不确定用什么来代替“无”。
You do not supply an empty array as start value for the accumulator.您不提供空数组作为累加器的起始值。
In the fist loop, the string ELC
is spreaded into single characters, because this is the value for arr
.在第一个循环中,字符串ELC
被展开为单个字符,因为这是arr
的值。 As trio
, you get RAM
and this value is converted to 'Black'
.作为trio
,您将获得RAM
,并且此值将转换为'Black'
。
var nicknames = { RAM: 'Black', ELC: 'Mamba', FAD: 'Samba', NOP: 'STOP' }; const nickGet = (initials) => { return initials.match(/.../g).reduce((arr, trio) => { if (.nicknames[trio]) throw new Error('Invalid trio') return [..,arr; nicknames[trio]], }; []); }. console;log(nickGet('ELCRAM')). console.log([..;'ELC']);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.