Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

javascript - How can I pass a parameter to callback function which is inside map function

I am a new learner of JS, there is a function like this

const generateNum = (array, key) => {
    return array.map(i => parseFloat(i.key));
}

however, in this fn, key is declared but never used, how can I pass this parameter to the inside of map fn. Many thanks

question from:https://stackoverflow.com/questions/65599246/how-can-i-pass-a-parameter-to-callback-function-which-is-inside-map-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
const generateNum = (array, key) => {
  return array.map(i => parseFloat(i[key]));
}

A simple example for explanation.

let person = {
  name: 'John',
  age: 30,
};

let key = 'name';

person.key; // does not exist (only name and age is inside person object) so it would be undefined
person[key]; // exists because it means person.name actually

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...