Week 2 - JavaScript 05. λ°°μ—΄

κΉ€λ―Όμž¬Β·2021λ…„ 8μ›” 2일
0

TIL, WeCode, CourseΒ 

λͺ©λ‘ 보기
5/48
post-thumbnail
post-custom-banner

*πŸ”Study Keyword :

πŸ”‘ 배열이 ν•„μš”ν•œ 이유λ₯Ό μ„€λͺ…ν•΄λ³΄μž

- 05. λ°°μ—΄


-WHAT IS❓

  • λ°°μ—΄? νŠΉμ •ν•œ μ§‘ν•œλ“€μ„ 일렬둜 λͺ¨μ•„놓은 데이터듀 즉 μš”μ†Œλ“€μ„ λͺ¨μ•„놓은 μ§‘ν•©μ„μ˜λ―Έν•œλ‹€. 말 κ·ΈλŒ€λ‘œ 데이터듀이 배열을 μ΄λ£¨μ–΄μ„œ λ‚˜μ—΄μ΄ λ˜μ–΄μžˆλŠ” μƒνƒœμ΄λ‹€.

πŸ”…μš”μ†Œ VS 인덱슀?πŸ”…)

  • μš”μ†Œλž€ 배열에 λ“€μ–΄μžˆλŠ” 데이터 ν•˜λ‚˜ν•˜λ‚˜λ₯Ό μš”μ†Œ(elment)λΌκ³ ν•œλ‹€.
  • μΈλ±μŠ€λž€ 배열이 가진 μˆœμ„œ(index) 이며 0λΆ€ν„° μ‹œμž‘ν•œλ‹€.

-HOW TO USE❕❓

  • 배열에 μš”μ†Œμ— μ ‘κ·Όν•  λ•Œ? ν•΄λ‹Ή λ°°μ—΄ λͺ…κ³Ό λŒ€κ΄„ν˜Έ ,[]μ•ˆμ— μ ‘κ·Όν•˜κ³ μž ν•˜λŠ” μš”μ†Œμ˜ 인덱슀 번호λ₯Ό λ„£μ–΄μ€€λ‹€.
  • μ ‘κ·Όν•œ μš”μ†Œλ₯Ό μƒˆλ‘œμš΄ λ³€μˆ˜μ— ν• λ‹Ήν•  μˆ˜λ„ μžˆλ‹€.
<script>
let myArray = [26, 'jamie', false];
console.log(myArray) // [26, "jamie", false]
console.log(myArray[0]) // 26
let first = myArray[0] // λ°°μ—΄ 인덱슀λ₯Ό μ΄μš©ν•΄μ„œ μš”μ†Œμ— μ ‘κ·Ό ν•œ λ’€ μƒˆλ‘œμš΄ λ³€μˆ˜μ— ν• λ‹Ή
console.log(first) // 26
</script>
  • 배열에 μš”μ†Œμ— 값을 λ³€κ²½ν•  땐? λ°°μ—΄ λͺ…[], λŒ€κ΄„μ•ˆ μ•ˆμ— λ³€κ²½ν•˜κ³ μž ν•˜λŠ” μš”μ†Œμ˜ 인덱슀 번호λ₯Ό 넣은 λ’€ ν• λ‹Ήμ—°μ‚°μž, ('=')λ₯Ό μ΄μš©ν•΄ λ³€κ²½ν•˜κ³ μžν•˜λŠ” 값을 ν• λ‹Ήν•œλ‹€.
<script>
let myArray = [26, 'jamie', false];
myArray[0] = 27; // λ°°μ—΄μ˜ 0번째 μš”μ†Œμ˜ 값을 27둜 λ³€κ²½
console.log(myArray) // [27, "jamie", false]
</script>
  • 배열에 길이λ₯Ό μ–»μ–΄λ‚Ό 땐? ν•΄λ‹Ή 배열에 length ν”„λ‘œνΌν‹°λ₯Ό μ΄μš©ν•˜λ‹€.
  • λ°°μ—΄μ˜ λ§ˆμ§€λ§‰ μš”μ†Œμ˜ 인덱슀 번호? arr[arr.length-1](length - 1 = λ°°μ—΄μ˜ λ§ˆμ§€λ§‰ μš”μ†Œμ˜ 인덱슀 번호)λ₯Ό ν™œμš©ν•˜μ—¬ λ§ˆμ§€λ§‰ μš”μ†Œμ— μ ‘κ·Όν•  μˆ˜κ°€ μžˆλ‹€.
<script>
let myArray = [26, 'jamie', false];
console.log(myArray.length) // 3, λ°°μ—΄μ˜ 길이
//λ°°μ—΄μ˜ 길이와 인덱슀λ₯Ό μ΄μš©ν•΄μ„œ λ§ˆμ§€λ§‰ μš”μ†Œμ— μ ‘κ·Όν•˜κΈ°
console.log(myArray[myArray.length-1]) // false
//λ°°μ—΄μ˜ λ§ˆμ§€λ§‰ μš”μ†Œμ˜ 인덱슀 번호 
console.log(myArray[2]) // arr.length - 1와 같은 κ°’
</script>
  • λ°°μ—΄μ˜ λ§ˆμ§€λ§‰ μΈλ±μŠ€μ— μš”μ†Œλ₯Ό μΆ”κ°€ν•˜κ³ μž ν•  땐?
    push λ©”μ†Œλ“œμ— μΆ”κ°€ν•˜κ³ μž ν•˜λŠ” 데이터 νƒ€μž…μ„ λ„£μ–΄μ€€λ‹€.
  • λ°°μ—΄μ˜ λ§ˆμ§€λ§‰ μΈλ±μŠ€μ— μš”μ†Œλ₯Ό μ‚­μ œν•˜κ³ μž ν•  땐?
    pop λ©”μ†Œλ“œλ₯Ό μ‚¬μš©ν•˜λ©΄ λ§ˆμ§€λ§‰ μš”μ†Œκ°€ μ‚­μ œλœλ‹€.
  • λ°°μ—΄μ˜ 첫 번째 인덱 μŠ€μ— μžˆλŠ” μš”μ†Œλ₯Ό μ‚­μ œν•˜κ³ μž ν•  땐?
    shift λ©”μ†Œλ“œλ₯Ό μ‚¬μš©ν•˜λ©΄ 첫번 μ§Έ μš”μ†Œκ°€ μ‚­μ œλœλ‹€.
<script>
//push λ©”μ†Œλ“œ, λ°°μ—΄μ˜ λ§ˆμ§€λ§‰ μš”μ†Œμ— κ°’ μΆ”κ°€
let myArray = [26, 'jamie', false];
myArray.push("banana")
console.log(myArray) // [27, "jamie", false, "banana"]
//pop λ©”μ†Œλ“œ, λ°°μ—΄μ˜ λ§ˆμ§€λ§‰ μš”μ†Œμ— κ°’ μ‚­μ œ
myArray.pop()
console.log(myArray) // [27, "jamie", false]
//shift λ©”μ†Œλ“œ, λ°°μ—΄μ˜ 첫번 μ§Έ μš”μ†Œμ— κ°’ μ‚­μ œ
myArray.shift()
console.log(myArray) // ["jamie", false]
</script>

*πŸ’‘conclusion

λ°°μ—΄ μ΅μˆ™ν•΄μ§€μžμ•„

#πŸ“‘Study Source

  1. weekcode κ°•μ˜ 쀑 λ‚΄μš©
profile
자기 μ‹ λ’°μ˜ νž˜μ„ λ―Ώκ³  μ‹€μ²œν•˜λŠ” κ°œλ°œμžκ°€ λ˜κ³ μžν•©λ‹ˆλ‹€.
post-custom-banner

0개의 λŒ“κΈ€