arrays - How console log element value during map() in javascript? - Stack Overflow

I have an array and I create an another array with Array.prototype.map(). How can I console log the x v

I have an array and I create an another array with Array.prototype.map(). How can I console log the x value (the current element being processed in the array) during the map function?

const array1 = [1, 4, 9, 16];
const map1 = array1.map((x) => x * 2);

I have an array and I create an another array with Array.prototype.map(). How can I console log the x value (the current element being processed in the array) during the map function?

const array1 = [1, 4, 9, 16];
const map1 = array1.map((x) => x * 2);
Share Improve this question edited Jan 6 at 9:49 ahuemmer 2,05913 gold badges27 silver badges36 bronze badges asked Jun 19, 2021 at 9:55 Milán NikolicsMilán Nikolics 6212 gold badges10 silver badges24 bronze badges 5
  • Use {} to create a block, instead of doing an implicit return => – PsyGik Commented Jun 19, 2021 at 10:00
  • Don't use arrow functions if you don't know how they work: MDN: Arrow function expressions – Andreas Commented Jun 19, 2021 at 10:00
  • 1 @PsyGik "Use {} to create a closure" - That's a block and not a "closure" – Andreas Commented Jun 19, 2021 at 10:01
  • I get -1 but my qestion but have legitimate. My question is very clear. For my aspect have resarch and effort, and answer for me was super useful. Thank you again. – Milán Nikolics Commented Jun 26, 2021 at 19:15
  • Yes, thank you again. Somebody else also give me +1 and other senior also answer for me but ... – Milán Nikolics Commented Jun 27, 2021 at 11:32
Add a ment  | 

5 Answers 5

Reset to default 3

You can use console.log in a map like this:

const array1 = [1, 4, 9, 16];
const map1 = array1.map((x) => {
  console.log(x);
  return x * 2;
});

You are using a shorthand return:

() => x returns x just as () => { return x; }.

But since you are not only returning something you can not use the concise arrow function syntax.

you can use like this:

const array1 = [1, 4, 9, 16];
const map1 = array1.map(function(x){
   console.log(x);
   return x* 2;
});

You can print it like below.

array1.map(function(x) {
      console.log(x*2);
      return x * 2
});   

const array1 = [1, 4, 9, 16];
const map1 = array1.map(function(x) {
      console.log(x*2);
      return x * 2
});

You can use an array:

const array1 = [1, 4, 9, 16];

console.log('Mapping array1...');
const map1 = array1.map((x) => [x * 2, console.log(x)][0]);
console.log('Maped successfully, map1 =', map1);

Use {} to create a block

const array1 = [1, 4, 9, 16];
const map1 = array1.map((x) => {
  console.log(x)
  return x * 2
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744276363a4566348.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信