자바스크립트 # 필수암기목록 (복습)

달다로·2024년 7월 24일

JS

목록 보기
26/26
post-thumbnail

📌 참고 사이트
강사님 블로그 / Mdn


⭐ 기본 함수와 매개변수

  1. function() 의 괄호 안에 들어가는 것은 매개변수(parameters) 입니다.
  2. 매개변수 ? 함수를 호출할 때 함수에 전달되는 값, 이를 사용해서 함수내부에서 특정 작업을 수행합니다.
  3. 매개변수는 함수의 인풋으로 정의됩니다.
  4. 인수 ? 함수 호출시 실제로 전달되는 값
// 기본적인 구성
function greet(name) {
    console.log('Hello, ' + name + '!');
}
greet('Alice'); // 'Hello, Alice!'
// 두 개 이상의 매개변수
function add(a, b) {
    return a + b;
}
console.log(add(3, 4)); // 7
// 기본값을 가지고 있어도 특정값을 지정하면 특정값으로 나옵니다.
function greet(name = 'stranger') {
    console.log('Hello, ' + name + '!');
}
greet(); // 'Hello, stranger!'
greet('Alice'); // 'Hello, Alice!'

📋 정적 메서드

from

  • 유사 배열 객체 혹은 반복 가능한 객채를 복사 후 새로운 배열을 생성하는 메서드입니다.
  • 배열이 아닌 객체를 배열로 변환하거나, 반복 가능한 객체에서 값을 추출하여 배열로 변환할 때 유용하게 사용할 수 있습니다.
// 유사 배열 객체 → 배열
const arrayLike = {0: 'a', 1: 'b', 2: 'c', length: 3};
const array = Array.from(arrayLike);
console.log(array); // ["a", "b", "c"]

// 문자열 → 배열
const str = 'hello';
const chars = Array.from(str);
console.log(chars); // ["h", "e", "l", "l", "o"]

// Map 함수와 함께 사용
const numbers = [1, 2, 3, 4, 5];
const doubled = Array.from(numbers, x => x * 2);
console.log(doubled); // [2, 4, 6, 8, 10]

// Set 객체 → 배열
const set = new Set(['foo', 'bar', 'baz']);
const array = Array.from(set);
console.log(array); // ["foo", "bar", "baz"]

isArray

값이 배열인지 판별하는 데 사용됩니다. (boolean)

console.log(Array.isArray([1, 3, 5])); // true

📋 인스턴스 매서드

at

배열에서 특정 위치의 요소를 반환하는 메서드입니다.

const arr = [10, 20, 30, 40];
console.log(arr.at(1)); // 20 (두 번째 요소)
console.log(arr.at(-1)); // 40 (마지막 요소)
console.log(arr.at(-2)); // 30 (뒤에서 두 번째 요소)

concat

두 개 이상의 배열을 병합하는 데 사용됩니다. 이 메서드는 기존 배열을 변경하지 않고, 새 배열을 반환합니다. 값을 추가할 수도 있습니다.

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const result = arr1.concat(arr2);
console.log(result); // [1, 2, 3, 4, 5, 6]
// 추가
const result = arr1.concat(3, [4, 5], 'hello');
console.log(result); // [1, 2, 3, 4, 5, "hello"]

every

  • 메서드는 배열의 모든 요소가 주어진 조건을 만족하는지 테스트하는 데 사용됩니다. (boolean)
  • 빈 배열은 무조건 결과값이 참 입니다.
const a = (currentValue) => currentValue < 10;
const array = [1, 2, 3, 4, 5];
console.log(array.every(a)); // true

const b = (num) => num % 2 === 0;
const numbers = [2, 4, 6, 8, 9];
console.log(numbers.every(b)); // false

// 객체 배열에서의 조건 검사도 가능합니다.
const people = [
    { name: 'Alice', age: 25 },
    { name: 'Bob', age: 30 },
    { name: 'Charlie', age: 35 }
];
const allAdults = people.every(person => person.age >= 18);
console.log(allAdults); // true

콜백 함수

배열의 각 요소에 대해 실행할 함수를 의미합니다.
break 혹은 return 을 사용할 수 없습니다. (반환못함)

  • element
    처리할 현재 요소
  • index (선택)
    처리할 현재 요소의 인덱스
  • array (선택)
    every 메서드가 호출된 배열
  • thisArg (선택)
    callback 함수 내에서 this 로 사용할 값
arr.every(callback(element[, index[, array]])[, thisArg])

❓ 코드 작성시에 콜백함수를 따로 작성하지 않는 이유

분명 예제를 보면 callback 이 있는데 막상 코드를 칠때는 callback 이 생략되어 보입니다.
하지만 이는 생략된 것이 아니라 작성하지 않는 것 뿐이라고 합니다. 이것을 익명함수 또는 화살표 함수 라고 부릅니다.
대부분 일회성 함수일 경우에 작성되지 않는다고 합니다. (보통 콜백함수는 우리가 지정한 것을 검사하여 조건을 만족시킨 것을 찾은 다음 소멸되기 때문입니다.)

filter

  • 배열의 각 요소에 대해 주어진 조건을 만족하는 요소들만을 포함하는 새로운 배열을 반환합니다.
  • 원본 배열을 변경하지 않습니다.
  • 주로 배열에서 특정 조건을 충족하는 요소를 선택하거나, 조건에 맞지 않는 요소를 제거할 때 사용됩니다.
const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(number => number % 2 === 0); // 숫자들중에서 2를 나눈 나머지값이 0인 숫자
console.log(evenNumbers); // [2, 4, 6]

find

  • 배열 내에서 주어진 함수가 true 를 반환하는 첫 번째 요소를 반환합니다.
  • 이 메서드는 조건에 맞는 요소를 찾으면 즉시 검색을 중단합니다.
  • 조건을 만족하는 요소가 없는 경우 undefined를 반환합니다.
const numbers = [1, 3, 5, 8, 10];
const firstEven = numbers.find(num => num % 2 === 0);
console.log(firstEven); // 8 (배열에서 첫 번째 짝수)

findIndex

  • 배열에서 주어진 함수를 만족하는 첫 번째 요소의 인덱스를 반환합니다.
  • find 와 다른점은 find는 값을 찾고, findindex는 값의 위치를 찾아준다는겁니다!
  • 조건을 만족하는 요소가 없는 경우 -1 을 반환합니다.
const people = [
    { name: 'Alice', age: 25 },
    { name: 'Bob', age: 20 },
    { name: 'Charlie', age: 30 }
];
const index = people.findIndex(person => person.age > 20);
console.log(index); // 0 (0번째에 존재함)

forEach

  • 배열의 각 요소에 한 번씩 지정된 함수를 실행해줍니다.
  • 반복문을 사용하지 않고도 배열 요소 순회가 가능합니다.
  • 순서대로 호출을 하며, 원본 배열을 변경하지 않습니다.
  • 요약 : 배열의 각 요소에 반복적인 작업을 수행할 때 유용합니다!
// 기본구성
const fruits = ['apple', 'banana', 'mango'];

fruits.forEach(function(fruit) {
    console.log(fruit);
}); // apple banana mango
// 배열의 각 요소
const numbers = [1, 2, 3];
const doubledNumbers = []; // 빈 배열을 준비
numbers.forEach(function(number) {
    doubledNumbers.push(number * 2);
});
console.log(doubledNumbers); // [2, 4, 6]

includes

배열에 특정 요소가 포함되어 있는지 확인하는 데 사용됩니다. (boolean)

// 기본 문법
arr.includes(valueToFind[, fromIndex])
// 사용법
const fruits = ['apple', 'banana', 'mango'];
console.log(fruits.includes('banana')); // true
const numbers = [1, 2, 3, 4, 5];
console.log(numbers.includes(3, 3)); // false, 3 을 검색했지만 3은 3 이후에 없음

indexOf

  • 배열에서 특정 요소를 찾아 그 첫 번째 인덱스를 반환합니다.
  • 해당 요소가 배열에 없으면 -1을 반환합니다.
// 기본 문법
arr.indexOf(searchElement[, fromIndex])
// 사용법
const fruits = ['apple', 'banana', 'mango', 'banana'];
console.log(fruits.indexOf('banana')); // 1
// 특정 위치 지정
const fruits = ['apple', 'banana', 'mango', 'banana'];
console.log(fruits.indexOf('banana', 2)); // 3, 2부터 검색 시작함 (기본값 0)

❓ indexof 와 findIndex 의 차이

  • indexof
    배열에서 정확한 값을 찾아 첫 번째 위치의 인덱스를 반환함 (단순한 배열에서 사용)
  • findIndex
    배열의 요소가 조건을 만족하는지 확인하는 함수를 받은 후 첫 번째 요소의 인덱스를 반환함 (복잡한 조건에서 사용 가능)
// index of
const fruits = ['apple', 'banana', 'mango'];
console.log(fruits.indexOf('banana')); // 1

// findIndex
const numbers = [5, 12, 8, 130, 44];
const index = numbers.findIndex(number => number > 10);
console.log(index); // 1 (12는 인덱스 1에 위치)

join

배열의 모든 요소를 연결하여 하나의 문자열로 반환하는 데 사용됩니다.

// 기본
const fruits = ['apple', 'banana', 'mango'];
const result = fruits.join();
console.log(result); // "apple,banana,mango"

// 사용자 지정 가능
const fruits = ['apple', 'banana', 'mango'];
const result = fruits.join(' - ');
console.log(result); // "apple - banana - mango"

keys

  • 배열의 각 요소에 대한 인덱스를 포함하는 새로운 배열 반복자 객체를 반환합니다.
  • 배열의 키(즉, 인덱스)를 반복할 수 있는 객체를 생성합니다.
const fruits = ['apple', 'banana', 'mango'];
const iterator = fruits.keys();
for (const key of iterator) {
    console.log(key);
} // 출력: 0 1 2

// next 사용
console.log(iterator.next().value); // 0

// 인덱스와 함께 출력
const colors = ['red', 'green', 'blue'];
const iterator = colors.keys();
for (const index of iterator) {
    console.log(`Index: ${index}, Value: ${colors[index]}`);
}
// 출력:
// Index: 0, Value: red
// Index: 1, Value: green
// Index: 2, Value: blue

// reverse 사용 (재배열)
const animals = ['dog', 'cat', 'elephant'];
const iterator = animals.keys();
const reversed = [];
for (const index of iterator) {
    reversed.unshift(animals[index]);
}
console.log(reversed); // ['elephant', 'cat', 'dog']

❓ const ( ) of 의 ( ) 부분은 지정이 가능한가?

네, 지정이 가능합니다.
괄호안의 변수는 반복될때마다 현재의 값을 가리키는 역할을 합니다, 그 말은 반복 대상이 무엇이냐에 따라 달라질 수 있다는 의미입니다!
이 변수는 반복문을 작성할 때 개발자(나) 가 지정할 수 있으며, 일반적으로 상대방이 잘 이해할 수 있도록 이름을 짓는 것이 중요합니다.

❓ keys 는 반드시 for..of 문을 사용해야 하는가?

아닙니다. 그 방법은 Array Iterator 객체를 순화하는 한가지 방법일 뿐입니다. 아래와 같이도 사용 가능합니다.

⭐ Array Iterator ?
배열의 요소를 순차적으로 접근할 수 있게 해주는 반복 가능한 객체를 의미합니다.

  • for ... of 반복문
  • next() 를 이용한 수동 순회
  • from() 을 사용해 배열로 변환
  • 스프레드 연산자 [...fruits.keys()]

map

  • 배열의 각 요소에 대해 주어진 함수를 호출하고, 그 결과를 새로운 배열로 반환하는 데 사용됩니다.
  • 원본 배열은 유지됩니다. (각 요소가 변환된 새로운 배열을 생성)
  • 특히 배열의 각 요소를 변환하거나, 배열의 구조를 재구성할 때 유용합니다.
// 기본 사용법
const users = [
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' },
    { id: 3, name: 'Charlie' }
];
const userNames = users.map(function(user) {
    return user.name;
});
console.log(userNames); // ['Alice', 'Bob', 'Charlie']

// 화살표 함수
const userNames = users.map(user => user.name);

pop

  • 배열의 마지막 요소를 제거하고 그 요소를 반환합니다.
  • 배열의 길이를 줄이며, 원본 배열을 변경합니다.
const fruits = ['apple', 'banana', 'mango'];
const lastFruit = fruits.pop();
console.log(lastFruit); // 'mango'
console.log(fruits); // ['apple', 'banana']

shift

  • 배열의 첫 번째 요소를 제거하고 그 값을 반환합니다.
  • 원본 배열을 변경하며, 배열의 길이를 줄입니다.
const fruits = ['apple', 'banana', 'mango'];
const firstFruit = fruits.shift();
console.log(firstFruit); // 'apple'
console.log(fruits); // ['banana', 'mango']

push

  • 배열의 끝에 하나 이상의 요소를 추가하고, 배열의 새로운 길이를 반환합니다.
  • 배열의 기존 요소를 변경하지 않고, 새로운 요소를 배열합니다.
const numbers = [1, 2, 3];
const newLength = numbers.push(4, 5, 6);
console.log(numbers); // [1, 2, 3, 4, 5, 6]
console.log(newLength); // 6

reduce

  • 배열의 각 요소에 대해 주어진 콜백 함수를 실행하여, 배열을 단일 값으로 줄여줍니다.
  • 모든 배열 요소를 순회하며, 누적 결과를 반환합니다.
  • 특히 배열의 합계, 평균, 최대값 등을 계산하거나, 배열을 객체로 변환하는 등의 작업에 유용합니다.
// 기본 문법
arr.reduce(callback(accumulator, currentValue[, index[, array]]), initialValue)

// 숫자 합산
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // 10

// 속성 값 합산
const items = [
    { name: 'apple', price: 10 },
    { name: 'banana', price: 5 },
    { name: 'cherry', price: 20 }
];
const totalPrice = items.reduce((accumulator, item) => accumulator + item.price, 0);
console.log(totalPrice); // 35

// 문자열 배열을 하나의 문자열로 결합
const words = ['The', 'quick', 'brown', 'fox'];
const sentence = words.reduce((accumulator, currentValue) => accumulator + ' ' + currentValue);
console.log(sentence); // "The quick brown fox"

// 특정 속성 값 한산 후 객체로 만들기
const people = [
    { name: 'Alice', favoriteColor: 'blue' },
    { name: 'Bob', favoriteColor: 'green' },
    { name: 'Charlie', favoriteColor: 'blue' },
    { name: 'Dave', favoriteColor: 'red' },
    { name: 'Eve', favoriteColor: 'green' }
];
const colorCounts = people.reduce((acc, person) => {
    if (acc[person.favoriteColor]) {
        acc[person.favoriteColor]++;
    } else {
        acc[person.favoriteColor] = 1;
    }
    return acc;
}, {});
console.log(colorCounts); // { blue: 2, green: 2, red: 1 }
  • accumulator
    누적된 결과값을 저장하는 변수.
    초기값은 + initialValue 또는 배열의 첫 번째 요소.
  • currentValue
    현재 처리 중인 배열 요소.
  • index (선택)
    현재 요소의 인덱스. 초기값이 주어지면 0에서 시작, 그렇지 않으면 1에서 시작.
  • array (선택)
    reduce() 메서드가 호출된 배열.
  • initialValue (선택)
    콜백 함수가 최초로 호출될 때 accumulator로 사용하는 값.
    생략하면 배열의 첫 번째 요소가 사용됩니다.

reverse

배열의 요소 순서를 반대로 (반전) 만들어주기 위해 사용됩니다.

let myArray = [1, 2, 3, 4, 5];
myArray.reverse();
console.log(myArray); // [5, 4, 3, 2, 1]

slice

배열의 일부를 선택해 새로운 배열로 반환할 때 사용됩니다.

let myArray = ['a', 'b', 'c', 'd', 'e'];

// 요소 'b', 'c', 'd'를 포함하는 새로운 배열을 생성
let slicedArray = myArray.slice(1, 4); // 1부터 3까지의 요소

console.log(slicedArray); // ['b', 'c', 'd']
console.log(myArray);     // ['a', 'b', 'c', 'd', 'e'] myArray 는 원본상태 유지

some

배열의 각 요소에 주어진 함수를 호출해 그 결과가 true 를 반환하는 요소가 있는지 검사해줍니다.
하나라도 true 이면 true 를 반환해줍니다.
원본 배열을 변경하지 않습니다.

let numbers = [1, 2, 3, 4, 5];

let hasEvenNumber = numbers.some(function(number) {
  return number % 2 === 0;
});

console.log(hasEvenNumber); // true, 2 와 4 가 존재함

sort

배열의 요소를 정렬 후 새로운 배열로 반환합니다. (원본배열 수정)

let numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
  return a - b; // a-b 는 오름차순, b-a 는 내림차순
});
console.log(numbers); // [1, 2, 3, 4, 5]

splice

배열의 기존 요소를 삭제 또는 교체 또는 요소 추가해 배열의 내용을 변경합니다. (원본배열 직접 수정, 삭제된 요소 배열로 반환)

let fruits = ['apple', 'banana', 'cherry', 'date'];
let removed = fruits.splice(1, 2);
console.log(fruits);   // ['apple', 'date']
console.log(removed);  // ['banana', 'cherry']

unshift

배열의 시작 부분에 하나 이상의 요소를 추가 후, 새로운 길이를 반환합니다. (원본배열 수정)

let fruits = ['banana', 'cherry'];

// 배열의 시작 부분에 'apple'과 'date'를 추가합니다.
let newLength = fruits.unshift('apple', 'date');

console.log(fruits);     // ['apple', 'date', 'banana', 'cherry']
console.log(newLength);  // 4

values

배열의 모든 요소에 대해 하나씩 접근할 수 있는 "반복자(iterator)"를 반환합니다.
이 반복자를 사용하여 배열의 각 요소를 순서대로 탐색할 수 있습니다.
배열의 모든 값에 반복 작업을 수행할 때 좋습니다.
원본배열 수정하지 않습니다.

let fruits = ['apple', 'banana', 'cherry']; // 배열을 생성합니다.

let iterator = fruits.values(); // 배열의 값들에 대한 반복자를 생성합니다.

for (let value of iterator) { // 반복자를 사용하여 배열의 각 요소를 하나씩 가져옵니다.
  console.log(value);
}
// apple
// banana
// cherry

📋 인스턴스 속성

length

배열이나 문자열 등의 객체의 길이를 나타내는 속성입니다.
변경가능한 속성입니다.
배열의 길이를 직접 설정할때 많이 사용됩니다.

let fruits = ['apple', 'banana', 'cherry'];
fruits.length = 2; 
console.log(fruits); // ['apple', 'banana']

fruits.length = 5;
console.log(fruits); // ['apple', 'banana', <3 empty items>]
profile
나이들어서 공부함

0개의 댓글