[TIL] Array

newjinnyยท2021๋…„ 9์›” 3์ผ
0

JavaScript

๋ชฉ๋ก ๋ณด๊ธฐ
4/6
post-thumbnail

๐Ÿ” Array(๋ฐฐ์—ด)

Array(๋ฐฐ์—ด)์€ ์—ฌ๋Ÿฌ๊ฐœ์˜ ๋ฐ์ดํ„ฐ๊ฐ’์„ ํ•˜๋‚˜๋กœ ๋ฌถ์–ด ๋†“์€ ๊ฒƒ์„ ๋งํ•œ๋‹ค.

  • [ ] ์•ˆ์— ์š”์†Œ(element)๋“ค์ด ์ˆœ์„œ๋Œ€๋กœ ๋‚˜์—ด๋œ๋‹ค.
  • ์š”์†Œ์—๋Š” ๋ชจ๋“  ๋ฐ์ดํ„ฐ ํƒ€์ž…์ด ์ž…๋ ฅ๊ฐ€๋Šฅํ•˜๊ณ  ๋˜ ๋‹ค๋ฅธ ๋ฐฐ์—ด๋„ ๋“ค์–ด๊ฐˆ ์ˆ˜ ์žˆ๋‹ค.
  • ๋ฐฐ์—ด์—๋Š” ์ˆœ์„œ๊ฐ€ ์กด์žฌํ•˜๋Š”๋ฐ, ๋ฐฐ์—ด ์•ˆ์˜ ์ˆœ์„œ๋ฅผ index๋ผ๊ณ  ํ•œ๋‹ค.
  • index๋Š” 0๋ถ€ํ„ฐ ์‹œ์ž‘ํ•œ๋‹ค.
  • ๋ฐฐ์—ด์„ ์ถœ๋ ฅํ•ด๋ณด์ž!

    ๐Ÿ’ป let ๋ณ€์ˆ˜์ด๋ฆ„ = [์š”์†Œ์ž…๋ ฅ]

    
    let myArray = ['ํ•˜๋‚˜',2,'three',4]
    let newArray = [100,200,300, [400]]
    
    //index๋กœ ์ถœ๋ ฅํ•ด๋ณด์ž!
    let first = myArray[0]// 0๋ฒˆ๋ถ€ํ„ฐ ์‹œ์ž‘ 
    let second = myArray[1]
    let third = myArray[2]
    let forth = myArray[3]
    

    console๋กœ ์ถœ๋ ฅํ•ด๋ณด๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๊ฒฐ๊ณผ๊ฐ€ ๋‚˜์˜จ๋‹ค.

    ๐Ÿ’ก myArray[ ]๋ฅผ ์ด์šฉํ•  ๋•Œ์—๋Š” [ ]์•ˆ์— ์ฒซ๋ฒˆ์งธ ์š”์†Œ๊ฐ€ 0๋ฒˆ index์ด๋ฏ€๋กœ ์ˆœ์„œ๋Œ€๋กœ ์ˆซ์ž๋ฅผ ๋„ฃ์–ด๋ณด๋ฉด ๋œ๋‹ค.

    ๋ฐฐ์—ด ์š”์†Œ ๋ณ€๊ฒฝ,์ถ”๊ฐ€,์‚ญ์ œ ํ•ด๋ณด์ž!

    let myArray = [100,200,'a','b','c']
    
    myArray[2]='A' //2๋ฒˆ์จฐ index๋ฅผ A๋กœ ๋ณ€๊ฒฝ
    myArray.push('d')//๋์— ์ถ”๊ฐ€
    myArray.unshift(true)//์•ž์—์ถ”๊ฐ€
    
    let eraseArray = [10,20,30,40]
    myArray.shift()
    
    let eraseArray2 = [10,20,30,40]
    eraseArray2.pop()

    console๋กœ ์ถœ๋ ฅํ•ด๋ณด๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๊ฒฐ๊ณผ๊ฐ€ ๋‚˜์˜จ๋‹ค.

    ๐Ÿ’ก push๋Š” ๋’ค์— ์ถ”๊ฐ€, unshift๋Š” ์•ž์—์ถ”๊ฐ€, shift๋Š” ์•ž์—๋ถ€ํ„ฐ ์‚ญ์ œ, pop์€ ๋’ค์—๋ถ€ํ„ฐ ์‚ญ์ œ๋œ๋‹ค๋Š” ๊ฑธ ์•Œ ์ˆ˜ ์žˆ๋‹ค.

    splice์‚ฌ์šฉํ•˜์—ฌ ์ถ”๊ฐ€ ์‚ญ์ œ ํ•ด๋ณด์ž!

    splice๋Š” ์›ํ•˜๋Š” ์œ„์น˜์— ์ถ”๊ฐ€ ์‚ญ์ œ๊ฐ€ ๊ฐ€๋Šฅํ•˜๋‹ค.

    ๐Ÿ’ป .splice("์‹œ์ž‘์œ„์น˜",0,์ถ”๊ฐ€์š”์†Œ) //์ถ”๊ฐ€
    ๐Ÿ’ป .splice("์‹œ์ž‘์œ„์น˜",์‚ญ์ œ ์š”์†Œ ๊ฐœ์ˆ˜) //์‚ญ์ œ
    ๐Ÿ’ป .splice("์‹œ์ž‘์œ„์น˜",์‚ญ์ œ ์š”์†Œ ๊ฐœ์ˆ˜, ์ถ”๊ฐ€์š”์†Œ) //์‚ญ์ œํ›„ ๊ทธ ์œ„์น˜์— ์ถ”๊ฐ€

    ์‚ญ์ œ ํ›„ ๊ทธ ์œ„์น˜์— ์ถ”๊ฐ€ํ•˜๋Š” ๋ฌธ์ œ๋ฅผ ํ’€์–ด๋ณด์ž!

    
    function goToMart() {
      let shoppingCart = ['ํ–„', '๊น€๋ฐฅ๊น€', '๋‹จ๋ฌด์ง€', '์šฐ์œ ', '์‹œ๊ธˆ์น˜', '์Œ€', '๋‹น๊ทผ', '๊ณ„๋ž€'];
      shoppingCart.splice(3,1,"๋‘์œ ");
      return shoppingCart;
    }
    //์ถœ๋ ฅ๊ฒฐ๊ณผ ['ํ–„', '๊น€๋ฐฅ๊น€', '๋‹จ๋ฌด์ง€', '๋‘์œ ', '์‹œ๊ธˆ์น˜', '์Œ€', '๋‹น๊ทผ', '๊ณ„๋ž€']
    

    shoppingCart.splice(3,1,"๋‘์œ ") ์ด ๋ถ€๋ถ„์„ ๋ณด๋ฉด index๋Š” 0๋ฒˆ๋ถ€ํ„ฐ ์‹œ์ž‘ํ•˜๋ฏ€๋กœ 3์€ ์šฐ์œ ๋ฅผ ์˜๋ฏธํ•œ๋‹ค.
    ๊ฒฐ๊ตญ 3๋ฒˆ index๋ถ€ํ„ฐ 1๊ฐœ ์‚ญ์ œ ํ›„ ๊ทธ ์œ„์น˜์— ๋‘์œ ๋ฅผ ์ถ”๊ฐ€ํ•œ๋‹ค๋Š” ๋œป์ด ๋œ๋‹ค.

    profile
    I Love Pizza, ๋‚˜๋งŒ์˜ ํ† ํ•‘์œผ๋กœ ํ•œ์กฐ๊ฐ์”ฉ ๋งž์ถฐ๊ฐ€๋Š” ์ค‘

    0๊ฐœ์˜ ๋Œ“๊ธ€