Javascript Spread 연산자란, 작동 방식, 사용 방법

JavaScript spread 연산자는 ES6에 도입된 비교적 유행하는 기능 중 하나입니다.이 강좌는 당신이 그것을 이해하는 데 도움을 줄 것입니다.spread 연산자가 무엇인지, 그리고 그것이 어떻게 작동하는지 알게 될 것입니다.수조와 대상 텍스트를 복사하고 통합하며 데이터를 삽입하는 방법도 배울 것입니다.

JavaScript 확장 연산자 소개
Spread operator는 iterable 객체의 컨텐트에 액세스할 수 있는 기능입니다.Iterable 객체는 for...of를 통해 컨텐트를 순환하여 액세스할 수 있는 객체 또는 데이터 구조입니다.iterable에서 가장 유행하는 예는 수조입니다.iterable의 또 다른 예는objects나literalsstrings일 수 있다.
어떤iterable의 모든 내용을 방문하고 싶을 때,spread 조작부호가 나타나기 전에, 앞에서 언급한 for...of 순환이나 방법, 예를 들어 forEach() 을 사용해야 한다.다른 선택은 색인입니다.Spread 연산자를 사용하면 더 적은 코드로 더 빨리 작업을 수행할 수 있습니다.문법에 관하여.
spread 연산자의 문법은 간단하고 기억하기 쉽다.그것은 세 개의 점으로 구성되어 있다(....이 세 개의 점 뒤에는iterable (...someIterable 이 있습니다. 내용을 방문하시기 바랍니다.
// Create array
const myArray = ['Venus', 'Ares', 'Mars']

// Use spread operator to access content of "myArray" variable
// Syntax: ...someIterable
console.log(...myArray)
// Output:
// 'Venus' 'Ares' 'Mars'

확장 연산자 및 객체 문자
객체 문자에 확장 연산자를 사용하려는 경우 구문은 동일합니다.이 세 점을 사용하지만 컨텐트에 액세스할 객체의 이름이 뒤에 옵니다.네가 얻게 될 결과는 내용이다. 단지 주위의 괄호가 없을 뿐이다.
// Create object literal
const myObj = {
  firstName: 'Sam',
  lastName: 'Dodge'
}

// Use spread operator to access content of "myObj" variable
// Note: the {} around ...myObj are to avoid TypeError
// console.log(...myObj) would not work
console.log({ ...myObj })
// Output:
// { firstName: 'Sam', lastName: 'Dodge' }

확장 산자로 숫자를 복제하다
spread 조작부호는iterable의 내용에 빠르게 접근할 수 있도록 합니다.이 기능은 복사할 수 있는 객체를 복사하려는 경우에 유용할 수 있습니다.당신은 이 점을 모를 수도 있지만, 대상을 복제하는 것은 매우 까다로울 수도 있습니다.숫자나 문자열 같은 것을 복제하려고 하면 진정한 복사본을 만들거나 복제할 수 있습니다.이것은primitive이라고 불린다.
deep copy
깊이 있는 복제품
대상에 대해iterables를 포함하는 것은 그렇지 않다.배열과 같은 객체를 복사하려고 하면 실제 복사본이 작성되지 않습니다.반대로 JavaScript는 객체에 대한 새 참조를 작성합니다.새 별명이나 이름을 만드는 것으로 볼 수 있습니다.
객체를 복사할 때는 객체의 새 별칭만 작성됩니다.그래서 이 물건은 두 개의 이름, 그 물체가 있다.그러나 여전히 두 개의 대상이 아니라 한 개의 대상만 있다.즉, 두 번째 별칭(참조)을 사용하여 객체에 특정 작업을 수행할 경우 이러한 변경 사항이 첫 번째 별칭에도 영향을 미칩니다.
객체는 하나뿐이지만 두 개의 참조(앨리어스)로 액세스할 수 있다는 점에 유의하십시오.이런 유형의 복사는 라고 하고, 이런 유형의 복사는 shallow copy라고 한다.
// Create an array
const myArray = ['Spread', 'Rest', 'JavaScript']

// Create shallow copy of "myArray" variable
const myShallowCopy = myArray

// Log the content of "myArray"
console.log(myArray)
// Output:
// [ 'Spread', 'Rest', 'JavaScript' ]

// Log the content of "myShallowCopy"
console.log(myShallowCopy)
// Output:
// [ 'Spread', 'Rest', 'JavaScript' ]

// Remove the last item from the original array ("myArray")
myArray.pop()

// Log the content of "myArray" again
// The last item is gone as it should
console.log(myArray)
// Output:
// [ 'Spread', 'Rest' ]

// Log the content of "myShallowCopy" again
// The change of "myArray" will also appear in "myShallowCopy"
// The last item is also gone
console.log(myShallowCopy)
// Output:
// [ 'Spread', 'Rest' ]
copying by reference
확장 연산자를 사용한 깊이 있는 복사
이것이 바로 JavaScript의 복제가 자동으로 작동하는 방법입니다.좋은 소식은 spread operator에서 이 문제를 해결하기 위해 간단한 복사를 사용할 수 있다는 것입니다.이것은iterables의 깊이 있는 복사본을 신속하게 만들 수 있습니다.그러니 생각지도 못한 곳에서 일어나는 변화에 대해 더 이상 걱정하지 마라.
spread 연산자를 사용하여 어떤iterable의 진실하고 깊이 있는 복사본을 만드는 것은 매우 간단합니다.우선, 변수를 만들고,iterable, 그룹을 분배합니다.이것은 복사할 iterable입니다.둘째, 새 변수를 만듭니다.이 새 변수에 첫 번째 변수의 사본을 분배하려면spread 연산자를 사용하고, 그 다음에 첫 번째 변수의 이름과 네모난 괄호로 묶을 것입니다.
spread 조작부호는 접근 내용을 기본적으로 원시 그룹의 네모난 괄호를 제거합니다.따라서, 그룹을 다시 만들기 위해서는 새로운 네모난 괄호에 내용을 포장해야 합니다.이렇게첫 번째iterable의 새 깊이 복사본을 가지고 있습니다. 이 예는 원시 그룹입니다.
원본 그룹이나 복사본을 변경하기로 결정하면, 이 변경은 특정한 그룹에만 적용됩니다.
// Create the original array
const myArray = ['Spread', 'Rest', 'JavaScript']

// Use spread operator to create deep copy of "myArray""
const myDeepCopy = [...myArray]

// Log the content of "myArray"
console.log(myArray)
// Output:
// [ 'Spread', 'Rest', 'JavaScript' ]

// Log the content of "myDeepCopy"
console.log(myDeepCopy)
// Output:
// [ 'Spread', 'Rest', 'JavaScript' ]

// Remove the last item from the original array "myArray"
myArray.pop()

// Log the content of "myArray" again
// The last item is gone as it should
console.log(myArray)
// Output:
// [ 'Spread', 'Rest' ]

// Log the content of "myDeepCopy" again
// The "myDeepCopy" is not affected by change made to "myArray"
// The last item is still there as it should
console.log(myDeepCopy)
// Output:
// [ 'Spread', 'Rest', 'JavaScript' ]

확장 연산자가 있는 객체 문자의 깊이 복사본
배열의 깊이 복사본을 만들 수 있는 것처럼 객체 문자의 깊이 복사본을 만들 수도 있습니다.문법이 거의 같다.복사할 객체 문자의 이름과 함께 이 세 점을 사용해야 합니다.그리고 그것을 새로운 변수에 분배합니다.반드시 이 모든 일을 방괄호 안에 넣어야지, 방괄호 안에 넣어서는 안 된다.
// Create the original array
const myObj = {
  title: 'Guards! Guards!',
  author: 'Terry Pratchett',
}

// Use spread operator to create deep copy of "myObj""
const myDeepCopy = { ...myObj }

// Log the content of "myObj"
console.log(myObj)
// Output:
// { title: 'Guards! Guards!', author: 'Terry Pratchett' }

// Log the content of "myDeepCopy"
console.log(myDeepCopy)
// Output:
// { title: 'Guards! Guards!', author: 'Terry Pratchett' }

// Add new property the original object "myObj"
myObj.format = 'Hardcover'

// Log the content of "myObj" again
// New property is there
console.log(myObj)
// Output:
// {
//   title: 'Guards! Guards!',
//   author: 'Terry Pratchett',
//   format: 'Hardcover'
// }

// Log the content of "myDeepCopy" again
// The "myDeepCopy" still contains only two properties
console.log(myDeepCopy)
// Output:
// { title: 'Guards! Guards!', author: 'Terry Pratchett' }
주의:spread operator를 사용하여 깊이 있는 복사본을 만듭니다. 첫 번째 항목에만 적용됩니다.네스트된 배열 및 객체에는 적용되지 않습니다.이를 위해 const myClone = JSON.parse(JSON.stringify(objToClone))를 사용할 수 있습니다.

확장 산자와 합병
spread 조작부호를 사용하면 두 개 이상의 Iterable를 통합할 수 있습니다.이전에, 예를 들어 두 개 이상의 그룹을 합치려면 concat() 등의 방법을 사용해야 했다.Spread 연산자를 사용하면 동일한 속도로 작업을 완료할 수 있습니다.더 빠르지 않으면문법이 더 간단해요.
이 프로세스는 기존 스토리지를 복제하는 것과 유사합니다.새 배열을 만듭니다.다음은spread 연산자와 통합할 첫 번째 그룹의 이름을 사용합니다.이 수조는 뒤에 쉼표가 있고, 다른 배열은 뒤에 두 번째 수조의 이름이 있다.마지막으로, 당신은 그것을 상대방의 괄호 안에 포장할 것입니다.
결과는 단일 그룹에서 통합하고자 하는 그룹의 모든 항목입니다.
// Create first array
const arrayOne = [1, 2, 3]

// Create second array
const arrayTwo = ['four', 'five', 'six']

// Merge first and second array using spread operator
// Syntax: [...arrayOne, ...arrayTwo, ...arrayThree, etc.]
const arrayMerged = [...arrayOne, ...arrayTwo]

// Log the content of "arrayMerged"
console.log(arrayMerged)
// Output:
// [ 1, 2, 3, 'four', 'five', 'six' ]

확장 연산자를 사용하여 객체 문자 병합
확장 연산자를 사용하여 객체 문자를 결합하는 작업은 배열과 유사합니다.문법상의 유일한 차이점은 네모난 괄호가 아닌 꽃괄호로 모든 것을 포장해야 한다는 것이다.나머지는 모두 같습니다. 결과는 지정한 대상 텍스트의 합병 내용을 포함하는 새로운 대상 텍스트입니다.
// Create first object
const myObjOne = {
  title: 'The Color of Magic',
  author: 'Terry Pratchett',
}

// Create second object
const myObjTwo = {
  publicationDate: '2009',
  format: 'Paperback'
}

// Create third object
const myObjThree = {
  language: 'English',
  genre: 'Fantasy'
}

// Use spread operator to merge "myObjOne", "myObjTwo" and "myObjThree"
const myMergedObj = { ...myObjOne, ...myObjTwo, ...myObjThree }

// Log the content of "myMergedObj"
console.log(myMergedObj)
// Output:
// {
//   title: 'The Color of Magic',
//   author: 'Terry Pratchett',
//   publicationDate: '2009',
//   format: 'Paperback',
//   language: 'English',
//   genre: 'Fantasy'
// }

확장 연산자를 사용하여 데이터 삽입
우리는 확장 연산자를 사용하여 수조와 대상 텍스트에 접근하는 방법을 토론했다.우리는 다시 사용할 수 있는 항목을 복제하고, 심지어는 그것들을 합병하는 데도 그것을 어떻게 사용하는지 토론했다.니가 할 수 있는 전부가 아니야.확장 연산자를 사용하여 데이터를 확장할 수도 있습니다.하나의iterable의 내용을 가져와 다른iterable에 삽입할 수 있습니다.
예를 들어, 어떤 내용을 포함하는 두 개의 그룹이 있다고 가정하십시오.Spread 연산자를 사용하면 컨텐트를 두 번째 위치에 삽입할 수 있습니다.대상 텍스트를 통해 내용을 한 텍스트에서 다른 텍스트의 임의의 위치로 삽입할 수도 있다.또는 객체 문자를 배열에 삽입하거나 배열에 삽입할 수도 있습니다.
// Example no.1: Arrays
// Create first array
const myArrayOne = ['C', 'C++', 'Java']

// Create second array with some content
// plus all the content from "myArrayOne"
const myArrayTwo = ['JavaScript', 'Python', 'PHP', ...myArrayOne, 'Assembly']

// Log the content of "myArrayTwo"
console.log(myArrayTwo)
// Output:
// [ 'JavaScript', 'Python', 'PHP', 'C', 'C++', 'Java', 'Assembly' ]


// Example no.2: Object literals
// Create first object literal
const myObjOne = {
  numOfPages: 706,
  publisher: 'O\'Reilly Media'
}

// Create second object literal with some content
// plus all the content from "myObjOne"
const myObjTwo = {
  title: 'JavaScript: The Definitive Guide',
  author: 'David Flanagan',
  ... myObjOne, // insert the content of "myObjOne"
  language: 'English'
}

// Log the content of "myObjTwo"
console.log(myObjTwo)
// Output:
// {
//   title: 'JavaScript: The Definitive Guide',
//   author: 'David Flanagan',
//   numOfPages: 706,
//   publisher: "O'Reilly Media",
//   language: 'English'
// }

확장 연산자 및 함수 매개변수
spread 연산자를 사용하여iterable의 내용에 접근할 때, 내용만 되돌려줍니다.배열의 경우 주위의 네모난 괄호를 삭제하고 객체 문자의 경우 중괄호를 삭제합니다.매개 변수가 있는 함수를 호출하고 싶을 때, 이것은 매우 편리하다.
매개 변수를 하나씩 전달하는 것이 아니라 하나의 그룹에서 모든 매개 변수를 전달할 수 있습니다. 그룹의 모든 매개 변수 앞에는 확장 연산자가 있습니다.결과는 모든 매개 변수를 하나씩 전달하는 것과 같다.
// Create an array with something
// that will be used as arguments
const myArgs = ['Jack', 'Joe', 'Tony']

// Create a simple function
// that will return all arguments one by one
function sayNames(name1, name2, name3) {
  return `Names you passed are ${name1}, ${name2} and ${name3}.`
}

// Call sayNames() function using spread operator
// to pass in content of "myArgs" as arguments
sayNames(...myArgs)
// Output:
// 'Names you passed are Jack, Joe and Tony.'
여러 개의 값을 매개 변수로 받아들이는 수학 함수에서spread 연산자를 사용하여 이 값을 전달할 수 있습니다.
// Create an array with numbers
const numbers = [15, 3, -5, 84, 653, Infinity]

// Get the highest number inside "numbers"
const highestNumber = Math.max(...numbers)

// Get the lowest number inside "numbers"
const lowestNumber = Math.min(...numbers)

// Log the value of "highestNumber"
console.log(highestNumber)
// Output:
// Infinity

// Log the value of "lowestNumber"
console.log(lowestNumber)
// Output:
// -5

문자열에 확장 연산자 사용
이 강좌의 시작 부분에서, 우리는spread 조작부호를iterable 대상에 사용할 수 있음을 토론했다.응, 오직 그들과 함께 있을 뿐이야.내가 말했듯이, 그중의iterables도 문자열이다.이것은 이상하게 들릴 수도 있지만, 이것은 정말이다.JavaScript에서는 문자열에 확장 연산자를 사용할 수 있습니다.
문자열에spread를 사용할 때 결과는 사용 split() 방법과 같습니다.다시 말하면spread 연산자는 문자열을 그룹으로 변환합니다.단어, 숫자, 공백 등 단일 문자 형식의 문자열을 얻을 수 있습니다.
// Create some text
const text = 'Sunny day.'

// Use spread to convert the string into an array
const processedText = [...text]

// Log the content
console.log(processedText)
// Output:
// [ 'S', 'u', 'n', 'n', 'y', ' ', 'd', 'a', 'y', '.' ]

결론: JavaScript spread 연산자가 무엇인지, 어떻게 작동하는지, 그리고 그것을 어떻게 사용하는지
JavaScript 확장 연산자는 사용하기 쉽습니다.그것은 네가 소량의 코드로 많은 일을 할 수 있도록 허락한다.이 자습서는 JavaScript 확장 연산자가 무엇인지, 어떻게 작동하는지, 어떻게 사용하는지 이해하는 데 도움을 줄 수 있기를 바랍니다.

좋은 웹페이지 즐겨찾기