티스토리 뷰

반응형

1. 배열(Array)

  • 키와 속성을 담고 있는 참조 타입의 객체
  • 순서를 보장한다

1. Declaration

  • []를 이용하여 생성할 수 있다. ⇒ python이랑 완전 똑같아!!
const arr1 = new Array();
const arr2 = [1,2];

2. Index position

  • 0 → 양의 정수로 인덱스 접근 가능 파이썬이랑 비슷!
const fruits = ['apple', 'banana']
console.log(fruits)
console.log(fruits.length) // 2
console.log(fruits[0]) // apple
console.log(fruits[3]) //undefined

3. append? push?

  • python 에서는 배열(list)에 새로운 값을 추가할 때 append라는 메서드를 사용한다.
  • js에서는 array에 새로운 값을 추가할 때 push라는 메서드를 사용한다.
  • 뒤에서 하나를 빼는 것은 pop 메서드를 사용 (python 이랑 비슷!)
# python

a = []
a.append('b')
print(a) #['b']
//JS

const a = [];
a.push('b')
console.log(a) //['b']

💡
그렇다면, 앞에서부터 넣는 메서드도 있을까?

⇒ YES!

4. shift & unshift

const fruits = ['apple', 'banana']
fruits.unshift('cherry') // unshift는 앞부터 추가!
console.log(fruits) // ["cherry", "apple", "banana"]

fruist.shift()
console.log(fruits) // ['apple', 'banana']
💡
shift, unshift는 pop, push보다 느리다~

⇒ why? 앞에서부터 하나 넣으려면 다~~ 당겨야 하니까

💡
그렇다면, 지정된 인덱스부터 삭제하는 메서드도 있을까?

⇒ YES!

5. splice

  • 배열에서 지우고 ⇒ 삭제된 값을 return 한다!
  • 배열의 특정한 부분만 리턴하고 싶다면 ⇒ .slice를 이용한다.
const fruits = ['apple', 'banana', 'cherry', 'melon']
fruits.splice(1); // ['apple']
// => 몇개나 지울 것인지 말하지 않으면 이후 데이터를 모두 지운다!

fruits.splice(1, 1); //['apple', 'cherry', 'melon']
fruits.splice(1, 1, 'orange') // ['apple', 'orange', 'cherry', 'melon']

6. Search!

  • Array 안에 있는지 검사 ⇒ includes
  • Array안의 index를 반환 ⇒ indexOf
    const fruits = ['apple', 'banana', 'cherry', 'melon']
    console.log(fruits.indexOf('banana')) // 1
    console.log(fruits.indexOf('coconut')) // -1
    
    console.log(fruits.includes('banana')) // true
    console.log(fruits.includes('coconut')) // false

7. Join

  • Python이랑 완전 비슷해~
  • 배열의 모든 요소를 연결하여 반환
  • 구분자는 지정할 수 있다. 생략 시 쉼표를 기본으로 사용
    const numbers = [1, 2, 3, 4, 5]
    let result
    
    result = numbers.join() // 1,2,3,4,5
    result = numbers.join('') //12345
    result = numbers.join(' ') //1 2 3 4 5
    result = numbers.join('-') //1-2-3-4-5

Uploaded by N2T

반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함