객체 배열 자료구조 JavaScript Array of Objects
- 객체가 들어있는 배열
과일의 이름(name)과 개수(num) 속성을 가진 객체를 저장하는 fruitarray 배열을 생성한다.
let fruitarray = [
{
name: "apple",
num: 3,
},
{
name: "banana",
num: 0,
},
{
name: "grape",
num: 1,
},
];
Methods - 인스턴스 메서드
- Array.prototype.unshift()
배열의 앞쪽에 추가하기
Adds one or more elements to the front of an array, and returns the new length of the array.
let fruit = { name: "mango" };
fruitarray.unshift(fruit);
num 값은 넣지 않은 채로 fruitarray 맨 앞에 추가
console.log(fruitarray) 한 결과
- Array.prototype.push()
배열의 뒤쪽에 추가하기
Adds one or more elements to the end of an array, and returns the new length of the array
- Array.prototype.splice()
배열의 중간에 추가하기
기존 요소를 삭제하려 할 때도 이 메서드를 사용 가능
Adds and/or removes elements from an array.
필요한 매개변수
(배열의 변경을 시작할 인덱스, 배열에서 제거할 요소의 수, 배열에 추가할 요소)
let fruit1 = { name: "lemon", num: 10 };
fruitarray.splice(1, 1, fruit1);
console.log(fruitarray);
index [1]에서 이름 "banana" 객체는 제거되고 fruit1이 추가된 걸 확인 가능하다.
배열에서 제거할 요소의 수를 1이 아닌 0으로 두면 index [1] 자리에 lemon 객체가 추가된다.
정규 표현식과 match, parseInt
RegExp (Regular Expression)
정규표현식(Regular Expression)은 문자열에서 특정 내용을 찾거나 대체 또는 발췌하는데 사용한다.
정규표현식은 리터럴 표기법으로 생성 가능하고 시작, 종료기호 / 패턴 / 플래그로 구성되어 있다.
/regexr/i
- 시작과 종료 기호 '/'
- 플래그
i : Ignore case, 대소문자를 구별하지 않고 검색
g : Global , 문자열 내의 모든 패턴을 검색
m : Multi Line, 문자열의 행이 바뀌더라도 검색 계속
- 패턴
const re = /^[0-9]+$/;
[] 바깥의 ^은 문자열의 처음을 의미하고, $은 문자열의 끝을 의미한다.
const re = /^[\s]+/;
\s은 여러 가지 공백 문자를 의미하는데 [\t \r \n \v \f]등이 있다.
const regex = /@(\w+\.\w+)/g;
\w은 단어 문자를 매칭한다.
+은 하나 이상을 의미한다.
\.은 문자 그대로 .(점)을 의미한다. 정규 표현식에서 마침표는 특수문자로 아무 문자 하나를 의미하므로 백슬래시를 추가하여 문자 그대로 점을 매칭한다.
const regex = /(\d{4})-\d{2}-\d{2}/g;
()은 캡처 그룹을 정의한다.
\d{4}는 정확히 4개의 숫자를 매칭한다.
-은 문자 그대로 "-"를 매칭한다.
RegExp 객체
자바스크립트에서 지원하는 RegExp 객체
다음 두 줄은 동일한 정규 표현식 생성
const re = /\w+/;
const re = new RegExp("\\w+");
RegExp와 문자열 간의 일치 결과는 일치에 대한 정보를 제공하는 속성과 요소를 포함하는 JavaScript 배열을 생성할 수 있다. 이러한 배열은 아래 메서드에서 반환된다.
- RegExp.prototype.exec()
인자로 문자열을 받고, 일치하는 문자열을 배열형태로 반환한다. result array 혹은 없다면 null
정규식과 일치하는 첫 번째 부분을 찾고, 일치하는 부분과 캡처 그룹의 값을 배열로 반환한다.
배열의 첫 번째 요소는 전체 매칭된 문자열, 이후는 () 캡처 그룹에 해당하는 값
- String.prototype.match()
match() 함수는 주어진 정규 표현식 패턴을 사용하여 문자열 내에서 매치(match, 일치)되는 첫 번째 부분을 찾아내는 함수
문자열에서 정규식과 일치하는 모든 부분을 배열로 반환한다. 만약 정규식에 g 플래그가 없으면, match는 첫 번째 일치하는 부분만 반환한다. match 메서드는 일치하는 전체 문자열만을 반환하며, 캡처 그룹에 해당하는 값은 반환하지 않는다.
const dates = '2024-07-15 2023-12-31 2022-01-01';
const regex = /(\d{4})-\d{2}-\d{2}/g;
const matches = dates.match(regex);
console.log(matches); // ["2024-07-15", "2023-12-31", "2022-01-01"]
let match;
while ((match = regex.exec(dates)) !== null) {
console.log(match);
// ["2024-07-15", "2024"]
// ["2023-12-31", "2023"]
// ["2022-01-01", "2022"]
}
parseInt() parseFloat()
parseInt() 함수는 문자열 인자를 파싱하여 특정 진수(수의 진법 체계에서 기준이 되는 값)의 정수를 반환한다.
parseInt(string);
parseInt(string, radix);
radix는 string의 진수를 나타내는 2부터 36까지의 정수. Number 자료형이 아닌 경우 Number로 자동 변환해준다.
이외에 radix 값이 [2, 36]의 범위를 벗어나는 경우 parseInt가 NaN을 반환한다. parseInt의 결과가 NaN인지 확인하려면 isNaN을 사용하면 된다.
let lotte = "34";
let num = "10";
console.log(typeof num); //string
console.log(typeof parseInt(lotte, num)); //number
parseFloat() 함수는 주어진 값을 필요한 경우 문자열로 변환한 후 부동소수점 실수로 파싱해 반환한다.
parseFloat(string);
문자열 포맷팅 with String Interpolation in JavaScript
Template Literals (ES6)
They use backticks (“ ` “) and ${} syntax to embed expressions.
const name = "Alice";
const greeting = `Hello, ${name}!`;
console.log(greeting);
String Concatenation (Before ES6)
Before ES6, string interpolation was achieved using the + operator to concatenate strings and variables.
const name = "Alice";
const greeting = "Hello, " + name + "!";
console.log(greeting);
String.concat() Method
String.prototype.concat() 메서드는 매개변수로 전달된 모든 문자열을 호출 문자열에 붙인 새로운 문자열을 반환한다.
str.concat(string2, string3[, ..., stringN])
//string2...stringN은 합칠 문자열.
const name = "Alice";
const greeting = "Hello, ".concat(name, "!");
console.log(greeting);
Array Join Method
Array.prototype.join() 메서드는 배열의 모든 요소를 쉼표나 지정된 구분 문자열로 구분하여 연결된 새 문자열을 만들어 반환한다. seperator가 생략되면 배열 요소는 쉼표(",")로 구분된다.
배열의 모든 요소들을 연결한 하나의 문자열을 반환합니다. 만약 arr.length 가 0이라면, 빈 문자열을 반환한다.
요소가 undefined, null인 경우, "null" 또는 "undefine" 문자열 대신 빈 문자열로 변환된다.
join()
join(separator)
const name = "Alice";
const greeting = ["Hello, ", name, "!"].join("");
console.log(greeting);
+ 함수 분리 기준
- 단일 책임 원칙 (Single Responsibility Principle): 함수가 하나의 작업만 수행하도록 분리.
- 재사용성 (Reusability): 각 함수가 재사용 가능하도록 설계.
- 가독성 (Readability): 코드의 가독성을 높이기 위해 주요 로직을 함수로 분리.
reference
Array of Object
.https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array
https://www.freecodecamp.org/korean/news/javascript-array-of-objects-tutorial/
RegExp.prototype.Exec,string.prototype.match
정규표현식
https://poiemaweb.com/js-regexp
parseInt, parseFloat
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/parseFloat
문자열 포맷팅
https://www.geeksforgeeks.org/string-interpolation-in-javascript/
'JS.TS' 카테고리의 다른 글
Worker threads 멀티쓰레드와 Javascript 비동기 처리 (0) | 2024.07.25 |
---|---|
javascript로 XML 태그, 속성 분석하기 (0) | 2024.07.17 |
JS 모듈 (CommonJS 모듈 / ES 모듈) (0) | 2024.06.26 |
자바스크립트 기본 문법 (자료형) (0) | 2024.06.25 |
자바스크립트 기본 문법 (입출력) (0) | 2024.06.23 |