JavaScript

Spread Operator

seoca 2020. 12. 26. 22:03

 

Spread Operator in Javascript

 

1. In ES6, By using the spread operator, you can simply populate an array to another array.

'=' only allows you to copy the reference not the value of the array.

'=' 는 단지 주소값을 전달할 뿐 진짜 값을 전달하지 못하기때문에 spread operator를 사용해서 array를 복사할 수 있다. 

function threeDots(arr) {
    let sticks = [...arr];
}

 

 

2. Math.min() and Math.max() expect a list of arguments not an array. If you want to use an array you need to use the '...' spread syntax. e.g. Math.min(...arr)

//Object.value() returns an array
let mostRepeated = Math.max(...Object.values(object)); 

 

3. 아래 코드에서 spread operator 없이는 error occured.

...this._defineItem("userInfo", userName.replace(/(\s*)/g, ""), "vaadin:user"),
 const userData = {
            ...this._defineItem("userInfo", userName.replace(/(\s*)/g, ""), "vaadin:user"),
            childNode: [
               {
                  "id": "userInfo",
                  "name": i18next.t("menu.userInfo"),
                  "icon": "vaadin:user",
               },
               {
                  "id": "readingList",
                  "name": i18next.t("menu.readingList"),
               },
            ],
         };

아래 코드로 대체 가능. 객체안에서 spread operator는 key value를 대체 할 수 있다.

_defineItem : ("userInfo", userName.replace(/(\s*)/g, ""), "vaadin:user"),