JavaScript 6. Array

khxxjxx·2021년 5월 3일
0

드림코딩 by 엘리

목록 보기
6/11

강좌 : 유튜브 드림코딩 by 엘리

6. Array

📄 Declaration

  • const arr1 = new Array();
  • const arr2 = [1, 2];
  • array의 index값은 0부터 시작

✍️Index position

// 예시
const fruits = ['🍎', '🍌'];

console.log(fruits.length);  // 2  // 배열의 크기
console.log(fruits[0]);  // 🍎
console.log(fruits[1]);  // 🍌
console.log(fruits[2]);  // undefined
console.log(fruits[fruits.length - 1]);  // 🍌  // 배열의 마지막 값

✍️Looping over an array

  • array안의 모든 value값 출력

for

// 예시
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

for of

// 예시
for (let fruit of fruits) {  // value of iterable
  console.log(fruit);
}

forEach

  • 배열에 있는 callback함수를 받아온다
  • 배열이름.forEach( callbackfn (value, index, array) : 배열크기만큼 value값과 index, array를 받아올 수 있다
// 예시
fruits.forEach(function (fluit) {
  consile.log(fluit);  // fruits의 배열크기만큼 value값을 반환
});

// Arrow를 사용해 간단히 표현
fruits.forEach((fruit) => console.log(fruit));

✍️Addtion, deletion, copy

  • shift와 unshift는 pop과 push보다 실행속도가 느리다 배열앞에 값이 추가되고 삭제되는 과정에서 전체 배열이 움직여야되기 때문

push

  • add an item to the end
  • 배열이름.push(추가할 값);

pop

  • remove an item from the end
  • 배열이름.pop(); : 삭제할 값이 두개면 두번 써준다

unshift

  • add an item to the benigging
  • 배열이름.unshift(추가할 값);

shift

  • remove an item from the benigging
  • 배열이름.shift(); : 삭제할 값이 두개면 두번 써준다

splice

  • remove an item by index position
  • 배열이름.splice(시작지점, 삭제개수)
  • 삭제개수를 지정하지 않으면 지정한 시작지점에서 모든 데이터를 지운다
// 예시
fruits.splice(1, 1);  //  1번째 index에 1개의 값 삭제
fruits.splice(1, 0, '🍏', '🍉');  // 삭제하고 그 위치에 추가도 가능하다

concat

  • combine two arrays
  • 배열이름.concat(배열이름)
// 예시
const array = [1, 2, 3];
const array2 = [4, 5];

const arr = array.concat(array2);
console.log(arr);[1, 2, 3, 4, 5]

✍️Searching

indexOf

  • 배열이름.indexOf('value'); : 찾는 value값의 첫번째 index위치를 알려준다 만약 값이 없을경우 -1를 반환

lastIndexOf

  • 배열이름.lastIndexOf('value'); : 찾는 value값의 마지막 index위치를 알려준다

includes

  • 배열이름.includes('value'); : 찾는 value값이 배열안에 있는지 없는지 true와 false로 알려준다
profile
코린이

0개의 댓글