Chapter 08: ๋ฐฐ์—ด ๋ฉ”์„œ๋“œ (Array improvements)

๐Ÿ’ก ๋„์„œ ๋ชจ๋˜ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ํ•ต์‹ฌ ๊ฐ€์ด๋“œ๋ฅผ ์ฝ๊ณ  ์ •๋ฆฌํ•ฉ๋‹ˆ๋‹ค.

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