객체 생성
기본적인 객체 생성
let person = {
name: "홍길동",
age: 30,
gender: "남자"
};
객체를 만들 때는 중괄호({})를 사용하며, 속성과 값을 콜론(:)으로 구분하여 작성
각 속성과 값은 쉼표(,)로 구분
생성자 함수를 사용한 객체 생성
생성자 함수는 일반적인 함수와 비슷하지만 객체를 초기화하고 속성을 설정하기 위해 사용
동일한 형식의 객체를 여러 개 생성할 수 있으며, 이러한 객체들은 생성자 함수에 정의된 속성과 메서드를 공유
생성자 함수를 사용하면 객체를 일괄적으로 생성할 수 있음
function Person(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
let person1 = new Person("홍길동", 30, "남자");
let person2 = new Person("홍길순", 25, "여자");
객체 속성 접근
객체의 속성에 접근할 때는 점(.)을 사용하여 속성 이름을 입력
let person = {
name: "홍길동",
age: 30,
gender: "남자"
};
console.log(person.name); // "홍길동"
console.log(person.age); // 30
console.log(person.gender); // "남자"
객체 메서드
Object.keys(obj)
객체의 속성 이름을 배열로 반환
let person = {
name: "홍길동",
age: 30,
gender: "남자"
};
let keys = Object.keys(person);
console.log(keys); // ["name", "age", "gender"]
Object.values(obj)
객체의 속성 값들을 배열로 반환
let person = {
name: "홍길동",
age: 30,
gender: "남자"
};
let values = Object.values(person);
console.log(values); // ["홍길동", 30, "남자"]
Object.entries(obj)
객체의 속성 이름과 속성 값들을 2차원 배열로 반환
let person = {
name: "홍길동",
age: 30,
gender: "남자"
};
let entries = Object.entries(person);
console.log(entries); //[ [ 'name', '홍길동' ], [ 'age', 30 ], [ 'gender', '남자' ] ]
Object.assign(target, ...sources)
기존 객체를 복사하여 새로운 객체를 만듦
- target: 병합할 대상의 객체
이 객체는 다른 객체의 속성을 복사할 대상이 됨 - sources: 복사하려는 하나 이상의 소스 객체
여러 소스 객체를 지정할 수 있음 - 대상 객체("target")에 소스 객체("sources")의 속성을 복사
동일한 키를 가진 속성이 이미 대상 객체에 존재한다면, 소스 객체의 속성으로 덮어 씌움
let person = {
name: "홍길동",
age: 30,
gender: "남자"
};
let newPerson = Object.assign({}, person, { age: 35 });
console.log(newPerson); // { name: "홍길동", age: 35, gender: "남자" }
객체 비교
일반적으로 객체는 주소값이 다르기 때문에 === 연산자를 사용할 수 없음
JSON.stringify() 함수를 사용하여 객체를 문자열로 변환한 후 문자열을 비교
let person1 = {
name: "홍길동",
age: 30,
gender: "남자"
};
let person2 = {
name: "홍길동",
age: 30,
gender: "남자"
};
console.log(person1 === person2); // false
console.log(JSON.stringify(person1) === JSON.stringify(person2)); // true
JSON.stringify(value [, replacer [, space]])
- value: JSON 문자열로 변환할 Javascript 객체 또는 값
- replacer(선택사항): 필터링 함수 또는 배열로 JSON 문자열에 포함할 속성을 지정할 때 사용
- space(선택사항): 문자열이나 숫자로 들여 쓰기를 위한 공백을 추가하는 데 사용
// 기본 사용
const person = {
name: "John",
age: 30,
city: "New York"
};
const jsonString = JSON.stringify(person);
console.log(jsonString);
// 출력: {"name":"John","age":30,"city":"New York"}
// replacer 매개변수를 사용하여 일부 속성 필터링
const person = {
name: "John",
age: 30,
city: "New York"
};
const jsonString = JSON.stringify(person, ["name", "age"]);
console.log(jsonString);
// 출력: {"name":"John","age":30}
// space 매개변수를 사용하여 들여쓰기 추가
const person = {
name: "John",
age: 30,
city: "New York"
};
const jsonString = JSON.stringify(person, null, 2); // 2칸 들여쓰기
console.log(jsonString);
// 출력:
// {
// "name": "John",
// "age": 30,
// "city": "New York"
// }
// 복합적인 예제 - replacer 및 space 모두 사용
const person = {
name: "John",
age: 30,
city: "New York"
};
const jsonString = JSON.stringify(person, (key, value) => {
if (key === "name") {
return value.toUpperCase(); // 이름을 대문자로 변환
} else {
return value; // 다른 속성은 그대로 유지
}
}, 2); // 2칸 들여쓰기
console.log(jsonString);
// 출력:
// {
// "name": "JOHN",
// "age": 30,
// "city": "New York"
// }
객체 병합
let person1 = {
name: "홍길동",
age: 30
};
let person2 = {
gender: "남자"
};
let mergedPerson = {...person1, ...person2};
console.log(mergedPerson); // { name: "홍길동", age: 30, gender: "남자" }
전개 연산자(...)
배열, 객체, 함수 매개변수 등을 확장하거나 결합하는 데 사용되는 연산자
// 배열 확장
// 배열을 확장하거나 다른 배열과 결합할 수 있음
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2]; // 배열 확장 및 결합
console.log(combined); // [1, 2, 3, 4, 5, 6]
// 객체 확장
// 객체를 확장하거나 다른 객체와 병합할 수 있음
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const merged = { ...obj1, ...obj2 }; // 객체 확장 및 병합
console.log(merged); // { a: 1, b: 3, c: 4 }
// 함수 매개변수
// 가변 매개변수를 처리할 수 있으며, 함수에 여러 인수를 동적으로 전달하는데 유용
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // 15
// 배열 요소 복사
// 배열의 요소를 새 배열에 복사할 수 있음
const originalArray = [1, 2, 3];
const copiedArray = [...originalArray]; // 배열 요소 복사
console.log(copiedArray); // [1, 2, 3]
가변 매개변수(Variable Arguments)는 함수의 매개변수(parameter)의 개수가 고정되지 않고, 호출할 때 제공된 인수(argument)의 개수에 따라 다르게 처리되는 매개변수
나머지 매개변수(Rest Parameters) 또는 전개 연산자(Spread Operator)를 사용하여 정의
1. 나머지 매개변수 (Rest Parameters)
... 연산자와 함께 매개변수를 정의하며 함수에 전달된 인수를 배열로 수집
함수 내에서는 이 배열을 사용할 수 있음
function sum(...numbers) { return numbers.reduce((total, num) => total + num, 0); } console.log(sum(1, 2, 3, 4, 5)); // 152. 전개 연산자 (Spread Operator)
함수를 호출할 때 배열의 요소를 분해하여 인수로 전달할 수 있음
함수 내에서 각 요소를 개별 매개변수로 처리할 수 있음
function displayNames(name1, name2, name3) { console.log(name1, name2, name3); } const names = ["John", "Alice", "Bob"]; displayNames(...names); // "John Alice Bob"
배열 생성
배열은 여러 요소로 구성되며, 이러한 요소들은 배열 내의 위치(인덱스)에 따라 접근 가능
- 배열의 크기: 배열에 포함된 요소의 개수(length)
- 배열의 요소: 배열에 저장된 개별 값
- 인덱스: 배열 내의 위치
기본적인 배열 생성
배열을 만들 때는 대괄호([])를 사용하며, 각 요소는 쉼표(,)로 구분
let fruits = ["사과", "바나나", "오렌지"];
배열의 크기 지정
배열의 크기를 지정할 수 있음
배열의 크기(길이)가 5인 배열을 생성하지만 초기화된 값이 없으므로 모든 요소가 undefined로 설정됨
let numbers = new Array(5);
console.log(numbers.length); // 5
console.log(numbers); // [undefined, undefined, undefined, undefined, undefined]
배열 요소 접근
대괄호([]) 안에 인덱스 값을 넣어서 접근
let fruits = ["사과", "바나나", "오렌지"];
console.log(fruits[0]); // "사과"
console.log(fruits[1]); // "바나나"
console.log(fruits[2]); // "오렌지"
배열 메서드
array.push(element1, element2, ..., elementN)
배열의 끝에 요소를 추가
- array: 요소를 추가할 배열
- element1, element2, ..., elementN: 배열에 추가할 하나 이상의 요소
const fruits = ["사과", "바나나"];
const newLength = fruits.push("딸기", "오렌지");
console.log(fruits); // ["사과", "바나나", "딸기", "오렌지"]
console.log(newLength); // 4 (배열의 새로운 길이)
array.pop()
배열의 마지막 요소를 삭제
- array: 마지막 요소를 제거할 배열
const fruits = ["사과", "바나나", "딸기"];
const removedFruit = fruits.pop();
console.log(fruits); // ["사과", "바나나"]
console.log(removedFruit); // "딸기" (제거된 요소)
array.shift()
배열의 첫 번째 요소를 삭제
- array: 첫 번째 요소를 제거할 배열
const fruits = ["사과", "바나나", "딸기"];
const removedFruit = fruits.shift();
console.log(fruits); // ["바나나", "딸기"]
console.log(removedFruit); // "사과" (제거된 요소)
array.unshift(element1, element2, ..., elementN)
배열의 맨 앞에 요소를 추가
- array: 요소를 추가할 배열
- element1, element2, ..., elementN: 배열의 시작 부분에 추가할 하나 이상의 요소
const fruits = ["바나나", "딸기"];
const newLength = fruits.unshift("사과", "오렌지");
console.log(fruits); // ["사과", "오렌지", "바나나", "딸기"]
console.log(newLength); // 4 (배열의 새로운 길이)
array.splice(start [, deleteCount [, item1 [, item2 [,...]]])
배열의 요소를 삭제하거나 새로운 요소를 추가할 수 있음
- array: 요소를 수정할 배열
- start: 요소를 추가 또는 제거할 시작 위치를 나타내는 인덱스
- deleceCount(선택사항): 삭제할 요소의 수를 나타내는 정수
생략하거나 0으로 설정하면 요소를 삭제하지 않음 - item1, item2, ...(선택사항): 배열에 추가할 요소
// 요소 추가
const fruits = ["사과", "바나나", "딸기"];
fruits.splice(1, 0, "오렌지"); // 인덱스 1에 "오렌지" 요소 추가
console.log(fruits); // ["사과", "오렌지", "바나나", "딸기"]
// 요소 제거
const fruits = ["사과", "바나나", "딸기"];
fruits.splice(1, 1); // 인덱스 1의 요소(바나나)를 제거
console.log(fruits); // ["사과", "딸기"]
// 요소 교체
const fruits = ["사과", "바나나", "딸기"];
fruits.splice(1, 1, "오렌지"); // 인덱스 1의 요소(바나나)를 "오렌지"로 교체
console.log(fruits); // ["사과", "오렌지", "딸기"]
array.slice([start [, end]])
배열의 일부분을 새로운 배열로 만듦
- array: 복사할 배열
- start(선택사항): 복사를 시작할 인덱스를 나타내는 정수
이 인덱스의 요소가 복사 결과에 포함되며, 음수 값을 사용할 수 있고 배열의 끝부터 역으로 셀 수 있음 - end(선택사항): 복사를 끝낼 인덱스를 나타내는 정수
이 인덱스의 요소는 복사결과에 포함되지 않음
음수 값을 사용할 수 있으며, 배열의 끝부터 역으로 셀 수 있음
const colors = ["빨강", "파랑", "노랑", "초록", "주황"];
const selectedColors = colors.slice(1, 4); // 인덱스 1부터 4 미만까지의 범위 복사
console.log(selectedColors); // ["파랑", "노랑", "초록"]
array.forEach(callback(currentValue [, index [, array]])[, thisArg])
배열의 각 요소에 대해 주어진 함수를 실행
반복문을 대체하고 배열의 요소를 반복하며 각 요소에 대해 지정된 작업을 수행
- array: 요소를 반복할 배열
- callback: 각 요소에 대해 실행할 함수 또는 콜백 함수
- currentValue: 현재 반복 중인 요소의 값
- index(선택사항): 현재 요소의 인덱스
- array(선택사항): forEach()를 호출한 배열 자체
- thisArg(선택사항): 콜백 함수 내에서 this의 값으로 사용할 객체를 나타냄
// 배열 요소 출력
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(number) {
console.log(number);
});
// 요소와 인덱스 출력
const fruits = ["사과", "바나나", "딸기"];
fruits.forEach(function(fruit, index) {
console.log(`인덱스 ${index}: ${fruit}`);
});
// 콜백 함수 내에서 this 사용
const person = {
name: "John",
age: 30
};
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(number) {
console.log(`${this.name} is ${number} years old.`);
}, person);
// 배열 자체를 변경하지 않고 요소 합산
const numbers = [1, 2, 3, 4, 5];
let sum = 0;
numbers.forEach(function(number) {
sum += number;
});
console.log("총합: " + sum);
// 화살표 함수와 함께 사용
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(number => {
console.log(number);
});
array.map(callback(currentValue [, index [, array]])[, thisArg])
각 요소를 변환하여 새로운 배열을 생성할 수 있으며,
이를 통해 원본 배열을 변경하지 않고, 배열의 요소를 변활 할 수 있음
- array: 변환할 배열
- callback: 각 요소에 대해 실행할 함수 또는 콜백 함수
- currentValue: 현재 반복 중인 요소의 값
- index(선택사항): 현재 요소의 인덱스
- array(선택사항): map()를 호출한 배열 자체
- thisArg(선택사항): 콜백 함수 내에서 this의 값으로 사용할 객체
// 각 요소를 제곱한 새로운 배열 생성
const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map(function(number) {
return number * number;
});
console.log(squaredNumbers); // [1, 4, 9, 16, 25]
// 각 요소의 길이를 구해 새로운 배열 생성
const fruits = ["사과", "바나나", "딸기"];
const fruitLengths = fruits.map(function(fruit) {
return fruit.length;
});
console.log(fruitLengths); // [2, 4, 3]
// 요소를 객체로 변환한 새로운 배열 생성
const names = ["John", "Alice", "Bob"];
const personObjects = names.map(function(name) {
return { name: name, age: 30 };
});
console.log(personObjects);
// [{ name: "John", age: 30 }, { name: "Alice", age: 30 }, { name: "Bob", age: 30 }]
// 화살표 함수와 함께 사용
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(number => number * 2);
console.log(doubledNumbers); // [2, 4, 6, 8, 10]
// thisArg를 사용하여 this 값을 지정
const person = {
age: 25,
doubleAge: function(number) {
return number * this.age;
}
};
const numbers = [1, 2, 3, 4, 5];
const doubledAges = numbers.map(person.doubleAge, person);
console.log(doubledAges); // [25, 50, 75, 100, 125]
array.filter(callback(currentValue [, index [, array]])[, thisArg])
배열의 요소를 조건에 따라 필터링하여 원하는 요소만 추출 가능
데이터를 필터링하고 새로운 배열을 생성할 수 있으며, 다양한 조건을 사용하여 사용자 지정 필터링 수행 가능
- array: 필터링할 배열
- callback: 각 요소에 대해 실행할 함수 또는 콜백함수로 조건을 정의
- currentValue: 현재 반복 중인 요소의 값
- index(선택사항): 현재 요소의 인덱스
- array(선택사항): filter()를 호출한 배열 자체
- thisArg(선택사항): 콜백 함수 내에서 this 값으로 사용할 객체
// 짝수만 추출
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evenNumbers = numbers.filter(function(number) {
return number % 2 === 0;
});
console.log(evenNumbers); // [2, 4, 6, 8, 10]
// 문자열의 길이가 3인 요소만 추출
const words = ["apple", "banana", "cherry", "date", "fig"];
const threeLetterWords = words.filter(function(word) {
return word.length === 3;
});
console.log(threeLetterWords); // ["fig"]
// 숫자 배열에서 특정 밤위의 숫자만 추출
const numbers = [15, 30, 45, 60, 75, 90];
const rangeNumbers = numbers.filter(function(number) {
return number >= 30 && number <= 60;
});
console.log(rangeNumbers); // [30, 45, 60]
// 객체 배열에서 특정 조건을 만족하는 객체만 추출
const persons = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 32 },
{ name: "Charlie", age: 28 },
];
const youngPeople = persons.filter(function(person) {
return person.age < 30;
});
console.log(youngPeople);
// [{ name: "Alice", age: 25 }, { name: "Charlie", age: 28 }]
// 화살표 함수와 함께 사용
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const oddNumbers = numbers.filter(number => number % 2 !== 0);
console.log(oddNumbers); // [1, 3, 5, 7, 9]
array.reduce(callback(accumulator, currentValue [, index [, array]])[, initialValue])
배열의 요소를 하나로 축소하거나 결합하는 데 사용
- array: 값을 축소할 배열
- callback: 각 요소에 대해 실행할 함수 또는 콜백 함수로, 누산기(accumulator) 및 현재 요소 값 처리
- accumulator: 누산기로서 각 단계에서의 결과를 나타냄
- currentValue: 현재 반복 중인 요소의 값
- index(선택사항): reduce()를 호출한 배열 자체
- initialValue: 초기 누산기 값을 제공하며, 이 매개변수가 생략되면 배열의 첫 번째 요소가 초기 누산기 값으로 적용
// 배열 요소의 합 구하기
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, 0);
console.log(sum); // 15
// 배열 요소의 평균 구하기
const numbers = [1, 2, 3, 4, 5];
const average = numbers.reduce(function(accumulator, currentValue, index, array) {
accumulator += currentValue;
if (index === array.length - 1) {
return accumulator / array.length;
}
return accumulator;
}, 0);
console.log(average); // 3
// 배열에서 최댓값 구하기
const numbers = [12, 3, 8, 19, 6, 17];
const max = numbers.reduce(function(accumulator, currentValue) {
return Math.max(accumulator, currentValue);
}, -Infinity);
console.log(max); // 19
// 객체 배열의 값을 합산
const expenses = [
{ item: "식비", cost: 50 },
{ item: "교통비", cost: 30 },
{ item: "쇼핑", cost: 70 }
];
const totalCost = expenses.reduce(function(accumulator, expense) {
return accumulator + expense.cost;
}, 0);
console.log(totalCost); // 150
// 초기값을 생략하여 배열의 첫 번째 요소를 초기값으로 사용
const numbers = [1, 2, 3, 4, 5];
const product = numbers.reduce(function(accumulator, currentValue) {
return accumulator * currentValue;
});
console.log(product); // 120
누산기(accumulator)는 reduce() 메서드에서 사용되는 변수로, 각 단계에서 중간 결과나 현재까지의 누적값을 저장하는 용도로 사용됨
reduce() 메서드는 배열의 요소를 반복하면서 누산기에 값을 누적(축적)시키는 작업을 수행하고, 최종적으로 누산기에 저장된 값이 reduce()의 최종 결과가 됨
array.find(callback(element [, index [, array]])[, thisArg])
배열에서 조건에 맞는 첫 번째 요소를 찾는 데 사용
배열을 반복하면서 조건을 검사하며, 조건에 맞는 요소를 찾으면 반환
- array: 검색할 배열
- callback: 각 요소에 대해 실행할 함수 또는 콜백함수로 조건을 정의
- element: 현재 검색 중인 요소의 값
- index(선택사항): 현재 요소의 인덱스
- array(선택사항): find()를 호출한 배열 자체
- thisArg(선택사항): 콜백 함수 내에서 this의 값으로 사용할 객체
// 배열에서 첫 번째 짝수를 찾기
const numbers = [1, 3, 5, 2, 7, 4, 6];
const firstEven = numbers.find(function(element) {
return element % 2 === 0;
});
console.log(firstEven); // 2
// 배열에서 길이가 5 이상인 첫 번째 문자열 찾기
const words = ["apple", "banana", "cherry", "date", "fig"];
const firstLongWord = words.find(function(word) {
return word.length >= 5;
});
console.log(firstLongWord); // "banana"
// 배열에서 특정 값과 일치하는 첫 번째 요소 찾기
const colors = ["red", "green", "blue", "yellow"];
const targetColor = "blue";
const firstMatch = colors.find(function(color) {
return color === targetColor;
});
console.log(firstMatch); // "blue"
// 화살표 함수와 함께 사용
const numbers = [1, 3, 5, 2, 7, 4, 6];
const firstEven = numbers.find(element => element % 2 === 0);
console.log(firstEven); // 2
// thisArg를 사용하여 this 값을 지정
const person = {
age: 25,
isAdult: function(element) {
return element >= this.age;
}
};
const ages = [18, 22, 30, 15, 28];
const firstAdult = ages.find(person.isAdult, person);
console.log(firstAdult); // 30
array.some(callback(element [, index [, array]])[, thisArg])
배열에서 하나 이상의 요소가 조건을 만족하는지 확인하는 데 사용
배열을 반복하면서 조건을 검사하며, 조건을 만족하는 요소가 하나 이상 있는 경우 true를 반환
그렇지 않으면 false를 반환
- array: 조건을 검사할 배열
- callback: 각 요소애 대해 실행할 함수 또는 콜백 함수로 조건을 정의
- element: 현재 검사 중인 요소의 값
- index(선택사항): 현재 요소의 인덱스
- array(선택사항): some()을 호출한 배열 자체
- thisArg(선택사항): 콜백 함수 내에서 this의 값으로 사용할 객체를 나타냄
// 배열에서 하나 이상의 짝수가 있는지 확인
const numbers = [1, 3, 5, 2, 7, 9, 11];
const hasEven = numbers.some(function(element) {
return element % 2 === 0;
});
console.log(hasEven); // true
// 배열에서 길이가 5 이상인 문자열이 하나 이상 있는지 확인
const words = ["apple", "banana", "cherry", "date", "fig"];
const hasLongWord = words.some(function(word) {
return word.length >= 5;
});
console.log(hasLongWord); // true
// 배열에서 특정 값과 일치하는 요소가 하나 이상 있는지 확인
const colors = ["red", "green", "blue", "yellow"];
const targetColor = "blue";
const hasTargetColor = colors.some(function(color) {
return color === targetColor;
});
console.log(hasTargetColor); // true
// 화살표 함수와 함께 사용
const numbers = [1, 3, 5, 2, 7, 9, 11];
const hasEven = numbers.some(element => element % 2 === 0);
console.log(hasEven); // true
// thisArg를 사용하여 this 값을 지정
const person = {
minAge: 18,
isAdult: function(element) {
return element >= this.minAge;
}
};
const ages = [12, 20, 30, 15, 28];
const hasAdult = ages.some(person.isAdult, person);
console.log(hasAdult); // true
array.every(callback(element [, index [, array]])[, thisArg])
배열의 모든 요소가 조건을 만족하는지 확인하는 데 사용
모든 요소가 조건을 만족해야 true를 반환하며 하나라도 조건을 만족하지 않으면 false를 반환
- array: 검사할 배열
- callback: 각 요소에 대해 실행할 함수 또는 콜백 함수로 조건을 정의
- element: 현재 검사 중인 요소의 값
- index(선택사항): 현재 요소의 인덱스
- array(선택사항): every()를 호출한 배열 자체
- thisArg(선택사항): 콜백 함수 내에서 this의 값으로 사용할 객체
// 배열의 모든 요소가 양수인지 확인
const numbers = [1, 3, 5, 2, 7, 9, 11];
const allPositive = numbers.every(function(element) {
return element > 0;
});
console.log(allPositive); // true
// 배열의 모든 문자열이 특정 길이보다 작은지 확인
const words = ["apple", "banana", "cherry", "date", "fig"];
const allShortWords = words.every(function(word) {
return word.length < 7;
});
console.log(allShortWords); // true
// 배열의 모든 요소가 특정 값과 일치하는지 확인
const numbers = [2, 2, 2, 2, 2];
const allTwos = numbers.every(function(element) {
return element === 2;
});
console.log(allTwos); // true
// 화살표 함수와 함께 사용
const numbers = [1, 3, 5, 2, 7, 9, 11];
const allPositive = numbers.every(element => element > 0);
console.log(allPositive); // true
// thisArg를 사용하여 this 값을 지정
const person = {
minAge: 18,
isAdult: function(element) {
return element >= this.minAge;
}
};
const ages = [18, 20, 30, 15, 28];
const allAdults = ages.every(person.isAdult, person);
console.log(allAdults); // false
array.sort([compareFunction])
배열의 요소를 알파벳순 또는 숫자순으로 정렬
배열을 유니코드 코드 포인트 순서로 정렬
- array: 정렬할 배열
- compareFunction(선택사항): 정렬 기준을 지정하는 함수로 두 개의 인자를 받음
compareFunction이 제공되지 않으면 요소가 문자열로 변환된 후 유니코드 코드 포인트 순서로 정렬
compareFunction(a, b)이 0보다 작으면 a를 b 앞에 둠
compareFunction(a, b)이 0보다 크면 b를 a 앞에 둠
compareFunction(a, b)이 0이면 a와 b의 순서를 변경하지 않음
// 배열을 알파벳순으로 정렬
const fruits = ["banana", "apple", "cherry", "date", "fig"];
fruits.sort();
console.log(fruits); // ["apple", "banana", "cherry", "date", "fig"]
// 숫자 배열을 오름차순으로 정렬
const numbers = [3, 1, 5, 2, 4];
numbers.sort(function(a, b) {
return a - b;
});
console.log(numbers); // [1, 2, 3, 4, 5]
// 숫자 배열을 내림차순으로 정렬
const numbers = [3, 1, 5, 2, 4];
numbers.sort(function(a, b) {
return b - a;
});
console.log(numbers); // [5, 4, 3, 2, 1]
// 객체 배열을 특정 속성을 기준으로 정렬
const persons = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 32 },
{ name: "Charlie", age: 28 }
];
persons.sort(function(a, b) {
return a.age - b.age;
});
console.log(persons);
// [{ name: "Alice", age: 25 }, { name: "Charlie", age: 28 }, { name: "Bob", age: 32 }]
// 문자열의 길이에 따라 정렬
const words = ["apple", "banana", "cherry", "date", "fig"];
words.sort(function(a, b) {
return a.length - b.length;
});
console.log(words); // ["fig", "date", "apple", "cherry", "banana"]
// 대소문자를 무시하여 알파벳순으로 정렬
const words = ["Apple", "banana", "Cherry", "date", "fig"];
words.sort(function(a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
});
console.log(words); // ["Apple", "banana", "Cherry", "date", "fig"]
string.localeCompare(compareString [, locales [, options]])
문자열을 유니코드 기반으로 비교하며, 두 문자열 간의 상대적인 정렬 순서를 결정하는 데 사용
지역화된 문자열 비교에 유용하며, 문자열이 어떤 언어 또는 지역 설정에서 올바르게 정렬되는지 확인할 때 사용
- string: 비교 대상이 되는 문자열
- compareString: string와 비교할 다른 문자열
- locales(선택사항): 비교에 사용할 로케일(언어 및 지역 설정)을 나타내는 문자열 또는 문자열 배열
언어 및 지역별 차이를 고려한 정렬 가능
- options(선택사항): 비교에 대한 옵션을 나타내는 객체
compareString을 기준으로 string와 비교하고 결과로 다음과 같은 값을 반환
- 0: 두 문자열이 동일한 순서에 있음
- 양수 값: string이 compareString 보다 정렬 상 뒤에 있음
- 음수 값: string이 compareString 보다 정렬 상 앞에 있음
// 기본 사용 const string1 = "apple"; const string2 = "banana"; const result = string1.localeCompare(string2); if (result < 0) { console.log(`${string1} comes before ${string2} in the sorting order.`); } else if (result > 0) { console.log(`${string2} comes before ${string1} in the sorting order.`); } else { console.log(`${string1} and ${string2} are in the same sorting position.`); } // 다국어 로케일 설정 const string1 = "café"; const string2 = "cafe"; // 프랑스어 로케일(프랑스어에서 é와 e는 다른 문자로 취급) const frenchLocale = "fr"; const result = string1.localeCompare(string2, frenchLocale); if (result < 0) { console.log(`${string1} comes before ${string2} in the sorting order.`); } else if (result > 0) { console.log(`${string2} comes before ${string1} in the sorting order.`); } else { console.log(`${string1} and ${string2} are in the same sorting position.`); } // 옵션 설정 const string1 = "apple"; const string2 = "Banana"; // 대소문자 구분 없음으로 설정 const options = { sensitivity: "base" }; const result = string1.localeCompare(string2, undefined, options); if (result < 0) { console.log(`${string1} comes before ${string2} in the sorting order.`); } else if (result > 0) { console.log(`${string2} comes before ${string1} in the sorting order.`); } else { console.log(`${string1} and ${string2} are in the same sorting position.`); } // 다중 로케일 비교 const string1 = "color"; const string2 = "farbe"; // 영어와 독일어 로케일 비교 const locales = ["en", "de"]; for (const locale of locales) { const result = string1.localeCompare(string2, locale); console.log(`In ${locale}, ${string1} vs. ${string2}: ${result}`); }
array.reverse()
배열의 요소를 역순으로 배치하여 원본 배열을 뒤집어줌
원본 배열을 직접 수정하므로 원본 배열을 변경하지 않고 역순으로 된 배열을 얻고 싶다면
해당 메서드를 호출하기 전에 배열을 복제해야 됨
const numbers = [1, 2, 3, 4, 5];
numbers.reverse();
console.log(numbers); // [5, 4, 3, 2, 1]'backend > JavaScript' 카테고리의 다른 글
| 자바스크립트 일급객체 (0) | 2023.10.17 |
|---|---|
| 자바스크립트 ES6 (1) | 2023.10.17 |
| 자바스크립트 반복문 (0) | 2023.10.13 |
| 자바스크립트 조건문 (0) | 2023.10.13 |
| 자바스크립트 함수 (0) | 2023.10.13 |
