# 배열 - 배열예제 ``` let animals= [ "Aardvark", "Albatross", "Alligator", "Alpaca", "Ant", "Ape", "Armadillo", "Donkey", "Baboon", "Badger", "Barracuda", "Bat", "Bear", "Beaver", "Bee", "Bison", "Cat", "Caterpillar", "Cattle", "Chamois", "Cheetah", "Chicken", "Chimpanzee", "Chinchilla", "Chough", "Clam", "Cobra", "Cockroach", "Cod", "Cormorant", "Dugong", "Dunlin", "Eagle", "Echidna", "Eel", "Eland", "Elephant", "Elk", "Emu", "Falcon", "Ferret", "Finch", "Fish", "Flamingo", "Fly", "Fox", "Frog", "Gaur", "Gazelle", "Gerbil", "Giraffe", "Grasshopper", "Heron", "Herring", "Hippopotamus", "Hornet", "Horse", "Kangaroo", "Kingfisher", "Koala", "Kookabura", "Moose", "Narwhal", "Newt", "Nightingale", "Octopus", "Okapi", "Opossum", "Quail", "Quelea", "Quetzal", "Rabbit", "Raccoon", "Rail", "Ram", "Rat", "Raven", "Red deer", "Sandpiper", "Sardine", "Sparrow", "Spider", "Spoonbill", "Squid", "Squirrel", "Starling", "Stingray", "Tiger", "Toad", "Whale", "Wildcat", "Wolf", "Worm", "Wren", "Yak", "Zebra" ] ``` ## 1. 어레이에 마지막 아이템 “Zebra” 제거하기 ``` animals.pop() console.log(animals) ``` - **pop()** 배열에서 마지막 요소가 제거된 후의 배열이 출력 - 반환된 값은 콘솔에 출력되지 않고 버려지기 때문에 zebra 빠진 나머지 값이 출력됨 ``` console.log(animals.pop()) ``` - 배열 animals에서 마지막 요소를 제거하고 그 값을 출력 - 호출한 후에 반환한 값을 콘솔에 출력하기 때문에 Zebra만 출력됨 차이점??? ``` console.log(animals.pop())는 호출한 후 반환된 값을 콘솔에 출력하고, animals.pop()은 pop() 호출하고 반환된 값을 사용하지 않는다. ``` ## 2. 주어진 어레이에 “Dog” 추가하기 - **push()** 배열 끝에 요소 추가 ``` animals.push("Dog") console.log(animals) ``` - **unshift()** 배열 맨앞에 요소 추가 ``` animals.unshift("Dog") console.log(animals) ``` - dog를 추가된 후 배열의 최종 길이 (97개) ``` animals.push("Dog") console.log(animals.push()) ``` ## 3. 주어진 어레이에 “Mosquito”,“Mouse”,“Mule” 추가하기 ### push(), unshift() - 요소를 추가하고 배열의 길이를 반환 ``` let animalsLength = animals.push("Mosquito","Mouse","Mule") console.log(animalsLength) //길이값 반환 console.log(animals) ``` ### concat() 배열 결합 - 배열에 다른 배열이나 값들을 추가하여 새로운 배열 - 원본 배열을 변형하고 싶지 않을 경우 유용함 ``` let animals2 = ["Mosquito","Mouse","Mule"] let newAnimals = animals.concat(animals2) console.log(animals) // 원본 배열 console.log(newAnimals) // concat() 새로운 배열 ``` ### concat() 배열복제 ``` let newAnimals = [].concat(animals) // animals을 복제하여 newAnimals 만듬 newAnimals.unshift("Mosquito","Mouse","Mule") // 복제한 배열의 맨앞에 요소 추가 console.log(animals) // 원본 배열 console.log(newAnimals) // 복사한 원본배열에 요소 추가된 배열 ``` ## 4. 해당 어레이에는 "Human"이 있는가? - **includes()** 배열에 특정 요소가 포함되어 있는지 확인하는 메소드 - 요소가 포함되어 있을경우는 true , 그렇지 않으면 false 반환 - 찾는 요소가 문자열일 경우 대소문자 구분 - 변수를 포함한다. ``` console.log(animals.includes("Human")) / 출력 : false ``` ### 4-1 매개변수(함수나 메서드에 전달되는 값을 받아들이는 변수) **animals.includes(searchElement[, fromIndex])** - searchElement : 배열에서 찾을 요소입니다. - fromIndex : 검색을 시작할 인덱스 생략하면 기본값으로 0이 사용됩니다. 만약 음수 값을 가진다면, 배열의 끝에서부터 역순으로 검색을 시작합니다. ``` console.log(animals.includes("Aardvark", 2)); / 출력 : false 인덱스 2부터 요소를 검색 0인 Aardvark 검색되지 않는다. ``` ## 5. 해당 어레이에는 “Cat” 이 있는가? - **indexOf()** 배열에서 인수로 전달된 요소를 찾아 첫번째로 검색된 요소의 인덱스 반환 - 전달 요소가 없는 경우 -1을 반환 - 옵션이므로 생략하면 0부터 검색 - 요소의 위치를 찾거나 존재하는지 확인할때 유용 - 음수값을 사용할 경우 배열의 끝에서부터 카운트된다.(왼쪽에서 오른쪽으로 검색) ``` let cat = animals.indexOf("Cat") console.log(animals.includes("Cat")) / 출력 : true console.log(cat) / 출력 : 16 ``` ## 6. "Red deer"을 "Deer"로 바꾸시오 ``` console.log(animals.indexOf("Red deer")) // red deer의 인덱스 번호를 찾는다 77번 ``` ``` animals[77] = "Deer" // 77번째 요소의 이름을 변경 console.log(animals) console.log(animals.indexOf("Deer")) // 출력 77 ``` ## 7. "Spider"부터 3개의 아이템을 기존 어레이에서 제거하시오 - **slice()** : 원본 문자열에서 특정 범위의 문자열을 잘라내어 추출한 결과를 새로운 문자열로 반환 - 원본 문자열은 바뀌지 않는다. - 시작 인덱스 부터 끝 인덱스 직전까지 추출 (끝점은 미포함) - 추출한 부분 문자열을 수정하거나 다른 문자열과 결합하여 새로운 문자열을 생성할때 유용 ``` console.log(animals.indexOf("Spider")) // index:81 console.log(animals.slice(0,81).concat(animals.slice(84))) ``` ## 8. "Tiger"이후의 값을 제거하시오 ``` console.log(animals.indexOf("Tiger")) // index:87 console.log(animals.slice(0,88)) ``` ## 9. "B"로 시작되는 아이템인 "Baboon"부터 "Bison"까지 가져와 새로운 어레이에 저장하시오 - slice()함수 이용 ``` console.log(animals.indexOf("Baboon")) / index : 8 console.log(animals.indexOf("Bison")) / index : 15 let extraAnimals = animals.slice(8,16) console.log(extraAnimals) ``` - splice()함수 이용 ``` let extraAnimals = animals.splice(8,8) / 시작점에서 몇개까지 console.log(extraAnimals) ```