Зміст курсу
Introduction to React
Introduction to React
ES6 Map Method
ES6 introduces a new array method called map
, using which we can apply a function on every element of an array. This is useful in React because, using a map
, we can generate lists and repeated elements with a minimal amount of code.
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]; let twosMultiples = numbers.map ((n) => n * 2); console.log (twosMultiples);
The map
iterates over the entire array, passing the elements one by one as an argument into the inline function and storing the return values of the inline function into an output array.
We can use the same logic combined with JSX and React to achieve amazing results. We will explore JSX in detail in later chapters.
Example
There is a popular coding problem called the ‘FizzBuzz’ problem. The user is given an array of integers and asked to go through the array and:
- Replace the element with
"FizzBuzz"
if it's divisible by 3 and 5; - Replace the element with
"Fizz"
if it's divisible by 3; - Replace the element with
"Buzz"
if it's divisible by 5; - Leave the integer as it is if it's divisible by none.
let terms = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; let result = terms.map ((element) => { if (element % 3 == 0 && element % 5 == 0) { return "FizzBuzz"; } else if (element % 3 == 0) { return "Fizz"; } else if (element % 5 == 0) { return "Buzz"; } else { return element; } }); console.log (result);
Дякуємо за ваш відгук!