# [TIL] Array

newjinnyยท2021๋ 9์ 3์ผ
0

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

# ๐ 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๊ฐ ์ญ์  ํ ๊ทธ ์์น์ ๋์ ๋ฅผ ์ถ๊ฐํ๋ค๋ ๋ป์ด ๋๋ค.

I Love Pizza, ๋๋ง์ ํ ํ์ผ๋ก ํ์กฐ๊ฐ์ฉ ๋ง์ถฐ๊ฐ๋ ์ค