简体   繁体   中英

.forEach() Javascript function is returning an Array?

Generally, It is said that 'forEach' doesn't return an array, whereas 'map' returns one. However, In my case, it is returning one. Below posted is my code. I am kind of confused. Any help would be appreciated.

//Code Snippet //
var arr = [1, 3, 2];
var arr_temp = [];

arr.forEach(function (i) {
  return arr_temp.push(i + i);
});

console.log(arr_temp);

I am getting the output as: [2,6,4]

It doesn't return anything. You can check that by logging the result of the forEach call:

 var arr = [1, 3, 2]; var arr_temp = []; console.log(arr.forEach(function (i) { return arr_temp.push(i + i); })); // undefined console.log(arr_temp); // 2, 6, 4

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