How to create an image array from a URL array in JavaScript using map?

Viewed 113

How to create an image array from a URL array in JavaScript using map? I don't want to render anything. Just want to use it in JavaScript. I tried this but it returns undefined in the console...

const urlArray = [
  'Images/black.png',
  'Images/yellow.png',
  'Images/pink.png',
]

const imgArray = urlArray.map(url => {
  let img = new Image()
  img.src = url
})

console.log(imgArray)
1 Answers

You need to return img in each iteration:

const urlArray = [ 'Images/black.png', 'Images/yellow.png', 'Images/pink.png'];

const imgArray = urlArray.map(url => {
  let img = new Image()
  img.src = url;
  return img; // add this
})

console.log(imgArray)

Related