JavaScript 배열

김정훈·2024년 3월 29일

JavaScript

목록 보기
11/19

배열

  • Array 생성자로 만들어진 객체-
  • 데이터군

    배열이란 같은자료형, 순차적인 나열구조 이어야한다.
    그러나 자바스크립트에서 배열은 배열이 아니다. 배열객체이다.

1. 리터럴로 생성하기

const 배열명 = [...];

const fruits = ["apple","orange","melon"];

2. Array 생성자로 생성하기

const fruits = new Array("apple","orange", "melon");

단, Array의 매개변수가 1개일때는 배열 공간의 갯수를 정의한다.

const fruits = new Array(5)

3. length 프로퍼티

  • 배열객체의 공간의 갯수
  • 배열의 length 프로퍼티에는 배열 요소의 최대 인덱스 값 + 1이 담겨 있다.

참고) 객체의 속성명이
변수명 규칙과 동일하면 .(마침표)로 접근가능
규칙에서 벗어나면 ['속성명']

4. 다차원배열

배열객체 안에 배열객체를 정의
const nums =[[1,2,3,],[4,5,6],[7,8,9]];

5. 배열요소의 추가와 삭제

1) 추가

push : 가장 끝에 요소 추가

const fruits = ["apple","orange"];
fruits.push("melon"); //마지막요소로 추가
fruits;
['apple', 'orange', 'melon']

unshift : 가장 앞에 요소 추가

const fruits = ["apple","orange"];
fruits.unshift("melon"); //첫요소로 추가
fruits;
['melon', 'apple', 'orange']

2) 삭제

pop() : 가장 끝에 요소 꺼내기

const fruits = ["apple","orange","melon"];
fruits.pop(); //마지막 요소 꺼내기
fruits;
['apple', 'orange']

shift() : 가장 앞에 요소 꺼내기

const fruits = ["apple","orange","melon"];
fruits.shift(); //첫 요소 꺼내기
fruits;
['orange', 'melon']

3) 중간 추가, 삭제, 변경

splice(start, delectCount, ...items)

const fruits = ["apple","orange","melon"];
fruits.splice(1(시작점),1(갯수),"mango","banana"); //1번째 인데스 값 제거후 , mango,banana 추가 
fruits;
['apple', 'mango', 'banana', 'melon']

6. 배열 요소 확인 메서드

1) in()

2) find()

첫번쨰 발견 요소

const fruits = ["apple","orange","melon", "mango"];
fruits.find(function(fruit){
    return fruit === "melon";
}); //> 'melon'

3) findIndex()

첫번째 발견 요소의 index

const fruits = ["apple","orange","melon", "mango"];
fruits.findIndex(function(fruit){
    return fruit ==="melon";
}); //> 2

4) findLastIndex()

오른쪽 → 왼쪽

5) includes()

요소가 있는지 체크 (true, false)

6) indeoxOf()

요소의 위치 index, 못찾으면 -1

7) lastindeoxOf()

요소의 위치 index, 못찾으면 -1(반대방향)

7. 그외 Araay 메서드

1) concat()

배열을 병합하는데 사용
기존 배열을 변경하지 않고, 새 배열 반환

2) filter(callbackFn)

참으로 반환되는 요소만 걸러주기

const nums = [1,2,3,4,5,6,7,8,9,10];
const odds = nums.filter(x => x % 2 ==1);
odds

3) every(callbackFn)

모든 요소가 참이면 → 참 (true, false)

4) some(callbackFn)

어떤 것이든지 참이면 → 참 (true, false)

5) forEach(callbackFn)

forEach(element, index, array)
array에서는 원본 배열객체를 가르킨다.

const fruits = ["apple","orange","melon", "mango"];
fruits.forEach((el,i)=>{
    console.log("el:", el, "index : " ,i);
});

6) map(callbackFn)

반환값으로 새로운 배열 객체 생성

const nums = [1,2,3,4,5,6,7,8,9,10];
const nums2 = nums.map( x => x * x);
nums2; // >(10) [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

7) flatMap(callbackFn)

중첩된 배열 객체 → 1차원적인 배열 객체 변환

const nums =[[1,2,3,],[4,5,6],[7,8,9]];
const nums2 = nums.flatMap( x => x);
nums2; // > [1, 2, 3, 4, 5, 6, 7, 8, 9]
const nums3 = nums.flatMap(x => x).map(x=>x*x);
nums3; // >

8) join()

join("결합문자열 -기본값,")

const fruits = ["apple","orange","melon", "mango"];
const str =fruits.join();
str; //>'apple,orange,melon,mango'
const str2 = fruits.join("#");
str2;  //>'apple#orange#melon#mango'

9) split()

split("구분문자열")
문자열을 구분 문자열로 쪼개서 배열 객체생성

const fruits = "apple,melon,banana";
const fruits2 = fruits.split(",");
fruits2 //>['apple', 'melon', 'banana']

10) keys()

배열의 각 인덱스에 대한 키를 포함하는 새로운 배열 반복자 객체를 반환

const array1 = ['a', 'b', 'c'];
const iterator = array1.keys();

for (const key of iterator) {
  console.log(key);
}
// Expected output: 0
// Expected output: 1
// Expected output: 2
const nums = [...(new Array(101)).keys()];
nums // > 0~100

11) reverse()

배열의 순서를 반전

const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);
// array1:" Array ["one", "two", "three"]

12) slice()

begin 부터 end 까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환합니다. 원본 배열은 바뀌지 않습니다.

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2, 4));
// Expected output: Array ["camel", "duck"]
console.log(animals.slice(2, -1));
// Expected output: Array ["camel", "duck"]

13) sort()

배열의 요소를 적절한 위치에 정렬한 후 그 배열을 반환합니다.

const nums = [10,5,99,33,1,30];
nums.sort((a,b)=> a-b); //오름차순
nums.sort((a,b) => b-a); //내림차순

14) reduce()

배열의 각 요소에 대해 주어진 리듀서 (reducer) 함수를 실행하고, 하나의 결과값을 반환합니다.
reduece(accumulator,currentValue)
accumulator : 누산기는 콜백의 반환값을 누적합니다.
currentValue : 처리할 현재 요소

총합구하기

const nums = [99,199,3,5,23];
const total = nums.reduce((acc,cur) => {
    console.log("acc",acc,"cur",cur);
    acc+=cur;
    return acc;
});
///acc 99 cur 199
///acc 298 cur 3
///acc 301 cur 5
///acc 306 cur 23

max값구하기

const nums = [99,199,3,5,23];
const max = nums.reduce((a,b) => a > b ?  a:b);
max; ///199

15) isArray()

전달된 값이 배열인지 판단.

8. Symbole.iterator가 정의된 경우

반복자 패턴 구현 → 디자인패턴
커서 : 이동위치

next()
커서를 이동하면서 다음 요소 접근

const fruits = ["apple","orange","melon"];
const iter = fruits[Symbol.iterator]();
iter
///Array Iterator {}
iter.next();
///{value: 'apple', done: false}
iter.next();
///{value: 'orange', done: false}
iter.next();
///{value: `melon`, done: false}
iter.next();
///{value: undefined, done: true}
///마지막요소까지 접근할경우 done:true

for ..of구문
Symbole.iterator가 구현된 객체이면 사용가능

const fruits = ["apple","orange","melon"];
for (const fruit of fruits){
    console.log(fruit);
}
//apple
//orage
//melon

sring에도 사용이 가능하다.

9. 화살표 함수

  • function 키워드 생략 가능
  • 매개변수와 구현 체 ({..}) 사이에 =>
  • 구현내용이 한줄이면 {...} 생략가능, return 예약어도 생략가능
  • 매개변수가 1개 → (...) 생략가능, 단 매개변수가 없으면 생략 불가
  • 생성자 함수로 역할 x
  • argumetns 지역변수X
  • this 범위가 함수를 정의할때 이미 정의된 this가 this가 된다.
const fruits = ["apple","orange","melon", "mango"];
fruits.findIndex((x) => x ==="melon");
const person = {
    name : '이이름',
    age : 40,
    showinfo : () => {
        console.log(this); //window
    }
};
person.showinfo(); // window
const person = {
    name : '이이름',
    age : 40,
    showinfo : funciton(){
        const printInfo = () => console.log(this);//person.showinfo 호출 -> 정의된객체 -> person
    printInfo();
       
    }
};

10. 유사배열

상속관계가(프로토타입 체인)이 Array.prototype이 아닌형태

비구조화

1. 비구조화 할당

const person = {
  name : "이이름",
  age : 40
};
const { name, age } = person;
name;
// 이이름
age;
// 40

값을 서로 스위치할때

let a=10, b=20;
[b,a] = [a,b];
profile
안녕하세요!

0개의 댓글