简体   繁体   中英

Why when apply Map.prototype.forEach will return undefined?

在此处输入图片说明

I try to study the Map object by reading document. However, it confuses me in the beginning. I wonder what does it mean by" Return undefined." here?

I wonder what does it mean by" Return undefined." here?

It means the function forEach will execute the provided function f and nothing else, basically, the function forEach doesn't return anything because its job is to loop the provided entries calling the callback function f on every entry within the map.

If the callback returns a value, this will be ignored.

 var undefinedValue = new Map([ ['foo', 3], ['bar', {}], ['baz', 2] ]).forEach(() => { console.log('Looping...'); return "HELLO WORLD!"; // This will be ignored! }); console.log("Value returned from forEach:", undefinedValue) 

This just means that the effect of forEach is entirely dependent on what you do inside the function f , you don't get an overall returned value from the forEach operation. If you did this:

let a = arr.forEach(myFunc);

...then a would be undefined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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