문자열에서 특정 문자 조합을 찾기 위한 패턴
JS에서는 이 정규표현식도 객체로서 exec(), test() 메서드 등이 사용 가능
const re = /ab+c/;
const re = new RegExp("ab+c");
// 회원가입 할때 휴대폰번호 양식 검사
// 예를 들어 010-1111-2222 라는 전호번호는
// "숫자3개", "-", "숫자4개", "-", "숫자4개" 로 이루어져 있는데,
const regex = /\d{3}-\d{4}-\d{4}/;
// (\d는 숫자를 의미하고, {} 안의 숫자는 갯수를 의미한다.)
regex.test('010-1111-2222') // true;
regex.test('01-11-22') // false;
const regEmail = /^[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*\.[a-zA-Z]{2,3}$/i
match
문자열에서 정규 표현식에 매칭되는 항목들을 배열로 리턴
replace
정규 표현식에 매칭되는 항목들을 대체 문자열로 반환
split
문자열을 정규표현식에 매칭되는 항목으로 쪼개서 배열로 반환
test
정규표현식과 매칭이 되면 true, 아니면 false
exec
match메서드와 유사(단 첫번째 매칭 결과만)
// 정규표현식을 담은 변수
const regex = /apple/; // apple 이라는 단어가 있는지 필터링
// "문자열"이 "정규표현식"과 매칭되면 true, 아니면 false반환
regex.test("Hello banana and apple hahahaha"); // true
// "문자열"에서 "정규표현식"에 매칭되는 항목들을 배열로 반환
const txt = "Hello banana and apple hahahaha";
txt.match(regex); // ['apple']
// "정규표현식"에 매칭되는 항목을 "대체문자열"로 변환
txt.replace(regex, "watermelon"); // 'Hello banana and watermelon hahahaha'
// flags 에 플래그 문자열이 들어간다.
cosnt flags = 'i';
const regex = new RegExp('abapplec', flags);
// 리터럴로 슬래쉬 문자뒤에 바로 표현이 가능
const regex1 = /apple/i; // 대소문자 구분없이 APPLE, apple 찾기
const regex2 = /apple/gm; // 문자 내 행이 바뀌어도 되고, 모든 apple 찾기
JS, 명시적인 배열 데이터 형식을 갖고 있지 않음.
단, 미리 정의된 Array 객체를 사용시 합치기, 뒤집기, 정렬 등 다양한 방법이 가능
생성자, 리터럴([]) 등으로 생성 가능
const arr1 = new Array(element0, element1, /* … ,*/ elementN);
const arr2 = Array(element0, element1, /* … ,*/ elementN);
const arr3 = [element0, element1, /* … ,*/ elementN];
const cats = [];
cats[30] = ["Dusty"];
console.log(cats.length); // 31
const colors = ["red", "green", "blue"];
colors.forEach((color) => console.log(color));
// red
// green
// blue
단, forEach 반복문으로 순회시 생략된 요소는 나타나지 않는다.
// 2번 Idx의 요소 생략
const sparseArray = ["first", "second", , "fourth"];
sparseArray.forEach((element) => {
console.log(element);
});
// Logs:
// first
// second
// fourth
if (sparseArray[2] === undefined) {
console.log("sparseArray[2] is undefined"); // true
}
const nonsparseArray = ["first", "second", undefined, "fourth"];
nonsparseArray.forEach((element) => {
console.log(element);
});
// Logs:
// first
// second
// undefined
// fourth
const a1 = ["a", "b", "c"];
const a2 = a1.map((item) => item.toUpperCase());
console.log(a2); // ['A', 'B', 'C']
let myArray = ["1", "2", "3"];
myArray = myArray.concat("a", "b", "c");
// myArray is now ["1", "2", "3", "a", "b", "c"]
const myArray = ["Wind", "Rain", "Fire"];
const list = myArray.join(" - "); // list is "Wind - Rain - Fire"
const myArray = ["1", "2"];
myArray.push("3"); // myArray is now ["1", "2", "3"]
const myArray = ["1", "2", "3"];
const last = myArray.pop();
// myArray is now ["1", "2"], last = "3"
const myArray = ["1", "2", "3"];
const first = myArray.shift();
// myArray is now ["2", "3"], first is "1"
let myArray = ["a", "b", "c", "d", "e"];
myArray = myArray.slice(1, 4); // [ "b", "c", "d"]
// 인덱스 1에서 시작하여 인덱스 3까지의 모든 요소
const myArray = ["1", "2", "3", "4", "5"];
myArray.splice(1, 3, "a", "b", "c", "d");
// myArray 는 이제 ["1", "a", "b", "c", "d", "5"] 가 됩니다.
// 이 코드는 첫 번째 인덱스("2"값이 있는 곳)에서 시작하여
// 3개의 요소를 삭제한 후 그 자리에 연속된 모든 요소를 모두 삽입합니다.
let myArray = [1, 2, [3, 4]];
myArray = myArray.flat();
// myArray is now [1, 2, 3, 4], since the [3, 4] subarray is flattened
arr.sort()
arr.sort((a, b) => a - b)
const a = [10, 20, 30];
const total = a.reduce(
(accumulator, currentValue) => accumulator + currentValue,
0,
);
console.log(total); // 60
배열처럼 보이지만 실제 배열은 아닌 객체
{0: "a", 1: "b", 2: "c", length: 3}
Array.isArray(obj) → false
obj instanceof Array → false
function test(a, b, c) {
console.log(arguments); // {0: a, 1: b, 2: c, length: 3}
}
const divs = document.querySelectorAll("div"); // NodeList
console.log(divs.length); // 가능
console.log(divs.map); // undefined (배열 메서드 없음)
const arrLike = {0: "a", 1: "b", 2: "c", length: 3};
Array.from(arrLike); // ["a", "b", "c"]
[...arrLike]; // 전개 연산자도 가능 (단, iterable 일 때만)