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
5 Answers
Reset to default 3You 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条)