🟨 JavaScript/개념

[mdn, 드림코딩 외] 배열(array) : 배열에의 접근과 looping

Zoeeey 2022. 5. 31. 14:22

object와 자료구조의 차이

  • object서로 연관된 특징을 묶어놓는다.
  • 자료구조비슷한 타입의 object들을 묶어놓는다.

배열(array)

배열은 0부터 시작하는 칸칸으로 짜여진 index를 가진 자료구조를 말한다.


배열의 선언

const coder1 = new Array();
const coder2 = [1,2];

index position (index에 접근하기)

배열을 만들었다.

const goodcoders = ['noran', 'paran'];

이 배열의 정보

console.log(goodcoders);
// 2) ['noran', 'paran']

//펼치면 아래 정보가 나온다.
//0: "noran"
//1: "paran"
//length: 2
//[[Prototype]]: Array(0)

이 배열의 index length각 순서의 값에 접근할 수 있다.

console.log(goodcoders.length);
//2

console.log(goodcoders[0]);
//'noran'
console.log(goodcoders[1]);
//'paran'
console.log(goodcoders[2]);
//undefined

length - 1을 하면 배열의 마지막 데이터에 접근할 수 있다. (index가 0부터 시작하기 때문에)

console.log(goodcoders[goodcoders.length - 1]);
// 'paran'

looping

배열의 모든 데이터를 print해보자. 아래로 갈수록 간단해진다.

for

for (let i = 0; i < goodcoders.length; i++) {
  console.log(goodcoders[i]);
}

//'noran'
//'paran'

for of

for (let coder of goodcoders) {
  console.log(coder);
}

//'noran'
//'paran'

 

forEach (콜백함수)

goodcoders.forEach((coder) => console.log(coder));

//'noran'
//'paran'

https://sunshineyellow.tistory.com/26 : 콜백함수

(위 화살표함수를 풀어쓰면 아래와 같다.)

goodcoders.forEach(function (coder) {
  console.log(coder);
});

//'noran'
//'paran'

출처 : 드림코딩 https://www.youtube.com/@dream-coding / MDN https://developer.mozilla.org/ko