자바스크립트 복습 - 6

Stulta Amiko·2022년 5월 11일
0

자바스크립트 복습

목록 보기
6/12
post-thumbnail

Array

Array.from()

Array.from()은 배열스럽지만 배열이 아닌 객체를 받아서 실제 객체로 변환해서 반환한다.

<HTML>
<div class="fruits">
    <p> Apple </p>
    <p> Banana </p>
    <p> Orange </p>
</div>

</HTML>

<script>
    const fruits = document.querySelectorAll(".fruits p");
    const fruitArray = Array.from(fruits);

    console.log(fruitArray);  // [p,p,p]

    const fruitNames = fruitArray.map(fruit => fruit.textContent);

    console.log(fruitNames); //[' Apple ', ' Banana ', ' Orange ']
</script>

스크립트 부분만 보자
이런식으로 fruits를 Array.from()을 통해서 배열로 만들고
map함수에 넣어서 값을 출력하는 모습을 볼 수 있다.

    const fruits = Array.from(document.querySelectorAll(".fruits p"))
    const fruitNames = fruits.map(fruit => fruit.textContent);
    console.log(fruitNames); //[' Apple ', ' Banana ', ' Orange ']

이런식으로 간략화 할 수 도있다.

    const fruits = Array.from(document.querySelectorAll(".fruits p"));
    const fruitArray = Array.from(fruits, fruit => {
        console.log(fruit); // <p> Apple </p> <p> Banana </p> <p> Orange </p>
        return fruit.textContent;
    });
    console.log(fruitArray); //[' Apple ', ' Banana ', ' Orange ']

이런식으로 from의 두번째 파라미터로 map 역할을 하는 함수를 넣어서 해결 할 수도있다.

Array.of()

Array.of()는 전달받은 모든 아규먼트로 배열을 생성한다.

const number = Array.of(1, 2, 3, 4, 5);
console.log(number); // [ 1, 2, 3, 4, 5 ]

Array.find()

Array.find()는 배열에서 조건을 충족하면 그 조건을 첫번째로 충족한 원소를 반환하는 함수이다.

const number = Array.of(1, 2, 3, 4, 5);

let search = number.find(e => e > 3);
console.log(search); // 4

주의 해야할점은 다른 함수들과 다르게 Array를 적는게 아니라 find 함수를 적용할 배열에 .find()를 해줘야한다.

Array.findIndex()

findIndex는 find와 다르게 요소를 반환하는게 아니라 인덱스를 반환한다.

const number = Array.of(1, 2, 3, 4, 5);

let search = number.findIndex(e => e > 3);
console.log(search); // 3

4는 number 배열에 3번째 인덱스에 있으니 3을 반환하는 모습을 볼 수 있다.

Array.some() / Array.every()

some은 함수의 파라미터값을 배열에 요소로 하나라도 포함하고 있으면 true를 반환한다.
every는 함수의 파라미터값을 배열의 요소가 전부 일치하면 true를 반환한다.

const number = Array.of(1, 2, 3, 4, 5, 6, 7, 8, 2, 1, 3, 4);

let some = number.some(e => e > 2);
console.log(some); //true

let every = number.every(e => e > 2);
console.log(every); //false

다음과 같다.

스프레드 연산자

MDN은 스프레드 연산자를 다음과 같이 설명한다.

스프레드 문법을 사용하면 배열이나 문자열과 같이 반복 가능한 문자를 0개 이상의 인수 (함수로 호출할 경우) 또는 요소 (배열 리터럴의 경우)로 확장하여, 0개 이상의 키-값의 쌍으로 객체로 확장시킬 수 있습니다.

스프레드 연산자를 이용해서 배열을 결합해보자.

const boeing = ["717", "727", "737"];
const airbus = ["300", "310", "320"];

const plane = [...boeing, "Q400", ...airbus];
console.log(plane); //[ '717', '727', '737', 'Q400', '300', '310', '320']

이런식으로 ...을 이용해서 중간에 추가 요소를 집어넣으면서 두 배열을 합치는 모습을 볼 수있다.

스프레드 연산자를 이용해서 배열을 복사해보자

const boeing = ["717", "727", "737"];
const boeing_copy = boeing;

console.log(boeing_copy); //[ '717', '727', '737' ]

boeing.push("747");

console.log(boeing_copy); // [ '717', '727', '737', '747' ]

위와 같이 이런식으로 단순히 배열의 이름을 넣게되면 얕은복사가 되서 단순히 배열에 대한 참조가 되버려서 만약 기존 배열의 값을 수정하게 되면 복사본까지 수정되게 되므로 제대로 복사했다고 할수 없다.

const boeing = ["717", "727", "737"];
const boeing_copy = [].concat(boeing);

console.log(boeing_copy); //[ '717', '727', '737' ]

boeing.push("747");

console.log(boeing_copy); // [ '717', '727', '737' ]

ES5 및 이전버전에서 배열을 복사하는 방법

const boeing = ["717", "727", "737"];
const boeing_copy = [...boeing];

console.log(boeing_copy); //[ '717', '727', '737' ]

boeing.push("747");

console.log(boeing_copy); // [ '717', '727', '737']

ES6 문법에서 새로 도입된 스프레드 문법을 사용한 배열의 복사

이런식으로 간단하게 배열의 복사를 할 수 있다.

스프레드 연산자를 이용하면 함수의 파라미터에 값을 편리하게 넣을 수 있다.

const add = (x, y, z) => {
    console.log(x + y + z);
}
var num = [1, 2, 3];

add.apply(null, num); // 6

add(...num); // 6

이런식으로 apply를 사용하지 않더라도 간단하게 배열의 파라미터로 전달할 수 있다.

const num = [1243, 2345];

const add = (x, y) => {
    console.log(`sum = ${x+y}`);
}

add(...num); //sum = 3588

배열의 두 값이 알아서 자동으로 할당된다.
만약 배열의 값이 하나 더많아서 하나 더많은양이 제공되면 어떻게될까
마지막값은 그냥 사라진다.

객체리터럴과 스프레드

ES2018에서 도입된 객체에 대한 스프레드 연산자이다.

const plane = {
    company: "boeing",
    type: "747",
    sub_type: "-400",
};

let clone = {...plane };
console.log(clone); //{ company: 'boeing', type: '747', sub_type: '-400' }

이런식으로 객체를 복사할 수 있다.

레스트 매개변수

레스트는 나머지라는 뜻이다 스프레드는 배열을 확장하는 반면 레스트는 여러개의 원소를 하나로 합친다.

const plane = ["b737", "b747", "b757", "b767"];
const [first, second, ...others] = plane;

console.log(...others); // b757 b767

변수를 키와 값으로 하는 객체 만들기

const company = "boeing";
const type = "747";
const operation = "delta";
const nationality = "United States";

const plane = {
    company,
    type,
    operation,
    nationality,
}

console.log(plane);

다음과 같이 변수가 4개있을때 객체 리터럴을 만들고 싶다면 직접 하나씩 key와 value를 할당해줬어야했던 반면 ES6에서는 위와같이 편리하게 key-value를 묶을 수 있다.

실행결과
{
company: 'boeing',
type: '747',
operation: 'delta',
nationality: 'United States'
}

변수의 이름과 값이 객체에서 동일하기 때문에 굳이 따로 설정해주지 않아도 된다.

객체에 함수 추가하기

const plane = {
    type: "747",
    fly: function() {
        console.log("fly");
    }
}

plane.fly(); //fly

기존에 함수를 넣는방법

const plane = {
    type: "747",
    fly() {
        console.log("fly");
    }
}

plane.fly(); //fly

ES6에서 새로 추가된 방법

const plane = {
    type: "747",
    fly: () => {
        console.log("fly");
    }
}

plane.fly(); //fly

이런식으로 애로우 함수를 이용해서도 표현할 수 있긴 하지만 애로우 함수는 익명함수이기 때문에 key를 넣어줘야한다 만약 key를 넣지 않는다면 오류가 발생할 것이다.

const name = "name";

const Person = {
    [name]: "name2",
};
 console.log(Person.name); // name2

ES6에서는 이렇게 객체를 생성함과 동시에 수정할 수 있다.

0개의 댓글