📝 정규표현식&유효성검사 사용해서 회원가입 만들기
📝 형변환,연산자 / 배열
#230227
변수를 묶음으로 다루는 것 (변수가 연속적으로 나열됨)
값이 저장되기 전까지 자료형이 지정되지 않음
→
Java의 Collection 중 List와 비슷함.
// 0칸짜리 배열 생성
// 3칸짜리 배열 생성
// 0칸짜리 배열 생성
// 3칸짜리 초기화된 배열 생성
<button id="btn1"> 배열 확인</button>
---------------------------------------------------------------------
document.getElementById("btn1").addEventListener("click", function() {
const arr1 = new Array();
const arr2 = new Array(3);
const arr3 = [];
const arr4 = ['사과','딸기','바나나'];
console.log(arr1) // 결과값 : []
console.log(arr2) // 결과값 : (3)
console.log(arr3) // 결과값 : []
console.log(arr4) // 결과값 : ['사과', '딸기', '바나나']
// 배열에 존재하지 않는 인덱스에 값 대입
// -> 자동으로 추가되면서 길이가 증가함
arr1[0] = "김밥";
arr1[1] = 5000;
arr1[2] = true;
// 중간 인덱스 건너뛰면, 건너 뛴 부분은 empty로 남음
arr1[5] = 111; // 추가가능ㅇ
console.log(arr1)
<button id="btn1"> for문 확인 </button>
<ul id="test">
<li>10</li>
<li>20</li>
<li>30</li>
<li>40</li>
<li>50</li>
</ul>
-----------------------------------------------
for(let i = 0; i < arr4.length; i++) {
console.log(arr4[i]);
}
2. 배열.forEach(function(item,index) {반복수행 코드} ) - 배열
배열일 때 만 사용 가능
item: 현재 접근중인 요소
index : 현재 인덱스
여러 요소를 얻어온 경우(HTMLCollection, NodeList)는
배열이 아니므로 forEach()문을 쓸 수 없다.
arr4.forEach(function (a, i) {
console.log( i + " : " + a)
})
3. for(item of 배열(또는 컬렉션 )) { } - 배열, 컬렉션
Symbol.iterator가 존재하는 객체에 사용가능함
Java 향상된 for문과 비슷하게 생김
for(let item of arr4) {
console.log(item)
}
li태그에 작성된 값 얻어와서 합 구하기
const list1 = document.getElementsByTagName("li"); // HTMLCollection
const list2 = document.querySelectorAll("#test > li"); // NodeList
//console.log(list1)
//console.log(list2)
let sum = 0;
for(let item of list2) {
sum += Number(item.innerText)
}
console.log("sum : " +sum) // 결과값 150
})
4. for (let key in 객체) - JS객체용 for문
//지금은 예시가 없어서 패스
// 다음에 쓸 때 다시 한번 설명해줄 예정
(Stack 구조 관련 함수 / 스택은 쌓이는 것!)
배열 마지막 요소로 추가
배열 마지막 요소를 꺼내옴
일치하는 값을 가진 요소의 index 반환
없으면 -1 반환
배열 내 요소를 오름차순 정렬(문자열)
단, [정렬 기준 함수]가 작성되면 정렬 결과가 달라짐
[]은 옵션임. 필수 아님
배열 요소를 하나의 문자열로 출력
요소 사이에 "," 추가
배열 요소를 하나의 문자열로 출력
요소 사이에 "구분자" 추가
<button id="btn2">배열 관련 함수 확인</button>
-------------------------------------------------
// 배열 관련 함수 확인.
document.getElementById("btn2").addEventListener("click", function() {
// 비어있는 배열 생성
const arr = [];
arr.push("조");
arr.push("미");
arr.push("현");
arr.push("천");
arr.push("재");
console.log(arr) // ['조', '미', '현', '천', '재']
console.log(arr.toString()); // 조,미,현,천,재
arr.pop(); // 마지막 요소인 '재' 빼옴
console.log(arr); // ['조', '미', '현', '천']
const temp = arr.pop(); // 마지막 요소인 '천' 빼옴
console.log(temp); // temp값 == 천
console.log(arr.indexOf('현')); // 2 (있으면 있는곳 index자리)
console.log(arr.indexOf('재')); // -1 (없으면 -1 출력)
console.log(arr.sort()) // 배열내요소 오름차순 ['미', '조', '현']
const numArr = [5,3,2,10,1];
console.log(numArr.sort(function(a,b) { return a - b; } ))
// [1, 2, 3, 5, 10]
console.log(numArr.sort(function(a,b) { return b - a; } ))
// [10, 5, 3, 2, 1]
// * sort() 함수는 원본 배열의 순서를 정렬함
// -> 원본 훼손 발생 ( 깊은 복사를 이용해 해결함 )
console.log(numArr)
})