๐ก ๋์ ๋ชจ๋ ์๋ฐ์คํฌ๋ฆฝํธ ํต์ฌ ๊ฐ์ด๋๋ฅผ ์ฝ๊ณ ์ ๋ฆฌํฉ๋๋ค.
8.1 Array.from()
๋ฐฐ์ด์ฒ๋ผ ๋ณด์ด์ง๋ง ๋ฐฐ์ด์ด ์๋ ๊ฐ์ฒด๋ฅผ ๋ฐ์ ์ค์ ๋ฐฐ์ด๋ก ๋ณํํด ๋ฐํํ๋ค.
<div class="fruits">
<p> Apple </p>
<p> Banana </p>
<p> Orange </p>
</div>
const fruits = document.querySelectorAll(".fruits p");
const fruitArray = Array.from(fruits);
console.log(fruitArray);
// [p,p,p]
const fruitNames = fruitArray.map( fruit => fruit.textContent);
console.log(fruitNames);
// ["Apple", "Banana", "Orange"]
์๋์ ๊ฐ์ด ๋จ์ํํ ์๋ ์๋ค.
const fruits = Array.from(document.querySelectorAll(".fruits p"));
const fruitNames = fruits.map(fruit => fruit.textContent);
console.log(fruitNames);
// ["Apple", "Banana", "Orange"]
๋ ๋ฒ์งธ ์ธ์๋ฅผ ์ด์ฉํด ๋ฐฐ์ด์ map
ํจ์๋ฅผ ์ ์ฉํ ๊ฒ๊ณผ ๋์ผํ ๊ธฐ๋ฅ์ ์ฝ๋๋ฅผ ์์ฑํ ์๋ ์๋ค.
const fruits = document.querySelectorAll(".fruits p");
const fruitArray = Array.from(fruits, fruit => {
console.log(fruit);
// <p> Apple </p>
// <p> Banana </p>
// <p> Orange </p>
return fruit.textContent;
// we only want to grab the content not the whole tag
});
console.log(fruitArray);
// ["Apple", "Banana", "Orange"]
8.2 Array.of()
์ ๋ฌ๋ฐ์ ๋ชจ๋ ์ธ์๋ก ๋ฐฐ์ด์ ์์ฑํ๋ค.
const digits = Array.of(1,2,3,4,5);
console.log(digits);
// Array [ 1, 2, 3, 4, 5];
8.3 Array.find()
์ ๊ณต๋ ํ ์คํธ ํจ์๋ฅผ ์ถฉ์กฑํ๋ ๋ฐฐ์ด์ ์ฒซ ๋ฒ์งธ ์์๋ฅผ ๋ฐํํ๋ค. ์ถฉ์กฑํ๋ ์์๊ฐ ์์ ๊ฒฝ์ฐ, undefined๋ฅผ ๋ฐํํ๋ค.
const array = [1,2,3,4,5];
// this will return the first element in the array with a value higher than 3
let found = array.find( e => e > 3 );
console.log(found);
// 4
8.4 Array.findIndex()
์กฐ๊ฑด๊ณผ ์ผ์นํ๋ ์ฒซ ๋ฒ์งธ ์์์ ์ธ๋ฑ์ค๋ฅผ ๋ฐํํ๋ค.
const greetings = ["hello","hi","byebye","goodbye","hi"];
let foundIndex = greetings.findIndex(e => e === "hi");
console.log(foundIndex);
// 1
8.5 Array.some()๊ณผ Array.every()
.some()
์ ์กฐ๊ฑด๊ณผ ์ผ์นํ๋ ์์๊ฐ ์๋์ง ๊ฒ์ํ๊ณ ์ฒซ ๋ฒ์งธ ์ผ์นํ๋ ์์๋ฅผ ์ฐพ์ผ๋ฉด ๋ฐ๋ก ์ค์งํ๋ค..every()
๋ ๋ชจ๋ ์์๊ฐ ์ฃผ์ด์ง ์กฐ๊ฑด๊ณผ ์ผ์นํ๋์ง ์ฌ๋ถ๋ฅผ ํ์ธํ๋ค.
const array = [1,2,3,4,5,6,1,2,3,1];
let arraySome = array.some( e => e > 2);
console.log(arraySome);
// true
let arrayEvery = array.every(e => e > 2);
console.log(arrayEvery);
// false
'Tech > JavaScript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
Chapter 10: ๊ฐ์ฒด ๋ฆฌํฐ๋ด (Object literal upgrades) (0) | 2022.01.24 |
---|---|
Chapter 09: Spread์ Rest (Spread operator and rest parameters) (0) | 2022.01.23 |
Chapter 07: ๋ฐ๋ณต๋ฌธ (Loop) (0) | 2022.01.20 |
Chapter 06: ๋์คํธ๋ญ์ฒ๋ง - ๊ตฌ์กฐ ๋ถํด ํ ๋น (Destructuring) (0) | 2022.01.19 |
Chapter 05: ๋ฌธ์์ด ๋ฉ์๋ (Additional string methods) (0) | 2022.01.18 |