배열과 배열 메소드 [JavaScript]

27932 단어 2021.042021.04

array

array = [element1, element2, element3]

[] === []

빈배열과 빈배열은 서로 같은 것인가 하는 질문에 답은 false다. 왜냐하면 자바스크립트 상에서는 두 배열을 주소(reference)가 다른 두 개의 빈 배열이라 생각하기 때문이다.
빈 배열 뿐만 아니라 값이 동일한 이름이 다른 변수도 경우는 같다.

const arr1 = [1,2,3];
const arr2 = [1,2,3];
arr1 === arr2 //false
arr1 === [1,2,3] // false

mutable data type 인 array는 변수에 주소를 저장하고, 그 주소는 값을 heap이라는 곳에 저장한다. 변수가 가르키고 있는 주소(reference)가 다르기 때문에 요소가 같아도 다른 것이 된다.

array를 인자로 전달할 경우, reference가 전달된다.

const arr = ['사과', '바나나','참외','수박'];

function passedByReference(refArr) {
	refArr[2] = '무궁화 꽃이 피었습니다.';
}

passedByReference(arr);
arr[2]; // '무궁화 꽃이 피었습니다.'

배열인지 확인하는 방법

Array.isArray(배열)

// 배열은 객체에 속하기 때문에 typeof를 사용해서 배열인지 아닌지 구별할 수 없다.
const arr = [1,2,3];
typeof arr === 'array' // false
typeof arr === 'object' // true
Array.isArray(arr)// true

배열 요소 확인하기

  1. arr[인덱스 넘버]
  2. arr[arr.length-1] : 배열의 마지막 요소 구하기
const arr = ['사과', '바나나', '오렌지'];

// 인덱스 넘버는 0부터 시작한다.
arr[0] // '사과' 

// 배열은 0부터 시작하기 때문에
// 배열의 마지막 요소는 arr.length에서 1을 뺀 값이다.
arr[arr.length-1] // '오렌지'

// 배열 요소는 여러 타입이 올 수 있다.
const multiTypeArr = [
'영',
1,
'two',
{value1: 3, value2: 4},
function(){
	return 5;
},
[6,7], 
];
multiTypeArr.length // 6
multiTypeArr[0] // '영'
multiTypeArr[3].value2 // 4
multiTypeArr[4]() // 5
multiTypeArr[5][1] // 7



array 메소드

  • 특정 엘리먼트 값 : array[ index숫자 ]
  • 배열의 마지막 값: array[ array.length-1 ]

array mutable methods

기존의 배열을 바꾸는 mutable methods 이다.
push, pop, unshift, shift, reverse, splice, sort, fill, copyWithin 등이 있다.

**아래 선언은 mutable methods 전체에서 사용한다. mutable이기 때문에 바뀐 배열을 이용해서 값이 출력됨에 유의하자.


const fruits = [ 'orange', 'apple', 'mango'];
  • push : arr.push('추가요소,(추가요쇼...)')
    배열의 끝에 하나 이상의 요소를 추가
// **push 
fruits.push('lemon');
console.log(fruits) // ['orange', 'apple', 'mango', 'lemon']
fruits.push('melon', 'grape');
console.log(fruits); //  ['orange', 'apple', 'mango', 'lemon', 'melon', 'grape']

// 주의점 : 메소드를 이용해서 바로 출력하면 요소의 총 갯수를 출력한다.
fruits.push('banana'); // 7
fruits; //['orange', 'apple', 'mango', 'lemon', 'melon', 'grape', 'banana'] 



  • pop : pop()
    배열에서 마지막요소를 제거하고, 제거된 요소를 반환한다.
//**pop
console.log(fruits.pop()); // banana
console.log(fruits);// ['orange', 'apple', 'mango', 'lemon', 'melon', 'grape']

fruits.pop(); // grape
fruits; // ['orange', 'apple', 'mango', 'lemon', 'melon' ]




unshift와 shift는 배열이 전체적으로 움직임인다. push나 pop 사용 권장

  • unshift : arr.unshift('추가요소,(추가요쇼...)')
    새로운 요소를 맨 앞쪽에 추가
fruits.unshift('mango'); // 6
fruits; // ['mango', 'orange', 'apple', 'mango', 'lemon', 'melon' ]
fruits.unshift('grape','pear'); // 8
fruits; //['grape','pear','mango', 'orange', 'apple', 'mango', 'lemon', 'melon' ] //



  • shift : arr.shift()
    배열의 첫 번째 요소를 제거하고, 제거된 요소를 반환한다.
fruits.shift(); // grape
fruits; // ['pear','mango', 'orange', 'apple', 'mango', 'lemon', 'melon' ]



  • splice : arr.splie(start,deletCount,(추가요소,추가요소...))
const num = ['0','3','4','5'];

// num 인덱스 1을 기준으로, 아무것도 지우지 않고, '1'을 추가
num.splice(1,0,'1');
console.log(num); // ["0", "1", "3", "4", "5"]

// num 인덱스 0을 기준으로, 2개를 지우고, '영' 과 '일' 을 추가
num.splice(0,2,'영','일')// ["영", "일", "3", "4", "5"]



array immutable methods

기존 배열을 바꾸지 않고, 새로은 배열 객체를 반환한다.

  • slice : arr.slice(begin, (end))
    begin 부터 end까지(end 미포함)에 대한 새로운 배열 객체를 반환한다.
    - begin이 undefined인 경우, 0번 인덱스부터 slice
    - begin이 배열의 길이보다 큰 경우, 빈 배열을 반환
const city = ['Seoul' ,'Deajeon','Busan', 'Deagu'];
console.log(city.slice(1)); // ['Deajeon','Busan', 'Deagu']
console.log(city.slice(1, 2)); // ['Deajeon']

// **음수 인덱스는 배열의 끝에서부터의 길이를 나타냄

// 마지막 2개의 엘리먼트 추출
console.log(city.slice(-2)); // ['Busan','Deagu'];

// 첫번째에서 끝에서 2번째 요소까지
console.log(city.slice(0,-1)) // ['Seoul' ,'Deajeon','Busan']



  • join :arr.join(sparator)
    array의 모든 요소를 하나의 string으로 만든다.
    array -> string
const elements = ['Apple', 'Lemon', 'Banana'];

console.log(elements.join()); // "Apple,Lemon,Banana"
console.log(elements.join(''));// "AppleLemonBanana"
console.log(elements.join(' ')); // "Apple Lemon Banana"
console.log(elements.join('-')); // "Apple-Lemon-Banana"



  • split : str.split(separator)
    string 객체를 seperator을 이용하여 한 개의 배열 안에 여러개의 문자열로 나눔.
    string -> array
const greeting = 'Welcom to my place.';

const words = greeting.split(' '); 
console.log(words[3]); // "place."
console.log(words); // ["Welcom", "to", "my", "place."]

const chars  = greeting.split('')// 공백없는 빈 스트링
console.log(chars[5]); // "m"
console.log(chars); // ["W", "e", "l", "c", "o", "m", " ", "t", "o", " ", "m", "y", " ", "p", "l", "a", "c", "e", "."]

const phoneNum = '010-1234-5678'
const dash = phoneNum.split('-');
console.log(dash); // ["010", "1234", "5678"]



  • concat : arr1.conat(arr2,arr3...)
    arr1+arr2 해주는 메소드
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);
console.log(array3); // ["a", "b", "c", "d", "e", "f"]

const num1 = [1, 2, 3];
const num2 = [4, 5, 6];
const num3 = [7, 8, 9];
num1.concat(num2, num3); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
### 보충 find fileter, map ,some, every, sort, reverse

좋은 웹페이지 즐겨찾기