[DAY26]_개발일지: 자바스크립트_배열과 for문

hanseungjune·2022년 6월 9일
0

DaeguFE

목록 보기
31/48

✅ 배열(Array)

☑️ 개념

말그대로 여러 자료를 나열한 것이라고 보면 됨. 배열은 요소(Element)로 구성되어 있음.
인덱스는 0부터 시작 인덱스로 연산도 가능

☑️ 구조

const array1 = [273, "문자열", true, [27, 35], {}, "fun"]
  • 배열 안에 배열이나 딕셔너리(객체) 형태로도 들어갈 수 있다. ex) JSON 파일
  • 구분은 ,
const str = "안녕하세요"
console.log(str.length) 		//5 
  • 문자열도 배열임 인덱스의 시작은 항상 0
  • length는 길이를 말한다.
<script>
        const array1 = [273, 56, 25, 278, 365]
        console.log(array1[1])		//56
</script>

✅ for문 (반복문 - 3가지)

☑️ 단순 for문

  • for문 기본구조
for(초기값; 조건식; 증감식){
		실행문
}
  • 예제1
for (let i=0; i < 100; i++){
       console.log(i);		// 0 ~ 99 까지 출력
}

💯 배열을 쓸 경우에만 let 말고 const도 사용가능하다. (예외)

  • 예제2
<script>
    const fsk = ['사과', '딸기', '수박', '참외']

    for (let i = 0; i < fsk.length; i++) {
      console.log(`${i + 1}번째 과일은 ${fsk[i]}`);		//1번째 과일은 사과 ~ 4번째 과일은 참외 순으로 출력됨
    }
</script>

☑️ for_in 문 (index 찾기)

  • for_in문 기본구조
for(const i in fask(배열객체) ){
    	실행문
}
  • 예제
<script>
        const fruits =["사과","딸기","수박","참외"]
        for(const i in fruits){
            console.log(`${i}번째 인덱스의 과일은 ${fruits[i]}`)
        }
        // 마지막에 배열로 작성하였다.
        // for_in은 index(0,1,2)를 가져온다.
</script>

☑️ for_of 문 (변수에 배열 하나씩 넣기)

  • for_of문 기본구조
for(const abc of fask(배열객체)) {
		실행문(배열 하나씩)
}  
  • 예제
const fruits =["사과","딸기","수박","참외"]
let a = 0
for(const frk of fruits){
	console.log(`${a}번째 인덱스의 과일은 ${frk}`)
	a++;
}

✅ 추가자료

☑️ unshift()

배열의 앞부분에 자료를 추가하는 메서드

	const arr = ['나','다','라','마']
    arr.unshift('가');	//['가', '나', '다', '라', '마']

☑️ shift()

배열의 앞부분에 자료를 삭제하는 메서드

	const arr = ['나','다','라','마']
    arr.shift('가');		// 	['다', '라', '마']

☑️ push()

배열의 뒷부분에 자료를 추가하는 메서드

	const arr = ['나','다','라','마']
    arr.push('바');		//	['나', '다', '라', '마', '바']

☑️ pop()

배열의 뒷부분에 자료를 추가하는 메서드

	const arr = ['나','다','라','마']
    arr.pop();			// ['나', '다', '라']

☑️ splice()

배열의 요소를 빼거나, 빼지 않더라도 또 다른 요소를 지정한 인덱스 앞에 추가할 수 있는 메서드

const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');			//["Jan", "Feb", "March", "April", "June"]
months.splice(4, 1, 'May');			//["Jan", "Feb", "March", "April", "May"]

☑️ slice()

배열의 요소 특정 부분을 빼내서 복사본을 출력할 때, 사용하는 메서드

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

console.log(animals.slice());
// expected output: Array ["ant", "bison", "camel", "duck", "elephant"]

☑️ indexof()

배열의 해당 요소가 몇번째 인덱스에 있는지 확인하기 위한 메서드 ( 없으면 -1 출력 )

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// expected output: 1

// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4 (2번째 인덱스 부터 'bison' 요소의 인덱스를 구함

console.log(beasts.indexOf('giraffe'));
// expected output: -1
profile
필요하다면 공부하는 개발자, 한승준

0개의 댓글