如何使这段代码片段成为箭头功能

问题描述 投票:-1回答:3

我正在构建货币转换器应用程序。如何将此代码转换为箭头函数populateCurrencies

currencies.forEach(function populateCurrencies (currency) {
    var option = document.createElement('option');
    option.value = currency.id;
    option.innerHTML = currency.name;
    selector.appendChild(option)
});
javascript ecmascript-6
3个回答
0
投票
populateCurrencies = () => {
    return currencies.forEach(function populateCurrencies (currency) {
        var option = document.createElement('option');
        option.value = currency.id;
        option.innerHTML = currency.name;
        selector.appendChild(option)
    });

0
投票

这是你在找什么?

var currencies = [{
  id: 0,
  name: "euro"
}, {
  id: 1,
  name: "usd"
}];
var selector = document.querySelector("#selector");


currencies.forEach(currency => {
  var option = document.createElement('option');
  option.value = currency.id;
  option.innerHTML = currency.name;
  selector.appendChild(option);
});
<select id="selector"></select>

您也可以这样做:

var currencies = [{
  id: 0,
  name: "euro"
}, {
  id: 1,
  name: "usd"
}];
var selector = document.querySelector("#selector");


selector.innerHTML = currencies.map(currency => `<option value=${currency.id}>${currency.name}</option>`).join("");
<select id="selector"></select>

如果你想将整个forEach转换为箭头功能,你可以这样做:

var currencies = [{
  id: 0,
  name: "euro"
}, {
  id: 1,
  name: "usd"
}];
var selector = document.querySelector("#selector");


var populateCurrencies = () => {
  currencies.forEach(currency => {
    var option = document.createElement('option');
    option.value = currency.id;
    option.innerHTML = currency.name;
    selector.appendChild(option);
  });
};

populateCurrencies();
<select id="selector"></select>

但是,您可以使用普通功能。


0
投票

您可以像这样替换内联:

currencies.forEach(currency => {
    var option = document.createElement('option');
    option.value = currency.id;
    option.innerHTML = currency.name;
    selector.appendChild(option);
});

由于您只有一个参数,因此可以省略参数周围的括号。如果你有两个参数,你需要parens,例如(currency, someOtherArg) => {...

热门问题
推荐问题
最新问题