简体   繁体   中英

JavaScript - Get the value of a variable generated inside a forEach loop

I would like to get the value of a variable generated inside a forEach loop outside of it, please look at the code snippet:

  var variable = "";

  array.forEach(el=>{
  variable =  el.checkStatus;
  })

  //How to get the value of variable here ?
  var statuses = array.map(el => {
    return el.checkStatus;
  })

Then simply call statuses[index] depending on the status you want

You could make variable an array of each elements checkStatus values.

var variable = new Array();

array.forEach(el => {
    variable.push(el.checkStatus());
})

This would be more elegantly done using an array map function though.

var variable = array.map(el => el.checkStatus())

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