returning from forEach javascript [duplicate]

2020-04-27 04:59发布

i have the following code:

options.forEach((option) => {
  return(option.get('template_name'))
})

where options contains a list of 2 maps

I expect this to return the template name, but instead I get 2 Why is this? How can I return from a forEach function in javascript?

2条回答
不美不萌又怎样
2楼-- · 2020-04-27 05:54

forEach does not return. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/forEach#Return_value

Use map instead. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/map#Return_value

Also, to use map options must be an array.

Check out this example.

var options = Array.from(document.getElementById('selections').options),
    newOptions = options.map(function(item){
        return item.value
    });

console.log(newOptions);

document.getElementById('results').insertAdjacentHTML('afterbegin', newOptions.reduce((a,b) => a.concat(`${b} `), ' '));
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>returning from forEach javascript</title>
</head>
<body>

    <select id="selections">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>
    
    <div id="results"></div>
    
</body>
</html>

查看更多
一纸荒年 Trace。
3楼-- · 2020-04-27 05:54

Thats what a gold old for loop is good for:

 for(var option of options){
    return option.get("template_name");
 }

Which equals:

 return options[0].get("template_name");

Or getting all names:

 const tnames = options.map( option => option.get("template_name") );
查看更多
登录 后发表回答