// 기본적인 구성
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!'
// 유사 배열 객체 → 배열
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"]
값이 배열인지 판별하는 데 사용됩니다. (boolean)
console.log(Array.isArray([1, 3, 5])); // true
배열에서 특정 위치의 요소를 반환하는 메서드입니다.
const arr = [10, 20, 30, 40];
console.log(arr.at(1)); // 20 (두 번째 요소)
console.log(arr.at(-1)); // 40 (마지막 요소)
console.log(arr.at(-2)); // 30 (뒤에서 두 번째 요소)
두 개 이상의 배열을 병합하는 데 사용됩니다. 이 메서드는 기존 배열을 변경하지 않고, 새 배열을 반환합니다. 값을 추가할 수도 있습니다.
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"]
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 을 사용할 수 없습니다. (반환못함)
this 로 사용할 값arr.every(callback(element[, index[, array]])[, thisArg])
분명 예제를 보면 callback 이 있는데 막상 코드를 칠때는 callback 이 생략되어 보입니다.
하지만 이는 생략된 것이 아니라 작성하지 않는 것 뿐이라고 합니다. 이것을 익명함수 또는 화살표 함수 라고 부릅니다.
대부분 일회성 함수일 경우에 작성되지 않는다고 합니다. (보통 콜백함수는 우리가 지정한 것을 검사하여 조건을 만족시킨 것을 찾은 다음 소멸되기 때문입니다.)
const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(number => number % 2 === 0); // 숫자들중에서 2를 나눈 나머지값이 0인 숫자
console.log(evenNumbers); // [2, 4, 6]
const numbers = [1, 3, 5, 8, 10];
const firstEven = numbers.find(num => num % 2 === 0);
console.log(firstEven); // 8 (배열에서 첫 번째 짝수)
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번째에 존재함)
// 기본구성
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]
배열에 특정 요소가 포함되어 있는지 확인하는 데 사용됩니다. (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 이후에 없음
// 기본 문법
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)
// 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에 위치)
배열의 모든 요소를 연결하여 하나의 문자열로 반환하는 데 사용됩니다.
// 기본
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"
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']
네, 지정이 가능합니다.
괄호안의 변수는 반복될때마다 현재의 값을 가리키는 역할을 합니다, 그 말은 반복 대상이 무엇이냐에 따라 달라질 수 있다는 의미입니다!
이 변수는 반복문을 작성할 때 개발자(나) 가 지정할 수 있으며, 일반적으로 상대방이 잘 이해할 수 있도록 이름을 짓는 것이 중요합니다.
아닙니다. 그 방법은 Array Iterator 객체를 순화하는 한가지 방법일 뿐입니다. 아래와 같이도 사용 가능합니다.
⭐ Array Iterator ?
배열의 요소를 순차적으로 접근할 수 있게 해주는 반복 가능한 객체를 의미합니다.
for ... of 반복문next() 를 이용한 수동 순회from() 을 사용해 배열로 변환[...fruits.keys()]// 기본 사용법
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);
const fruits = ['apple', 'banana', 'mango'];
const lastFruit = fruits.pop();
console.log(lastFruit); // 'mango'
console.log(fruits); // ['apple', 'banana']
const fruits = ['apple', 'banana', 'mango'];
const firstFruit = fruits.shift();
console.log(firstFruit); // 'apple'
console.log(fruits); // ['banana', 'mango']
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
// 기본 문법
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 }
배열의 요소 순서를 반대로 (반전) 만들어주기 위해 사용됩니다.
let myArray = [1, 2, 3, 4, 5];
myArray.reverse();
console.log(myArray); // [5, 4, 3, 2, 1]
배열의 일부를 선택해 새로운 배열로 반환할 때 사용됩니다.
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 는 원본상태 유지
배열의 각 요소에 주어진 함수를 호출해 그 결과가 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 가 존재함
배열의 요소를 정렬 후 새로운 배열로 반환합니다. (원본배열 수정)
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]
배열의 기존 요소를 삭제 또는 교체 또는 요소 추가해 배열의 내용을 변경합니다. (원본배열 직접 수정, 삭제된 요소 배열로 반환)
let fruits = ['apple', 'banana', 'cherry', 'date'];
let removed = fruits.splice(1, 2);
console.log(fruits); // ['apple', 'date']
console.log(removed); // ['banana', 'cherry']
배열의 시작 부분에 하나 이상의 요소를 추가 후, 새로운 길이를 반환합니다. (원본배열 수정)
let fruits = ['banana', 'cherry'];
// 배열의 시작 부분에 'apple'과 'date'를 추가합니다.
let newLength = fruits.unshift('apple', 'date');
console.log(fruits); // ['apple', 'date', 'banana', 'cherry']
console.log(newLength); // 4
배열의 모든 요소에 대해 하나씩 접근할 수 있는 "반복자(iterator)"를 반환합니다.
이 반복자를 사용하여 배열의 각 요소를 순서대로 탐색할 수 있습니다.
배열의 모든 값에 반복 작업을 수행할 때 좋습니다.
원본배열 수정하지 않습니다.
let fruits = ['apple', 'banana', 'cherry']; // 배열을 생성합니다.
let iterator = fruits.values(); // 배열의 값들에 대한 반복자를 생성합니다.
for (let value of iterator) { // 반복자를 사용하여 배열의 각 요소를 하나씩 가져옵니다.
console.log(value);
}
// apple
// banana
// cherry
배열이나 문자열 등의 객체의 길이를 나타내는 속성입니다.
변경가능한 속성입니다.
배열의 길이를 직접 설정할때 많이 사용됩니다.
let fruits = ['apple', 'banana', 'cherry'];
fruits.length = 2;
console.log(fruits); // ['apple', 'banana']
fruits.length = 5;
console.log(fruits); // ['apple', 'banana', <3 empty items>]