배열이란 같은자료형, 순차적인 나열구조 이어야한다.
그러나 자바스크립트에서 배열은 배열이 아니다. 배열객체이다.
const 배열명 = [...];
const fruits = ["apple","orange","melon"];
const fruits = new Array("apple","orange", "melon");
단, Array의 매개변수가 1개일때는 배열 공간의 갯수를 정의한다.
const fruits = new Array(5)
참고) 객체의 속성명이
변수명 규칙과 동일하면 .(마침표)로 접근가능
규칙에서 벗어나면 ['속성명']
배열객체 안에 배열객체를 정의
const nums =[[1,2,3,],[4,5,6],[7,8,9]];
push : 가장 끝에 요소 추가
const fruits = ["apple","orange"];
fruits.push("melon"); //마지막요소로 추가
fruits;
['apple', 'orange', 'melon']
unshift : 가장 앞에 요소 추가
const fruits = ["apple","orange"];
fruits.unshift("melon"); //첫요소로 추가
fruits;
['melon', 'apple', 'orange']
pop() : 가장 끝에 요소 꺼내기
const fruits = ["apple","orange","melon"];
fruits.pop(); //마지막 요소 꺼내기
fruits;
['apple', 'orange']
shift() : 가장 앞에 요소 꺼내기
const fruits = ["apple","orange","melon"];
fruits.shift(); //첫 요소 꺼내기
fruits;
['orange', 'melon']
splice(start, delectCount, ...items)
const fruits = ["apple","orange","melon"];
fruits.splice(1(시작점),1(갯수),"mango","banana"); //1번째 인데스 값 제거후 , mango,banana 추가
fruits;
['apple', 'mango', 'banana', 'melon']
첫번쨰 발견 요소
const fruits = ["apple","orange","melon", "mango"];
fruits.find(function(fruit){
return fruit === "melon";
}); //> 'melon'
첫번째 발견 요소의 index
const fruits = ["apple","orange","melon", "mango"];
fruits.findIndex(function(fruit){
return fruit ==="melon";
}); //> 2
오른쪽 → 왼쪽
요소가 있는지 체크 (true, false)
요소의 위치 index, 못찾으면 -1
요소의 위치 index, 못찾으면 -1(반대방향)
배열을 병합하는데 사용
기존 배열을 변경하지 않고, 새 배열 반환
참으로 반환되는 요소만 걸러주기
const nums = [1,2,3,4,5,6,7,8,9,10];
const odds = nums.filter(x => x % 2 ==1);
odds
모든 요소가 참이면 → 참 (true, false)
어떤 것이든지 참이면 → 참 (true, false)
forEach(element, index, array)
array에서는 원본 배열객체를 가르킨다.
const fruits = ["apple","orange","melon", "mango"];
fruits.forEach((el,i)=>{
console.log("el:", el, "index : " ,i);
});
반환값으로 새로운 배열 객체 생성
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]
중첩된 배열 객체 → 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; // >
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'
split("구분문자열")
문자열을 구분 문자열로 쪼개서 배열 객체생성
const fruits = "apple,melon,banana";
const fruits2 = fruits.split(",");
fruits2 //>['apple', 'melon', 'banana']
배열의 각 인덱스에 대한 키를 포함하는 새로운 배열 반복자 객체를 반환
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
배열의 순서를 반전
const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);
// array1:" Array ["one", "two", "three"]
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"]
배열의 요소를 적절한 위치에 정렬한 후 그 배열을 반환합니다.
const nums = [10,5,99,33,1,30];
nums.sort((a,b)=> a-b); //오름차순
nums.sort((a,b) => b-a); //내림차순
배열의 각 요소에 대해 주어진 리듀서 (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
const nums = [99,199,3,5,23];
const max = nums.reduce((a,b) => a > b ? a:b);
max; ///199
전달된 값이 배열인지 판단.
반복자 패턴 구현 → 디자인패턴
커서 : 이동위치
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에도 사용이 가능하다.
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();
}
};
상속관계가(프로토타입 체인)이 Array.prototype이 아닌형태
const person = {
name : "이이름",
age : 40
};
const { name, age } = person;
name;
// 이이름
age;
// 40
값을 서로 스위치할때
let a=10, b=20;
[b,a] = [a,b];