我有以下代码:
options.forEach((option) => {
return(option.get('template_name'))
})
选项包含2个地图的列表
我希望这会返回模板名称,但我得到2为什么是这样?如何从JavaScript中的forEach
函数返回?
forEach
不返回。https://developer.mozilla.org/en-us/docs/web/javascript/Reference/global_objects/typedarray/foreach#rethn_value
改用map
。https://developer.mozilla.org/en-us/docs/web/javascript/Reference/global_objects/typedarray/map#return_value
另外,要使用map
选项必须是一个数组。
查看此示例。
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>
那是循环的黄金旧的好:
for(var option of options){
return option.get("template_name");
}
等于:
return options[0].get("template_name");
或获取所有名称:
const tnames = options.map( option => option.get("template_name") );