我正在构建货币转换器应用。
如何将这段代码变成箭头函数populateCurrencies
?
currencies.forEach(function populateCurrencies (currency) {
var option = document.createElement('option');
option.value = currency.id;
option.innerHTML = currency.name;
selector.appendChild(option)
});
答案 0 :(得分:0)
populateCurrencies = () => {
return currencies.forEach(function populateCurrencies (currency) {
var option = document.createElement('option');
option.value = currency.id;
option.innerHTML = currency.name;
selector.appendChild(option)
});
答案 1 :(得分:0)
您可以像这样内联替换它:
currencies.forEach(currency => {
var option = document.createElement('option');
option.value = currency.id;
option.innerHTML = currency.name;
selector.appendChild(option);
});
由于只有一个自变量,因此可以省略该自变量周围的括号。如果有两个参数,则需要使用括号,例如(currency, someOtherArg) => {...
答案 2 :(得分: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>
尽管如此,您可以只使用普通函数。