這幾天 ES6 的一些介紹:
今天是綜合以上主題的挑戰練習。
題目 1:
把以下改為 arrow function 的寫法:
////Map -Create a new array by doing something with each item in an array.
// const newNumbers = numbers.map(function (x) {
// return x * 2;
// });
//我的答案:
const newNumbers = numbers.map(x => x * 2);
題目 2:
把以下改為 arrow function 的寫法:
const newNumbers = numbers.filter(function(num) {
return num < 10;
});
//我的答案:
const newNumbers = numbers.filter(num => num < 10)
題目 3:
把以下改為 arrow function 的寫法:
//Reduce - Accumulate a value by doing something to each item in an array.
var newNumber = numbers.reduce(function (accumulator, currentNumber) {
return accumulator + currentNumber;
})
//我的答案:
var newNumber = numbers.reduce( (accumulator, currentNumber) => accumulator + currentNumber);
題目 4:
把以下改為 arrow function 的寫法:
////Find - find the first item that matches from an array.
// const newNumber = numbers.find(function (num) {
// return num > 10;
// })
//我的答案:
const newNumber = numbers.find( num => num > 10)
題目 5:
把以下改為 arrow function 的寫法:
////FindIndex - find the index of the first item that matches.
// const newNumber = numbers.findIndex(function (num) {
// return num > 10;
// })
//我的答案:
const newNumber = numbers.findIndex(num => num > 10)
題目 6:
把以下改為 arrow function 的寫法:
import React from "react";
import Entry from "./Entry";
import emojipedia from "../emojipedia";
function createEntry(emojiTerm) {
return (
<Entry
key={emojiTerm.id}
emoji={emojiTerm.emoji}
name={emojiTerm.name}
description={emojiTerm.meaning}
/>
);
}
function App() {
return (
<div>
<h1>
<span>emojipedia</span>
</h1>
<dl className="dictionary">{emojipedia.map(createEntry)}</dl>
</div>
);
}
export default App;
我的答案:
import React from "react";
import Entry from "./Entry";
import emojipedia from "../emojipedia";
function App() {
return (
<div>
<h1>
<span>emojipedia</span>
</h1>
<dl className="dictionary">{emojipedia.map((emojiTerm)=>
<Entry
key={emojiTerm.id}
emoji={emojiTerm.emoji}
name={emojiTerm.name}
description={emojiTerm.meaning}
/>
)
}</dl>
</div>
);
}
export default App;