diff options
Diffstat (limited to 'files/ko/web/javascript')
572 files changed, 82607 insertions, 0 deletions
diff --git a/files/ko/web/javascript/about/index.html b/files/ko/web/javascript/about/index.html new file mode 100644 index 0000000000..c7ec0f9f28 --- /dev/null +++ b/files/ko/web/javascript/about/index.html @@ -0,0 +1,58 @@ +--- +title: JavaScript에 대하여 +slug: Web/JavaScript/About +tags: + - 비기너 + - 소개 + - 자바스크립트 +translation_of: Web/JavaScript/About_JavaScript +--- +<p>{{JsSidebar}}</p> + +<h2 id="JavaScript란_무엇인가">JavaScript란 무엇인가?</h2> + +<p><strong>JavaScript</strong><sup>®</sup> (줄여서 <strong>JS</strong>)는 일급 함수를 사용하는 가벼운 객체 지향 인터프리터 언어이며 웹페이지의 스크립트 언어로 잘 알려져 있지만, 브라우저가 아닌 환경에서도 많이 사용된다. 프로토타입 기반, 다중 패러다임 스크립트 언어이며, 동적이고 명령어, 객체 지향, 함수 프로그래밍 스타일을 지원한다.</p> + +<p>자바스크립트는 클라이언트 측 웹(브라우저)에서 실행 되고, 웹 페이지가 이벤트 발생시 어떻게 작동하는 지 디자인 / 프로그래밍할 수 있다. 자바스크립트는 쉽게 배울 수 있고 강력한 스크립트 언어로 웹 페이지 동작을 제어하는 데 널리 사용된다.</p> + +<p>대중적인 오해와 달리, <strong>Javascript는 인터프리트 형태 자바가 아니다. </strong>간단히 말하면, Javascript는 프로토 타입 기반 객체 생성을 지원하는 동적 스크립트 언어이다. <span style="line-height: 1.5;">기본적인 문법은 언어 학습에 필요한 새로운 개념을 줄이기 위해 Java와 C++의 if문, for와 while문, switch문과 try...catch 구문을 사용하는 언어구조를 사용하며, 그와 같은 (거의 가까운) 동작을 한다. </span></p> + +<p style="padding-right: 0px; padding-left: 0px; padding-bottom: 0px; margin: 0px 0px 1.7em; padding-top: 0px;">Javascript는 <a class="external" href="http://www.instantweb.com/%7Efoldoc/foldoc.cgi?query=procedural&action=Search">절차지향 (procedural)</a> 언어와 <a class="external" href="http://www.instantweb.com/%7Efoldoc/foldoc.cgi?query=object+oriented&action=Search">객체지향 (object oriented)</a> 언어 두가지 형태로 만들수 있다. 자바스크립트에서 객체는 실시간으로 빈 객체를 오버라이딩하여 메소드와 프로퍼티를 연결하는 (프로그래밍)방식으로 생성된다. <span style="line-height: 1.5;">C++ 및 Java와 같은 컴파일 언어에서 공통적인 구문 클래스 정의와 반대되는 개념이다. 한번 객체가 생성하면, 비슷한 객체를 생성할 때 프로토타입으로 사용할 수 있다.</span></p> + +<p style="padding-right: 0px; padding-left: 0px; padding-bottom: 0px; margin: 0px 0px 1.7em; padding-top: 0px;">JavaScript의 동적인 성질은, 실행시의 오브젝트 구축, 가변 인수 리스트, 함수 변수, (eval 에 의한)동적 스크립트 작성, (for ... in 에 의한) 오브젝트의 내부참조, 또는 소스코드 복원 (JavaScript 의 프로그램은 함수본체를 소스텍스트에 역컴파일할 수 있다.) 을 포함하고 있다.</p> + +<p style="padding-right: 0px; padding-left: 0px; padding-bottom: 0px; margin: 0px 0px 1.7em; padding-top: 0px;">자바스크립트 프로그래밍에 대한 더 자세한 설명은 아래의 <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/About#JavaScript_%EC%9E%90%EC%9B%90">자바스크립트 리소스</a> 링크를 참조하면 된다.</p> + +<h2 id="어떠한_JavaScript_구현이_유용한가">어떠한 JavaScript 구현이 유용한가?</h2> + +<p style="padding-right: 0px; padding-left: 0px; padding-bottom: 0px; margin: 0px 0px 1.7em; padding-top: 0px;">Mozilla 프로젝트는 두 가지 자바스크립트 구현을 제공한다. 최초의 Javascript는 Netscape의 Brendan Eich에 의해 만들었다. 이후 ECMA-262 에디션 5 와 최신 버전을 준수하도록 업데이트되었다. <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey" title="en-US/docs/SpiderMonkey">SpiderMonkey</a> 라는 이름의 엔진은 C/C++로 구현되었다. <a href="https://developer.mozilla.org/en-US/docs/Rhino" title="en-US/docs/Rhino">Rhino</a> 엔진은 주로 Norris Boys(또한 Netscape)가 만들었고 Java로 작성된 Javascript 구현체이다. SpiderMonkey와 마찬가지로 Rhino도 ECMA-262 에디션 5를 준거한다.</p> + +<p style="padding-right: 0px; padding-left: 0px; padding-bottom: 0px; margin: 0px 0px 1.7em; padding-top: 0px;">TraceMonkey (Firefox 3.5), JägerMonkey (Firefox 4) 그리고 IonMonkey와 같은 몇가지 주요한 실시간 최적화는 차츰 SpiderMonkey 자바스크립트 엔진에 추가되었다. 자바스크립트 실행 성능 향상을 위한 작업은 지금도 진행 중이다.</p> + +<p style="padding-right: 0px; padding-left: 0px; padding-bottom: 0px; margin: 0px 0px 1.7em; padding-top: 0px;">위의 구현 이외에도 다음과 같은 다른 인기있는 자바스크립트 엔진이 있다.</p> + +<ul> + <li style="padding: 0px; margin: 0px 0px 1.7em;">구글의 <a href="https://code.google.com/p/v8/" title="https://code.google.com/p/v8/">V8</a> 은 크롬 브라우저와 최신 버전의 오페라 브라우저에 사용된다. 또 Node.js의 엔진으로 사용된다.</li> + <li style="padding: 0px; margin: 0px 0px 1.7em;"><a href="https://www.webkit.org/projects/javascript/index.html" title="https://www.webkit.org/projects/javascript/index.html">JavaScriptCore</a> (SquirrelFish/Nitro) 는 Apple 사파리와 같은 일부 WebKit 브라우저에서 사용된다.</li> + <li style="padding: 0px; margin: 0px 0px 1.7em;"><a href="http://my.opera.com/ODIN/blog/carakan-faq" title="http://my.opera.com/ODIN/blog/carakan-faq">Carakan</a> 는 오페라의 예전 버전안에 있다.</li> + <li style="padding: 0px; margin: 0px 0px 1.7em;"><a href="http://en.wikipedia.org/wiki/Chakra_%28JScript_engine%29" title="http://en.wikipedia.org/wiki/Chakra_%28JScript_engine%29">Chakra</a> 엔진은 Internet Explorer에서 사용된다. (상표권 문제를 피하기 위해 공식적으로 "JScript"라고 불린다.)</li> +</ul> + +<p style="padding-right: 0px; padding-left: 0px; padding-bottom: 0px; margin: 0px 0px 1.7em; padding-top: 0px;">mozilla.org의 각 JavaScript 엔진은, 애플리케이션이 JavaScript를 지원하기 위해 부를 수 있는 공개 API를 공개하고 있다. JavaScript 를 지원하는 가장 일반적인 호스트환경은 웹브라우저이다. 웹 브라우저는 일반적으로 공개 API를 사용하여 <a class="external external-icon" href="http://www.w3.org/DOM/">DOM</a>을 Javascript로 반영하는 <strong>호스트 객체</strong>를 만든다.</p> + +<p style="padding-right: 0px; padding-left: 0px; padding-bottom: 0px; margin: 0px 0px 1.7em; padding-top: 0px;">JavaScript 의 또 다른 일반적인 애플리케이션은 (웹) 서버사이드 스크립팅 언어이다. 자바스크립트 웹 서버는 HTTP 요청 및 응답 객체를 나타내는 호스트 객체를 공개하며 자바 스크립트 프로그램에 의해 조작되어 웹 페이지를 동적으로 생성 할 수 있다. <a href="http://nodejs.org/">Node.js</a>는 이에 대한 대중적인 예이다.</p> + +<h2 id="JavaScript_자원">JavaScript 자원</h2> + +<dl style="padding-right: 0px; padding-left: 0px; padding-bottom: 0px; margin: 0px 0px 1.7em; padding-top: 0px;"> + <dt style="font-weight: bold; font-style: normal;"><a href="https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey" title="en-US/docs/SpiderMonkey">SpiderMonkey</a></dt> + <dd style="padding-left: 15px; margin-bottom: 0.5em; margin-left: 0px;">애플리케이션에 임베드하는 방법을 포함하는, C/C++ 엔진(SpiderMonkey)으로 구현된 Mozilla의 JavaScript 구현체에 관한 정보.</dd> + <dt style="font-weight: bold; font-style: normal;"><a href="https://developer.mozilla.org/en-US/docs/Rhino" title="en-US/docs/Rhino">Rhino</a></dt> + <dd style="padding-left: 15px; margin-bottom: 0.5em; margin-left: 0px;">Java(Rhino)로 작성된 자바스크립트 구현체에 관련 정보.</dd> + <dt style="font-weight: bold; font-style: normal;"><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Language_Resources" title="en-US/docs/JavaScript_Language_Resources">Language resources</a></dt> + <dd style="padding-left: 15px; margin-bottom: 0.5em; margin-left: 0px;">자바스크립트 표준을 출판하기 위한 포인터들.</dd> + <dt style="font-weight: bold; font-style: normal;"><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript" title="en-US/docs/A_re-introduction_to_JavaScript">A re-introduction to JavaScript</a></dt> + <dd style="padding-left: 15px; margin-bottom: 0.5em; margin-left: 0px;"><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide" title="en-US/docs/JavaScript/Guide">자바스크립트 가이드</a>와 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference" title="en-US/docs/JavaScript/Reference">자바스크립트 레퍼런스</a>.</dd> +</dl> + +<p>JavaScript® 는 미국 및 여러 나라의 Oracle 트레이드마크 또는 등록된 트레이드마크입니다.</p> diff --git a/files/ko/web/javascript/data_structures/index.html b/files/ko/web/javascript/data_structures/index.html new file mode 100644 index 0000000000..14967ae250 --- /dev/null +++ b/files/ko/web/javascript/data_structures/index.html @@ -0,0 +1,221 @@ +--- +title: 자바스크립트의 자료형 +slug: Web/JavaScript/Data_structures +translation_of: Web/JavaScript/Data_structures +--- +<div>{{jsSidebar("More")}}</div> + +<p>모든 프로그래밍 언어는 내장 자료형이 있지만, 종종 이러한 내장 자료형은 언어마다 다르다. 이 문서에서는 자바스크립트의 내장 자료형과, 내장 자료형에서 사용할 수 있는 속성들에 대해 알아본다. 이로써 내장 자료형들로 더 복잡한 자료형을 만드는데 사용할 수 있을 것이다. 가능하다면 다른 언어와도 비교해보자.</p> + +<h2 id="동적_타이핑">동적 타이핑</h2> + +<p>자바스크립트는 <em>느슨한 타입 (loosely typed)</em> 언어, 혹은 <em>동적 (dynamic)</em> 언어이다. 그 말은, 변수의 타입을 미리 선언할 필요가 없다는 뜻이다. 타입은 프로그램이 처리되는 과정에서 자동으로 파악될 것이다. 또한 그 말은 같은 변수에 여러 타입의 값을 넣을 수 있다는 뜻이다.</p> + +<pre class="brush: js notranslate">var foo = 42; // foo 는 이제 Number 임 +var foo = "bar"; // foo 는 이제 String 임 +var foo = true; // foo 는 이제 Boolean 임 +</pre> + +<h2 id="데이터_타입">데이터 타입</h2> + +<p>최신 ECMAScript 표준은 다음과 같은 7개의 자료형을 정의한다.</p> + +<ul> + <li>{{Glossary("Primitive", "기본 자료형 (Primitive)")}} 인 여섯가지 데이터 타입 + <ul> + <li>{{Glossary("Boolean")}}</li> + <li>{{Glossary("Null")}}</li> + <li>{{Glossary("Undefined")}}</li> + <li>{{Glossary("Number")}}</li> + <li>{{Glossary("String")}}</li> + <li>{{Glossary("Symbol")}} (ECMAScript 6 에 추가됨)</li> + </ul> + </li> + <li>별도로 {{Glossary("Object")}} 도 있음</li> +</ul> + +<p>다음 장에서 이 여섯개의 자료형을 사용하는 방법과 자료형을 조합하여 더 복잡한 자료형을 만드는 방법에 대해 알아보자.</p> + +<h2 id="기본_타입_Primitive_value">기본 타입 (Primitive value)</h2> + +<p>오브젝트를 제외한 모든 값은 변경 불가능한 값 (immutable value) 이다. 예를 들자면, 특히 C 언어와는 다르게도, 문자열은 불변값 (immutable) 이다. 이런 값을 "primitive values" 라고 일컫는다. 아래의 {{ anch("Strings") }} 장에서 더 자세히 설명할 것이다.</p> + +<h3 id="Boolean_타입">Boolean 타입</h3> + +<p>Boolean 은 논리적인 요소를 나타내고, <code>true</code> 와 <code>false</code> 의 두 가지 값을 가질 수 있다.</p> + +<h3 id="Null_타입">Null 타입</h3> + +<p>Null 타입은 딱 한 가지 값, <code>null</code> 을 가질 수 있다. 더 알아보려면 {{jsxref("null")}} 와 {{Glossary("Null")}} 을 보라.</p> + +<h3 id="Undefined_타입">Undefined 타입</h3> + +<p>값을 할당하지 않은 변수는 <code>undefined</code> 값을 가진다. 더 알아보려면 {{jsxref("undefined")}} 와 {{Glossary("Undefined")}} 을 보라.</p> + +<h3 id="Number_타입">Number 타입</h3> + +<p>ECMAScript 표준에 따르면, 숫자의 자료형은 <a href="https://en.wikipedia.org/wiki/Double-precision_floating-point_format">배정밀도 64비트 형식 IEEE 754 값</a> (-(2<sup>53</sup> -1) 와 2<sup>53</sup> -1 사이의 숫자값) 단 하나만 존재한다. <strong>정수만을 표현하기 위한 특별한 자료형은 없다.</strong> 부동 소수점을 표현할 수 있는 것 말고도, Number 타입은 세 가지 의미있는 몇가지 상징적인 값들도 표현할 수 있다. 이 값에는 <code>+무한대</code>, <code>-무한대</code>, and <code><a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/NaN">NaN</a></code> (숫자가 아님)이 있다.</p> + +<p><code>+/-Infinity</code> 보다 크거나 작은지 확인하는 용도로 상수값인 {{jsxref("Number.MAX_VALUE")}} 나 {{jsxref("Number.MIN_VALUE")}} 을 사용할 수 있다. 또한, ECMAScript 6 부터는 숫자가 배정밀도 부동소수점 숫자인지 확인하는 용도로 {{jsxref("Number.isSafeInteger()")}} 과 {{jsxref("Number.MAX_SAFE_INTEGER")}}, {{jsxref("Number.MIN_SAFE_INTEGER")}} 을 사용할 수 있다. 이 범위를 넘어서면, 자바스크립트의 숫자는 더 이상 안전하지 않다.</p> + +<p>Number 타입의 값 중에는 두 가지 방식으로 표현할 수 있는 유일한 값이 있는데, 0 이다. 0 은 -0 이나 +0 으로 표시할 수 있다. ("0" 은 물론 +0 이다.) 실제로는 이러한 사실은 거의 효력이 없다. 그 예로, <code>+0 === -0</code> 은 <code>true</code> 이다. 하지만 0으로 나누는 경우 그 차이가 눈에 띌 것이다.</p> + +<pre class="brush: js language-js notranslate"><code class="language-js"><span class="operator token">></span> <span class="number token">42</span> <span class="operator token">/</span> <span class="operator token">+</span><span class="number token">0</span> +<span class="number token">Infinity</span> +<span class="operator token">></span> <span class="number token">42</span> <span class="operator token">/</span> <span class="operator token">-</span><span class="number token">0</span> +<span class="operator token">-</span><span class="number token">Infinity</span></code></pre> + +<p>숫자가 보통 값만으로 표현되긴 하지만, 자바스크립트는 <a href="/en/JavaScript/Reference/Operators/Bitwise_Operators" title="en/JavaScript/Reference/Operators/Bitwise_Operators">몇 가지 이진 연산자</a>도 제공한다. 이러한 이진 연산자들은 <a class="external" href="http://en.wikipedia.org/wiki/Mask_%28computing%29">비트 마스킹(bit masking)</a> 기법으로 한 숫자 안에 여러 Boolean 값을 저장하는데도 쓸 수 있다. 일반적으로 이런 방법은 나쁜 방법이지만, 자바스크립트에서는 (Boolean 값의 배열이나 Boolean 값들을 이름있는 속성들로 가지는 객체 같은) Boolean 덩어리를 나타낼 다른 방법이 없다. 비트 마스킹은 또한 코드를 이해하고, 읽고, 유지보수하는데에 있어서 좀 더 어렵게 만드는 경향이 있다. 하지만 이러한 기법은 local storage 의 저장공간이 부족해서 절약하려고 하거나, 네트워크 상에서 각각의 비트를 전송하는 등의 극단적인 상황 같은 굉장히 제한적인 환경에서 필요할 수도 있다. 그래서 비트 마스킹 기법은 크기를 최대한 줄여야하는 상황에서만 사용을 고려해야 한다.</p> + +<h3 id="String_타입">String 타입</h3> + +<p>자바스크립트의 {{jsxref("Global_Objects/String", "String")}} 타입은 텍스트 데이터를 나타내는데 사용한다. 이는 16비트 부호없는 정수 값 요소들의 집합이다. String의 각 요소는 String의 위치를 차지한다. 첫 번째 요소는 0번 인덱스에 있고, 다음 요소는 1번, 그 다음 요소는 2번... 같은 방식이다. String 의 길이는 String이 가지고있는 요소의 갯수이다.</p> + +<p>C 같은 언어와는 다르게, 자바스크립트의 문자열은 변경 불가능 (immutable) 하다. 이것은 한 번 문자열이 생성되면, 그 문자열을 수정할 수 없다는걸 의미한다. 그러나 원래 문자열에서 일부가 수정된 다른 문자열을 만드는건 가능하다. 예를 들자면 이렇다.</p> + +<ul> + <li>원래 문자열에서 각각의 글자를 추출하거나 <code><a href="/en/JavaScript/Reference/Global_Objects/String/substr" title="substr">String.substr()</a></code>을 사용해서 만든 부분 문자열</li> + <li>접합 연산자 (<code>+</code>) 나 <code><a href="/en/JavaScript/Reference/Global_Objects/String/concat" title="concat">String.concat()</a></code> 으로 두 문자열을 합친 문자열</li> +</ul> + +<h4 id="문자열의_자료형화를_조심하라!">"문자열의 자료형화"를 조심하라!</h4> + +<p>문자열을 복잡한 자료형을 표현하는 용도로 쓰는 방법이 꽤나 매력적일 수 있다. 단기적으로 이런 장점들이 있다.</p> + +<ul> + <li>접합 연산자로 손쉽게 복잡한 문자열을 만들 수 있다.</li> + <li>문자열은 디버깅이 쉽다 (화면에 출력한 내용이 문자열 변수에 있는 값과 같다)</li> + <li>문자열은 많은 API 에서 사용하는 공통분모이고 (<a href="/en/DOM/HTMLInputElement" title="HTMLInputElement">입력 필드</a>, <a href="/en/Storage" title="Storage">로컬 스토리지</a> 값, {{ domxref("XMLHttpRequest") }} 요청에서 <code>responseText</code>를 사용할 때 등) 그러다보니 문자열만으로 작업하는게 매혹적일 수 있다.</li> +</ul> + +<p>규칙만 잘 정의해놓는다면, 어떤 자료구조가 되던 문자열로 표시할 수 있다. 그렇다고 해서 이게 좋은 방법이 되는 건 아니다. 예를 들자면, 구분자로 리스트 자료형을 흉내낼 수 있을 것이다 (하지만 자바스크립트의 배열을 사용하는게 더 알맞을 것이다). 불행하게도, 리스트의 요소중에 구분자가 들어있는 요소가 있다면 리스트는 엉망진창이 될 것이다. 물론 탈출 문자 (escape character) 등을 사용하거나 할 수도 있을 것이다. 하지만 이런 것들은 모두 미리 정해놓은 규칙을 필요로 하고, 덕분에 불필요한 관리 부담을 낳는다.</p> + +<p>문자열은 텍스트 데이터에만 사용하자. 복잡한 데이터를 나타낼때는, 문자열을 분석해서 적합한 추상화를 선택해 사용하자.</p> + +<h3 id="Symbol_타입">Symbol 타입</h3> + +<p>Symbol 은 ECMAScript 6 에서 추가되었다. Symbol은 <strong>유일</strong>하고 <strong>변경 불가능한</strong> (immutable) 기본값 (primitive value) 이다. 또한, 객체 속성의 key 값으로도 사용될 수 있다 (아래를 볼 것). 몇몇 프로그래밍 언어에서는 Symbol을 atom 이라고 부른다. 또, C 언어의 이름있는 열거형 (enum) 과도 비슷하다. 좀 더 자세히 알아보려면, 자바스크립트의 {{Glossary("Symbol")}} 와 {{jsxref("Symbol")}} 객체 래퍼 (wrapper) 를 보라.</p> + +<h2 id="객체_Objects">객체 (Objects)</h2> + +<p>컴퓨터 과학에서, 객체는 {{Glossary("Identifier", "식별자 (Identifier)")}} 로 참조할 수 있는, 메모리에 있는 값이다.</p> + +<h3 id="속성_Properties">속성 (Properties)</h3> + +<p>자바스크립트에서, 객체는 속성들을 담고있는 가방 (collection) 으로 볼 수 있다. <a href="/en/JavaScript/Guide/Values,_variables,_and_literals#Object_literals" title="en/JavaScript/Guide/Values,_variables,_and_literals#Object_literals">객체 리터럴 문법 (object literal syntax)</a> 으로 제한적으로 몇 가지 속성을 초기화할 수 있고, 그러고 나서 속성들을 추가하거나 제거할 수도 있다. 속성 값은 객체를 포함해 어떠한 자료형도 될 수 있고, 그 덕분에 복잡한 데이터 구조를 형성하는게 가능해진다. 속성은 키 (key) 값으로 식별된다. 키 값은 String 이거나 Symbol 값이다.</p> + +<p>두 종류의 객체 속성이 있는데, 이들은 종류에 따라 특성값들을 가질 수 있다. 데이터 (data) 속성과 접근자 (accessor) 속성이 그것이다.</p> + +<h4 id="데이터_속성_Data_property">데이터 속성 (Data property)</h4> + +<p>키에 값을 연결하고, 아래와 같은 특성들 (attribute) 이 있다.</p> + +<table class="standard-table"> + <caption>데이터 속성의 특성들</caption> + <tbody> + <tr> + <th>특성 (Attribute)</th> + <th>자료형</th> + <th>설명</th> + <th>기본값</th> + </tr> + <tr> + <td>[[Value]]</td> + <td>JavaScript 타입 모두 가능</td> + <td>이 속성에 대한 get 접근으로 반환되는 값.</td> + <td>undefined</td> + </tr> + <tr> + <td>[[Writable]]</td> + <td>Boolean</td> + <td><code>false</code> 라면, 이 속성의 [[Value]] 을 바꿀 수 없다.</td> + <td>false</td> + </tr> + <tr> + <td>[[Enumerable]]</td> + <td>Boolean</td> + <td><code>true</code> 라면, 이 속성은 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in">for...in</a> 루프에서 열거될 수 있다.</td> + <td>false</td> + </tr> + <tr> + <td>[[Configurable]]</td> + <td>Boolean</td> + <td><code>false</code> 라면, 이 속성은 제거될 수 없고, [[Value]]와 [[Writable]] 외에는 수정될 수 없다.</td> + <td>false</td> + </tr> + </tbody> +</table> + +<h4 id="접근자_속성_Accessor_property">접근자 속성 (Accessor property)</h4> + +<p>값을 가져오거나 값을 저장하기 위해 키에 하나 혹은 두 개의 접근자 함수 (get, set) 연결짓는다. 아래와 같은 특성이 있다.</p> + +<table class="standard-table"> + <caption>접근자 속성</caption> + <tbody> + <tr> + <th>특성 (Attribute)</th> + <th>자료형</th> + <th>설명</th> + <th>기본값</th> + </tr> + <tr> + <td>[[Get]]</td> + <td>Function 객체 혹은 undefined</td> + <td>이 속성의 값에 접근할 때마다, 인자 목록 없이 함수가 호출되고, 함수의 반환된 값으로 속성값을 가져온다. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/get"><code>get</code></a> 을 볼 것</td> + <td>undefined</td> + </tr> + <tr> + <td>[[Set]]</td> + <td>Function 객체 혹은 undefined</td> + <td> + <p>이 속성의 값이 바뀌려고 할 때마다, 할당된 값을 인자로 함수가 호출된다. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/set"><code>set</code></a> 을 볼 것</p> + </td> + <td>undefined</td> + </tr> + <tr> + <td>[[Enumerable]]</td> + <td>Boolean</td> + <td><code>true</code> 라면, 이 속성은 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in">for...in</a> 루프에서 열거될 수 있다.</td> + <td>false</td> + </tr> + <tr> + <td>[[Configurable]]</td> + <td>Boolean</td> + <td><code>false</code> 라면, 이 속성은 제거될 수 없고, 데이터 속성을 수정할 수 없다.</td> + <td>false</td> + </tr> + </tbody> +</table> + +<h3 id="Normal_objects_and_functions">"Normal" objects, and functions</h3> + +<p>자바스크립트 오브젝트는 키와 값의 매핑이다. 키는 문자열이고 값은 다른 어떤 값도 될 수 있다. 오브젝트는 <a class="external" href="http://en.wikipedia.org/wiki/Hash_table">hashmaps</a>을 표현하는데 적합하다. 표준이 아닌 <a href="/en/JavaScript/Reference/Global_Objects/Object/proto" title="__proto__">__proto__</a> 슈도 프로퍼티를 사용할 때는 주의하자. 이것을 지원하는 환경에서는 <code>'__proto__'는 오브젝트의 프로토타입을 의미하므로 이 이름을 키로 사용할 수 없다. 속성을 사용할 수 없다. 문자열의 출처가 분명하지 않을 때(입력 필드의 입력값 등)</code>주의가 필요하다. <a class="external" href="http://productforums.google.com/forum/#!category-topic/docs/documents/0hQWeOvCcHU">이런 일이 생길 수도 있다</a>. 이 때는 <a class="external" href="http://code.google.com/p/google-caja/source/browse/trunk/src/com/google/caja/ses/StringMap.js?r=4779">StringMap abstraction</a> 같은 대안을 사용해보자.함수는 일반 오브젝트에서 호출 가능한 특성을 추가한 오브젝트이다.</p> + +<h3 id="Dates">Dates</h3> + +<p>시간을 나타내려면 <a href="/en/JavaScript/Reference/Global_Objects/Date" title="en/JavaScript/Reference/Global_Objects/Date">Date utility</a>를 사용하자. 최고의 선택이다.</p> + +<h3 id="Arrays">Arrays</h3> + +<p><a href="/en/JavaScript/Reference/Global_Objects/Array" title="Array">배열(Arrays</a>) 는 정수키를 가지는 일련의 값들을 표현하기 위한 오브젝트이다. 배열 오브젝트에는 길이를 나타내는 'length'란 속성도 있다. 배열은 Array.prototype을 상속받으므로 배열을 다룰 때 편한 <a href="/en/JavaScript/Reference/Global_Objects/Array/indexOf" title="en/JavaScript/Reference/Global_Objects/Array/indexOf">indexOf</a> (배열에서 값 검색)와 <a href="/en/JavaScript/Reference/Global_Objects/Array/push" title="en/JavaScript/Reference/Global_Objects/Array/push">push</a> (새로운 값 추가) 같은 함수를 사용할 수 있다. 배열은 리스트나 집합을 표현하는데 적합하다.</p> + +<h3 id="WeakMaps_Maps_Sets">WeakMaps, Maps, Sets</h3> + +<p>표준이 아니지만 ECMAScript 6에서 표준이 될 것 같다.</p> + +<p>이 자료형들에서는 키가 문자열 뿐만 아니라 오브젝트도 될 수 있다. Set은 오브젝트의 집합을 나타내는 반면에 WeakMaps와 Maps는 오브젝트에 값을 연관시킬 수 있다. Map과 WeakMap의 차이는 전자는 오브젝트 키를 열거할 수 있다는 것이다. 이것은 가비지 콜렉션에서 이점을 준다.</p> + +<p>ECMAScript 5를 이용해서 Map과 Set을 구현할 수 있을 것이다. 그러나 오브젝트는 크기 비교가 안된다는 점 때문에(예를들어 어떤 오브젝트는 다른 오브젝트보다 '작다'라고 할 수 없다) look-up에 소요되는 시간이 선형 시간이지 않을 것이다. 네이티브 구현은(WeakMaps를 포함해서) look-up 시간이 거의 로그 시간에서 상수 시간이다.</p> + +<p>DOM 노드에 데이터를 지정하기 위해서 직접 속성을 지정할 수도 있지만 data-* 속성을 사용할 수도 있다. 여기에는 다른 스크립트도 모두 그 속성에 접근할 수 있다는 나쁜 점이 있다. Map과 WeakMap은 오브젝트만 사용할 수 있는 개인 데이터를 쉽게 만들 수 있게 해준다.</p> + +<h3 id="TypedArrays">TypedArrays</h3> + +<p>표준이 아니지만 ECMAScript 6에서 표준이 될 것 같다.</p> + +<h2 id="더_보기">더 보기</h2> + +<ul> + <li><a class="link-https" href="https://github.com/nzakas/computer-science-in-javascript/">Nicholas Zakas collection of common data structure and common algorithms in JavaScript.</a></li> +</ul> diff --git a/files/ko/web/javascript/differential_inheritance_in_javascript/index.html b/files/ko/web/javascript/differential_inheritance_in_javascript/index.html new file mode 100644 index 0000000000..70fd4256c3 --- /dev/null +++ b/files/ko/web/javascript/differential_inheritance_in_javascript/index.html @@ -0,0 +1,63 @@ +--- +title: Differential inheritance in JavaScript +slug: Web/JavaScript/Differential_inheritance_in_JavaScript +translation_of: Web/JavaScript/Differential_inheritance_in_JavaScript +--- +<h2 id="Introduction">Introduction</h2> + +<p>차등 상속(Differential Inheritance)은 자바 스크립트와 같은 프로토 타입 기반 프로그래밍 언어에서 사용되는 일반적인 상속 모델입니다. 대부분의 객체는 다른 일반적인 객체에서 파생되고 몇 가지 작은 측면에서만 차이가 있다는 원칙에 따라 동작합니다. 일반적으로 객체가 다른 다른 객체에 대한 포인터 목록을 내부적으로 유지합니다.</p> + +<h2 id="Example">Example</h2> + + + +<p>다음 코드는 개체를 "상속"하는 간단한 메서드 예제입니다.</p> + +<pre class="brush: js notranslate">Object.prototype.inherit = function(){ + // Create a new object with this as its prototype + var p = Object.create(this); + + /* actually not necessary: + // Apply the constructor on the new object + this.constructor.apply(p, arguments); + */ + + return p; +}; +</pre> + +<p>상속(<font face="Consolas, Liberation Mono, Courier, monospace">inherit)</font>을 사용하면 일반 프로토 타입에서보다 구체적인 개체를 간단히 파생시킬 수 있습니다. 다음은 상속 방법 및 차등 상속을 사용하여 점점 더 구체적인 객체를 구성하는 간단한 예입니다.</p> + +<pre class="brush: js notranslate">var root = {}; // Could be any object with any prototype object + +var record = root.inherit(); +record.toString = function(){ return "a Record"; }; + +var person = root.inherit(); +person.firstName = false; +person.lastName = false; +person.toString = function(){ + if (this.firstName) { + if (this.lastName) { + return this.firstName + " " + this.lastName; + } else { + return this.firstName; + } + } else if (this.lastName) { + return this.lastName; + } else { + return "a Person"; + } +}; + +JoePerson = person.inherit(); +JoePerson.firstName = "Joe"; +alert( JoePerson.toString() ); +</pre> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en/JavaScript/Reference/Global_Objects/Object/create" title="create">Object.create</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain">inheritance and the prototype chain</a></li> +</ul> diff --git a/files/ko/web/javascript/enumerability_and_ownership_of_properties/index.html b/files/ko/web/javascript/enumerability_and_ownership_of_properties/index.html new file mode 100644 index 0000000000..41252c39d1 --- /dev/null +++ b/files/ko/web/javascript/enumerability_and_ownership_of_properties/index.html @@ -0,0 +1,331 @@ +--- +title: Enumerability and ownership of properties +slug: Web/JavaScript/Enumerability_and_ownership_of_properties +translation_of: Web/JavaScript/Enumerability_and_ownership_of_properties +--- +<div>{{JsSidebar("More")}}</div> + + + +<p>'Enumerable properties'(열거 가능한 속성)는 내부 열거 형 플래그가 true로 설정된 property로, 이는 간단한 할당 또는 property initializer (<a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty</a>를 통해 정의 된 특성 및 이러한 기본 열거 형을 false로 정의한 특성)를 통해 작성된 property의 기본값입니다. 등록 정보의 키가 <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol">Symbol</a>이 아니면 열거 가능한 등록 정보가 <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in">for...in</a> 루프에 표시됩니다. 'Ownership of properties' (속성의 소유권)은 속성이 프로토 타입 체인이 아닌 개체에 직접 속하는지 여부에 따라 결정됩니다. 객체의 속성도 전체적으로 검색 할 수 있습니다. 개체 속성을 감지, 반복 / 열거 및 검색하는 여러 가지 기본 제공 방법이 있으며 아래 표와 같이 사용할 수 있습니다. 누락 된 범주를 얻는 방법을 보여주는 샘플 코드는 다음과 같습니다.</p> + +<div style="overflow: auto; width: 100%;"> +<table> + <caption>Property enumerability and ownership - built-in methods of detection, retrieval, and iteration</caption> + <tbody> + <tr> + <th>Functionality</th> + <th>Own object</th> + <th>Own object and its prototype chain</th> + <th>Prototype chain only</th> + </tr> + <tr> + <td>Detection</td> + <td> + <table> + <thead> + <tr> + <th scope="col">Enumerable</th> + <th scope="col">Nonenumerable</th> + <th scope="col">Enumerable and Nonenumerable</th> + </tr> + </thead> + <tbody> + <tr> + <td> + <p><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/propertyIsEnumerable">propertyIsEnumerable</a></code></p> + + <p><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty">hasOwnProperty</a></code></p> + </td> + <td> + <p><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty">hasOwnProperty</a></code> – filtered to exclude enumerables using <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/propertyIsEnumerable">propertyIsEnumerable</a></code></p> + </td> + <td><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty">hasOwnProperty</a></code></td> + </tr> + </tbody> + </table> + </td> + <td> + <table> + <thead> + <tr> + <th scope="col">Enumerable</th> + <th scope="col">Nonenumerable</th> + <th scope="col">Enumerable and Nonenumerable</th> + </tr> + </thead> + <tbody> + <tr> + <td>Not available without extra code</td> + <td>Not available without extra code</td> + <td><code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/in">in</a></code></td> + </tr> + </tbody> + </table> + </td> + <td>Not available without extra code</td> + </tr> + <tr> + <td>Retrieval</td> + <td> + <table> + <thead> + <tr> + <th scope="col">Enumerable</th> + <th scope="col">Nonenumerable</th> + <th scope="col">Enumerable and Nonenumerable</th> + </tr> + </thead> + <tbody> + <tr> + <td> + <p><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys">Object.keys</a></code></p> + + <p><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames">getOwnPropertyNames</a></code> </p> + + <p><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertySymbols">getOwnPropertySymbols</a></code></p> + </td> + <td><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames">getOwnPropertyNames</a></code>, <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertySymbols">getOwnPropertySymbols</a> </code>– filtered to exclude enumerables using <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/propertyIsEnumerable">propertyIsEnumerable</a></code></td> + <td> + <p><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames">getOwnPropertyNames</a></code></p> + + <p><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertySymbols">getOwnPropertySymbols</a></code></p> + </td> + </tr> + </tbody> + </table> + </td> + <td>Not available without extra code</td> + <td>Not available without extra code</td> + </tr> + <tr> + <td>Iterable</td> + <td> + <table> + <thead> + <tr> + <th scope="col">Enumerable</th> + <th scope="col">Nonenumerable</th> + <th scope="col">Enumerable and Nonenumerable</th> + </tr> + </thead> + <tbody> + <tr> + <td> + <p><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys">Object.keys</a></code></p> + + <p><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames">getOwnPropertyNames</a></code> </p> + + <p><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertySymbols">getOwnPropertySymbols</a></code></p> + </td> + <td><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames">getOwnPropertyNames</a></code>, <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertySymbols">getOwnPropertySymbols</a></code> – filtered to exclude enumerables using <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/propertyIsEnumerable">propertyIsEnumerable</a></code></td> + <td> + <p><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames">getOwnPropertyNames</a></code></p> + + <p><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertySymbols">getOwnPropertySymbols</a></code></p> + </td> + </tr> + </tbody> + </table> + </td> + <td> + <table> + <thead> + <tr> + <th scope="col">Enumerable</th> + <th scope="col">Nonenumerable</th> + <th scope="col">Enumerable and Nonenumerable</th> + </tr> + </thead> + <tbody> + <tr> + <td> + <p><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in">for..in</a></code></p> + + <p>(excluding symbols)</p> + </td> + <td>Not available without extra code</td> + <td>Not available without extra code</td> + </tr> + </tbody> + </table> + </td> + <td>Not available without extra code</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Obtaining_properties_by_enumerabilityownership">Obtaining properties by enumerability/ownership</h2> + + + +<p>아래는 모든 경우에 가장 효율적인 알고리즘은 아니지만 빠르게 코드를 작성하여 확인하기 좋습니다.</p> + +<ul> + <li>Detection can occur by <code>SimplePropertyRetriever.theGetMethodYouWant(obj).indexOf(prop) > -1</code></li> + <li>Iteration can occur by <code>SimplePropertyRetriever.theGetMethodYouWant(obj).forEach(function (value, prop) {});</code> (or use<code> filter()</code>, <code>map()</code>, etc.)</li> +</ul> + +<pre class="brush: js notranslate">var SimplePropertyRetriever = { + getOwnEnumerables: function(obj) { + return this._getPropertyNames(obj, true, false, this._enumerable); + // Or could use for..in filtered with hasOwnProperty or just this: return Object.keys(obj); + }, + getOwnNonenumerables: function(obj) { + return this._getPropertyNames(obj, true, false, this._notEnumerable); + }, + getOwnEnumerablesAndNonenumerables: function(obj) { + return this._getPropertyNames(obj, true, false, this._enumerableAndNotEnumerable); + // Or just use: return Object.getOwnPropertyNames(obj); + }, + getPrototypeEnumerables: function(obj) { + return this._getPropertyNames(obj, false, true, this._enumerable); + }, + getPrototypeNonenumerables: function(obj) { + return this._getPropertyNames(obj, false, true, this._notEnumerable); + }, + getPrototypeEnumerablesAndNonenumerables: function(obj) { + return this._getPropertyNames(obj, false, true, this._enumerableAndNotEnumerable); + }, + getOwnAndPrototypeEnumerables: function(obj) { + return this._getPropertyNames(obj, true, true, this._enumerable); + // Or could use unfiltered for..in + }, + getOwnAndPrototypeNonenumerables: function(obj) { + return this._getPropertyNames(obj, true, true, this._notEnumerable); + }, + getOwnAndPrototypeEnumerablesAndNonenumerables: function(obj) { + return this._getPropertyNames(obj, true, true, this._enumerableAndNotEnumerable); + }, + // Private static property checker callbacks + _enumerable: function(obj, prop) { + return obj.propertyIsEnumerable(prop); + }, + _notEnumerable: function(obj, prop) { + return !obj.propertyIsEnumerable(prop); + }, + _enumerableAndNotEnumerable: function(obj, prop) { + return true; + }, + // Inspired by http://stackoverflow.com/a/8024294/271577 + _getPropertyNames: function getAllPropertyNames(obj, iterateSelfBool, iteratePrototypeBool, includePropCb) { + var props = []; + + do { + if (iterateSelfBool) { + Object.getOwnPropertyNames(obj).forEach(function(prop) { + if (props.indexOf(prop) === -1 && includePropCb(obj, prop)) { + props.push(prop); + } + }); + } + if (!iteratePrototypeBool) { + break; + } + iterateSelfBool = true; + } while (obj = Object.getPrototypeOf(obj)); + + return props; + } +};</pre> + +<h2 id="Detection_Table">Detection Table</h2> + +<div style="overflow: auto; width: 100%;"> +<table> + <thead> + <tr> + <th scope="row"></th> + <th scope="col"><code>in</code></th> + <th scope="col"><code>for..in</code></th> + <th scope="col"><code>obj.hasOwnProperty</code></th> + <th scope="col"><code>obj.propertyIsEnumerable</code></th> + <th scope="col"><code>Object.keys</code></th> + <th scope="col"><code>Object.getOwnPropertyNames</code></th> + <th scope="col"><code>Object.getOwnPropertyDescriptors</code></th> + <th scope="col"><code>Reflect.ownKeys()</code></th> + </tr> + </thead> + <tbody> + <tr> + <th scope="row">Enumerable</th> + <td>true</td> + <td>true</td> + <td>true</td> + <td>true</td> + <td>true</td> + <td>true</td> + <td>true</td> + <td>true</td> + </tr> + <tr> + <th scope="row">Nonenumerable</th> + <td>true</td> + <td>false</td> + <td>true</td> + <td>false</td> + <td>false</td> + <td>true</td> + <td>true</td> + <td>true</td> + </tr> + <tr> + <th scope="row">Symbols keys</th> + <td>true</td> + <td>false</td> + <td>true</td> + <td>true</td> + <td>false</td> + <td>false</td> + <td>true</td> + <td>true</td> + </tr> + <tr> + <th scope="row">Inherited Enumerable</th> + <td>true</td> + <td>true</td> + <td>false</td> + <td>false</td> + <td>false</td> + <td>false</td> + <td>false</td> + <td>false</td> + </tr> + <tr> + <th scope="row">Inherited Nonenumerable</th> + <td>true</td> + <td>false</td> + <td>false</td> + <td>false</td> + <td>false</td> + <td>false</td> + <td>false</td> + <td>false</td> + </tr> + <tr> + <th scope="row">Inherited Symbols keys</th> + <td>true</td> + <td>false</td> + <td>false</td> + <td>false</td> + <td>false</td> + <td>false</td> + <td>false</td> + <td>false</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/in">in</a></code></li> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in">for..in</a></code></li> + <li>{{jsxref("Object.hasOwnProperty()")}}</li> + <li>{{jsxref("Object.propertyIsEnumerable()")}}</li> + <li>{{jsxref("Object.getOwnPropertyNames()")}}</li> + <li>{{jsxref("Object.keys()")}}</li> + <li>{{jsxref("Object.getOwnPropertyDescriptors()")}}</li> +</ul> diff --git a/files/ko/web/javascript/equality_comparisons_and_sameness/index.html b/files/ko/web/javascript/equality_comparisons_and_sameness/index.html new file mode 100644 index 0000000000..31d1778d5d --- /dev/null +++ b/files/ko/web/javascript/equality_comparisons_and_sameness/index.html @@ -0,0 +1,503 @@ +--- +title: 동치 비교 및 동일성 +slug: Web/JavaScript/Equality_comparisons_and_sameness +tags: + - Comparison + - Equality + - Intermediate + - JavaScript + - SameValue + - SameValueZero + - Sameness +translation_of: Web/JavaScript/Equality_comparisons_and_sameness +--- +<div>{{jsSidebar("Intermediate")}}</div> + +<div class="summary"> +<p>ES2015에는 4가지 같음(equality) 알고리즘이 있습니다:</p> + +<ul> + <li>추상적(abstract) 같음 비교 (<code>==</code>)</li> + <li>엄격한(strict) 같음 비교 (<code>===</code>): <code>Array.prototype.indexOf</code>, <code>Array.prototype.lastIndexOf</code> 및 <code>case</code> 절 매칭에 쓰임</li> + <li>등가0(SameValueZero): <code>Map</code> 및 <code>Set</code> 연산뿐만 아니라 <code>%TypedArray%</code> 및 <code>ArrayBuffer</code> 생성자, 그리고 ES2016에 예정된 <code>String.prototype.includes</code>에 쓰임</li> + <li>등가(SameValue): 그 외 모든 곳에 쓰임</li> +</ul> + +<p>JavaScript는 3가지 서로 다른 값 비교 연산을 제공합니다:</p> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Identity">===</a>를 사용하는 엄격한 같음 (또는 "삼중 등호" 또는 "항등(identity)"),</li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Equality">==</a>를 사용하는 느슨한(loose) 같음 ("이중 등호"),</li> + <li>그리고 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Object/is"><code>Object.is</code></a> (ECMAScript 2015에 새로 들임).</li> +</ul> + +<p>어느 연산을 쓸 지 그 선택은 당신이 어떤 종류의 비교를 수행하기 위해 찾고 있는 지에 달렸습니다.</p> + +<p> </p> + +<ul> + <li>이중 equals (<code>==</code>)는 두 가지를 비교할 때 유형 변환을 수행하고 IEEE 754를 준수하기 위해 <code>NaN</code>, <code>-0</code> 및 <code>+0</code>을 특별히 처리합니다 (그래서<code>NaN != NaN</code>이고 <code>-0 == +0</code>입니다);</li> + <li>트리플 equals (<code>===</code>)는 이중 equals (<code>NaN</code>, <code>-0</code> 및 <code>+0</code>의 특수 처리 포함)와 동일한 비교를 수행하지만 유형 변환은 수행하지 않습니다. 형식이 다른 경우 <code>false</code>가 반환됩니다.</li> + <li><code>Object.is</code>는 형식 변환을하지 않으며 <code>NaN</code>, <code>-0</code> 및 <code>+0</code>에 대한 특수 처리를 수행하지 않습니다 (특수 숫자 값을 제외하고는 <code>===</code>와 동일한 동작을 제공함).</li> +</ul> + +<p> </p> +</div> + +<p>이들 사이의 구분은 모두 원시형(primitive) 처리와 관련이 있습니다. 매개 변수가 구조적, 개념적으로 유사한 지 비교하는 것이 없습니다. 같은 구조를 가지지만 개체 자체가 각각인 비원시형(non-primitive) 개체 x 및 y의 경우 위의 모든 형태(form)는 false로 평가됩니다.</p> + +<h2 id="를_사용하는_엄격한_같음"><code>===</code>를 사용하는 엄격한 같음</h2> + +<p>엄격한 같음(strict equality)은 두 값이 같은 지 비교합니다. 어느 값도 비교되기 전에 어떤 다른 값으로 남몰래 변환되지 않습니다. 둘이 서로 다른 형이면, 둘은 같지 않다고 여깁니다. 그렇지 않고 둘이 같은 형이고 숫자가 아닌 경우, 같은 값이면 같다고 여깁니다. 끝으로, 둘이 숫자인 경우, 둘 다 <code>NaN</code>이 아닌 같은 값이거나 하나는 <code>+0</code> 또 하나는 <code>-0</code>인 경우 같다고 여깁니다.</p> + +<pre class="brush: js">var num = 0; +var obj = new String("0"); +var str = "0"; +var b = false; + +console.log(num === num); // true +console.log(obj === obj); // true +console.log(str === str); // true + +console.log(num === obj); // false +console.log(num === str); // false +console.log(obj === str); // false +console.log(null === undefined); // false +console.log(obj === null); // false +console.log(obj === undefined); // false +</pre> + +<p>엄격한 같음은 거의 항상 사용하는 올바른 비교 연산입니다. 숫자를 뺀 모든 값에 대해, 분명한 의미(semantics)를 사용합니다: 값은 그 자체와만 같습니다(/ 단지 그 자체입니다). 숫자는 서로 다른 두 극단 상황(edge case)을 얼버무리기(gloss over) 위해 약간 다른 의미를 사용합니다. 첫째는 부동 소수점 0은 양이든 음이든 하나의 부호를 지닙니다. 이는 특정 수학상의 해결책을 나타내는 데 유용하지만, 대부분의 상황에 <code>+0</code>과 <code>-0</code>의 차이에 신경쓰지 않기에, 엄격한 같음은 둘을 같은 값으로 다룹니다. 둘째는 부동 소수점은 not-a-number 값(<code>NaN</code>) 개념을 포함합니다, 특정 잘못 정의된(ill-defined) 수학 문제의 해결책을 보여주기 위해: 예를 들어, 양의 무한대(infinity)에 추가된 음의 무한대. 엄격한 같음은 <code>NaN</code>을 다른 모든 값과 같지 않게 다룹니다 -- 자신 포함. (<code>(x !== x)</code>가 <code>true</code>인 유일한 경우는 <code>x</code>가 <code>NaN</code>일 때입니다.)</p> + +<h2 id="를_사용하는_느슨한_같음">==를 사용하는 느슨한 같음</h2> + +<p>느슨한 같음(loose equality)은 두 값이 같은 지 비교합니다, 두 값을 공통(common) 형으로 변환한 <em>후</em>에. 변환 후 (하나 또는 양쪽이 변환을 거칠 수 있음), 최종 같음 비교는 꼭 <code>===</code>처럼 수행됩니다. 느슨한 같음은 대칭(<em>symmetric</em>)입니다: <code>A == B</code>는 <code>A</code> 및 <code>B</code>가 어떤 값이든 항상 <code>B == A</code>와 같은 의미를 갖습니다 (적용된 변환의 순서 말고는).</p> + +<p>같음 비교는 다양한 형의 피연산자에 대해 다음과 같이 수행됩니다:</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="row"> </th> + <th colspan="7" scope="col" style="text-align: center;">피연산자 B</th> + </tr> + </thead> + <tbody> + <tr> + <th scope="row"> </th> + <td> </td> + <td style="text-align: center;">Undefined</td> + <td style="text-align: center;">Null</td> + <td style="text-align: center;">Number</td> + <td style="text-align: center;">String</td> + <td style="text-align: center;">Boolean</td> + <td style="text-align: center;">Object</td> + </tr> + <tr> + <th colspan="1" rowspan="6" scope="row">피연산자 A</th> + <td>Undefined</td> + <td style="text-align: center;"><code>true</code></td> + <td style="text-align: center;"><code>true</code></td> + <td style="text-align: center;"><code>false</code></td> + <td style="text-align: center;"><code>false</code></td> + <td style="text-align: center;"><code>false</code></td> + <td style="text-align: center;"><code>false</code></td> + </tr> + <tr> + <td>Null</td> + <td style="text-align: center;"><code>true</code></td> + <td style="text-align: center;"><code>true</code></td> + <td style="text-align: center;"><code>false</code></td> + <td style="text-align: center;"><code>false</code></td> + <td style="text-align: center;"><code>false</code></td> + <td style="text-align: center;"><code>false</code></td> + </tr> + <tr> + <td>Number</td> + <td style="text-align: center;"><code>false</code></td> + <td style="text-align: center;"><code>false</code></td> + <td style="text-align: center;"><code>A === B</code></td> + <td style="text-align: center;"><code>A === ToNumber(B)</code></td> + <td style="text-align: center;"><code>A === ToNumber(B)</code></td> + <td style="text-align: center;"><code>A == ToPrimitive(B)</code></td> + </tr> + <tr> + <td>String</td> + <td style="text-align: center;"><code>false</code></td> + <td style="text-align: center;"><code>false</code></td> + <td style="text-align: center;"><code>ToNumber(A) === B</code></td> + <td style="text-align: center;"><code>A === B</code></td> + <td style="text-align: center;"><code>ToNumber(A) === ToNumber(B)</code></td> + <td style="text-align: center;"><code>A == ToPrimitive(B)</code></td> + </tr> + <tr> + <td>Boolean</td> + <td style="text-align: center;"><code>false</code></td> + <td style="text-align: center;"><code>false</code></td> + <td style="text-align: center;"><code>ToNumber(A) === B</code></td> + <td style="text-align: center;"><code>ToNumber(A) === ToNumber(B)</code></td> + <td style="text-align: center;"><code>A === B</code></td> + <td style="text-align: center;"><code>ToNumber(A) == ToPrimitive(B)</code></td> + </tr> + <tr> + <td>Object</td> + <td style="text-align: center;"><code>false</code></td> + <td style="text-align: center;"><code>false</code></td> + <td style="text-align: center;"><code>ToPrimitive(A) == B</code></td> + <td style="text-align: center;"><code>ToPrimitive(A) == B</code></td> + <td style="text-align: center;"><code>ToPrimitive(A) == ToNumber(B)</code></td> + <td style="text-align: center;"><code>A === B</code></td> + </tr> + </tbody> +</table> + +<p>위 표에서, <code>ToNumber(A)</code>는 비교 전에 그 인수를 숫자로 변환하려고 시도합니다. 그 동작(behavior)은 <code>+A</code>(단항 + 연산자)에 해당합니다. <code>ToPrimitive(A)</code>는 그 객체 인수를 원시형 값으로 변환하려고 시도합니다, 다양한 순서로 <code>A</code>의 <code>A.toString</code> 및 <code>A.valueOf</code> 메서드 호출을 시도하여.</p> + +<p>전통 및 ECMAScript에 따르면, 모든 객체는 <code>undefined</code> 및 <code>null</code>과 느슨하게 같지 않습니다. 그러나 대부분의 브라우저는 일부 문맥(context)에서 <code>undefined</code>값을 모방하는(<em>emulate</em>) 것처럼 행동하기 위해 매우 좁은 부류의 객체(특히, 모든 페이지에 대한 <code>document.all</code> 객체)에 허용합니다. 느슨한 같음이 그러한 문맥 중 하나입니다: <code>null == A</code> 및 <code>undefined == A</code>는 A가 <code>undefined</code>를 <em>모방</em>하는 객체인 경우, 그리고 그 경우에만 true로 평가합니다. 다른 모든 경우에 객체는 결코 <code>undefined</code> 또는 <code>null</code>과 느슨하게 같지 않습니다.</p> + +<p> </p> + +<p>전통적으로 ECMAScript에 따르면 모든 객체는 <code>undefined</code> 및 <code>null</code>과 느슨하게 같지 않습니다. 그러나 대부분의 브라우저는 일부 문맥(context)에서 정의되지 않은 값(<code>undefined</code>)을 모방하는(<em>emulate</em>) 것처럼 동작하는 매우 좁은 개체 클래스 (특히 모든 페이지의 <code>document.all</code> 개체)를 허용합니다. Loose equality는 다음과 같은 컨텍스트 중 하나입니다. <code>null == A</code> 및 <code>undefined == A</code>는 <code>undefined</code>를 에뮬레이트하는 객체 인 경우에만 true로 평가됩니다. 다른 모든 경우에는 객체가 <code>undefined</code>거나 <code>null</code>이 될 수 없습니다.</p> + +<pre class="brush: js">var num = 0; +var obj = new String("0"); +var str = "0"; +var b = false; + +console.log(num == num); // true +console.log(obj == obj); // true +console.log(str == str); // true + +console.log(num == obj); // true +console.log(num == str); // true +console.log(obj == str); // true +console.log(null == undefined); // true + +// 둘 다 false, 드문 경우를 제외하고는 +console.log(obj == null); +console.log(obj == undefined); +</pre> + +<p>대부분의 경우 느슨한 같음을 사용하는 것은 바람직하지 않습니다. strict equality를 사용한 비교의 결과는 예측하기가 쉽고 형 강제(coercion) 변환이 일어나지 않기에 평가가 빠를 수 있습니다.</p> + +<p> </p> + +<h2 id="Same-value_equality">Same-value equality</h2> + +<p>등가(same-value) 같음은 최종 사용 사례(use case)를 다룹니다: 두 값이 모든 문맥에서 <em>기능상 같은지</em> 여부를 결정하는. (이 사용 사례는 <a href="https://ko.wikipedia.org/wiki/리스코프_치환_원칙" title="Liskov substitution principle">리스코프 치환 원칙</a>의 실례를 보입니다.) 다음은 불변 속성(property)을 변화시키려 시도할 때 일어나는 한 사례입니다:</p> + +<pre class="brush: js">// 불변(immutable) NEGATIVE_ZERO 속성을 Number 생성자에 추가. +Object.defineProperty(Number, "NEGATIVE_ZERO", + { value: -0, writable: false, configurable: false, enumerable: false }); + +function attemptMutation(v) +{ + Object.defineProperty(Number, "NEGATIVE_ZERO", { value: v }); +} +</pre> + +<p><code>Object.defineProperty</code>는 변경 불가능한 속성을 변경하려고 시도 할 때 예외를 throw하지만 실제 변경이 요청되지 않으면 아무 것도 수행하지 않습니다. <code>v</code>가 <code>-0</code>이면, 변경 사항이 요청되지 않고 오류가 발생하지 않습니다. 내부적으로, 불변의 property가 재정의 (redefined)되었을 때, 새롭게 지정된 값은 같은 값의 동등성을 사용해 현재의 값과 비교됩니다.</p> + +<p>Same-value equality는 {{jsxref("Object.is")}} 메서드로 제공됩니다.</p> + +<h2 id="Same-value-zero_equality">Same-value-zero equality</h2> + +<p>등가 같음과 비슷하지만 +0과 -0이 같다고 여깁니다.</p> + +<h2 id="스펙_내_추상적_같음_엄격한_같음_및_등가">스펙 내 추상적 같음, 엄격한 같음 및 등가</h2> + +<p>In ES5, the comparison performed by <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators"><code>==</code></a> is described in <a href="http://ecma-international.org/ecma-262/5.1/#sec-11.9.3">Section 11.9.3, The Abstract Equality Algorithm</a>. The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators"><code>===</code></a> comparison is <a href="http://ecma-international.org/ecma-262/5.1/#sec-11.9.6">11.9.6, The Strict Equality Algorithm</a>. (Go look at these. They're brief and readable. Hint: read the strict equality algorithm first.) ES5 also describes, in <a href="http://ecma-international.org/ecma-262/5.1/#sec-9.12">Section 9.12, The SameValue Algorithm</a> for use internally by the JS engine. It's largely the same as the Strict Equality Algorithm, except that 11.9.6.4 and 9.12.4 differ in handling {{jsxref("Number")}}s. ES2015 simply proposes to expose this algorithm through {{jsxref("Object.is")}}.</p> + +<p>We can see that with double and triple equals, with the exception of doing a type check upfront in 11.9.6.1, the Strict Equality Algorithm is a subset of the Abstract Equality Algorithm, because 11.9.6.2–7 correspond to 11.9.3.1.a–f.</p> + +<h2 id="같음_비교를_이해하기_위한_모델은">같음 비교를 이해하기 위한 모델은?</h2> + +<p>ES2015 이전에, 이중 등호 및 삼중 등호에 대해 하나가 다른 하나의 "확장"판이라고 (말)했을 지 모릅니다. 예를 들어, 누군가는 이중 등호는 삼중 등호의 확장판이라고 합니다, 전자는 후자가 하는 모든 것을 하지만 그 피연산자에 형 변환을 하기에. 가령, <code>6 == "6"</code>. (대신에, 이중 등호는 기준선이고 삼중 등호는 향상판이라고 하는 이도 있습니다, 두 피연산자가 같은 형이길 요구하고 그래서 별도 제약을 추가하기에. 어느 게 더 이해하기 좋은 모델인지는 당신이 상태(things)를 보기 위해 선택한 방법에 달렸습니다.)</p> + +<p>However, this way of thinking about the built-in sameness operators is not a model that can be stretched to allow a place for ES2015's {{jsxref("Object.is")}} on this "spectrum". {{jsxref("Object.is")}} isn't simply "looser" than double equals or "stricter" than triple equals, nor does it fit somewhere in between (i.e., being both stricter than double equals, but looser than triple equals). We can see from the sameness comparisons table below that this is due to the way that {{jsxref("Object.is")}} handles {{jsxref("NaN")}}. Notice that if <code>Object.is(NaN, NaN)</code>evaluated to <code>false</code>, we <em>could</em> say that it fits on the loose/strict spectrum as an even stricter form of triple equals, one that distinguishes between <code>-0</code> and <code>+0</code>. The {{jsxref("NaN")}} handling means this is untrue, however. Unfortunately, {{jsxref("Object.is")}} simply has to be thought of in terms of its specific characteristics, rather than its looseness or strictness with regard to the equality operators.</p> + +<p> </p> + +<table> + <caption>Sameness Comparisons</caption> + <thead> + <tr> + <th scope="col">x</th> + <th scope="col">y</th> + <th scope="col"><code>==</code></th> + <th scope="col"><code>===</code></th> + <th scope="col"><code>Object.is</code></th> + <th scope="col"><code>SameValueZero</code></th> + </tr> + </thead> + <tbody> + <tr> + <td><code>undefined</code></td> + <td><code>undefined</code></td> + <td><code>true</code></td> + <td><code>true</code></td> + <td><code>true</code></td> + <td><code>true</code></td> + </tr> + <tr> + <td><code>null</code></td> + <td><code>null</code></td> + <td><code>true</code></td> + <td><code>true</code></td> + <td><code>true</code></td> + <td><code>true</code></td> + </tr> + <tr> + <td><code>true</code></td> + <td><code>true</code></td> + <td><code>true</code></td> + <td><code>true</code></td> + <td><code>true</code></td> + <td><code>true</code></td> + </tr> + <tr> + <td><code>false</code></td> + <td><code>false</code></td> + <td><code>true</code></td> + <td><code>true</code></td> + <td><code>true</code></td> + <td><code>true</code></td> + </tr> + <tr> + <td><code>'foo'</code></td> + <td><code>'foo'</code></td> + <td><code>true</code></td> + <td><code>true</code></td> + <td><code>true</code></td> + <td><code>true</code></td> + </tr> + <tr> + <td><code>0</code></td> + <td><code>0</code></td> + <td><code>true</code></td> + <td><code>true</code></td> + <td><code>true</code></td> + <td><code>true</code></td> + </tr> + <tr> + <td><code>+0</code></td> + <td><code>-0</code></td> + <td><code>true</code></td> + <td><code>true</code></td> + <td><code>false</code></td> + <td><code>true</code></td> + </tr> + <tr> + <td><code>+0</code></td> + <td><code>0</code></td> + <td><code>true</code></td> + <td><code>true</code></td> + <td><code>true</code></td> + <td><code>true</code></td> + </tr> + <tr> + <td><code>-0</code></td> + <td><code>0</code></td> + <td><code>true</code></td> + <td><code>true</code></td> + <td><code>false</code></td> + <td><code>true</code></td> + </tr> + <tr> + <td><code>0</code></td> + <td><code>false</code></td> + <td><code>true</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + </tr> + <tr> + <td><code>""</code></td> + <td><code>false</code></td> + <td><code>true</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + </tr> + <tr> + <td><code>""</code></td> + <td><code>0</code></td> + <td><code>true</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + </tr> + <tr> + <td><code>'0'</code></td> + <td><code>0</code></td> + <td><code>true</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + </tr> + <tr> + <td><code>'17'</code></td> + <td><code>17</code></td> + <td><code>true</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + </tr> + <tr> + <td><code>[1, 2]</code></td> + <td><code>'1,2'</code></td> + <td><code>true</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + </tr> + <tr> + <td><code>new String('foo')</code></td> + <td><code>'foo'</code></td> + <td><code>true</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + </tr> + <tr> + <td><code>null</code></td> + <td><code>undefined</code></td> + <td><code>true</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + </tr> + <tr> + <td><code>null</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + </tr> + <tr> + <td><code>undefined</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + </tr> + <tr> + <td><code>{ foo: 'bar' }</code></td> + <td><code>{ foo: 'bar' }</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + </tr> + <tr> + <td><code>new String('foo')</code></td> + <td><code>new String('foo')</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + </tr> + <tr> + <td><code>0</code></td> + <td><code>null</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + </tr> + <tr> + <td><code>0</code></td> + <td><code>NaN</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + </tr> + <tr> + <td><code>'foo'</code></td> + <td><code>NaN</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + </tr> + <tr> + <td><code>NaN</code></td> + <td><code>NaN</code></td> + <td><code>false</code></td> + <td><code>false</code></td> + <td><code>true</code></td> + <td><code>true</code></td> + </tr> + </tbody> +</table> + +<p> </p> + +<h2 id="jsxref(Object.is)_대신_삼중_등호를_사용하는_경우">{{jsxref("Object.is")}} 대신 삼중 등호를 사용하는 경우</h2> + +<p>In general, the only time {{jsxref("Object.is")}}'s special behavior towards zeros is likely to be of interest is in the pursuit of certain meta-programming schemes, especially regarding property descriptors, when it is desirable for your work to mirror some of the characteristics of {{jsxref("Object.defineProperty")}}. If your use case does not require this, it is suggested to avoid {{jsxref("Object.is")}} and use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators" title="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators"><code>===</code></a> instead. Even if your requirements involve having comparisons between two {{jsxref("NaN")}} values evaluate to <code>true</code>, generally it is easier to special-case the {{jsxref("NaN")}} checks (using the {{jsxref("isNaN")}} method available from previous versions of ECMAScript) than it is to work out how surrounding computations might affect the sign of any zeros you encounter in your comparison.</p> + +<p>여기 당신 코드에서 그 자체를 드러내기 위해 <code>-0</code>과 <code>+0</code> 사이의 구별을 일으킬 수도 있는 철저하지 않은(in-exhaustive) 내장 메서드 및 연산자 목록이 있습니다:</p> + +<dl> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#-_.28Unary_Negation.29"><code>- (unary negation)</code></a><span style="font-size: 1rem; letter-spacing: -0.00278rem;"> </span></dt> +</dl> + +<pre class="syntaxbox">let stoppingForce = obj.mass * -obj.velocity</pre> + +<dl> + <dd> + <p><code>obj.velocity</code>가 <code>0</code>인 (또는 <code>0</code>으로 계산하는) 경우, <code>-0</code>이 그 자리에 소개되고 <code>stoppingForce</code>로 전해집니다. </p> + </dd> + <dt>{{jsxref("Math.atan2")}}</dt> + <dt>{{jsxref("Math.ceil")}}</dt> + <dt>{{jsxref("Math.pow")}}</dt> + <dt>{{jsxref("Math.round")}}<span style="font-size: 1rem; letter-spacing: -0.00278rem;"> </span></dt> + <dd>In some cases,it's possible for a <code>-0</code> to be introduced into an expression as a return value of these methods even when no <code>-0</code> exists as one of the parameters. For example, using {{jsxref("Math.pow")}} to raise {{jsxref("Infinity", "-Infinity")}} to the power of any negative, odd exponent evaluates to <code>-0</code>. Refer to the documentation for the individual methods. </dd> +</dl> + +<dl> + <dt>{jsxref("Math.floor")}}</dt> + <dt>{{jsxref("Math.max")}}</dt> + <dt>{{jsxref("Math.min")}}</dt> + <dt>{{jsxref("Math.sin")}}</dt> + <dt>{{jsxref("Math.sqrt")}}</dt> + <dt>{{jsxref("Math.tan")}}<span style="font-size: 1rem; letter-spacing: -0.00278rem;"> </span></dt> + <dd>It's possible to get a <code>-0</code> return value out of these methods in some cases where a <code>-0</code> exists as one of the parameters. E.g., <code>Math.min(-0, +0)</code> evaluates to <code>-0</code>. Refer to the documentation for the individual methods.</dd> +</dl> + +<dl> + <dt><code><a href="/ko/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators">~</a></code></dt> + <dt><code><a href="/ko/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators"><<</a></code></dt> + <dt><code><a href="/ko/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators">>></a></code></dt> + <dd>이러한 연산자 각각은 내부에서 ToInt32 알고리즘을 사용합니다. 내부 32-bit 정수형에는 0에 대해 한 표현만 있기에, <code>-0</code>은 역(inverse) 연산 후 왕복 여행(round trip, 이중 역 연산)에 살아남지 못합니다. 가령, <code>Object.is(~~(-0), -0)</code>와 <code>Object.is(-0 << 2 >> 2, -0)</code>는 <code>false</code>로 평가합니다.</dd> +</dl> + +<p>Relying on {{jsxref("Object.is")}} when the signedness of zeros is not taken into account can be hazardous. Of course, when the intent is to distinguish between <code>-0</code> and <code>+0</code>, it does exactly what's desired.</p> + +<h2 id="Caveat_jsxref(Object.is)_and_NaN">Caveat: {{jsxref("Object.is")}} and NaN</h2> + +<p>The {{jsxref("Object.is")}} specification treats all instances of {{jsxref("NaN")}} as the same object. However, since <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays">typed arrays</a> are available, we can have distinct instances, which don't behave identically in all contexts. For example:</p> + +<pre><code>var f2b = x => new Uint8Array(new Float64Array([x]).buffer); +var b2f = x => new Float64Array(x.buffer)[0]; +var n = f2b(NaN); +n[0] = 1; +var nan2 = b2f(n); +nan2; +// > NaN +Object.is(nan2, NaN); +// > true +f2b(NaN); +// > Uint8Array(8) [0, 0, 0, 0, 0, 0, 248,127) +f2b(nan2); +// > Uint8Array(8) [1, 0, 0, 0, 0, 0, 248,127)</code></pre> + +<h2 id="참조">참조</h2> + +<ul> + <li><a href="http://dorey.github.io/JavaScript-Equality-Table/">JS 비교 표</a></li> +</ul> diff --git a/files/ko/web/javascript/eventloop/index.html b/files/ko/web/javascript/eventloop/index.html new file mode 100644 index 0000000000..bc4330700d --- /dev/null +++ b/files/ko/web/javascript/eventloop/index.html @@ -0,0 +1,147 @@ +--- +title: 동시성 모델과 이벤트 루프 +slug: Web/JavaScript/EventLoop +tags: + - 이벤트 루프 +translation_of: Web/JavaScript/EventLoop +--- +<div>{{JsSidebar("Advanced")}}</div> + +<p>자바스크립트는 코드 실행, 이벤트 수집과 처리, 큐에 놓인 하위 작업들을 담당하는 <strong>이벤트 루프</strong>에 기반한 동시성(concurrency) 모델을 가지고 있습니다. 이 모델은 C 또는 Java와 같은 언어와 완전히 다릅니다.</p> + +<h2 id="런타임_개념">런타임 개념</h2> + +<p>이어지는 섹션에서는 이론적 모델을 설명합니다. 모던 자바스크립트 엔진들은 아래 묘사된 개념들을 구현하고 최적화 합니다.</p> + +<h3 id="시각적_표현">시각적 표현</h3> + +<p style="text-align: center;"><img alt="Stack, heap, queue" src="/files/4617/default.svg" style="height: 270px; width: 294px;"></p> + +<h3 id="Stack">Stack</h3> + +<p>함수 호출은 <em>프레임</em>들의 스택을 형성합니다.</p> + +<pre class="brush: js"><code>function foo(b) { + var a = 10; + return a + b + 11; +} + +function bar(x) { + var y = 3; + return foo(x * y); +} + +console.log(bar(7)); //returns 42</code></pre> + +<p><code>bar</code>를 호출할 때, <code>bar</code>의 인자와 지역 변수를 포함하는 첫 번째 프레임이 생성됩니다. <code>bar</code>가 <code>foo</code>를 호출하면 두 번째 프레임이 만들어져 <code>foo</code>의 인수와 지역 변수가 들어있는 첫 번째 프레임의 맨 위에 푸시됩니다. <code>foo</code>가 반환되면, 최상위 프레임 요소는 <code>bar</code>의 호출 프레임만을 남겨둔 채로 스택 밖으로 빠져나옵니다. <code>bar</code>가 반환되면, 스택은 비워집니다.</p> + +<h3 id="Heap">Heap</h3> + +<p>객체들은 힙 안에 할당됩니다. 힙은 구조화되지 않은 넓은 메모리 영역을 지칭합니다.</p> + +<h3 id="Queue">Queue</h3> + +<p>JavaScript 런타임은 처리 할 메시지 목록 인 메시지 대기열을 사용합니다. 각 메시지에는 메시지를 처리하기 위해 호출되는 관련 함수가 있습니다.</p> + +<p>{{anch("Event loop", "event loop")}} 중 어떤 시점에서 런타임은 대기열에서 가장 오래된 메시지부터 처리하기 시작합니다. 그렇게하기 위해, 메시지는 큐에서 제거되고 해당 기능이 메시지를 입력 매개 변수로 호출됩니다. 언제나 그렇듯이, 함수를 호출하면 그 함수의 사용을위한 새로운 스택 프레임이 생성됩니다.</p> + +<p>함수의 처리는 스택이 다시 비워 질 때까지 계속됩니다. 이벤트 루프는 큐의 다음 메시지를 처리합니다(존재할 경우).</p> + +<h2 id="Event_loop">Event loop</h2> + +<p><strong>Event loop</strong>는 그 구현 방식 때문에 붙은 이름이며 보통 다음과 유사합니다 :</p> + +<pre class="brush: js">while(queue.waitForMessage()){ + queue.processNextMessage(); +}</pre> + +<p><code>queue.waitForMessage()</code> 함수는 현재 아무 메시지도 없다면 새로운 메시지 도착을 동기적으로 기다립니다.</p> + +<h3 id="Run-to-completion">"Run-to-completion"</h3> + +<p>각 메시지는 다른 메시지가 처리되기 전에 완전히 처리됩니다.</p> + +<p>이것은 함수가 실행될 때마다 미리 비워질 수 없고 다른 코드가 실행되기 전에 완전히 실행되며 함수가 조작하는 데이터를 수정할 수 있다는 사실을 포함하여 프로그램에 대한 추론을 할 때 좋은 속성을 제공합니다. 이것은 C와는 다릅니다. 예를 들어 함수가 쓰레드에서 실행된다면 런타임 시스템이 다른 쓰레드에서 다른 코드를 실행하기 위해 어느 시점에서 멈출 수 있습니다.</p> + +<p>이 모델의 부정적인 면은 어떤 메시지가 완료되기 까지 지나치게 오래 걸린다면 웹 어플리케이션은 클릭이나 스크롤과 같은 사용자 인터랙션을 처리할 수 없게 됩니다. 브라우저는 이러한 상황을 "a script is taking too long to run"과 같은 대화상자로 완화 합니다. 추천되는 좋은 방법은 메시지 처리를 짧도록 만드는 것과 하나의 메시지를 여러개의 메시지로 나누는 것 입니다.</p> + +<h3 id="메시지_추가하기">메시지 추가하기</h3> + +<p>웹 브라우저에서 이벤트 리스너가 부착된 이벤트가 발생할 때마다 메시지가 추가됩니다. 리스너가 없으면 이벤트는 손실됩니다. 클릭 이벤트 핸들러가 있는 요소를 클릭하면 다른 이벤트와 마찬가지로 메시지가 추가됩니다.</p> + +<p><code><a href="/en-US/docs/Web/API/WindowTimers.setTimeout" title="/en-US/docs/window.setTimeout">setTimeout</a></code> 함수는 2 개의 인수, 대기열에 추가 할 메시지와 시간값(선택사항, 기본값은 0)으로 호출됩니다. 시간 값은 메시지가 실제로 큐에 푸시 될 때까지의 (최소) 지연을 나타냅니다. 대기열에 다른 메시지가 없으면 지연 직후에 메시지가 처리됩니다. 그러나 메시지가있는 경우 setTimeout 메시지는 다른 메시지가 처리 될 때까지 기다려야합니다. 따라서 두 번째 인수는 최소 시간을 나타내지 만 보장 된 시간은 아닙니다.</p> + +<p>다음은 이 개념에 대한 예제입니다 (<code>setTimeout</code>은 타이머 만료 직후에 실행되지 않습니다).</p> + +<pre class="brush: js"><code>const s = new Date().getSeconds(); + +setTimeout(function() { + // prints out "2", meaning that the callback is not called immediately after 500 milliseconds. + console.log("Ran after " + (new Date().getSeconds() - s) + " seconds"); +}, 500); + +while(true) { + if(new Date().getSeconds() - s >= 2) { + console.log("Good, looped for 2 seconds"); + break; + } +}</code></pre> + +<h3 id="Zero_delays">Zero delays</h3> + +<p>Zero delay는 실제로 0ms 후에 콜백이 시작된다는 의미는 아닙니다. 0ms 지연된 {{domxref("WindowTimers.setTimeout", "setTimeout")}}은 주어진 간격 후에 콜백 함수를 실행하지 않습니다.</p> + +<p>실행은 큐에 대기중인 작업 수에 따라 다릅니다. 아래 예에서, 콜백의 메시지가 처리되기 전에 콘솔에 "this is just message"메시지가 기록됩니다. 왜냐하면 지연(delay)은 보장된 시간이 아니라 요청을 처리하기 위해 필요한 최소의 시간이기 때문입니다.</p> + +<p>기본적으로 setTimeout은 setTimeout에 대한 특정 시간 제한을 지정 했더라도 대기중인 메시지의 모든 코드가 완료 될 때까지 대기해야합니다.</p> + +<pre class="brush: js"><code>(function() { + + console.log('this is the start'); + + setTimeout(function cb() { + console.log('this is a msg from call back'); + }); + + console.log('this is just a message'); + + setTimeout(function cb1() { + console.log('this is a msg from call back1'); + }, 0); + + console.log('this is the end'); + +})(); + +// "this is the start" +// "this is just a message" +// "this is the end" +// note that function return, which is undefined, happens here +// "this is a msg from call back" +// "this is a msg from call back1"</code></pre> + +<h3 id="몇가지_런타임_통신">몇가지 런타임 통신</h3> + +<p>웹워커 또는 크로스 오리진 <code>iframe</code>은 자신의 스택, 힙, 메시지 큐를 가지고 있습니다. 두 별개의 런타임들은 <a href="/en-US/docs/DOM/window.postMessage" title="/en-US/docs/DOM/window.postMessage"><code>postMessage</code></a> method를 통해서만 서로 통신할 수 있습니다. 이 메서드는 다른 런타임이 <code>message</code> 이벤트 핸들러를 등록하고 있다면 해당 런타임의 큐에 메시지를 추가합니다.</p> + +<h2 id="Never_blocking">Never blocking</h2> + +<p>이벤트 루프 모델의 무척 재밌는 부분은 다른 언어와 달리 자바스크립트는 결코 Block하지 않는다는 것입니다. I/O 처리는 흔히 이벤트와 콜백으로 처리 됩니다. 그래서 응용프로그램이 <a href="/en-US/docs/Web/API/IndexedDB_API" title="/en-US/docs/IndexedDB">IndexedDB</a> query 반환을 기다리고 있거나 <a href="/en-US/docs/Web/API/XMLHttpRequest" title="/en-US/docs/DOM/XMLHttpRequest">XHR</a> 요청 반환을 기다릴 때에도 여전히 사용자 입력과 같은 다른 것을을 처리할 수 있습니다.</p> + +<p><code>alert</code> 또는 synchronous XHR과 같은 구현 예외가 존재 합니다. 그러나 그것들은 사용되지 않는 것이 좋다라고 여겨집니다. <a href="http://stackoverflow.com/questions/2734025/is-javascript-guaranteed-to-be-single-threaded/2734311#2734311" title="http://stackoverflow.com/questions/2734025/is-javascript-guaranteed-to-be-single-threaded/2734311#2734311">예외를 위한 예외</a>를 조심하세요 (그러나 보통 구현 버그일뿐 그이상 아무것도 아닙니다).</p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', 'webappapis.html#event-loops', 'Event loops')}}</td> + </tr> + <tr> + <td><a href="https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#what-is-the-event-loop">Node.js Event Loop</a></td> + </tr> + </tbody> +</table> diff --git a/files/ko/web/javascript/guide/closures/index.html b/files/ko/web/javascript/guide/closures/index.html new file mode 100644 index 0000000000..b56d843b2b --- /dev/null +++ b/files/ko/web/javascript/guide/closures/index.html @@ -0,0 +1,454 @@ +--- +title: 클로저 +slug: Web/JavaScript/Guide/Closures +tags: + - Closure + - ES5 + - Intermediate + - JavaScript + - Reference +translation_of: Web/JavaScript/Closures +--- +<div>{{jsSidebar("Intermediate")}}</div> + +<p>클로저는 함수와 함수가 선언된 어휘적 환경의 조합이다. 클로저를 이해하려면 자바스크립트가 어떻게 변수의 유효범위를 지정하는지(Lexical scoping)를 먼저 이해해야 한다.</p> + +<h2 id="어휘적_범위_지정Lexical_scoping">어휘적 범위 지정(Lexical scoping)</h2> + +<p>다음을 보자:</p> + +<pre>function init() { + var name = "Mozilla"; // name은 init에 의해 생성된 지역 변수이다. + function displayName() { // displayName() 은 내부 함수이며, 클로저다. + alert(name); // 부모 함수에서 선언된 변수를 사용한다. + } + displayName(); +} +init();</pre> + +<p><code>init()</code>은 지역 변수 <code>name</code>과 함수 <code>displayName()</code>을 생성한다. <code>displayName()</code>은 <code>init()</code> 안에 정의된 내부 함수이며 <code>init()</code> 함수 본문에서만 사용할 수 있다. 여기서 주의할 점은 <code>displayName()</code> 내부엔 자신만의 지역 변수가 없다는 점이다. 그런데 함수 내부에서 외부 함수의 변수에 접근할 수 있기 때문에 <code>displayName()</code> 역시 부모 함수 <code>init()</code>에서 선언된 변수 <code>name</code>에 접근할 수 있다. 만약 <code>displayName()</code>가 자신만의 <code>name</code>변수를 가지고 있었다면, <code>name</code>대신 <code>this.name</code>을 사용했을 것이다.</p> + +<p>{{JSFiddleEmbed("https://jsfiddle.net/78dg25ax/", "js,result", 250)}}</p> + +<p>위 코드를 <a href="http://jsfiddle.net/xAFs9/3/">실행</a>하면 <code>displayName()</code> 함수 내의 <code>alert()</code>문이 부모 함수에서 정의한 변수 <code>name</code>의 값을 성공적으로 출력한다. 이 예시를 통해 함수가 중첩된 상황에서 파서가 어떻게 변수를 처리하는지 알 수 있다. 이는 어휘적 범위 지정(lexical scoping)의 한 예이다. 여기서 "lexical"이란, 어휘적 범위 지정(lexical scoping) 과정에서 변수가 어디에서 사용 가능한지 알기 위해 그 변수가 소스코드 내 어디에서 선언되었는지 고려한다는 것을 의미한다. 단어 "lexical"은 이런 사실을 나타낸다. 중첩된 함수는 외부 범위(scope)에서 선언한 변수에도 접근할 수 있다.</p> + +<h2 id="클로저Closure">클로저(Closure)</h2> + +<p>이제 다음 예제를 보자:</p> + +<pre>function makeFunc() { + var name = "Mozilla"; + function displayName() { + alert(name); + } + return displayName; +} + +var myFunc = makeFunc(); +//myFunc변수에 displayName을 리턴함 +//유효범위의 어휘적 환경을 유지 +myFunc(); +//리턴된 displayName 함수를 실행(name 변수에 접근)</pre> + +<p>이 코드는 바로 전의 예제와 완전히 동일한 결과가 실행된다. 하지만 흥미로운 차이는 <code>displayName()</code>함수가 실행되기 전에 외부함수인 <code>makeFunc()</code>로부터 리턴되어 <code>myFunc</code> 변수에 저장된다는 것이다.</p> + +<p>한 눈에 봐서는 이 코드가 여전히 작동하는 것이 직관적으로 보이지 않을 수 있다. 몇몇 프로그래밍 언어에서, 함수 안의 지역 변수들은 그 함수가 처리되는 동안에만 존재한다. <code>makeFunc()</code> 실행이 끝나면(<code>displayName</code>함수가 리턴되고 나면) <code>name</code> 변수에 더 이상 접근할 수 없게 될 것으로 예상하는 것이 일반적이다.</p> + +<p>하지만 위의 예시와 자바스크립트의 경우는 다르다. 그 이유는 자바스크립트는 함수를 리턴하고, 리턴하는 함수가 클로저를 형성하기 때문이다. 클로저는 함수와 함수가 선언된 어휘적 환경의 조합이다. 이 환경은 클로저가 생성된 시점의 유효 범위 내에 있는 모든 지역 변수로 구성된다. 첫 번째 예시의 경우, <code>myFunc</code>은 <code>makeFunc</code>이 실행될 때 생성된 <code>displayName</code> 함수의 인스턴스에 대한 참조다. <code>displayName</code>의 인스턴스는 변수 <code>name</code> 이 있는 어휘적 환경에 대한 참조를 유지한다. 이런 이유로 <code>myFunc</code>가 호출될 때 변수 <code>name</code>은 사용할 수 있는 상태로 남게 되고 "Mozilla" 가 <code>alert</code> 에 전달된다.</p> + +<p>다음은 조금 더 흥미로운 예제인 makeAdder 함수이다:</p> + +<pre>function makeAdder(x) { + var y = 1; + return function(z) { + y = 100; + return x + y + z; + }; +} + +var add5 = makeAdder(5); +var add10 = makeAdder(10); +//클로저에 x와 y의 환경이 저장됨 + +console.log(add5(2)); // 107 (x:5 + y:100 + z:2) +console.log(add10(2)); // 112 (x:10 + y:100 + z:2) +//함수 실행 시 클로저에 저장된 x, y값에 접근하여 값을 계산 + +</pre> + +<p>이 예제에서 단일 인자 <code>x</code>를 받아서 새 함수를 반환하는 함수 <code>makeAdder(x)를 정의했다.</code> 반환되는 함수는 단일 인자 <font face="consolas, Liberation Mono, courier, monospace">z</font>를 받아서 x와 y와 z의 합을 반환한다.</p> + +<p>본질적으로 <code>makeAdder</code>는 함수를 만들어내는 공장이다. 이는 <code>makeAdder</code>함수가 특정한 값을 인자로 가질 수 있는 함수들을 리턴한다는 것을 의미한다. 위의 예제에서 <code>add5, add10</code> 두 개의 새로운 함수들을 만들기 위해 <code>makeAdder</code>함수 공장을 사용했다. 하나는 매개변수 <font face="consolas, Liberation Mono, courier, monospace">x</font>에 5를 더하고 다른 하나는 매개변수 <font face="consolas, Liberation Mono, courier, monospace">x</font>에 10을 더한다.</p> + +<p><code>add5</code>와 <code>add10</code>은 둘 다 클로저이다. 이들은 같은 함수 본문 정의를 공유하지만 서로 다른 맥락(어휘)적 환경을 저장한다. 함수 실행 시 <code>add5</code>의 맥락적 환경에서 클로저 내부의 x는 5 이지만 <code>add10</code>의 맥락적 환경에서 x는 10이다. 또한 리턴되는 함수에서 초기값이 1로 할당된 y에 접근하여 y값을 100으로 변경한 것을 볼 수 있다. (물론 x값도 동일하게 변경 가능하다.) 이는 클로저가 리턴된 후에도 외부함수의 변수들에 접근 가능하다는 것을 보여주는 포인트이며 클로저에 단순히 값 형태로 전달되는 것이 아니라는 것을 의미한다.</p> + +<h2 id="실용적인_클로저">실용적인 클로저</h2> + +<p>클로저는 어떤 데이터(어휘적 환경)와 그 데이터를 조작하는 함수를 연관시켜주기 때문에 유용하다. 이것은 객체가 어떤 데이터와(그 객체의 속성) 하나 혹은 그 이상의 메소드들을 연관시킨다는 점에서 객체지향 프로그래밍과 분명히 같은 맥락에 있다.</p> + +<p>결론적으로 오직 하나의 메소드를 가지고 있는 객체를 일반적으로 사용하는 모든 곳에 클로저를 사용할 수 있다.</p> + +<p>이렇게 할 수 있는 상황은 특히 웹에서 일반적이다. 프론트 엔드 자바스크립트에서 우리가 쓰는 많은 코드가 이벤트 기반이다. 우리는 몇 가지 동작을 정의한 다음 사용자에 의한 이벤트에(클릭 혹은 키 누르기 같은) 연결한다. 우리의 코드는 일반적으로 콜백으로 첨부된다: 이벤트에 응답하여 실행되는 단일 함수다.</p> + +<p>예를 들면 페이지의 글자 크기를 조정하는 몇 개의 버튼을 추가한다고 가정하자. 이 작업을 수행하는 한 가지 방법은 body 요소의 font-size를 픽셀 단위로 지정하고 상대적인 em 단위를 사용하여 페이지의 다른 요소들의 (예: 헤더) 크기를 설정하는 것이다.</p> + +<pre>body { + font-family: Helvetica, Arial, sans-serif; + font-size: 12px; +} + +h1 { + font-size: 1.5em; +} + +h2 { + font-size: 1.2em; +} +</pre> + +<p>우리의 대화식 글자 크기 버튼들은 body 요소의 font-size 속성을 변경할 수 있고 이런 조정은 상대적 단위들 덕분에 페이지의 다른 요소에 의해 선택된다.</p> + +<p>여기 자바스크립트 코드가 있다.</p> + +<pre>function makeSizer(size) { + return function() { + document.body.style.fontSize = size + 'px'; + }; +} + +var size12 = makeSizer(12); +var size14 = makeSizer(14); +var size16 = makeSizer(16); +</pre> + +<p><code>size12</code>, <code>size14</code>, <code>size16</code>은 body 요소의 글자 크기를 각각 12, 14, 16 픽셀로 바꾸는 함수이다. 이 함수들을 아래처럼 버튼들에(이 경우에는 링크) 연결할 수 있다.</p> + +<pre>document.getElementById('size-12').onclick = size12; +document.getElementById('size-14').onclick = size14; +document.getElementById('size-16').onclick = size16; +</pre> + +<pre><a href="#" id="size-12">12</a> +<a href="#" id="size-14">14</a> +<a href="#" id="size-16">16</a> +</pre> + +<p>{{JSFiddleEmbed("https://jsfiddle.net/vnkuZ/","","200")}}</p> + +<h2 id="클로저를_이용해서_프라이빗_메소드_private_method_흉내내기">클로저를 이용해서 프라이빗 메소드 (private method) 흉내내기</h2> + +<p>자바와 같은 몇몇 언어들은 메소드를 프라이빗으로 선언할 수 있는 기능을 제공한다. 이는 같은 클래스 내부의 다른 메소드에서만 그 메소드들을 호출할 수 있다는 의미이다.</p> + +<p>자바스크립트는 태생적으로는 이런 방법을 제공하지 않지만 클로저를 이용하여 프라이빗 메소드를 흉내내는 것이 가능하다. 프라이빗 메소드는 코드에 제한적인 접근만을 허용한다는 점 뿐만 아니라 전역 네임 스페이스를 관리하는 강력한 방법을 제공하여 불필요한 메소드가 공용 인터페이스를 혼란스럽게 만들지 않도록 한다.</p> + +<p>아래 코드는 프라이빗 함수와 변수에 접근하는 퍼블릭 함수를 정의하기 위해 클로저를 사용하는 방법을 보여준다. 이렇게 클로저를 사용하는 것을 <a href="http://www.google.com/search?q=javascript+module+pattern" title="http://www.google.com/search?q=javascript+module+pattern">모듈 패턴</a>이라 한다.</p> + +<pre>var counter = (function() { + var privateCounter = 0; + function changeBy(val) { + privateCounter += val; + } + return { + increment: function() { + changeBy(1); + }, + decrement: function() { + changeBy(-1); + }, + value: function() { + return privateCounter; + } + }; +})(); + +console.log(counter.value()); // logs 0 +counter.increment(); +counter.increment(); +console.log(counter.value()); // logs 2 +counter.decrement(); +console.log(counter.value()); // logs 1 +</pre> + +<p>이전 예제에서 각 클로저들이 고유한 문법적 환경을 가졌지만 여기서 우리는 <code>counter.increment</code>, <code>counter.decrement</code>, <code>counter.value </code>세 함수에 의해 공유되는 하나의 어휘적 환경을 만든다.</p> + +<p>공유되는 어휘적 환경은 실행되는 익명 함수 안에서 만들어진다. 이 익명 함수는 정의되는 즉시 실행된다. 이 어휘적 환경은 두 개의 프라이빗 아이템을 포함한다. 하나는 <code>privateCounter</code>라는 변수이고 나머지 하나는 <code>changeBy</code>라는 함수이다. 둘 다 익명 함수 외부에서 접근될 수 없다. 대신에 익명 래퍼에서 반환된 세 개의 퍼블릭 함수를 통해서만 접근되어야만 한다.</p> + +<p>위의 세 가지 퍼블릭 함수는 같은 환경을 공유하는 클로저다. 자바스크립트의 어휘적 유효 범위 덕분에 세 함수 각각 <code>privateCounter</code> 변수와 <code>changeBy</code> 함수에 접근할 수 있다.</p> + +<p>카운터를 생성하는 익명 함수를 정의하고 그 함수를 즉시 호출하고 결과를 counter 변수에 할당하는 것을 알아차렸을 것이다. 이 함수를 별도의 변수 makeCounter 저장하고 이 변수를 이용해 여러 개의 카운터를 만들 수 있다.</p> + +<pre>var makeCounter = function() { + var privateCounter = 0; + function changeBy(val) { + privateCounter += val; + } + return { + increment: function() { + changeBy(1); + }, + decrement: function() { + changeBy(-1); + }, + value: function() { + return privateCounter; + } + } +}; + +var counter1 = makeCounter(); +var counter2 = makeCounter(); +alert(counter1.value()); /* 0 */ +counter1.increment(); +counter1.increment(); +alert(counter1.value()); /* 2 */ +counter1.decrement(); +alert(counter1.value()); /* 1 */ +alert(counter2.value()); /* 0 */ +</pre> + +<p>두 개의 카운터가 어떻게 다른 카운터와 독립성을 유지하는지 주목해보자. 각 클로저는 그들 고유의 클로저를 통한 privateCounter 변수의 다른 버전을 참조한다. 각 카운터가 호출될 때마다; 하나의 클로저에서 변수 값을 변경해도 다른 클로저의 값에는 영향을 주지 않는다.</p> + +<p>이런 방식으로 클로저를 사용하여 객체지향 프로그래밍의 정보 은닉과 캡슐화 같은 이점들을 얻을 수 있다.</p> + +<h2 id="클로저_스코프_체인">클로저 스코프 체인</h2> + +<p>모든 클로저에는 세가지 스코프(범위)가 있다:-</p> + +<ul> + <li>지역 범위 (Local Scope, Own scope)</li> + <li>외부 함수 범위 (Outer Functions Scope)</li> + <li>전역 범위 (Global Scope)</li> +</ul> + +<p>따라서, 우리는 클로저에 대해 세가지 범위 모두 접근할 수 있지만, 중첩된 내부 함수가 있는 경우 종종 실수를 저지른다. 아래 예제를 확인해보자:</p> + +<pre><code>// 전역 범위 (global scope) +var e = 10; +function sum(a){ + return function(b){ + return function(c){ + // 외부 함수 범위 (outer functions scope) + return function(d){ + // 지역 범위 (local scope) + return a + b + c + d + e; + } + } + } +} + +console.log(sum(1)(2)(3)(4)); // log 20 + +// 익명 함수 없이 작성할 수도 있다. + +// 전역 범위 (global scope) +var e = 10; +function sum(a){ + return function sum2(b){ + return function sum3(c){ + // 외부 함수 범위 (outer functions scope) + return function sum4(d){ + // 지역 범위 (local scope) + return a + b + c + d + e; + } + } + } +} + +var s = sum(1); +var s1 = s(2); +var s2 = s1(3); +var s3 = s2(4); +console.log(s3) //log 20</code></pre> + +<p>위의 예제를 보면 일련의 중첩된 함수들을 확인할 수 있다. 이 함수들은 전부 외부 함수의 스코프에 접근할 수 있다. 그런데 문제는 즉각적인 외부 함수의 스코프만을 추측한다는 것이다. 이 문맥에서는 모든 클로저가 선언된 외부 함수의 스코프에 접근한다라고 말할 수 있다.</p> + +<h2 id="루프에서_클로저_생성하기_일반적인_실수">루프에서 클로저 생성하기: 일반적인 실수</h2> + +<p>ECMAScript 2015의 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let" title="방해"><code>let</code> 키워드</a> 소개 전에는 클로저와 관련된 일반적인 문제는 루프 안에서 클로저가 생성되었을 때 발생한다.다음 예제를 보자.</p> + +<pre><p id="help">Helpful notes will appear here</p> +<p>E-mail: <input type="text" id="email" name="email"></p> +<p>Name: <input type="text" id="name" name="name"></p> +<p>Age: <input type="text" id="age" name="age"></p> +</pre> + +<pre>function showHelp(help) { + document.getElementById('help').innerHTML = help; +} + +function setupHelp() { + var helpText = [ + {'id': 'email', 'help': 'Your e-mail address'}, + {'id': 'name', 'help': 'Your full name'}, + {'id': 'age', 'help': 'Your age (you must be over 16)'} + ]; + + for (var i = 0; i < helpText.length; i++) { + var item = helpText[i]; + document.getElementById(item.id).onfocus = function() { + showHelp(item.help); + } + } +} + +setupHelp(); +</pre> + +<p>{{JSFiddleEmbed("https://jsfiddle.net/v7gjv/", "", 200)}}</p> + +<p>helpText 배열은 세 개의 도움말 힌트를 정의한다. 각 도움말은 문서의 입력 필드의 ID와 연관된다. 루프를 돌면서 각 입력 필드 ID에 해당하는 엘리먼트의 onfocus 이벤트에 관련된 도움말을 보여주는 메소드에 연결한다.</p> + +<p>이 코드를 사용하면 제대로 동작하지 않는 것을 알게 된다. 어떤 필드에 포커스를 주더라도 나이에 관한 도움말이 표시된다.</p> + +<p>onfocus 이벤트에 연결된 함수가 클로저이기 때문이다. 이 클로저는 함수 정의와 setupHelp 함수 범위에서 캡처된 환경으로 구성된다. 루프에서 세 개의 클로저가 만들어졌지만 각 클로저는 값이 변하는 변수가 (item.help) 있는 같은 단일 환경을 공유한다. onfocus 콜백이 실행될 때 콜백의 환경에서 item 변수는 (세개의 클로저가 공유한다) helpText 리스트의 마지막 요소를 가리키고 있을 것이다.</p> + +<p>이 경우 한 가지 해결책은 더 많은 클로저를 사용하는 것이다: 특히 앞에서 설명한 함수 팩토리를 사용하는 것이다.</p> + +<pre>function showHelp(help) { + document.getElementById('help').innerHTML = help; +} + +function makeHelpCallback(help) { + return function() { + showHelp(help); + }; +} + +function setupHelp() { + var helpText = [ + {'id': 'email', 'help': 'Your e-mail address'}, + {'id': 'name', 'help': 'Your full name'}, + {'id': 'age', 'help': 'Your age (you must be over 16)'} + ]; + + for (var i = 0; i < helpText.length; i++) { + var item = helpText[i]; + document.getElementById(item.id).onfocus = makeHelpCallback(item.help); + } +} + +setupHelp(); +</pre> + +<p>{{JSFiddleEmbed("https://jsfiddle.net/v7gjv/1/", "", 300)}}</p> + +<p>이것은 예상대로 동작한다. 모두 단일 환경을 공유하는 콜백대신, <code>makeHelpCallback</code> 함수는 각각의 콜백에 새로운 어휘적 환경을 생성한다. 여기서 help는 helpText 배열의 해당 문자열을 나타낸다.</p> + +<p>익명 클로저를 사용하여 위 코드를 작성하는 또 다른 방법은 다음과 같다.</p> + +<pre>function showHelp(help) { + document.getElementById('help').innerHTML = help; +} + +function setupHelp() { + var helpText = [ + {'id': 'email', 'help': 'Your e-mail address'}, + {'id': 'name', 'help': 'Your full name'}, + {'id': 'age', 'help': 'Your age (you must be over 16)'} + ]; + + for (var i = 0; i < helpText.length; i++) { + (function() { + var item = helpText[i]; + document.getElementById(item.id).onfocus = function() { + showHelp(item.help); + } + })(); // Immediate event listener attachment with the current value of item (preserved until iteration). + } +} + +setupHelp();</pre> + +<p>더 많은 클로저를 사용하는 것이 싫다면 ES2015의 <code><a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/let">let</a></code> 키워드를 사용할 수 있다.</p> + +<pre>function showHelp(help) { + document.getElementById('help').innerHTML = help; +} + +function setupHelp() { + var helpText = [ + {'id': 'email', 'help': 'Your e-mail address'}, + {'id': 'name', 'help': 'Your full name'}, + {'id': 'age', 'help': 'Your age (you must be over 16)'} + ]; + + for (var i = 0; i < helpText.length; i++) { + let item = helpText[i]; + document.getElementById(item.id).onfocus = function() { + showHelp(item.help); + } + } +} + +setupHelp();</pre> + +<p>위의 경우 var 대신 let을 사용하여 모든 클로저가 블록 범위 변수를 바인딩할 것이므로 추가적인 클로저를 사용하지 않아도 완벽하게 동작할 것이다.</p> + +<h2 id="성능_관련_고려_사항">성능 관련 고려 사항</h2> + +<p>특정 작업에 클로저가 필요하지 않는데 다른 함수 내에서 함수를 불필요하게 작성하는 것은 현명하지 않다. 이것은 처리 속도와 메모리 소비 측면에서 스크립트 성능에 부정적인 영향을 미칠 것이다.</p> + +<p>예를 들어, 새로운 객체/클래스를 생성 할 때, 메소드는 일반적으로 객체 생성자에 정의되기보다는 객체의 프로토타입에 연결되어야 한다. 그 이유는 생성자가 호출 될 때마다 메서드가 다시 할당되기 때문이다 (즉, 모든 개체가 생성 될 때마다).</p> + +<p>비실용적이지만 시범적인 다음 예를 고려하라:</p> + +<pre>function MyObject(name, message) { + this.name = name.toString(); + this.message = message.toString(); + this.getName = function() { + return this.name; + }; + + this.getMessage = function() { + return this.message; + }; +} +</pre> + +<p>앞의 코드는 클로저의 이점을 이용하지 않음으로 다음과 같이 다시 쓸 수 있다.</p> + +<pre>function MyObject(name, message) { + this.name = name.toString(); + this.message = message.toString(); +} +MyObject.prototype = { + getName: function() { + return this.name; + }, + getMessage: function() { + return this.message; + } +}; +</pre> + +<p>그러나 프로토타입을 다시 정의하는 것은 권장되지 않음으로 기존 프로토타입에 추가하는 다음 예제가 더 좋다.</p> + +<pre>function MyObject(name, message) { + this.name = name.toString(); + this.message = message.toString(); +} +MyObject.prototype.getName = function() { + return this.name; +}; +MyObject.prototype.getMessage = function() { + return this.message; +}; +</pre> + +<p>위의 코드는 같은 결과를 가진 더 깨끗한 방법으로 작성할 수도 있다:</p> + +<pre>function MyObject(name, message) { + this.name = name.toString(); + this.message = message.toString(); +} +(function() { + this.getName = function() { + return this.name; + }; + this.getMessage = function() { + return this.message; + }; +}).call(MyObject.prototype); +</pre> + +<p>앞의 두 가지 예제에서 상속된 프로토타입은 모든 객체에서 공유될 수 있으며 메소드 정의는 모든 객체 생성시 발생할 필요가 없다. <a href="/en-US/docs/JavaScript/Guide/Details_of_the_Object_Model" title="en-US/docs/JavaScript/Guide/Details of the Object Model">객체 모델의 세부 사항</a>을 참고하라.</p> diff --git a/files/ko/web/javascript/guide/control_flow_and_error_handling/index.html b/files/ko/web/javascript/guide/control_flow_and_error_handling/index.html new file mode 100644 index 0000000000..fa007d6997 --- /dev/null +++ b/files/ko/web/javascript/guide/control_flow_and_error_handling/index.html @@ -0,0 +1,433 @@ +--- +title: 제어 흐름과 에러 처리 +slug: Web/JavaScript/Guide/Control_flow_and_error_handling +tags: + - 가이드 + - 자바 스크립트 + - 초보자 +translation_of: Web/JavaScript/Guide/Control_flow_and_error_handling +--- +<p>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Grammar_and_types", "Web/JavaScript/Guide/Loops_and_iteration")}}</p> + +<p class="summary">JavaScript는 어플리케이션 상의 상호작용을 통합하는데 사용할 수 있는 일련의 문법, 특히 제어흐름 문을 지원합니다. 이 장에서는 이러한 문법의 개요를 제공합니다.</p> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Statements">JavaScript reference</a>는 이 장의 문법에 대한 철저하고 자세한 내용은 포함하고 있습니다. 세미콜론 (;) 은 JavaScript 코드 상에서 문장을 나누는데 사용됩니다. </p> + +<p> JavaScript 표현식도 문법입니다. 표현식에 대한 자세한 내용은 <a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators">Expressions and operators</a>를 참조하세요.</p> + +<h2 id="Block_문">Block 문</h2> + +<p>Block 문은 코드를 묶는 가장 기본적인 문법입니다. Block 문은 중괄호 ( { } )에 의해 범위가 결정됩니다.</p> + +<pre class="brush: js">{ + statement_1; + statement_2; + . + . + . + statement_n; +} +</pre> + +<h3 id="예시">예시</h3> + +<p>Block 문은 일반적으로 제어 흐름 문(if, for, while)과 함께 사용됩니다.</p> + +<pre class="brush: js">while (x < 10) { + x++; +} +</pre> + +<p>여기서, <code>{ x++; }</code>는 block 문입니다.</p> + +<p><strong>중요</strong>: ECMAScript2015 이전의 JavaScript는 <strong>블록 범위를 가지고 있지 않습니다.</strong> Block 내에서 선언한 변수는 블록을 넘어 변수가 위치한 함수 혹은 스크립트에 영향을 끼치게 됩니다.즉, block 문은 변수의 범위를 정의하지 않습니다. 자바스크립트의 "독립" block 은 C 혹은 Java의 그것과 완전히 다른 결과를 가집니다. 예를 들어:</p> + +<pre class="brush: js">var x = 1; +{ + var x = 2; +} +console.log(x); // outputs 2 +</pre> + +<p>블록 내에 var x 문이 블록 전에 var x 문과 같은 범위에 있기 때문에 2를 출력합니다. C 나 Java에서 해당 코드는 1을 출력합니다.</p> + +<p>ECMAScript2015부터, <code>let</code> 그리고 <code>const</code> 변수 선언으로 변수의 블록 범위를 제한할 수 있습니다. 자세한 내용은 {{jsxref("Statements/let", "let")}}와 {{jsxref("Statements/const", "const")}} 참조 페이지를 참조하세요.</p> + +<h2 id="조건문">조건문</h2> + +<p>조건문은 특정 조건이 참인 경우에 실행하는 명령의 집합입니다. JavaScript는 두 가지 조건문을 지원합니다: <code>if...else</code> and <code>switch</code>.</p> + +<h3 id="if...else_문"><code>if...else</code> 문</h3> + +<p>특정 조건이 참인 경우 문장을 실행하기 위해 if 문을 사용합니다. 또한 선택적으로 조건이 거짓인 경우 문장을 실행하기 위해서는 else 절을 사용합니다. 다음과 같은 경우 :</p> + +<pre class="brush: js">if (condition) { + statement_1; +} else { + statement_2; +}</pre> + +<p>조건의 참과 거짓에 따라 수행문이 정해질 때 사용할 수 있습니다.. 무엇이 참과 거짓으로 평가되는 지에 대한 설명은 <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean#Description">Boolean</a>을 참조하세요. 조건이 참으로 평가되면, statement_1은 실행됩니다. 그렇지 않으면, statement_2가 실행됩니다. statement_1과 statement_2는 if문이 더 중첩 된 경우를 포함한 문장이 될 수도 있습니다.</p> + +<p>다음과 같은 순서대로 나열된 여러 조건을 가지고 else if를 사용하여 문장을 복잡하게 할 수 있습니다:</p> + +<pre class="brush: js">if (condition_1) { + statement_1; +} else if (condition_2) { + statement_2; +} else if (condition_n) { + statement_n; +} else { + statement_last; +} +</pre> + +<p>여러 줄의 문장을 실행하기 위해, block 문(<code>{ ... }</code>)안에 코드들을 작성합니다. 일반적으로, 특히 코드가 중첩할 때, 항상 block 문을 사용하는 것이 좋은 습관입니다:</p> + +<pre class="brush: js">if (condition) { + statement_1_runs_if_condition_is_true; + statement_2_runs_if_condition_is_true; +} else { + statement_3_runs_if_condition_is_false; + statement_4_runs_if_condition_is_false; +} +</pre> + +<div>조건문 안에서의 변수값 할당은 사용하지 않는 것이 좋습니다. 왜냐하면 그것은 코드를 자세히 보지 않는 경우, 동등비교연산자로 오해할 수 있기 때문입니다. 예를 들어, 다음 코드는 사용하지 마세요.</div> + +<div class="warning"> +<p>if (x = y) {<br> + /* statements here */<br> + }</p> +</div> + +<p>만약 조건식에 할당을 사용해야하는 경우, 일반적인 관행은 할당 주위에 추가 괄호를 넣는 것입니다. 예를 들어:</p> + +<pre class="brush: js">if ((x = y)) { + /* statements here */ +} +</pre> + +<h4 id="거짓으로_취급하는_값">거짓으로 취급하는 값</h4> + +<p>다음과 같은 값은 거짓으로 평가됩니다:</p> + +<ul> + <li><code>false</code></li> + <li><code>undefined</code></li> + <li><code>null</code></li> + <li><code>0</code></li> + <li><code>NaN</code></li> + <li>the empty string (<code>""</code>)</li> +</ul> + +<p>조건문에 전달되었을 때 모든 개체를 포함하여 다른 모든 값은 참으로 평가합니다.</p> + +<p>{{jsxref("Boolean")}} 개체의 참과 거짓 값으로 원시 boolean 값 true와 false를 혼동하지 마세요. 예를 들어:</p> + +<pre class="brush: js">var b = new Boolean(false); +if (b) // this condition evaluates to true +</pre> + +<h4 id="예시_2">예시</h4> + +<p>다음 예에서, <code>텍스트</code> 개체의 문자 수가 3인 경우 함수 <code>checkData</code>는 <code>true</code>를 반환합니다; 그렇지 않으면 경고를 표시하고 <code>false</code>를 반환합니다.</p> + +<pre class="brush: js">function checkData() { + if (document.form1.threeChar.value.length == 3) { + return true; + } else { + alert("Enter exactly three characters. " + + document.form1.threeChar.value + " is not valid."); + return false; + } +} +</pre> + +<h3 id="switch문"><font face="Consolas, Monaco, Andale Mono, monospace"><code>switch</code>문</font></h3> + +<p>Switch문은 프로그램이 표현식을 평가하고 값을 조건과 비교합니다. 만약 값이 일치한다면, 프로그램은 각 조건의 하위 문장을 실행합니다. Switch문은 아래와 같이 사용합니다.:</p> + +<pre class="brush: js">switch (expression) { + case label_1: + statements_1 + [break;] + case label_2: + statements_2 + [break;] + ... + default: + statements_def + [break;] +} +</pre> + +<p>프로그램은 주어진 값과 일치하는 case 라벨을 찾습니다. 그리고나서 관련된 구문을 수행합니다. 만약 매치되는 라벨이 없다면 그 default 절을 찾습니다. 찾게되면, 관련된 구문을 수행합니다. default 절을 못 찾게 된다면 프로그램의 switch문은 종료됩니다. 관례상, default 절은 마지막절입니다. 하지만 꼭 그럴 필요는 없습니다.</p> + +<p>한번 일치된 문장이 수행되고 switch문을 따라서 계속 수행한다면 각각의 조건절로 연결된 선택적인 break문은 그 프로그램이 switch문을 벗어나게 합니다. 만약 break문이 생략된다면, 그 프로그램은 switch문안에서 다음 문장을 계속 수행합니다.</p> + +<h4 id="예시_3"><strong>예시</strong></h4> + +<p>아래 예에서, 만약 "fruittype"가 "Bananas"라면, 프로그램은 case "Bananas"와 값이 일치합니다. 그리고 관련된 문장을 실행합니다. 프로그램의 switch문은 break문을 만났을 때 종료됩니다. 그리고 switch문 다음에 나오는 문장을 실행합니다. 만약 break문이 생략되면, 조건문 "Cherries" 와 관련된 문장도 실행됩니다.</p> + +<pre class="brush: js">switch (fruittype) { + case "Oranges": + console.log("Oranges are $0.59 a pound."); + break; + case "Apples": + console.log("Apples are $0.32 a pound."); + break; + case "Bananas": + console.log("Bananas are $0.48 a pound."); + break; + case "Cherries": + console.log("Cherries are $3.00 a pound."); + break; + case "Mangoes": + console.log("Mangoes are $0.56 a pound."); + break; + case "Papayas": + console.log("Mangoes and papayas are $2.79 a pound."); + break; + default: + console.log("Sorry, we are out of " + fruittype + "."); +} +console.log("Is there anything else you'd like?");</pre> + +<p> </p> + +<h2 id="예외처리문">예외처리문</h2> + +<p>여러분은 throw문을 사용하는 예외들을 사용 할 수 있고 try...catch문을 사용하는 예외들 또한 다룰 수 있습니다.</p> + +<ul> + <li><a href="#throw_statement"><code>throw</code> </a>문</li> + <li><a href="#try_catch_statement"><code>try...catch</code> </a>문</li> +</ul> + +<h3 id="예외_유형">예외 유형</h3> + +<p>대부분 자바스크립트안에서 사용될 수 있습니다. 그럼에도 불구하고, 반드시 사용되는 객체들이 같은 것으로 만들어 지지는 않습니다. 이것들은 에러같은 숫자들이나 문자열들을 사용하는데 흔한 일이지만 특히 이런 목적으로 만들어진 예외 유형중 하나를 사용하는데 더 효과적입니다:</p> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Reference/Global_Objects#Fundamental_objects">ECMAScript exceptions</a></li> + <li>{{domxref("DOMException")}} and {{domxref("DOMError")}}</li> +</ul> + +<h3 id="throw_문"><code>throw</code> 문</h3> + +<p>예외를 사용할 때 <code>throw</code> 문을 사용합니다. 여러분이 예외를 사용할 때, 사용되는 값을 포함하는 표현을 명시해야합니다:</p> + +<pre class="syntaxbox">throw expression; +</pre> + +<p>여러분은 구체적 유형의 표현이 아니라도 어떤 표현이든지 사용할 것입니다. 다음 코드는 다양한 유형중의 여러 예외들을 사용합니다:</p> + +<pre class="brush: js">throw "Error2"; // String type +throw 42; // Number type +throw true; // Boolean type +throw {toString: function() { return "I'm an object!"; } }; +</pre> + +<div class="note"><strong>Note:</strong> 여러분은 <em> 예외를 사용할때 </em>객체를 명시할 수 있습니다. 그리고나서 <code>catch</code> 문안에서 객체의 특성들을 참조 할 수 있습니다. 다음 예시는 <code>myUserException</code> of type <code>UserException</code>객체를 만듭니다 그리고 throw문에서 사용합니다.</div> + +<pre class="brush: js">// Create an object type UserException +function UserException (message){ + this.message=message; + this.name="UserException"; +} + +// Make the exception convert to a pretty string when used as a string +// (e.g. by the error console) +UserException.prototype.toString = function () { + return this.name + ': "' + this.message + '"'; +} + +// Create an instance of the object type and throw it +throw new UserException("Value too high");</pre> + +<h3 id="try...catch_문법"><code>try...catch</code> 문법</h3> + +<p><code>try...catch</code> 문법은 시도할 블록을 표시하고, 예외가 발생하였을때, 하나 이상의 반응을 명시합니다. 만약 예외가 발생하였을때, <code>try...catch</code> 문법은 예외를 잡아냅니다.</p> + +<p><code>try...catch</code> 문법은 하나 이상의 문장을 포함한 <code>try</code> 블록과, <code>try</code> 블록 에서 예외가 발생하였을때, 어떤 것을 할 것인지 명시된 문장을 포함한 0개 이상의 <code>catch</code> 블록으로 구성됩니다. <code>try</code> 블록이 성공하길 원하고, <code>try</code> 블록이 성공하지 않았다면, 제어를 <code>catch</code> 블록으로 넘기고 싶을 것입니다. 만약 <code>try</code> 블록(또는 <code>try</code> 블록에서 호출하는 함수) 의 문장이 예외를 발생시켰을때, 제어는 즉시 <code>catch</code> 블록으로 이동합니다. 만약 <code>try</code> 블록에서 예외가 발생하지 않았을 때, <code>catch</code> 블록을 건너뜁니다. <code>finally</code> 블록은 <code>try</code> 블록과 <code>catch</code> 블록의 시행이 끝나고 <code>try...catch</code> 문법 다음의 문장이 시행 되기 전에 시행됩니다.</p> + +<p>다음의 예제는 <code>try...catch</code> 문법을 사용합니다. 예제는 함수에 전해진 값을 토대로 달의 이름을 검색하는 함수를 호출합니다. 만약 값이 달 숫자값(1-12) 에 일치하지 않으면,<code>"InvalidMonthNo"</code> 라는 값과 함께 예외가 발생하고 <code>catch</code> 블록의 문장들이 <code>monthName</code> 변수를 <code>unknown</code> 값으로 설정합니다.</p> + +<pre class="brush: js">function getMonthName (mo) { + mo = mo-1; // Adjust month number for array index (1=Jan, 12=Dec) + var months = ["Jan","Feb","Mar","Apr","May","Jun","Jul", + "Aug","Sep","Oct","Nov","Dec"]; + if (months[mo] != null) { + return months[mo]; + } else { + throw "InvalidMonthNo"; //throw keyword is used here + } +} + +try { // statements to try + monthName = getMonthName(myMonth); // function could throw exception +} +catch (e) { + monthName = "unknown"; + logMyErrors(e); // pass exception object to error handler +} +</pre> + +<h4 id="The_catch_Block" name="The_catch_Block"><code>catch</code> 블록</h4> + +<p><code>try</code> 블록에서 발생할수 있는 모든 예외를 처리하기 위해 <code>catch</code> 블록을 사용할 수 있습니다.</p> + +<pre class="syntaxbox">catch (catchID) { + statements +} +</pre> + +<p><code>catch</code> 블록은 <code>throw</code>문장에 의해 명시된 값을 가지고 있는 식별자(앞 구문의 <code>catchID</code>)를 명시합니다; 이 식별자를 발생된 예외에 대한 정보를 얻기 위하여 사용할 수 있습니다. 자바스크립트는 <code>catch</code> 블록에 진입했을때 식별자를 생성합니다; 식별자는 <code>catch</code> 블록에 있는 동안만 유지됩니다; <code>catch</code> 블록의 시행이 끝난 후, 식별자는 더이상 사용하실 수 없습니다.</p> + +<p>예를 들어, 다음의 코드는 예외를 발생시킵니다. 예외가 발생하였을때, 제어는 <code>catch</code> 블록으로 넘어갑니다.</p> + +<pre class="brush: js">try { + throw "myException" // generates an exception +} +catch (e) { + // statements to handle any exceptions + logMyErrors(e) // pass exception object to error handler +} +</pre> + +<h4 id="finally_블록"><code>finally</code> 블록</h4> + +<p><code>finally</code> 블록은 <code>try</code> 블록과 <code>catch</code> 블록이 시행되고, <code>try...catch</code> 문법 다음 문장이 시행되기 전에 시행되는 문장들을 포함하고 있습니다. <code>finally</code> 블록은 예외가 발생하든 안하든 수행됩니다. 만약 예외가 발생하였을때, <code>finally</code> 블록 안의 문장들은 어떤 <code>catch</code> 블록도 예외를 처리하지 않더라도 시행됩니다.</p> + +<p><code>finally</code> 블록을 예외가 발생하였을때 여러분의 스크립트가 우아하게 실패하도록 만들기 위하여 사용할 수 있습니다. 예를 들어, 여러분의 스크립트가 묶어둔 자원들을 풀어줄 필요가 있습니다. 다음의 예제는 파일을 열고, 파일을 사용하는 문장(서버 측 자바스크립트는 파일에 접근하는 것을 허가합니다)을 시행합니다. 만약 파일이 열린 동안 예외가 발생했다면, <code>finally</code> 블록은 스크립트가 실패하기 전에 파일을 닫아줍니다.</p> + +<pre class="brush: js">openMyFile(); +try { + writeMyFile(theData); //This may throw a error +} catch(e) { + handleError(e); // If we got a error we handle it +} finally { + closeMyFile(); // always close the resource +} +</pre> + +<p>만약 <code>finally</code> 블록이 값을 반환하였을 경우, <code>try</code> 블록과 <code>catch</code>블록의 <code>return</code> 문장과 상관없이 전체 <code>try-catch-finally</code> 생산물의 반환값이 됩니다:</p> + +<pre class="brush: js">function f() { + try { + console.log(0); + throw "bogus"; + } catch(e) { + console.log(1); + return true; // this return statement is suspended + // until finally block has completed + console.log(2); // not reachable + } finally { + console.log(3); + return false; // overwrites the previous "return" + console.log(4); // not reachable + } + // "return false" is executed now + console.log(5); // not reachable +} +f(); // alerts 0, 1, 3; returns false +</pre> + +<p><code>finally</code> 블록에 의한 반환값 덮어쓰기는 예외가 발생하거나 다시 예외가 발생했을때 또한 적용됩니다.</p> + +<pre class="brush: js">function f() { + try { + throw "bogus"; + } catch(e) { + console.log('caught inner "bogus"'); + throw e; // this throw statement is suspended until + // finally block has completed + } finally { + return false; // overwrites the previous "throw" + } + // "return false" is executed now +} + +try { + f(); +} catch(e) { + // this is never reached because the throw inside + // the catch is overwritten + // by the return in finally + console.log('caught outer "bogus"'); +} + +// OUTPUT +// caught inner "bogus"</pre> + +<h4 id="Nesting_try...catch_Statements" name="Nesting_try...catch_Statements">try...catch 문법 중첩하기</h4> + +<p> </p> + +<p>하나 이상의 <code>try ... catch</code> 문을 중첩 할 수 있습니다. 중첩된 안쪽 <code>try ... catch</code> 문에 <code>catch</code> 블록이 없으면 <code>finally</code> 블록이 있어야하고 <code>try ... catch</code> 문의 <code>catch</code> 블록에 일치하는 항목이 있는지 확인해야합니다. 자세한 내용은 <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/try...catch">try...catch</a> 참조 페이지의 <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/try...catch#Nested_try-blocks">nested try-blocks</a>을 참조하십시오.</p> + +<h3 id="Error_객체를_도구화_하기"><code>Error</code> 객체를 도구화 하기</h3> + +<p>오류의 종류에 따라, 더 정제된 메세지를 얻기 위하여 'name'속성과 'message'속성을 사용할수도 있습니다. 'name'속성은 오류의 일반 클래스(e.g., 'DOMException' 또는 'Error')를 제공하고, 'message' 속성이 error 객체를 문자열로 바꿀수 있는 것 보다 더 간결한 메세지를 제공합니다.</p> + +<p>만약 이 속성들에 대하여 이득을 얻기 위해(여러분의 catch 블록이 시스템의 예외와 여러분의 예외를 구분하지 않을 때와 같은 것) 여러분만의 예외를 발생시킨다면, 여러분은 Error 생성자를 사용할 수 있습니다. 예를 들어:</p> + +<pre class="brush: js">function doSomethingErrorProne () { + if (ourCodeMakesAMistake()) { + throw (new Error('The message')); + } else { + doSomethingToGetAJavascriptError(); + } +} +.... +try { + doSomethingErrorProne(); +} +catch (e) { + console.log(e.name); // logs 'Error' + console.log(e.message); // logs 'The message' or a JavaScript error message) +}</pre> + +<h2 id="Promises">Promises</h2> + +<p>ECMAScript2015를 시작하면서, 자바스크립트는 지연된 흐름과 비동기식의 연산을 제어할 수 있게 하는 {{jsxref("Promise")}} 객체에 대한 지원을 얻게 되었습니다.</p> + +<p><code>Promise</code> 는 다음의 상태중 하나입니다:</p> + +<ul> + <li><em>pending</em>: 초기상태, fulfilled 되거나 rejected 되지 않음.</li> + <li><em>fulfilled</em>: 연산 수행 성공.</li> + <li><em>rejected</em>: 연산 수행 실패.</li> + <li><em>settled</em>: Promise 가 fulfilled 이거나 rejected 이지만 pending 은 아님.</li> +</ul> + +<p><img alt="" src="https://mdn.mozillademos.org/files/8633/promises.png" style="height: 297px; width: 801px;"></p> + +<h3 id="XHR_를_통해_이미지_불러오기">XHR 를 통해 이미지 불러오기</h3> + +<p>이미지를 불러오기 위해 <code>Promise</code> 와 <code><a href="/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequest</a></code> 를 사용한 간단한 예제는 MDN GitHub <a href="https://github.com/mdn/promises-test/blob/gh-pages/index.html"> promise-test</a> repository 에 있습니다. <a href="http://mdn.github.io/promises-test/">이 예제 가 동작하는 것을 보실 수 있습니다.</a> 각 단계는 설명되어있고 Promise 와 XHR 구조를 친밀하게 이해할수 있게 합니다. 여기 Promise 흐름을 보여줘서 아이디어를 얻을 수 있는 설명되지 않은 버전이 있습니다:</p> + +<pre class="brush: js">function imgLoad(url) { + return new Promise(function(resolve, reject) { + var request = new XMLHttpRequest(); + request.open('GET', url); + request.responseType = 'blob'; + request.onload = function() { + if (request.status === 200) { + resolve(request.response); + } else { + reject(Error('Image didn\'t load successfully; error code:' + + request.statusText)); + } + }; + request.onerror = function() { + reject(Error('There was a network error.')); + }; + request.send(); + }); +}</pre> + +<p>더 자세한 정보를 얻기 위해선, {{jsxref("Promise")}} 참고 페이지를 보세요.</p> + +<div>{{PreviousNext("Web/JavaScript/Guide/Grammar_and_types", "Web/JavaScript/Guide/Loops_and_iteration")}}</div> diff --git a/files/ko/web/javascript/guide/expressions_and_operators/index.html b/files/ko/web/javascript/guide/expressions_and_operators/index.html new file mode 100644 index 0000000000..f5e711304f --- /dev/null +++ b/files/ko/web/javascript/guide/expressions_and_operators/index.html @@ -0,0 +1,926 @@ +--- +title: 표현식과 연산자 +slug: Web/JavaScript/Guide/Expressions_and_Operators +tags: + - Beginner + - Expressions + - Guide + - JavaScript + - Operators + - 'l10n:priority' + - 연산자 +translation_of: Web/JavaScript/Guide/Expressions_and_Operators +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Functions", "Web/JavaScript/Guide/Numbers_and_dates")}}</div> + +<p class="summary">이 장은 JavaScript의 표현식과 할당, 비교, 산술, 비트 계산, 논리, 문자열, 삼항 등 여러 가지 연산자를 설명합니다.</p> + +<p>연산자와 표현식의 완전하고 구체적인 목록도 <a href="/ko/docs/Web/JavaScript/Reference/Operators">참고서</a>에서 확인할 수 있습니다.</p> + +<h2 id="연산자">연산자</h2> + +<p>JavaScript는 다음과 같은 형태의 연산자가 있습니다. 이 절은 연산자에 대하여 설명하고, 연산자 우선순위에 관한 정보를 포함하고 있습니다.</p> + +<ul> + <li><a href="#할당_연산자">할당 연산자</a></li> + <li><a href="#비교_연산자">비교 연산자</a></li> + <li><a href="#산술_연산자">산술 연산자</a></li> + <li><a href="#비트_연산자">비트 연산자</a></li> + <li><a href="#논리_연산자">논리 연산자</a></li> + <li><a href="#문자열_연산자">문자열 연산자</a></li> + <li><a href="#조건_(삼항)_연산자">조건 (삼항) 연산자</a></li> + <li><a href="#쉼표_연산자">쉼표 연산자</a></li> + <li><a href="#단항_연산자">단항 연산자</a></li> + <li><a href="#관계_연산자">관계 연산자</a></li> +</ul> + +<p>JavaScript는 이항 연산자와 단항연산자, 조건연산자인 단 하나 존재하는 삼항 연산자를 가지고 있습니다. 이항 연산자는 하나는 좌변에 다른 하나는 우변에 두개의 피연산자가 필요합니다:</p> + +<pre class="syntaxbox"><em>피연산자1</em> <em>연산자</em> <em>피연산자2</em> +</pre> + +<p>예를 들면 <code>3+4</code> 또는 <code>x*y</code>와 같습니다.</p> + +<p>단항 연산자는 연산자 뒤에든 앞에든 하나의 피연산자를 필요로 합니다.:</p> + +<pre class="syntaxbox"><em>연산자</em> <em>피연산자</em> +</pre> + +<p>또는</p> + +<pre class="syntaxbox"><em>피연산자</em> <em>연산자</em> +</pre> + +<p><code>x++</code> 또는 <code>++x</code>를 예시로 들 수 있습니다.</p> + +<h3 id="할당_연산자">할당 연산자</h3> + +<p><a href="/ko/docs/Web/JavaScript/Reference/Operators/Assignment_Operators">할당 연산자</a>는 오른쪽 피연산자의 값을 왼쪽 피연산자에 할당합니다. 기본적인 할당 연산자는 오른쪽의 피연산자 값을 왼쪽 피연산자 값에 할당하는 등호(<code>=</code>) 입니다. 즉 <code>x = y</code> 는 <code>y</code> 값을 <code>x</code>에 할당합니다.</p> + +<p>다음의 표에 나열된 연산의 약칭인 복합 할당 연산자도 존재합니다:</p> + +<table class="standard-table"> + <caption>복합 할당 연산자</caption> + <thead> + <tr> + <th>이름</th> + <th>복합 할당 연산자</th> + <th>뜻</th> + </tr> + </thead> + <tbody> + <tr> + <td><a href="#Assignment">할당</a></td> + <td><code>x = y</code></td> + <td><code>x = y</code></td> + </tr> + <tr> + <td><a href="#Addition_assignment">덧셈 할당</a></td> + <td><code>x += y</code></td> + <td><code>x = x + y</code></td> + </tr> + <tr> + <td><a href="#Subtraction_assignment">뺄셈 할당</a></td> + <td><code>x -= y</code></td> + <td><code>x = x - y</code></td> + </tr> + <tr> + <td><a href="#Multiplication_assignment">곱셈 할당</a></td> + <td><code>x *= y</code></td> + <td><code>x = x * y</code></td> + </tr> + <tr> + <td><a href="#Division_assignment">나눗셈 할당</a></td> + <td><code>x /= y</code></td> + <td><code>x = x / y</code></td> + </tr> + <tr> + <td><a href="#Remainder_assignment">나머지 연산 할당</a></td> + <td><code>x %= y</code></td> + <td><code>x = x % y</code></td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#지수_연산_할당">지수 연산 할당</a> {{experimental_inline}}</td> + <td><code>x **= y</code></td> + <td><code>x = x ** y</code></td> + </tr> + <tr> + <td><a href="#Left_shift_assignment">왼쪽 이동 연산 할당</a></td> + <td><code>x <<= y</code></td> + <td><code>x = x << y</code></td> + </tr> + <tr> + <td><a href="#Right_shift_assignment">오른쪽 이동 연산 할당</a></td> + <td><code>x >>= y</code></td> + <td><code>x = x >> y</code></td> + </tr> + <tr> + <td><a href="#Unsigned_right_shift_assignment">부호 없는 오른쪽 이동 연산 할당</a></td> + <td><code>x >>>= y</code></td> + <td><code>x = x >>> y</code></td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#비트_AND_할당">비트 AND 할당</a></td> + <td><code>x &= y</code></td> + <td><code>x = x & y</code></td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#비트_XOR_할당">비트 XOR 할당</a></td> + <td><code>x ^= y</code></td> + <td><code>x = x ^ y</code></td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#비트_OR_할당">비트 OR 할당</a></td> + <td><code>x |= y</code></td> + <td><code>x = x | y</code></td> + </tr> + </tbody> +</table> + +<h4 id="구조_분해">구조 분해</h4> + +<p>복잡한 할당 연산에서, <a href="/ko/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">구조 분해 할당</a> 구문은 배열이나 객체의 구조를 반영하여 배열이나 객체에서 데이터를 추출할 수 있게 해주는 JavaScript 표현식입니다.</p> + +<pre class="brush: js">var foo = ['one', 'two', 'three']; + +// 구조 분해를 활용하지 않은 경우 +var one = foo[0]; +var two = foo[1]; +var three = foo[2]; + +// 구조 분해를 활용한 경우 +var [one, two, three] = foo;</pre> + +<h3 id="비교_연산자">비교 연산자</h3> + +<p><a href="/ko/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">비교 연산자</a>는 피연산자들을 비교하고 비교에 따라 논리 값을 반환합니다. 피연산자들은 숫자, 문자열, 논리형, 객체 를 사용할 수 있습니다. 문자열은 유니코드 값을 사용하여 표준 사전순서를 기반으로 비교합니다. 만약 두 피연산자가 다른 형태일 경우, JavaScript는 대부분 비교를 위해 피연산자를 적절한 타입으로 변환합니다. 이런 행동은 보통 숫자로 피연산자를 숫자로 비교하는 형태로 나타납니다. 형태를 바꾸기의 유일한 예외는 엄격한 비교를 수행하는 <code>===</code> 과 <code>!==</code> 연산이 관련되는 경우입니다. 이런 연산자는 비교를 위해 피연산자의 형태를 적절히 바꾸려고 시도하지 않습니다. 다음 표는 샘플 코드를 통해 비교 연산자에 대하여 설명합니다:</p> + +<pre><code>var var1 = 3; +var var2 = 4;</code> +</pre> + +<table class="standard-table"> + <caption>비교 연산자</caption> + <thead> + <tr> + <th scope="col">연산자</th> + <th scope="col">설명</th> + <th scope="col">참을 반환하는 예제</th> + </tr> + </thead> + <tbody> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Equality">동등</a> (<code>==</code>)</td> + <td>피연산자들이 같으면 참을 반환합니다.</td> + <td><code>3 == var1</code> + <p><code>"3" == var1</code></p> + <code>3 == '3'</code></td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Inequality">부등</a> (<code>!=</code>)</td> + <td>피연산자들이 다르면 참을 반환합니다.</td> + <td><code>var1 != 4<br> + var2 != "3"</code></td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Identity">일치</a> (<code>===</code>)</td> + <td>피연산자들이 같고 피연산자들의 같은 형태인 경우 참을 반환합니다. {{jsxref("Object.is")}} 와 <a href="/ko/docs/Web/JavaScript/Equality_comparisons_and_sameness" title="/ko/docs/Web/JavaScript/Guide/Sameness">JavaScript에서의 같음</a>을 참고하세요.</td> + <td><code>3 === var1</code></td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Nonidentity">불일치</a> (<code>!==</code>)</td> + <td>피연산자들이 다르거나 형태가 다른 경우 참을 반환합니다.</td> + <td><code>var1 !== "3"<br> + 3 !== '3'</code></td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Greater_than_operator">~보다 큰</a> (<code>></code>)</td> + <td>좌변의 피연산자 보다 우변의 피연산자가 크면 참을 반환합니다.</td> + <td><code>var2 > var1<br> + "12" > 2</code></td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Greater_than_or_equal_operator">~보다 크거나 같음</a> (<code>>=</code>)</td> + <td>좌변의 피연산자 보다 우변의 피연산자가 크거나 같으면 참을 반환합니다.</td> + <td><code>var2 >= var1<br> + var1 >= 3</code></td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Less_than_operator">~보다 작음</a> (<code><</code>)</td> + <td>좌변의 피연산자 보다 우변의 피연산자가 작으면 참을 반환합니다.</td> + <td><code>var1 < var2<br> + "2" < 12</code></td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Less_than_or_equal_operator">~보다 작거나 같음</a> (<code><=</code>)</td> + <td>좌변의 피연산자 보다 우변의 피연산자가 작거나 같으면 참을 반환합니다.</td> + <td> + <p><code>var1 <= var2<br> + var2 <= 5</code></p> + </td> + </tr> + </tbody> +</table> + +<div class="note"> +<p><strong>참고: </strong>(<code>=></code>) 은 연산자가 아니고, 화살표 함수(<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">Arrow functions</a>)를 나타내는 기호입니다.</p> +</div> + +<h3 id="산술_연산자">산술 연산자</h3> + +<p><a href="/ko/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators">산술 연산자</a>는 숫자값(리터럴 또는 변수)을 피연산자로 갖고, 하나의 숫자 값을 반환합니다. 기본적인 산술 연산자는 덧셈(<code>+</code>), 뺄셈 (<code>-</code>), 곱셈 (<code>*</code>), 나눗셈 (<code>/</code>)입니다. 이 연산자들은 대부분의 다른 프로그래밍 언어들이 부동소수점 값을 연산하는것처럼 동작합니다. (0 으로 나누는 것은 {{jsxref("Infinity")}} 을 발생시키는 것을 기억하세요) 예를 들면:</p> + +<pre class="brush: js">1 / 2; // 0.5 +1 / 2 == 1.0 / 2.0; // this is true +</pre> + +<p>또한, 표준 산술 연산자 (+, -, *, /) 에 대해 JavaScript는 다음의 표에 나와 있는 산술 연산자를 제공합니다.</p> + +<table class="fullwidth-table"> + <caption>산술 연산자</caption> + <thead> + <tr> + <th scope="col">연산자</th> + <th scope="col">설명</th> + <th scope="col">예제</th> + </tr> + </thead> + <tbody> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder">나머지 연산자</a> (<code>%</code>)</td> + <td>이항 연산자입니다. 두 피연산자를 나눈후 나머지를 반환합니다.</td> + <td>12 % 5 는 2를 반환합니다.</td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment">증가 연산자</a> (<code>++</code>)</td> + <td>단항 연산자입니다. 피연산자에 1을 더합니다. 만약 연산자를 피연산자 앞(<code>++x</code>)에 사용하면, 피연산자에 1을 더한 값을 반환합니다.; 만약 연산자를 피연산자 뒤(<code>x++</code>)에 사용하면, 피연산자에 1을 더하기 전 값을 반환합니다.</td> + <td><code>x</code> 가 3이면 <code>++x</code> 는 <code>x</code> 를 4로 만들고 4를 반환합니다. 반면 <code>x++</code> 는 3을 반환하고 <code>x</code> 를 4로 만듭니다.</td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Decrement">감소 연산자</a> (<code>--</code>)</td> + <td>단항 연산자입니다. 피연산자로 부터 1을 뺍니다. 반환값은 증가 연산자와 유사합니다.</td> + <td><code>x</code> 가 3이면 <code>--x</code> 는 <code>x</code> 를 2로 만들고2를 반환합니다. 반면 <code>x--</code> 는 3을 반환하고 <code>x</code> 를 2로 만듭니다.</td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_negation">단항 부정 연산자</a> (<code>-</code>)</td> + <td>단항 연산자 입니다. 피연산자의 반대값(부호 바뀐값)을 반환합니다.</td> + <td> <code>x</code> 가 3이면 <code>-x</code> 는 -3을 반환합니다.</td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus">숫자화 연산자</a> (<code>+</code>)</td> + <td>단항연산자 입니다. 피연산자가 숫자값이 아니라면 피연산자를 숫자로 변환하기를 시도합니다.</td> + <td><code>+"3"</code> 은 <code>3</code>을 반환합니다.<br> + <code>+true</code> 는 <code>1.</code> 을 반환합니다.</td> + </tr> + </tbody> +</table> + +<h3 id="비트_연산자">비트 연산자</h3> + +<p><a href="/ko/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators">비트 연산자</a>는 피연산자를 10진수, 16진수, 8진수처럼 취급하지 않고 32비트의 집합으로 취급합니다. 예를 들면, 10진수의 9는 2진수의 1001로 나타낼 수 있습니다. 비트 단위 연산자는 이진법으로 연산을 수행하지만, JavaScript의 표준 숫자값을 반환합니다..</p> + +<p>다음의 표는 JavaScript의 비트단위 연산자의 요약입니다.</p> + +<table class="standard-table"> + <caption>비트 연산자</caption> + <thead> + <tr> + <th scope="col">연산자</th> + <th scope="col">사용법</th> + <th scope="col">설명</th> + </tr> + </thead> + <tbody> + <tr> + <td><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_AND">비트단위 논리곱</a></td> + <td><code>a & b</code></td> + <td>두 피연산자의 각 자리 비트의 값이 둘다 1일 경우 해당하는 자리에 1을 반환합니다.</td> + </tr> + <tr> + <td><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_OR">비트단위 논리합</a></td> + <td><code>a | b</code></td> + <td>두 피연산자의 각 자리 비트의 값이 둘다 0일 경우 해당하는 자리에 0을 반환합니다.</td> + </tr> + <tr> + <td><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_XOR">비트단위 배타적 논리합</a></td> + <td><code>a ^ b</code></td> + <td>두 피연산자의 각 자리 비트의 값이 같을 경우 해당하는 자리에 0을 반환합니다.<br> + [두 피연산자의 각 자리 비트의 값이 다를 경우 해당하는 자리에 1을 반환합니다.]</td> + </tr> + <tr> + <td><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_NOT">비트단위 부정</a></td> + <td><code>~ a</code></td> + <td>피연산자의 각 자리의 비트를 뒤집습니다.</td> + </tr> + <tr> + <td><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Left_shift">왼쪽 시프트</a></td> + <td><code>a << b</code></td> + <td>오른쪽에서 0들을 이동시키면서, a의 이진수의 각 비트를 b비트 만큼 왼쪽으로 이동시킨 값을 반환합니다.</td> + </tr> + <tr> + <td><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Right_shift">부호 전파 오른쪽 시프트</a></td> + <td><code>a >> b</code></td> + <td>사라지는 비트를 버리면서, a의 이진수의 각 비트를 b비트만큼 이동시킨값을 반환합니다.</td> + </tr> + <tr> + <td><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Unsigned_right_shift">부호 없는 오른쪽 시프트</a></td> + <td><code>a >>> b</code></td> + <td>사라지는 비트를 버리고 왼쪽에서 0을 이동시키면서, a의 이진수의 각 비트를 b비트 만큼 이동시킨 값을 반환합니다.</td> + </tr> + </tbody> +</table> + +<h4 id="Bitwise_Logical_Operators" name="Bitwise_Logical_Operators">비트 논리 연산자</h4> + +<p>개념상으로, 비트단위 논리 연산자는 다음과 같이 동작합니다:</p> + +<ul> + <li>피연산자들은 32비트 정수로 변환되고, 비트(0 과 1)의 연속으로 표현됩니다. 숫자는 32비트가 넘는 경우 가장 중요한(왼쪽) 비트부터 제거됩니다. 예를 들면 아래 예처럼 32비트가 넘는 정수는 32비트 정수형으로 변환됩니다: + <pre><code>변환전: 11100110111110100000000000000110000000000001 +변환수: 10100000000000000110000000000001</code></pre> + </li> + <li>처음 피연산자의 각 비트는 두번째 피연산자의 해당하는 비트와 짝지어집니다: 첫번째 비트는 첫번째 비트에, 두번째 비트는 두번째 비트에, 이런식으로 쭉.</li> + <li>연산자는 각 비트 묶음에 적용되고, 결과는 조립된 비트입니다.</li> +</ul> + +<p>예를 들면, 9의 이진표현은 1001이고, 15의 이진표현은 1111입니다. 따라서, 비트단위 연산자가 이 값들에 적용될때, 결과는 다음과 같습니다:</p> + +<table class="standard-table"> + <caption>비트 연산자 예제</caption> + <thead> + <tr> + <th scope="col">표현</th> + <th scope="col">결과</th> + <th scope="col">이진법 설명</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>15 & 9</code></td> + <td><code>9</code></td> + <td><code>1111 & 1001 = 1001</code></td> + </tr> + <tr> + <td><code>15 | 9</code></td> + <td><code>15</code></td> + <td><code>1111 | 1001 = 1111</code></td> + </tr> + <tr> + <td><code>15 ^ 9</code></td> + <td><code>6</code></td> + <td><code>1111 ^ 1001 = 0110</code></td> + </tr> + <tr> + <td><code>~15</code></td> + <td><code>-16</code></td> + <td><code>~</code><code>00000000...</code><code>00001111 = </code><code>1111</code><code>1111</code><code>...</code><code>11110000</code></td> + </tr> + <tr> + <td><code>~9</code></td> + <td><code>-10</code></td> + <td><code>~</code><code>00000000</code><code>...</code><code>0000</code><code>1001 = </code><code>1111</code><code>1111</code><code>...</code><code>1111</code><code>0110</code></td> + </tr> + </tbody> +</table> + +<p>모든 32비트가 비트단위 부정연산자를 통해 뒤집히고, 가장 의미있는(가장 왼쪽의) 비트가 1인 값들이 음수(2의 보수 표기법)로 표현되는것에 주목하세요 . ~x 의 평가 값은 -x -1의 평가값과 동일합니다.</p> + +<h4 id="Bitwise_Shift_Operators" name="Bitwise_Shift_Operators">비트 시프트 연산자</h4> + +<p>비트 단위 연산자는 2개의 피연산자를 가집니다: 첫번째는 이동될 수치이고, 두번째는 첫번째 피연산자가 이동될 비트 자리수를 명시합니다. 비트 이동 연산의 방향은 연산자의 사용에 의해 조종됩니다.</p> + +<p>이동 연산자는 피연산자를 32비트의 정수로 변환하고, 왼쪽의 피연산자와 같은 형태를 반환합니다.</p> + +<p>이동 연산자는 다음의 표에 나열되었습니다.</p> + +<table class="fullwidth-table"> + <caption>비트 시프트 연산자</caption> + <thead> + <tr> + <th scope="col">연산자</th> + <th scope="col">설명</th> + <th scope="col">예제</th> + </tr> + </thead> + <tbody> + <tr> + <td>왼쪽 시프트<br> + (<code><<</code>)</td> + <td>이 연산자는 첫번째 피연산자를 특정한 수의 비트를 왼쪽으로 이동시킵니다. 왼쪽으로 초과되어 이동되는 비트들은 버려집니다. 오른쪽으로부터 0이 이동됩니다.</td> + <td><code>9<<2</code> yields 36, because 1001 shifted 2 bits to the left becomes 100100, which is 36.</td> + </tr> + <tr> + <td>부호 전파 오른쪽 시프트(<code>>></code>)</td> + <td>이 연산자는 첫번째 피연산자를 특정한 수의 비트를 오른쪽으로 이동시킵니다. 오른쪽으로 초과되어 이동되는 비트들은 버려집니다. 왼쪽으로부터 제일 왼쪽의 비트 값이 이동됩니다.</td> + <td><code>9>>2</code> yields 2, because 1001 shifted 2 bits to the right becomes 10, which is 2. Likewise, <code>-9>>2</code> yields -3, because the sign is preserved.</td> + </tr> + <tr> + <td>부호 없는 오른쪽 시프트(<code>>>></code>)</td> + <td>이 연산자는 첫번째 피연산자를 특정한 수의 비트를 오른쪽으로 이동시킵니다. 오른쪽으로 초과되어 이동되는 비트들은 버려집니다. 왼쪽으로부터 0이 이동됩니다 .</td> + <td><code>19>>>2</code> yields 4, because 10011 shifted 2 bits to the right becomes 100, which is 4. For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result.</td> + </tr> + </tbody> +</table> + +<h3 id="논리_연산자">논리 연산자</h3> + +<p><a href="/ko/docs/Web/JavaScript/Reference/Operators/Logical_Operators">논리 연산자</a>는 보통 부울 값과 사용됩니다; 부울 값들과 사용될때, 연산자는 부울값을 반환합니다. <code>그러나,&& 과 </code><code>||</code> 연산자는 실제로 명시된 피연자들 중 하나를 반환합니다. 따라서, 만약 이 연산자들이 부울 값이 아닌 값들과 함께 쓰였을때, 그들은 부울 값이 아닌 값을 반환할지도 모릅니다. 논리 연산자들은 다음의 표에서 설명됩니다.</p> + +<table class="fullwidth-table"> + <caption>논리 연산자</caption> + <tbody> + <tr> + <th>연산자</th> + <th>구문</th> + <th>설명</th> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_AND">논리 AND</a> (<code>&&</code>)</td> + <td><code><em>expr1</em> && <em>expr2</em></code></td> + <td><code>expr1</code>을 <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">true</span></font>로 변환할 수 있는 경우 <code>expr2</code>을 반환하고, 그렇지 않으면 <code>expr1</code>을 반환합니다.</td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_OR">논리 OR</a> (<code>||</code>)</td> + <td><code><em>expr1</em> || <em>expr2</em></code></td> + <td> + <p><code>expr1</code>을 <code>true</code>로 변환할 수 있으면 <code>expr1</code>을 반환하고, 그렇지 않으면 <code>expr2</code>를 반환합니다.</p> + </td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_NOT">논리 NOT</a> (<code>!</code>)</td> + <td><code>!<em>expr</em></code></td> + <td>단일 피연산자를 <code>true</code>로 변환할 수 있으면 <code>false</code>를 반환합니다. 그렇지 않으면 <code>true</code>를 반환합니다.</td> + </tr> + </tbody> +</table> + +<p><code>false</code>로 변환될 수 있는 표현 예제들은 null, 0, NaN, 빈 문자열 (""), 또는 정의되지 않음 으로 평가될 수 있습니다.</p> + +<p>다음의 코드는 <code>&&</code> (논리 곱) 연산자의 예제를 보여주고 있습니다.</p> + +<pre class="brush: js">var a1 = true && true; // t && t returns true +var a2 = true && false; // t && f returns false +var a3 = false && true; // f && t returns false +var a4 = false && (3 == 4); // f && f returns false +var a5 = "Cat" && "Dog"; // t && t returns Dog +var a6 = false && "Cat"; // f && t returns false +var a7 = "Cat" && false; // t && f returns false +</pre> + +<p>다음의 코드는 || (논리 합) 연산자의 예제를 보여주고 있습니다.</p> + +<pre class="brush: js">var o1 = true || true; // t || t returns true +var o2 = false || true; // f || t returns true +var o3 = true || false; // t || f returns true +var o4 = false || (3 == 4); // f || f returns false +var o5 = "Cat" || "Dog"; // t || t returns Cat +var o6 = false || "Cat"; // f || t returns Cat +var o7 = "Cat" || false; // t || f returns Cat +</pre> + +<p>다음의 코드는 ! (논리 부정) 연산자의 예제를 보여주고 있습니다.</p> + +<pre class="brush: js">var n1 = !true; // !t returns false +var n2 = !false; // !f returns true +var n3 = !"Cat"; // !t returns false +</pre> + +<h4 id="Short-Circuit_Evaluation" name="Short-Circuit_Evaluation">단락 평가</h4> + +<p>논리 연산자가 왼쪽에서 오른쪽으로 평가될때, 논리연산자는 다음의 규칙을 따라서 "단축 계산"으로 검사됩니다:</p> + +<ul> + <li><code>false</code> && <em>anything</em> 는 false로 단축 계산됩니다.</li> + <li><code>true</code> || <em>anything</em> 는 true로 단축 계산됩니다.</li> +</ul> + +<p>이 논리 규칙들은 이러한 평가가 언제나 정확하다고 보증합니다. <em>위에서 anything</em> 부분은 평가되지 않았고, 어떤 부작용도 아무런 효과를 미치지 못한다는 것에 주목하세요.</p> + +<h3 id="문자열_연산자">문자열 연산자</h3> + +<p>문자열 값으로 사용될 수 있는 비교 연산자에 덧붙여서, 연결 연산자 (+)는 두 문자열 값을 연결하고,두 문자열이 합쳐진 새로운 문자열을 반환합니다.</p> + +<p>예를 들어,</p> + +<pre class="brush: js"><code>console.log("my " + "string");</code> // console logs the string <code>"my string"</code>.</pre> + +<p>복합 할당 연산자인 += 또한 문자열을 연결하는데 사용할 수 있습니다.</p> + +<p>예를 들어,</p> + +<pre class="brush: js">var <code>mystring</code> = "alpha"; +<code>mystring += "bet"; // </code>evaluates to "alphabet" and assigns this value to <code>mystring</code>.</pre> + +<h3 id="조건_삼항_연산자">조건 (삼항) 연산자</h3> + +<p><a href="/ko/docs/Web/JavaScript/Reference/Operators/Conditional_Operator">조건 연산자</a> 는 JavaScript에서 3개의 항을 사용하는 유일한 연산자 입니다. 조건 연산자는 조건에 따라 2개의 값중 하나를 가질 수 있습니다. 문법은 다음과 같습니다:</p> + +<pre class="syntaxbox"><em>조건</em> ? <em>값1</em> : <em>값2</em> +</pre> + +<p><code>만약 조건이 참이라면, 조건 연산자는 값1을 값으로 갖습니다</code>.<code> 그렇지 않은 경우 조건 연산자는 값2을 값으로 갖습니다</code>. 표준 연산자를 사용하는 어디든 조건연산자를 사용할 수 있습니다.</p> + +<p>에들 들어,</p> + +<pre class="brush: js">var status = (age >= 18) ? "adult" : "minor"; +</pre> + +<p>이 구문은 age 변수가 18보다 같거나 클때 "adult" 값을 <code>status 변수에 할당합니다</code>. 그렇지 않은 경우, 이 구문은 "minor"값을<code> status</code>변수에 할당합니다.</p> + +<h3 id="쉼표_연산자">쉼표 연산자</h3> + +<p><a href="/ko/docs/Web/JavaScript/Reference/Operators/Comma_Operator">쉼표 연산자</a> (<code>,</code>)는 두 피연산자를 평가하고, 마지막 피연산자의 값을 반환합니다. 이 연산자는 주로 <code>for</code> 반복문 안에서 각각의 시간에 복수의 변수들을 갱신하기 위하여 사용합니다.</p> + +<p>예를 들어, a는 각 변에 10개의 원소가 있는 2차원 배열일때, 다음의 코드는 콤마 연산자를 두 변수를 한번에 증가 시키기 위하여 사용하였습니다. 이 코드는 배열의 대각선에 위치한 원소를 출력합니다:</p> + +<pre><code>var x = [0,1,2,3,4,5,6,7,8,9] +var a = [x, x, x, x, x]; + +for (var i = 0, j = 9; i <= j; i++, j--) + console.log('a[' + i + '][' + j + ']= ' + a[i][j]);</code></pre> + +<h3 id="단항_연산자">단항 연산자</h3> + +<p>단항 연산자는 오직 하나의 피연산자를 가지고 연산을합니다.</p> + +<h4 id="delete" name="delete"><code>delete</code></h4> + +<p><code><a href="/ko/docs/Web/JavaScript/Reference/Operators/delete">delete</a></code>연산자는 객체, 객체의 속성 또는 배열의 특정한 위치에 있는 객체를 삭제합니다. 문법은 다음과 같습니다:</p> + +<pre class="brush: js">delete objectName; +delete objectName.property; +delete objectName[index]; +delete property; // legal only within a with statement +</pre> + +<p><code>objectName</code>은 객체의 이름이고, <code>property</code>는 객체에 존재하는 속성이고,<code>index</code>는 배열의 위치를 나타내는 정수입니다.</p> + +<p>네번째 형태의 경우,객체의 속성을 삭제하기 위하여 <code><a href="/ko/docs/Web/JavaScript/Reference/Statements/with">with</a></code> 구문이 있어야만 동작합니다.</p> + +<p><code>delete</code> 연산자를 <code>var</code> 구문을 사용하지 않고 묵시적으로 만들어진 변수를 삭제할 때 사용할 수 있습니다.</p> + +<p>만약 <code>delete</code>연산자의 동작이 성공했다면, delete 연산자는 속성이나, 원소를 <code>undefined</code> 로 설정합니다. <code>delete</code> 연산자는 연산이 수행 가능할때 true값을 반환합니다; 수행이 불가능 할 경우 <code>false</code> 값을 반환합니다.</p> + +<pre class="brush: js">x = 42; +var y = 43; +myobj = new Number(); +myobj.h = 4; // create property h +delete x; // returns true (can delete if declared implicitly) +delete y; // returns false (cannot delete if declared with var) +delete Math.PI; // returns false (cannot delete predefined properties) +delete myobj.h; // returns true (can delete user-defined properties) +delete myobj; // returns true (can delete if declared implicitly) +</pre> + +<h5 id="배열의_원소를_삭제하기">배열의 원소를 삭제하기</h5> + +<p>배열의 원소를 삭제할때, 배열의 길이에는 영향을 주지 못합니다. 예를 들어, 만약 <code>a[3]</code>, <code>a[4]를 삭제 했다면</code> <code>a[4]</code> 와 <code>a[3]는 undefined(정의되지 않음)상태로 되어 있습니다</code>.</p> + +<p><code>delete</code> 연산자가 배열의 한 원소를 삭제하였을때, 그 원소는 배열에 존재하지 않습니다. 다음의 예제에서, <code>trees[3]</code>는 <code>delete 연산자에 의해 제거되었습니다</code>.그러나, <code>trees[3]</code> 는 아직도 다룰수 있고 <code>undefined</code>(정의 되지 않음) 을 반환합니다.</p> + +<pre class="brush: js">var trees = ["redwood", "bay", "cedar", "oak", "maple"]; +delete trees[3]; +if (3 in trees) { + // this does not get executed +} +</pre> + +<p>만약 배열의 원소가 존재하지만 undefined(정의 되지 않음)값을 가지고 싶으면,<code> delete 연산자 대신 undefined</code> 키워드를 사용하세요. 다음의 예제에서, <code>trees[3]</code> 은 <code>undefined값을 할당받습니다</code>,그러나 배열의 원소는 아직도 존재합니다:</p> + +<pre class="brush: js">var trees = ["redwood", "bay", "cedar", "oak", "maple"]; +trees[3] = undefined; +if (3 in trees) { + // this gets executed +} +</pre> + +<h4 id="typeof" name="typeof"><code>typeof</code></h4> + +<p><a href="/ko/docs/Web/JavaScript/Reference/Operators/typeof"><code>typeof</code> 연산자</a>는 다음과 같은 방법으로 사용됩니다:</p> + +<pre class="syntaxbox">typeof 피연산자 +typeof (피연산자) +</pre> + +<p><code>typeof</code> 연산자 피연산자의 타입을 나타내는 문자열을 반환합니다. <code>피연산자</code> 는 어떤 타입인지 반환될 문자열, 변수, 키워드,또는 객체입니다 . 괄호 표현은 선택사항입니다.</p> + +<p>다음의 변수를 정의했다고 가정하세요:</p> + +<pre class="brush: js">var myFun = new Function("5 + 2"); +var shape = "round"; +var size = 1; +var foo = ['Apple', 'Mango', 'Orange']; +var today = new Date(); +</pre> + +<p><code>typeof</code> 연산자는 이 변수들에 대하여 다음과 같은 값을 반환합니다:</p> + +<pre class="brush: js">typeof myFun; // returns "function" +typeof shape; // returns "string" +typeof size; // returns "number" +typeof foo; // returns "object" +typeof today; // returns "object" +typeof dontExist; // returns "undefined" +</pre> + +<p><code>typeof</code> 연산자는 키워드<code>true</code> 와 <code>null</code>에 대하여 다음과 같은 결과를 반환합니다:</p> + +<pre class="brush: js">typeof true; // returns "boolean" +typeof null; // returns "object" +</pre> + +<p>typeof 연산자는 숫자와 문자열에 대하여 다음과 같은 결과를 반환합니다:</p> + +<pre class="brush: js">typeof 62; // returns "number" +typeof 'Hello world'; // returns "string" +</pre> + +<p><code>typeof</code> 연산자는 객체의 속성에 대하여 속성이 갖고있는 타입의 값을 반환합니다.</p> + +<pre class="brush: js">typeof document.lastModified; // returns "string" +typeof window.length; // returns "number" +typeof Math.LN2; // returns "number" +</pre> + +<p><code>typeof</code> 연산자는 메소드와 함수들에 대하여 다음과 같은 결과를 반환합니다:</p> + +<pre class="brush: js">typeof blur; // returns "function" +typeof eval; // returns "function" +typeof parseInt; // returns "function" +typeof shape.split; // returns "function" +</pre> + +<p><code>typeof 연산자는</code> 미리 정의된 객체에 대하여 다음과 같은 결과를 반환합니다:</p> + +<pre class="brush: js">typeof Date; // returns "function" +typeof Function; // returns "function" +typeof Math; // returns "object" +typeof Option; // returns "function" +typeof String; // returns "function" +</pre> + +<h4 id="void" name="void"><code>void</code></h4> + +<p><a href="/ko/docs/Web/JavaScript/Reference/Operators/void"><code>void</code> 연산자</a> 는 다음과 같은 방법들로 사용됩니다:</p> + +<pre class="syntaxbox">void (식) +void 식 +</pre> + +<p><code>void</code> 연산자는 값을 반환하지 않고 평가되도록 명시합니다. <code>식</code>은 JavaScript의 평가될 표현 입니다. 괄호 로 둘러싸는것은 선택사항이지만, 괄호로 둘러싸는게 좋은 사용방법입니다.</p> + +<p><code>void</code> 연산자를 표현을 하이퍼링크 에서 명시할때 사용할 수 있습니다 . 구문은 실행이 되나, 현재의 문서에는 로드되지 않습니다.</p> + +<p>다음의 코드는 사용자가 클릭을 하였을때 아무 일도 안하는 하이퍼링크를 생성합니다. 사용자가 클릭을 했을때, <code>void(0)</code>는<code> JavaScript에서 아무런 영향을 줄 수 없는 undefined(정의 되지않음)</code>으로 평가됩니다.</p> + +<pre class="brush: html"><a href="javascript:void(0)">Click here to do nothing</a> +</pre> + +<p>다음의 코드는 사용자가 클릭을 하였을때, 폼을 제출하는 하이퍼링크를 생성합니다.</p> + +<pre class="brush: html"><a href="javascript:void(document.form.submit())"> +Click here to submit</a></pre> + +<h3 id="관계_연산자">관계 연산자</h3> + +<p>관계 연산자는 피연산자들을 비교하고 <code>,비교의 참 여부에 기반하여 부울 값을 반환합니다</code>.</p> + +<h4 id="in"><code>in</code></h4> + +<p><a href="/ko/docs/Web/JavaScript/Reference/Operators/in"><code>in</code> 연산자</a>는 객체에 특정한 속성이 있는경우 true를 반환합니다. 구문은 다음과 같습니다:</p> + +<pre class="brush: js">propNameOrNumber in objectName +</pre> + +<p><code>propNameOrNumber</code>는 속성의 이름을 나타내는 문자열 또는 배열의 인덱스를 나타내는 숫자이고, <code>objectName은 객체의 이름입니다</code>.</p> + +<p>다음의 예제는 <code>in</code> 연산자의 사용 예를 보여줍니다.</p> + +<pre class="brush: js">// Arrays +var trees = ["redwood", "bay", "cedar", "oak", "maple"]; +0 in trees; // returns true +3 in trees; // returns true +6 in trees; // returns false +"bay" in trees; // returns false (you must specify the index number, + // not the value at that index) +"length" in trees; // returns true (length is an Array property) + +// built-in objects +"PI" in Math; // returns true +var myString = new String("coral"); +"length" in myString; // returns true + +// Custom objects +var mycar = { make: "Honda", model: "Accord", year: 1998 }; +"make" in mycar; // returns true +"model" in mycar; // returns true +</pre> + +<h4 id="instanceof" name="instanceof"><code>instanceof</code></h4> + +<p><a href="/ko/docs/Web/JavaScript/Reference/Operators/instanceof"><code>instanceof</code> 연산자</a>는 명시된 객체가 명시된 객체형인 경우 true를 반환합니다. 구문은 다음과 같습니다:</p> + +<pre class="syntaxbox">objectName instanceof objectType +</pre> + +<p><code>objectName은 objectType 과 비교할 객체의 이름이고</code>, <code>objectType</code> 은 {{jsxref("Date")}} 또는 {{jsxref("Array")}}과 같은 객체형 입니다.</p> + +<p><code>instanceof</code> 연산자를 동작시간에 객체의 형태를 확인할 필요가 있을때 사용하세요. 예를 들어, 예외가 발생하였을때, 던저진 예외의 형태에 따라 예외를 처리하는 코드로 나뉘게 할 수 있습니다.</p> + +<p>예를 들어, 다음의 코드는<code>instanceof</code> 연산자를<code>theDay 객체가</code> <code>Date</code> 형의 객체인지 알아내는 코드입니다. <code>theDay</code>객체는 <code>Date</code> 형의 객체이기 때문에, <code>if</code> 문 안의 명령문들은 실행됩니다.</p> + +<pre class="brush: js">var theDay = new Date(1995, 12, 17); +if (theDay instanceof Date) { + // statements to execute +} +</pre> + +<h3 id="연산자_우선순위">연산자 우선순위</h3> + +<p>연산자의 우선순위는 구문을 수행할 때 수행될 순서를 결정합니다. 괄호를 통하여 우선순위를 재정의 할 수 있습니다.</p> + +<p>다음의 표는 우선순위가 높은 순서부터 낮은 순서까지, 연산자의 우선순위에 대하여 설명하고 있습니다.</p> + +<table class="standard-table"> + <caption>연산자 우선순위</caption> + <thead> + <tr> + <th scope="col">Operator type</th> + <th scope="col">Individual operators</th> + </tr> + </thead> + <tbody> + <tr> + <td>맴버 연산자</td> + <td><code>. []</code></td> + </tr> + <tr> + <td>객체 호출/생성 연산자</td> + <td><code>() new</code></td> + </tr> + <tr> + <td>부정/증가 연산자</td> + <td><code>! ~ - + ++ -- typeof void delete</code></td> + </tr> + <tr> + <td>곱셈/나눗셈 연산자</td> + <td><code>* / %</code></td> + </tr> + <tr> + <td>덧셈/뺄셈 연산자</td> + <td><code>+ -</code></td> + </tr> + <tr> + <td>비트단위 시프트 연산자</td> + <td><code><< >> >>></code></td> + </tr> + <tr> + <td>관계 연산자</td> + <td><code>< <= > >= in instanceof</code></td> + </tr> + <tr> + <td>같음 비교 연산자</td> + <td><code>== != === !==</code></td> + </tr> + <tr> + <td>비트 단위 논리곱 연산자</td> + <td><code>&</code></td> + </tr> + <tr> + <td>비트단위 배타적 논리합 연산자</td> + <td><code>^</code></td> + </tr> + <tr> + <td>비트단위 논리합 연산자</td> + <td><code>|</code></td> + </tr> + <tr> + <td>논리 곱 연산자</td> + <td><code>&&</code></td> + </tr> + <tr> + <td>논리 합 연산자</td> + <td><code>||</code></td> + </tr> + <tr> + <td>조건 연산자</td> + <td><code>?:</code></td> + </tr> + <tr> + <td>할당 연산자</td> + <td><code>= += -= *= /= %= <<= >>= >>>= &= ^= |=</code></td> + </tr> + <tr> + <td>콤마 연산자</td> + <td><code>,</code></td> + </tr> + </tbody> +</table> + +<p>각 각의 연산자에 대한 추가적인 상세사항에 대해 연결된, 더 자세한 표를 보고 싶으면, <a href="/ko/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table">JavaScript Reference</a>에서 보실 수 있습니다.</p> + +<h2 id="표현식">표현식</h2> + +<p><span>코드 값으로 확인된 표현은 그 어떤 타당한 단위입니다.</span></p> + +<p>개념적으로, 2가지의 유형이 있습니다. 첫번째는, 변수에 값을 할당시키는 것, 두번째는 단순히 값을 갖는것이 있습니다.</p> + +<p>x = 7이란 표현은 첫번째 유형입니다. 이 표현은 x에다가 7을 할당시키기위해 =연산자를 사용합니다. 그 표현자체 7로 계산됩니다.</p> + +<p>3 + 4란 코드는 두번째 표현방식의 예입니다. 이 표현은 7이라는 결과로 할당하는것없이 3과 4를 더하기위해 +연산자를 사용합니다.</p> + +<p>JavaScript는 아래 표현범주를 따릅니다.</p> + +<ul> + <li>산수 : 예를 들어 3.14159를 숫자로 평가합니다. (일반적으로 <a href="#산술_연산자">산술 연산자</a>를 사용합니다.)</li> + <li>문자열 : 예를 들어 "Fred"나 "234"를 문자열로 평가합니다. (일반적으로 <a href="#문자열_연산자">문자열 연산자</a>를 사용합니다.)</li> + <li>논리 : 참이나 거짓으로 평가합니다. (종종 <a href="#논리_연산자">논리 연산자</a>를 수반합니다.)</li> + <li>일차식 : JavaScript에서 기본핵심어와 일반적인 표현입니다.</li> + <li>좌변식 : 좌변값들이 배치의 목적입니다.</li> +</ul> + +<h3 id="중요한_표현식">중요한 표현식</h3> + +<p>JavaScript에서의 기본적인 키워드와 일반적인 표현식입니다.</p> + +<h4 id="this"><code>this</code></h4> + +<p>현재 객체를 참조하는 데 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this"><code>this</code> 키워드</a>를 사용합니다. 일반적으로, this는 메소드에서 호출하는 객체를 참조합니다. 점(.)이나 괄호([])로 접근할 수 있습니다.</p> + +<pre class="syntaxbox">this["propertyName"] +this.propertyName +</pre> + +<p>어떤 객체의 최솟값 최댓값에 대하여, value 프로퍼티가 유효범위에 속하는지를 평가하는 validate 함수를 호출했다고 가정해봅시다.</p> + +<pre class="brush: js">function validate(obj, lowval, hival){ + if ((obj.value < lowval) || (obj.value > hival)) + console.log("Invalid Value!"); +} +</pre> + +<p>다음과 같이 각 form 요소의 onChange 이벤트 처리기에서 validate 함수를 호출할 수 있습니다. this 일차식을 사용하여 form 요소(element)를 전달할 수 있습니다:</p> + +<pre class="brush: html"><p>Enter a number between 18 and 99:</p> +<input type="text" name="age" size=3 onChange="validate(this, 18, 99);"> +</pre> + +<h4 id="그룹_연산자">그룹 연산자</h4> + +<p>그룹연산자 ()는 표현식 평가의 우선순위를 조절합니다. 예를 들어, 곱셈과 나눗셈 연산을 무시하고, 우선 덧셈 뺄셈 연산을 먼저 수행할 수도 있습니다.</p> + +<pre class="brush:js">var a = 1; +var b = 2; +var c = 3; + +// default precedence +a + b * c // 7 +// evaluated by default like this +a + (b * c) // 7 + +// now overriding precedence +// addition before multiplication +(a + b) * c // 9 + +// which is equivalent to +a * c + b * c // 9 +</pre> + +<h3 id="좌변식">좌변식</h3> + +<p>좌측값들이 좌변식의 목적입니다.</p> + +<h4 id="new" name="new"><code>new</code></h4> + +<p><span>당신은 사용자 정의 객체 형식 또는 한 내장된 객체 형식의 인스턴스를 만드는 데는 </span><code><a href="/ko/docs/Web/JavaScript/Reference/Operators/new">new 연산자</a>를 </code><span>사용할 수 있습니다.</span> new는 아래와 같이 사용할 수 있습니다:</p> + +<pre class="brush: js">var objectName = new objectType([param1, param2, ..., paramN]); +</pre> + +<h4 id="super">super</h4> + +<p><a href="/ko/docs/Web/JavaScript/Reference/Operators/super">Super 키워드</a>는<span>개체의 부모에 함수를 호출하는 데 사용됩니다. 예를 들어 이것은 부모생성자를 부르는 </span> <a href="/ko/docs/Web/JavaScript/Reference/Classes">클래스들</a><span>과 함께 유용합니다 </span></p> + +<pre class="syntaxbox">super([arguments]); // calls the parent constructor. +super.functionOnParent([arguments]); +</pre> + +<h4 id="확산연산자">확산연산자</h4> + +<p><a href="/ko/docs/Web/JavaScript/Reference/Operators/Spread_operator">확산연산자</a>는 다중인수(함수호출)또는 다중요소(문자배열)들이 예상되는 곳에서 확장될 수 있는 표현을 하게합니다.</p> + +<p><strong>Example:</strong> 만약 하나의 배열에 다른 하나의 배열을 추가하고 싶을 때에는 Array 리터럴 구문이 더이상 충분하지않으므로 <code>push</code>, <code>splice</code>, <code>concat</code>과 같은 함수를 사용하는 것이 좋습니다. 하지만 확산연산자를 사용할 경우 좀 더 간결한 구문으로 구현할 수 있습니다. </p> + +<pre class="brush: js">var parts = ['shoulder', 'knees']; +var lyrics = ['head', ...parts, 'and', 'toes']; + +//[ 'head', 'shoulders', 'knees', 'and', 'toes' ] +</pre> + +<p><span>위와 같이, 확산연산자의 함수 호출은 다음과 같이 사용합니다.</span></p> + +<pre class="brush: js">function f(x, y, z) { } +var args = [0, 1, 2]; +f(...args);</pre> + +<div>{{PreviousNext("Web/JavaScript/Guide/Functions", "Web/JavaScript/Guide/Numbers_and_dates")}}</div> diff --git a/files/ko/web/javascript/guide/index.html b/files/ko/web/javascript/guide/index.html new file mode 100644 index 0000000000..7ae4ac0fcf --- /dev/null +++ b/files/ko/web/javascript/guide/index.html @@ -0,0 +1,138 @@ +--- +title: JavaScript 안내서 +slug: Web/JavaScript/Guide +tags: + - Guide + - JavaScript + - 'l10n:priority' + - 자바스크립트 +translation_of: Web/JavaScript/Guide +--- +<div>{{jsSidebar("JavaScript Guide")}}</div> + +<p class="summary">JavaScript 안내서에서 <a href="/ko/docs/Web/JavaScript">JavaScript</a> 언어 개요와 사용법을 알아보세요. 언어 기능에 대해 상세한 정보가 필요하면 <a href="/ko/docs/Web/JavaScript/Reference">JavaScript 참고서</a>를 방문하세요.</p> + +<h2 id="목차">목차</h2> + +<p>본 안내서는 여러 장으로 구성되어 있습니다.</p> + +<ul class="card-grid"> + <li><span><a href="/ko/docs/Web/JavaScript/Guide/Introduction">소개</a></span> + + <p><a href="/ko/docs/Web/JavaScript/Guide/Introduction#Where_to_find_JavaScript_information">이 가이드에 대해서</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Introduction#What_is_JavaScript.3F">JavaScript에 대하여</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Introduction#JavaScript_and_Java">JavaScript와 Java</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Introduction#JavaScript_and_the_ECMAScript_Specification">ECMAScript</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Introduction#Getting_started_with_JavaScript">도구</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Introduction#Hello_world">Hello World</a></p> + </li> + <li><span><a href="/ko/docs/Web/JavaScript/Guide/Grammar_and_types">문법과 자료형</a></span> + <p><a href="/ko/docs/Web/JavaScript/Guide/Grammar_and_types#Basics">기본 구문 & 주석</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Grammar_and_types#Declarations">선언문</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Grammar_and_types#Variable_scope">변수 범위</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Grammar_and_types#Variable_hoisting">변수 가져오기</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Grammar_and_types#Data_structures_and_types">데이터 구조와 타입</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Grammar_and_types#Literals">리터럴</a></p> + </li> + <li><span><a href="/ko/docs/Web/JavaScript/Guide/Control_flow_and_error_handling">흐름 제어과 오류 처리</a></span> + <p><code><a href="/ko/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#if...else_statement">if...else</a></code><br> + <code><a href="/ko/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#switch_statement">switch</a></code><br> + <a href="/ko/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#Exception_handling_statements"><code>try</code>/<code>catch</code>/<code>throw</code></a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#Utilizing_Error_objects">Error objects</a></p> + </li> + <li><span><a href="/ko/docs/Web/JavaScript/Guide/Loops_and_iteration">반복과 순회</a></span> + <p><code><a href="/ko/docs/Web/JavaScript/Guide/Loops_and_iteration#for_statement">for</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Loops_and_iteration#while_statement">while</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Loops_and_iteration#do...while_statement">do...while</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Loops_and_iteration#break_statement">break</a>/<a href="/ko/docs/Web/JavaScript/Guide/Loops_and_iteration#continue_statement">continue</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Loops_and_iteration#for...in_statement">for..in</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Loops_and_iteration#for...of_statement">for..of</a></code></p> + </li> +</ul> + +<ul class="card-grid"> + <li><span><a href="/ko/docs/Web/JavaScript/Guide/Functions">함수</a></span> + + <p><a href="/ko/docs/Web/JavaScript/Guide/%ED%95%A8%EC%88%98#%ED%95%A8%EC%88%98_%EC%A0%95%EC%9D%98">함수 선언하기</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/%ED%95%A8%EC%88%98#%ED%95%A8%EC%88%98_%ED%98%B8%EC%B6%9C">함수 호출하기</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/%ED%95%A8%EC%88%98#%ED%95%A8%EC%88%98%EC%9D%98_%EB%B2%94%EC%9C%84">함수 범위</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/%ED%95%A8%EC%88%98#%ED%81%B4%EB%A1%9C%EC%A0%80">클로저(Closures</a>)<br> + <a href="/ko/docs/Web/JavaScript/Guide/%ED%95%A8%EC%88%98#%EC%9D%B8%EC%88%98(arguments)_%EA%B0%9D%EC%B2%B4_%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0">아규먼트</a> & <a href="/ko/docs/Web/JavaScript/Guide/%ED%95%A8%EC%88%98#%ED%95%A8%EC%88%98%EC%9D%98_%EB%A7%A4%EA%B0%9C%EB%B3%80%EC%88%98">파라미터</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/%ED%95%A8%EC%88%98#%ED%99%94%EC%82%B4%ED%91%9C_%ED%95%A8%EC%88%98">Arrow 함수</a></p> + </li> + <li><span><a href="/ko/docs/Web/JavaScript/Guide/Expressions_and_Operators">표현식과 연산자</a></span> + <p><a href="/ko/docs/Web/JavaScript/Guide/Expressions_and_Operators#Assignment_operators">할당 연산</a> & <a href="/ko/docs/Web/JavaScript/Guide/Expressions_and_Operators#Comparison_operators">비교 연산</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Expressions_and_Operators#Arithmetic_operators">산술 연산자</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Expressions_and_Operators#Bitwise_operators">비트연산</a> & <a href="/ko/docs/Web/JavaScript/Guide/Expressions_and_Operators#Logical_operators">논리 연산자</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Expressions_and_Operators#Conditional_(ternary)_operator">Conditional (ternary) operator</a></p> + </li> + <li><span><a href="/ko/docs/Web/JavaScript/Guide/Numbers_and_dates">숫자와 날짜</a></span><a href="/ko/docs/Web/JavaScript/Guide/Numbers_and_dates#Numbers"> 리터럴</a> + <p><a href="/ko/docs/Web/JavaScript/Guide/Numbers_and_dates#Number_object"><code>Number</code> 오브젝트</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Numbers_and_dates#Math_object"><code>Math</code> </a><a href="/ko/docs/Web/JavaScript/Guide/Numbers_and_dates#Number_object" style="background-color: rgba(234, 239, 242, 0.498039);">오브젝트</a><br> + <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/Numbers_and_dates#Date_object"><code>Date</code> </a><a href="/ko/docs/Web/JavaScript/Guide/Numbers_and_dates#Number_object" style="background-color: rgba(234, 239, 242, 0.498039);">오브젝트</a></p> + </li> + <li><span><a href="/ko/docs/Web/JavaScript/Guide/Text_formatting">텍스트 서식</a></span> + <p><a href="/ko/docs/Web/JavaScript/Guide/Text_formatting#String_literals">String 리터럴</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Text_formatting#String_objects"><code>String</code> 오브젝트</a><br> + <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/Text_formatting#Multi-line_template_literals">템플릿 리터럴</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Text_formatting#Internationalization">지역 별 서식</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Regular_Expressions">정규식</a></p> + </li> +</ul> + +<ul class="card-grid"> + <li><span><a href="/ko/docs/Web/JavaScript/Guide/Indexed_collections">인덱스 콜렉션</a></span> + + <p><a href="/ko/docs/Web/JavaScript/Guide/Indexed_collections#Array_object">Arrays</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Indexed_collections#Typed_Arrays">Typed arrays</a></p> + </li> + <li><span><a href="/ko/docs/Web/JavaScript/Guide/Keyed_collections">키 콜렉션</a></span> + <p><code><a href="/ko/docs/Web/JavaScript/Guide/Keyed_collections#Map_object">Map</a></code><br> + <code><a href="/ko/docs/Web/JavaScript/Guide/Keyed_collections#WeakMap_object">WeakMap</a></code><br> + <code><a href="/ko/docs/Web/JavaScript/Guide/Keyed_collections#Set_object">Set</a></code><br> + <code><a href="/ko/docs/Web/JavaScript/Guide/Keyed_collections#WeakSet_object">WeakSet</a></code></p> + </li> + <li><span><a href="/ko/docs/Web/JavaScript/Guide/Working_with_Objects">객체와 작업하기</a></span> + <p><a href="/ko/docs/Web/JavaScript/Guide/Working_with_Objects#Objects_and_properties">오브젝트와 속성</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Working_with_Objects#Creating_new_objects">오브젝트 생성하기</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_methods">메소드 정의하기</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters">Getter 와 setter</a></p> + </li> + <li><span><a href="/ko/docs/Web/JavaScript/Guide/Details_of_the_Object_Model">객체 모델</a><a href="/ko/docs/Web/JavaScript/Guide/Details_of_the_Object_Model" style="font-family: Arial, x-locale-body, sans-serif; letter-spacing: -0.00278rem;"> </a></span> + <p><a href="/ko/docs/Web/JavaScript/Guide/Details_of_the_Object_Model#Class-based_vs._prototype-based_languages">프로토타입 기반 객체 지향 프로그래밍</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Details_of_the_Object_Model#Creating_the_hierarchy">오브젝트 계층 생성하기</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Details_of_the_Object_Model#Property_inheritance_revisited">상속</a></p> + </li> +</ul> + +<ul class="card-grid"> + <li><a href="/ko/docs/Web/JavaScript/Guide/Using_promises">프로미스</a> + + <p><a href="/ko/docs/Web/JavaScript/Guide/Using_promises#Guarantees">Guarantees</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Using_promises#Chaining">Chaining</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Using_promises#Error_propagation">Error propagation</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Using_promises#Composition">Composition</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Using_promises#Timing">Timing</a></p> + </li> + <li><span><a href="/ko/docs/Web/JavaScript/Guide/Iterators_and_Generators">반복기와 생성기</a></span> + <p><a href="/ko/docs/Web/JavaScript/Guide/Iterators_and_Generators#Iterators">Iterators</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Iterators_and_Generators#Iterables">Iterables</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Iterators_and_Generators#Generators">Generators</a></p> + </li> + <li><span><a href="/ko/docs/Web/JavaScript/Guide/Meta_programming">메타 프로그래밍</a></span> + <p><code><a href="/ko/docs/Web/JavaScript/Guide/Meta_programming#Proxies">프록시(Proxy</a></code><a href="/ko/docs/Web/JavaScript/Guide/Meta_programming#Proxies" style="font-family: Consolas, Monaco, 'Andale Mono', monospace; background-color: rgba(234, 239, 242, 0.498039);">)</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Meta_programming#Handlers_and_traps">Handlers와 traps</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Meta_programming#Revocable_Proxy">Revocable Proxy</a><br> + <code><a href="/ko/docs/Web/JavaScript/Guide/Meta_programming#Reflection">Reflect</a></code></p> + </li> + <li><span><a href="/ko/docs/Web/JavaScript/Guide/Modules">JavaScript 모듈</a></span> + <p><a href="/ko/docs/Web/JavaScript/Guide/Modules#Exporting_module_features">Exporting</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Modules#Importing_features_into_your_script">Importing</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Modules#Default_exports_versus_named_exports">Default exports</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Modules#Renaming_imports_and_exports">Renaming features</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Modules#Aggregating_modules">Aggregating modules</a><br> + <a href="/ko/docs/Web/JavaScript/Guide/Modules#Dynamic_module_loading">Dynamic module loading</a></p> + </li> +</ul> + +<p>{{Next("Web/JavaScript/Guide/Introduction")}}</p> diff --git a/files/ko/web/javascript/guide/indexed_collections/index.html b/files/ko/web/javascript/guide/indexed_collections/index.html new file mode 100644 index 0000000000..f048ddc752 --- /dev/null +++ b/files/ko/web/javascript/guide/indexed_collections/index.html @@ -0,0 +1,456 @@ +--- +title: Indexed collections +slug: Web/JavaScript/Guide/Indexed_collections +translation_of: Web/JavaScript/Guide/Indexed_collections +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Regular_Expressions", "Web/JavaScript/Guide/Keyed_Collections")}}</div> + +<p class="summary">이번장에서는 인덱스값에 의해 정렬이 되는 데이터 자료구조에 대해 소개합니다. 배열과 유사 배열 생성자인 {{jsxref("Array")}} 객체와 {{jsxref("TypedArray")}} 객체 같은 생성자들을 포함합니다. </p> + +<h2 id="배열_객체"><font face="Consolas, Liberation Mono, Courier, monospace">배열 객체</font></h2> + +<p>배열은 이름과 인덱스로 참조되는 정렬된 값들의 집합입니다. 예를 들면, 숫자로 된 사원번호를 index로하여 사원명을 가지고 있는 emp라는 배열을 가질 수 있습니다. 그래서 emp[1]은 사원번호 1번, emp[2]는 사원번호 2번, 이런식으로 사원번호를 인덱스 값으로 가질 수 있는 것입니다.</p> + +<p>자바스크립트는 명시적인 배열 데이터 형식을 가지고 있지 않습니다. 그러나 미리 정의된 배열 객체를 사용할 수 있고 배열 객체의 메서드를 개발하는 어플리케이션에서 사용되는 배열에 사용할 수 있습니다. 배열 객체는 합치기(joining), 순서 뒤집기(reversing) 그리고 정렬(sorting)과 같은 다양한 방법으로 배열을 조작하는 메서드들을 제공합니다. 정규 표현식과 함께 사용할 배열 길이와 기타 속성을 결정하는 속성이 있습니다.</p> + +<h3 id="배열_생성">배열 생성</h3> + +<p>아래의 구문들은 동일한 요소를 가지는 배열을 생성하는 방법들입니다. </p> + +<pre class="brush: js">var arr = new Array(element0, element1, ..., elementN); +var arr = Array(element0, element1, ..., elementN); +var arr = [element0, element1, ..., elementN]; +</pre> + +<p>요소0, 요소1, ..., 요소N은 배열내에 포함된 요소의 값 목록 입니다. 해당 값들이 명시되어 있을 경우, 해당 배열은 주어진 요소들을 포함하도록 초기화 됩니다. 해당 배열의 길이는 주어진 요소들의 갯수가 됩니다. </p> + +<p>대괄호 문법은 일명 "배열 문자" 혹은 "배열 초기화"라고 합니다. 대괄호 문법은 다른 배열 생성 표기법 보다 짧고 일반적으로 선호하는 문법입니다. 보다 상세한 내용은 <a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Array_literals" title="en-US/docs/JavaScript/Guide/Values, Variables, and Literals#Array Literals">Array literals</a>를 참조하세요.</p> + +<p> 길이가 0보다 크지만 아무런 요소를 가지고 있지 않은 배열을 생성하기 위한 방법은 아래와 같습니다. </p> + +<pre class="brush: js">var arr = new Array(arrayLength); +var arr = Array(arrayLength); + +// This has exactly the same effect +var arr = []; +arr.length = arrayLength; +</pre> + +<div class="note"> +<p>Note : 위의 예제 코드에서, <code>arrayLength</code>는 반드시 <code>숫자</code>여야 합니다. 그렇지 않으면 하나의 요소(주어진 값)을 가지는 배열이 생성 됩니다. <code>arr.length</code>를 호출하면 <code>arrayLength</code>가 반환이 되지만 해당 배열은 실제로 아무런 요소를 가지고 있지 않습니다. {{jsxref("Statements/for...in","for...in")}} 반복문을 실행하면 해당 배열은 아무런 요소를 반환하지 않습니다.</p> +</div> + +<p>추가로 아래의 예제에서 볼 수 있듯이, 새로이 정의된 혹은 이미 존재하는 객체 변수의 속성으로 배열을 할당 할 수 있습니다.</p> + +<pre class="brush: js">var obj = {}; +// ... +obj.prop = [element0, element1, ..., elementN]; + +// OR +var obj = {prop: [element0, element1, ...., elementN]} +</pre> + +<p>값이 <code>숫자</code>인 하나의 요소만을 가지는 배열을 생성하고자 할 경우, 반드시 대괄호 문법을 사용해야 합니다. 하나의 <code>숫자</code> 값을 Array() 생성자에게 전달할 경우, 그 숫자 값은 해당 배열의 요소가 아니라 <code>arrayLength</code>(배열의 길이)로 해석됩니다. </p> + +<pre class="brush: js">var arr = [42]; +var arr = Array(42); // Creates an array with no element, + // but with arr.length set to 42 + +// The above code is equivalent to +var arr = []; +arr.length = 42; +</pre> + +<p>만약 숫자이지만 0이 아닌 소수점을 가지는 숫자를 <code>Array()생성자에게 인자로 줄 경우, 범위 에러(RangeError)가 발생하게 됩니다. 아래의 예제는 범위 에러가 발생되는 상황을 보여 줍니다. </code></p> + +<pre class="brush: js">var arr = Array(9.3); // RangeError: Invalid array length +</pre> + +<p>만약 임의의 데이터 형식인 하나의 요소를 가지는 배열을 생성하고자 할 경우, 배열 표기법을 사용하는 것이 안전합니다. 혹은 빈 배열을 먼저 선언한 후 임의의 데이터 값을 해당 배열에 추가하는 것도 방법이 됩니다. </p> + +<p>ES2015에서 요소가 하나인 배열을 만들기 위해 Array.of 정적 메소드를 사용할 수 있습니다.</p> + +<pre><em>let wisenArray = Array.of(9.3) // wisenArray contains only one element 9.3</em></pre> + +<h3 id="배열에_값_저장">배열에 값 저장</h3> + +<p>배열의 요소에 값을 할당하여 배열에 값을 저장할 수 있습니다. 예를 들면, </p> + +<pre class="brush: js">var emp = []; +emp[0] = 'Casey Jones'; +emp[1] = 'Phil Lesh'; +emp[2] = 'August West'; +</pre> + +<div class="note"> +<p><strong>참고: </strong>위의 코드 예제 처럼 배열 연산자에 양의 정수가 아닌 값을 줄 경우, 배열의 요소가 대신 배열로 대변되는 객체의 속성이 생성이 됩니다. </p> +</div> + +<pre class="brush: js">var arr = []; +arr[3.4] = 'Oranges'; +console.log(arr.length); // 0 +console.log(arr.hasOwnProperty(3.4)); // true +</pre> + +<p>배열을 생성함과 동시에 배열에 값을 저장할 수 있습니다. </p> + +<pre class="brush: js">var myArray = new Array('Hello', myVar, 3.14159); +var myArray = ['Mango', 'Apple', 'Orange']; +</pre> + +<h3 id="배열_요소의_참조">배열 요소의 참조</h3> + +<p>배열의 요소를 참조하기 위해서 해당 요소의 인덱스(요소의 순서를 나타내는 )를 사용할 수 있습니다. 예를 들어, 아래와 같이 배열을 선언 하였다면</p> + +<pre class="brush: js">var myArray = ['Wind', 'Rain', 'Fire']; +</pre> + +<p>배열의 첫번째 요소는 <code>myArray[0]로 참조할 수 있고 두번째 요소는 myArray[1]로 참조할 수 있습니다. 배열의 인덱스 값은 0부터 시작합니다.</code></p> + +<div class="note"> +<p><strong>참고: </strong>배열 연산자(대괄호)는 배열의 속성에 접근하기 위해서도 사용될 수 있습니다.(배열 또한 객체이기 때문입니다.) 예를 들면 아래와 같습니다.</p> +</div> + +<pre class="brush: js">var arr = ['one', 'two', 'three']; +arr[2]; // three +arr["length"]; // 3 +</pre> + +<h3 id="배열_길이에_대한_이해">배열 길이에 대한 이해</h3> + +<p>실제 구현에서, 자바스트립트의 배열은 배열에 포함된 요소들을 배열의 인덱스 값을 속성 이름으로 사용하여 표준 객체의 속성처럼 저장을 합니다. 길이 속성은 좀 특별합니다. 배열의 길이는 항상 마지막 요소의 인덱스에 1을 더한 값을 반환합니다.(다음 예제에서 Dusty는 인덱스 30번째에 위치하기때문에 cats배열의 길이는 31이 됩니다.) 기억하실 것은 자바스크립트 배열의 인덱스는 항상 1부터가 아닌 0부터 시작합니다. 이것이 의미하는 바는 배열의 길이 속성은 배열에 저장되어 있는 가장 큰 인덱스보다 1만큼 큰 값이 된다는 것입니다. </p> + +<pre class="brush: js">var cats = []; +cats[30] = ['Dusty']; +console.log(cats.length); // 31 + +</pre> + +<p>배열의 길이(<code>length</code>) 속성을 지정하는 것 또한 가능합니다. 만약 배열에 저장되어 있는 요소의 갯수보다 작은 값을 배열 길이로 지정하게 되면, 지정된 배열 길이보다 큰 인덱스 값을 가지는 요소는 배열에서 삭제됩니다. 0을 배열 길이로 지정하게 되면 해당 배열은 요소를 가지지 않는 빈 배열이 되는 것입니다.</p> + +<pre class="brush: js">var cats = ['Dusty', 'Misty', 'Twiggy']; +console.log(cats.length); // 3 + +cats.length = 2; +console.log(cats); // logs "Dusty,Misty" - Twiggy has been removed + +cats.length = 0; +console.log(cats); // logs []; the cats array is empty + +cats.length = 3; +console.log(cats); // logs [ <3 empty items ] +</pre> + +<h3 id="배열의_요소를_반복처리하기">배열의 요소를 반복처리하기</h3> + +<p>배열을 가지고 처리하는 주된 작업은 배열의 요소를 반복적으로 접근해서 읽어오는 작업입니다. 가장 간단한 방법은 아래와 같습니다. </p> + +<pre class="brush: js">var colors = ['red', 'green', 'blue']; +for (var i = 0; i < colors.length; i++) { + console.log(colors[i]); +} +</pre> + +<p>배열이 아무런 요소를 포함하고 있지 않다면 반복문 조건에서 false로 평가됩니다. 배열의 요소가 <a href="https://developer.mozilla.org/en-US/docs/DOM" title="en-US/docs/DOM">DOM</a> node들을 포함한다면 보다 효율적인 코드 관용구를 사용할 수 있습니다. </p> + +<pre class="brush: js">var divs = document.getElementsByTagName('div'); +for (var i = 0, div; div = divs[i]; i++) { + /* Process div in some way */ +} +</pre> + +<p>위의 예제 코드의 for반복문 조건은 배열의 길이을 확인하는 작업을 피할 수 있고, div변수가 매 반복마다 현재의 요소를 가지게 됩니다. </p> + +<p>{{jsxref("Array.forEach", "forEach()")}} 메서드는 배열의 요소를 반복처리할 수 있는 또 다른 방법입니다:</p> + +<pre class="brush: js">var colors = ['red', 'green', 'blue']; +colors.forEach(function(color) { + console.log(color); +}); +// red +// green +// blue +</pre> + +<p>ES2015 Arrow Function으로 다음과 같이 더 짧게 코드를 짤 수 있습니다.</p> + +<pre>var colors = ['red', 'green', 'blue']; +color.forEach(color => console.log(color)); +// red +// green +// blue +</pre> + +<p><code>forEach</code>에 인자로 주어진 함수는 배열의 각 요소에 대해 한번씩 실행이 되고 배열의 각 요소는 인자로 주어진 함수의 인자로 주어지게 됩니다. 할당 되지 않은 요소 값은 <code>forEach</code> 반복문에서 처리 되지 않습니다. </p> + +<p><code>forEach</code>반복문으로 배열의 요소를 반복처리할때, 배열을 정의할 때 생략된 요소는 처리대상이 되지 않는 것에 유의 하세요. 하지만 <code>undefined</code>을 생략된 요소에 할당하게 되면 undefined로 처리됩니다. </p> + +<p> </p> + +<pre class="brush: js">var array = ['first', 'second', , 'fourth']; + +array.forEach(function(element) { + console.log(element); +}) +// first +// second +// fourth + +if(array[2] === undefined) { + console.log('array[2] is undefined'); // true +} + +var array = ['first', 'second', undefined, 'fourth']; + +array.forEach(function(element) { + console.log(element); +}); +// first +// second +// undefined +// fourth +</pre> + +<p>JavaScript 요소는 표준 객체 속성으로 저장되므로 {{jsxref ( "Statements / for ... in", "for ... in")}} 루프를 사용하여 JavaScript 배열을 반복하는 것은 바람직하지 않습니다. 왜냐면 일반 요소들과 그리고 모든 열거할 수 있는 속성들이 나열이 되기 때문입니다.</p> + +<h3 id="배열_객체의_메서드">배열 객체의 메서드</h3> + +<p>{{jsxref("Array")}} 객체는 다음과 같은 메서드들을 가지고 있습니다:</p> + +<p>{{jsxref("Array.concat", "concat()")}} 메서드는 두개의 배열을 합쳐 새로운 배열을 반환합니다.</p> + +<pre><code>var myArray = new Array('1', '2', '3'); +myArray = myArray.concat('a', 'b', 'c'); +// myArray is now ["1", "2", "3", "a", "b", "c"]</code></pre> + +<p>{{jsxref("Array.join", "join(delimiter = ',')")}} 메서드는 배열의 모든 요소를 주어진 구분자로 연결된 하나의 문자열을 반환 합니다. </p> + +<pre><code>var myArray = new Array('Wind', 'Rain', 'Fire'); +var list = myArray.join(' - '); // list is "Wind - Rain - Fire"</code></pre> + +<p>{{jsxref("Array.push", "push()")}}메서드는 하나 혹은 그 이상의 요소를 배열의 마지막에 추가하고 추가된 요소를 포함한 길이를 반환합니다.</p> + +<pre><code>var myArray = new Array('1', '2'); +myArray.push('3'); // myArray is now ["1", "2", "3"]</code></pre> + +<p>{{jsxref("Array.pop", "pop()")}} 메서드는 배열의 마지막 요소를 제거 하고 그 제거된 요소를 반환합니다.</p> + +<pre><code>var myArray = new Array('1', '2', '3'); +var last = myArray.pop(); +// myArray is now ["1", "2"], last = "3"</code></pre> + +<p>{{jsxref("Array.shift", "shift()")}}메서드는 배열의 첫번째 요소를 제거하고 그 제거된 요소를 반환합니다.</p> + +<pre><code>var myArray = new Array('1', '2', '3'); +var first = myArray.shift(); +// myArray is now ["2", "3"], first is "1"</code></pre> + +<p>{{jsxref("Array.shift", "unshift()")}}메서드는 하나 혹은 그 이상의 요소를 배열의 앞쪽에 추가하고 추가한 요소를 포함한 길이를 반환 합니다.</p> + +<pre><code>var myArray = new Array('1', '2', '3'); +myArray.unshift('4', '5'); +// myArray becomes ["4", "5", "1", "2", "3"]</code></pre> + +<p>{{jsxref("Array.slice", "slice(start_index, upto_index)")}}메서드는 배열의 특정 부분을 추출하여 그 추출된 부분을 포함하는 새로운 배열을 반환 합니다. upto_index에 해당하는 요소는 포함되지 않습니다. </p> + +<pre><code>var myArray = new Array('a', 'b', 'c', 'd', 'e'); +myArray = myArray.slice(1, 4); // starts at index 1 and extracts all elements + // until index 3, returning [ "b", "c", "d"]</code></pre> + +<p>{{jsxref("Array.splice", "splice(index, count_to_remove, addElement1, addElement2, ...)")}} 메세드는 주어진 인덱스 요소를 포함하여 count_to_remove 갯수만큼 삭제 하고 주어진 요소로 바꿔 줍니다. </p> + +<pre><code>var myArray = new Array('1', '2', '3', '4', '5'); +myArray.splice(1, 3, 'a', 'b', 'c', 'd'); +// myArray is now ["1", "a", "b", "c", "d", "5"] +// This code started at index one (or where the "2" was), +// removed 3 elements there, and then inserted all consecutive +// elements in its place.</code></pre> + +<p> </p> + +<p>{{jsxref ( "Array.reverse", "reverse ()")}} 배열의 요소를 제자리에 배치합니다. 첫 번째 배열 요소가 마지막 요소가되고 마지막 요소가 첫 번째 요소가됩니다. 배열에 대한 참조를 반환합니다.</p> + +<pre><code>var myArray = new Array('1', '2', '3'); +myArray.reverse(); +// transposes the array so that myArray = ["3", "2", "1"]</code></pre> + +<p> </p> + +<p>{{jsxref ( "Array.sort", "sort ()")}} 배열의 요소를 제자리에 정렬하고 배열에 대한 참조를 반환합니다.</p> + +<pre class="brush: js">var myArray = new Array('Wind', 'Rain', 'Fire'); +myArray.sort(); +// sorts the array so that myArray = [ "Fire", "Rain", "Wind" ] +</pre> + +<p><code>sort()</code> 메서드에 어떻게 해당 배열의 요소를 정렬할 지 결정하는 콜백 함수를 인자로 줄 수 있습니다.</p> + +<p>콜백을 사용하는 sort 메소드 및 다른 메소드는 반복 메소드로 알려져 있습니다. 일부 메소드에서는 전체 배열을 반복하기 때문입니다. 각각은 <code>thisObject</code>라는 선택적인 두 번째 인수를 취합니다. 제공되면 <code>thisObject</code>는 콜백 함수의 본문에있는 <code>this</code> 키워드의 값이됩니다.</p> + +<p>제공되지 않으면 함수가 명시 적 객체 컨텍스트 외부에서 호출되는 다른 경우와 마찬가지로이 함수는 콜백으로 화살표 함수를 사용할 때 전역 객체 ({{domxref ( "window")}})를 참조합니다. 정상적인 기능은 콜백입니다.</p> + +<p>콜백 함수는 배열의 요소 인 두 개의 인수로 호출됩니다.</p> + +<p>아래 함수는 두 값을 비교하여 세 값 중 하나를 반환합니다.</p> + +<p>예를 들어, 다음은 문자열의 마지막 문자로 정렬합니다.</p> + +<pre class="brush: js">var sortFn = function(a, b){ + if (a[a.length - 1] < b[b.length - 1]) return -1; + if (a[a.length - 1] > b[b.length - 1]) return 1; + if (a[a.length - 1] == b[b.length - 1]) return 0; +} +myArray.sort(sortFn); +// sorts the array so that myArray = ["Wind","Fire","Rain"] +</pre> + +<ul> + <li>a의 순서가 b보다 뒤에 오면 -1(혹은 음수)을 반환합니다.</li> + <li>a의 순서가 b보다 앞에 오면 1(혹은 양수)을 반환합니다.</li> + <li>a와 b가 같으면 0을 반환합니다.</li> +</ul> + +<p>{{jsxref ( "Array.indexOf", "indexOf (searchElement [, fromIndex])")}}는 배열에서 <code>searchElement</code>를 검색하고 첫 번째 일치 항목의 인덱스를 반환합니다.</p> + +<pre class="brush: js">var a = ['a', 'b', 'a', 'b', 'a']; +console.log(a.indexOf('b')); // logs 1 +// Now try again, starting from after the last match +console.log(a.indexOf('b', 2)); // logs 3 +console.log(a.indexOf('z')); // logs -1, because 'z' was not found +</pre> + +<p>{{jsxref("Array.lastIndexOf", "lastIndexOf(searchElement[, fromIndex])")}}메서드는 <code>indexOf</code>메서드와 유사하게 작동하지만 배열의 뒤쪽에서부터 요소를 찾습니다.</p> + +<pre class="brush: js">var a = ['a', 'b', 'c', 'd', 'a', 'b']; +console.log(a.lastIndexOf('b')); // logs 5 +// Now try again, starting from before the last match +console.log(a.lastIndexOf('b', 4)); // logs 1 +console.log(a.lastIndexOf('z')); // logs -1 +</pre> + +<p>{{jsxref("Array.forEach", "forEach(callback[, thisObject])")}}메서드는 배열의 모든 요소에 대해 반복적으로 주어진 <code>callback</code> 함수를 실행합니다. </p> + +<pre class="brush: js">var a = ['a', 'b', 'c']; +a.forEach(function(element) { console.log(element);} ); +// logs each item in turn +</pre> + +<p>{{jsxref("Array.map", "map(callback[, thisObject])")}}메서드는 배열의 모든 요소에 대해 콜백함수를 실행하고 콜백함수의 실행결과를 새로운 배열에 담아 반환합니다.</p> + +<pre class="brush: js">var a1 = ['a', 'b', 'c']; +var a2 = a1.map(function(item) { return item.toUpperCase(); }); +console.log(a2); // logs ['A', 'B', 'C'] +</pre> + +<p>{{jsxref("Array.filter", "filter(callback[, thisObject])")}}메서드는 배열의 모든 요소에 대해 콜백 함수가 true를 반환하는 요소를 새로운 배열에 담아 반환 합니다. </p> + +<pre class="brush: js">var a1 = ['a', 10, 'b', 20, 'c', 30]; +var a2 = a1.filter(function(item) { return typeof item == 'number'; }); +console.log(a2); // logs ['10', '20', '30'] +</pre> + +<p> </p> + +<p>{{jsxref ( "Array.every", "every (callback [, thisObject])")}}는 콜백이 배열의 모든 항목에 대해 true를 반환하면 true를 반환합니다.</p> + +<pre class="brush: js">function isNumber(value){ + return typeof value == 'number'; +} +var a1 = [1, 2, 3]; +console.log(a1.every(isNumber)); // logs true +var a2 = [1, '2', 3]; +console.log(a2.every(isNumber)); // logs false +</pre> + +<p>{{jsxref("Array.some", "some(callback[, thisObject])")}}메서드는 배열의 모든 요소에 대해 콜백 함수를 실행하고 하나의 요소라도 콜백 함수의 결과가 true이면 some()메서드의 결과는 true가 됩니다.</p> + +<pre class="brush: js">function isNumber(value){ + return typeof value == 'number'; +} +var a1 = [1, 2, 3]; +console.log(a1.some(isNumber)); // logs true +var a2 = [1, '2', 3]; +console.log(a2.some(isNumber)); // logs true +var a3 = ['1', '2', '3']; +console.log(a3.some(isNumber)); // logs false +</pre> + +<p>{{jsxref("Array.reduce", "reduce(callback[, initialValue])")}}메서드는 배열내의 요소를 하나의 요소로 줄이기 위해 <code>firstValue, secondValue</code>를 인자로 받는 콜백 함수를 실행합니다.</p> + +<pre class="brush: js">var a = [10, 20, 30]; +var total = a.reduce(function(first, second) { return first + second; }, 0); +console.log(total) // Prints 60 +</pre> + +<p>{{jsxref("Array.reduceRight", "reduceRight(callback[, initalvalue])")}}메서드는 reduce()와 유사하게 작동하지만 배열의 마지막 요소부터 시작합니다.</p> + +<p><code>reduce</code>와 <code>reduceRight</code> 메서드는 반복적인 배열 메서드 중 가장 명백합니다. 두 메서드는 재귀적으로 하나의 시퀀스를 하나의 값으로 줄이기 위해 두개의 값을 합치는 알고리즘을 위해 사용되어야 합니다. </p> + +<h3 id="다차원_배열">다차원 배열</h3> + +<p>배열은 중첩될 수 있습니다. 즉, 하나의 배열은 또 다른 배열을 요소로 포함할 수 있습니다. 자바스크립트 배열의 이런 특성을 사용하여, 다차원 배열을 생성할 수 있습니다.</p> + +<p>아래의 예제는 2차원 배열을 생성하는 예제입니다.</p> + +<pre><code>var a = new Array(4); +for (i = 0; i < 4; i++) { + a[i] = new Array(4); + for (j = 0; j < 4; j++) { + a[i][j] = '[' + i + ', ' + j + ']'; + } +}</code></pre> + +<p>이 예제는 다음과 같은 열을 포함하는 배열을 생성합니다.</p> + +<pre>Row 0: [0,0] [0,1] [0,2] [0,3] +Row 1: [1,0] [1,1] [1,2] [1,3] +Row 2: [2,0] [2,1] [2,2] [2,3] +Row 3: [3,0] [3,1] [3,2] [3,3] +</pre> + +<h3 id="배열과_정규표현식">배열과 정규표현식</h3> + +<p>문자열내에 정규 표현식에 일치하는 결과가 배열일 경우, 해당 배열은 정규 표현식에 일치하는 문자열들의 정보를 제공해 주는 속성들과 요소들을 반환합니다. {{jsxref ( "Global_Objects / RegExp / exec", "RegExp.exec ()")}}, {{jsxref("Global_Objects/String/match","String.match()")}}, 와 {{jsxref("Global_Objects/String/split","String.split()")}}메서드는 결과를 배열로 반환합니다. 정규식과 함께 배열을 어떻게 사용하는지에 대한 정보는 <a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions" title="en-US/docs/JavaScript/Guide/Regular Expressions">정규표현식</a>을 참조하시면 됩니다. </p> + +<h3 id="배열과_유사한_객체_사용">배열과 유사한 객체 사용</h3> + +<p>{{domxref ( "document.getElementsByTagName ()")}} 또는 {{jsxref ( "Functions / arguments", "arguments")}}에서 반환하는 {{domxref("NodeList")}} 객체는 함수 본문 내에서 사용할 수 있게 만들어졌으며 겉으로는 배열처럼 보이고 작동하지만 모든 메서드를 공유하지는 않습니다. arguments 객체는 {{jsxref ( "Global_Objects / Function / length", "length")}} 속성을 제공하지만 {{jsxref ( "Array.forEach", "forEach ()")}} 메소드는 구현하지 않습니다.</p> + +<p>배열 프로토 타입 메소드는 다른 배열과 유사한 객체에 대해 호출 될 수 있습니다.</p> + +<pre class="brush: js">function printArguments() { + Array.prototype.forEach.call(arguments, function(item) { + console.log(item); + }); +} +</pre> + +<p>배열 프로토 타입 메서드는 배열과 비슷한 방식으로 문자에 순차적으로 액세스 할 수 있으므로 문자열에서도 사용할 수 있습니다.</p> + +<pre><code>Array.prototype.forEach.call('a string', function(chr) { + console.log(chr); +});</code></pre> + +<h2 id="타입_배열">타입 배열</h2> + +<p>자바스크립트 타입 배열은 배열과 유사한 객체이며 원시 이진 데이터 접근에 대한 메카니즘을 제공합니다. 이미 알고 있듯이, {{jsxref("Array")}}객체는 동적으로 크기가 커지고 작아 질 수 있으며 어떤 자바스크립트 값이라도 가질 수 있습니다. 자바스크립트 엔진은 그런 배열을 빠르게 만들기 위해 최적화를 수행합니다. 그러나 웹 어플케이션이 보다 강력해지고, 음성, 영상 조작, <a href="/en-US/docs/WebSockets">웹소켓</a>을 사용하여 원시 데이터에 접근하는 등의 기능들이 추가 되면서 자바스크립트 코드가 타입배열을 가지고 빠르고 쉽게 원시 이진 데이터를 조작할 수 있는 것이 가능한 시점이 되었다는 것은 보다 명백해졌습니다.</p> + +<h3 id="버퍼와_뷰_타입_배열_구조">버퍼와 뷰: 타입 배열 구조</h3> + +<p>유연성과 효율성을 극대화 하기 위해, 자바스크립트 타입 배열을 <strong>버퍼</strong>와 <strong>뷰</strong>라는 구조로 구현되어 있습니다. 하나의 버퍼({{jsxref("ArrayBuffer")}}객체로 구현되어 있습니다.)는 하나의 데이터 덩어리를 의미하는 객체입니다. 버퍼는 구체적으로 언급할 형식이 없고, 버퍼가 담고 있는 내용에 접근할 메카니즘을 제공하지 않습니다. 버퍼에 담겨져 있는 메모리에 접근하기 위해선, 뷰를 사용해야 합니다. 하나의 뷰는 컨덱스트를 제공하는데, 컨텍스트는 데이터 형, 시작 오프셋 그리고 실제 타입배열로 변경되는 요소의 갯수를 제공합니다. </p> + +<p><img alt="Typed arrays in an ArrayBuffer" src="https://mdn.mozillademos.org/files/8629/typed_arrays.png" style="height: 278px; width: 666px;"></p> + +<h3 id="배열버퍼">배열버퍼</h3> + +<p>{{jsxref("ArrayBuffer")}}는 일반적이고, 고정길이의 이진 데이터 버퍼를 표현하기 위해 사용되는 데이터 타입입니다. <code>ArrayBuffer의 내용을 직접 수정할 수는 없는 대신 타입 배열 뷰 혹은 특정 형식 그리고 해당 버퍼의 내용을 읽고 쓸수 있게 해주는 </code>{{jsxref("DataView")}}<code>를 생성할 수 있습니다.</code></p> + +<h3 id="타입_배열_뷰">타입 배열 뷰</h3> + +<p>타입 배열 뷰들은 스스로를 나타낼 수 있는 이름과 <code>Int8</code>, <code>Uint32</code>, <code>Float64등의 일반적인 숫자 형들을 위한 뷰를 제공합니다.Uint8ClampedArray라는 특별한 타입 배열 뷰가 있습니다. 0부터 255까지의 값을 가질수 있습니다. 예를 들며, Uint8ClampedArray는 </code><a href="/en-US/docs/Web/API/ImageData">Canvas data processing</a>에 유용합니다. </p> + +<p>{{page("/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray", "TypedArray_objects")}}</p> + +<p><a href="/en-US/docs/Web/JavaScript/Typed_arrays">JavaScript typed arrays</a>를 참조하시면 보다 많은 정보를 보실 수 있습니다. </p> + +<p>{{PreviousNext("Web/JavaScript/Guide/Regular_Expressions", "Web/JavaScript/Guide/Keyed_Collections")}}</p> diff --git a/files/ko/web/javascript/guide/inheritance_and_the_prototype_chain/index.html b/files/ko/web/javascript/guide/inheritance_and_the_prototype_chain/index.html new file mode 100644 index 0000000000..e05bab3102 --- /dev/null +++ b/files/ko/web/javascript/guide/inheritance_and_the_prototype_chain/index.html @@ -0,0 +1,531 @@ +--- +title: 상속과 프로토타입 +slug: Web/JavaScript/Guide/Inheritance_and_the_prototype_chain +tags: + - JavaScript + - 객체지향 + - 상속 + - 중급 +translation_of: Web/JavaScript/Inheritance_and_the_prototype_chain +--- +<p>{{jsSidebar("Advanced")}}</p> + +<p>Java 나 C++ 같이 클래스 기반의 언어를 사용하던 프로그래머는 자바스크립트가 동적인 언어라는 점과 클래스가 없다는 것에서 혼란스러워 한다. (ES2015부터 class 키워드를 지원하기 시작했으나, 문법적인 양념일 뿐이며 자바스크립트는 여전히 프로토타입 기반의 언어다.)</p> + +<p>상속 관점에서 자바스크립트의 유일한 생성자는 객체뿐이다. 각각의 객체는 [[Prototype]]이라는 은닉(private) 속성을 가지는데 자신의 <strong>프로토타입</strong>이 되는 다른 객체를 가리킨다. 그 객체의 프로토타입 또한 프로토타입을 가지고 있고 이것이 반복되다, 결국 <code>null</code>을 프로토타입으로 가지는 오브젝트에서 끝난다. null은 더 이상의 프로토타입이 없다고 정의되며, <strong>프로토타입 체인</strong>의 종점 역할을 한다.</p> + +<p>종종 이러한 점이 자바스크립트의 약점이라고 지적되지만, 프로토타입적 상속 모델은 사실 고전적인 방법보다 좀 더 강력한 방법이다. 그 말은, 예를 들자면, 프로토타입적 모델에서 고전적인 방식을 구현하는 건 꽤나 사소한 일이지만, 그 반대는 훨씬 더 어려운 일이기 때문이다.</p> + +<h2 id="프로토타입_체인을_이용한_상속">프로토타입 체인을 이용한 상속</h2> + +<h3 id="속성_상속">속성 상속</h3> + +<p>자바스크립트 객체는 속성을 저장하는 동적인 "가방"과 (<strong>자기만의 속성</strong>이라고 부른다) 프로토타입 객체에 대한 링크를 가진다. 객체의 어떤 속성에 접근하려할 때 그 객체 자체 속성 뿐만 아니라 객체의 프로토타입, 그 프로토타입의 프로토타입 등 프로토타입 체인의 종단에 이를 때까지 그 속성을 탐색한다.</p> + +<div class="note">ECMAScript 표준은 someObject.[[Prototype]]을 객체 someObject의 프로토타입을 지시하도록 명시하였다. ECMAScript 2015부터 [[Prototype]]에 조상 {{jsxref("Object.getPrototypeOf()")}}과 {{jsxref("Object.setPrototypeOf()")}}을 이용하여 접근하기 때문이다. 이것은 자바스크립트의 표준은 아니나 많은 브라우저에 구현되어 사실상의 표준이 된 속성 __proto__과 동일하다.</div> + +<p>아래 코드에는 어떤 속성에 접근 하려할 때 일어나는 상황이다.</p> + +<pre class="brush: js">// o라는 객체가 있고, 속성 'a' 와 'b'를 갖고 있다고 하자. +let f = function () { + this.a = 1; + this.b = 2; +} +let o = new f(); // {a: 1, b: 2} + +// f 함수의 prototype 속성 값들을 추가 하자. +f.prototype.b = 3; +f.prototype.c = 4; + +// f.prototype = {b: 3, c: 4}; 라고 하지 마라, 해당 코드는 prototype chain 을 망가뜨린다. +// o.[[Prototype]]은 속성 'b'와 'c'를 가지고 있다. +// o.[[Prototype]].[[Prototype]] 은 Object.prototype 이다. +// 마지막으로 o.[[Prototype]].[[Prototype]].[[Prototype]]은 null이다. +// null은 프로토타입의 종단을 말하며 정의에 의해서 추가 [[Prototype]]은 없다. +// {a: 1, b: 2} ---> {b: 3, c: 4} ---> Object.prototype ---> null + +console.log(o.a); // 1 +// o는 'a'라는 속성을 가지는가? 그렇다. 속성의 값은 1이다. + +console.log(o.b); // 2 +// o는 'b'라는 속성을 가지는가? 그렇다. 속성의 값은 2이다. +// 프로토타입 역시 'b'라는 속성을 가지지만 이 값은 쓰이지 않는다. 이것을 "속성의 가려짐(property shadowing)" 이라고 부른다. + +console.log(o.c); // 4 +// o는 'c'라는 속성을 가지는가? 아니다. 프로토타입을 확인해보자. +// o.[[Prototype]]은 'c'라는 속성을 가지는가? 가지고 값은 4이다. + +console.log(o.d); // undefined +// o는 'd'라는 속성을 가지는가? 아니다. 프로토타입을 확인해보자. +// o.[[Prototype]]은 'd'라는 속성을 가지는가? 아니다. 다시 프로토타입을 확인해보자. +// o.[[Prototype]].[[Prototype]]은 null이다. 찾는 것을 그만두자. +// 속성이 발견되지 않았기 때문에 undefined를 반환한다. +</pre> + +<p>객체의 속성에 값을 지정하면 "자기만의 속성"이 생긴다. 단, <a href="/en/JavaScript/Guide/Obsolete_Pages/Creating_New_Objects/Defining_Getters_and_Setters" title="Defining Getters and Setters">getter or a setter</a>가 적용되는 속성이 상속되는 경우 예외적인 규칙이 적용된다.</p> + +<h3 id="메소드_상속">메소드 상속</h3> + +<p>자바스크립트에 "메소드"라는건 없다. 하지만 자바스크립트는 객체의 속성으로 함수를 지정할 수 있고 속성 값을 사용하듯 쓸 수 있다. 속성 값으로 지정한 함수의 상속 역시 위에서 본 속성의 상속과 동일하다. (단 위에서 언급한 "속성의 가려짐" 대신 "<em>메소드 오버라이딩, method overriding</em>" 라는 용어를 사용한다)</p> + +<p>상속된 함수가 실행 될 때, <a href="/en/JavaScript/Reference/Operators/this" title="this"><code>this</code></a> 라는 변수는 상속된 오브젝트를 가르킨다. 그 함수가 프로토타입의 속성으로 지정되었다고 해도 말이다.</p> + +<pre class="brush: js">var o = { + a: 2, + m: function(b){ + return this.a + 1; + } +}; + +console.log(o.m()); // 3 +// o.m을 호출하면 'this' 는 o를 가리킨다. + +var p = Object.create(o); +// p 는 프로토타입을 o로 가지는 오브젝트이다. + +p.a = 12; // p 에 'a'라는 새로운 속성을 만들었다. +console.log(p.m()); // 13 +// p.m이 호출 될 때 'this' 는 'p'를 가리킨다. +// 따라서 o의 함수 m을 상속 받으며, +// 'this.a'는 p.a를 나타내며 p의 개인 속성 'a'가 된다. +</pre> + +<h2 id="Javascript_에서_프로토타입을_사용하는_방법">Javascript 에서 프로토타입을 사용하는 방법</h2> + +<p>뒤에서 일어나는 일을 좀 더 자세히 파헤쳐보자.</p> + +<p>위에서 언급했듯이, 자바스크립트에서 함수는 속성을 가질 수 있다. 모든 함수에는 <code>prototype</code>이라는 특수한 속성이 있다. 아래의 예제 코드는 독립적이라는 것에 유의하자. (아래의 코드 이외에는 웹페이지에 다른 자바스크립트가 없다고 가정하는 것이 좋다.)</p> + +<p>최적의 실습을 위해서 콘솔을 열고 "Console" 탭으로 이동하여 아래의 JavaScript 코드를 복사하여 붙여넣은 다음 , 엔터키를 눌러 실행할 것을 적극 권한다. (콘솔은 대부분 웹 브라우저의 Developer Tools에 포함되어있다. 자세한 내용은 <a href="https://developer.mozilla.org/ko-KR/docs/Tools">Firefox Developer Tools</a>, <a href="https://developers.google.com/web/tools/chrome-devtools/">Chrome DevTools</a>,<a href="https://docs.microsoft.com/en-us/microsoft-edge/devtools-guide"> Edge DevTools</a> 에서 확인할 수 있다. )</p> + +<div></div> + +<pre><code>function doSomething(){} +console.log( doSomething.prototype ); +// It does not matter how you declare the function, a +// function in JavaScript will always have a default +// prototype property. +var doSomething = function(){}; +console.log( doSomething.prototype );</code></pre> + +<p>위 내용을 토대로, 콘솔을 보면 <code>doSomething()</code> 은 기본 <code>prototype</code> 속성을 가진다. 코드를 실행한 뒤에 콘솔에서는 다음과 유사한 형태의 객체가 표시되어야한다.</p> + +<pre><code>{ + constructor: ƒ doSomething(), + __proto__: { + constructor: ƒ Object(), + hasOwnProperty: ƒ hasOwnProperty(), + isPrototypeOf: ƒ isPrototypeOf(), + propertyIsEnumerable: ƒ propertyIsEnumerable(), + toLocaleString: ƒ toLocaleString(), + toString: ƒ toString(), + valueOf: ƒ valueOf() + } +}</code></pre> + +<p>우리는 아래에 보이는 것과 같이 <code>doSomething()</code> 프로토타입에 속성을 추가할 수 있다.</p> + +<pre><code>function doSomething(){} +doSomething.prototype.foo = "bar"; +console.log( doSomething.prototype );</code></pre> + +<p>결과:</p> + +<pre><code>{ + foo: "bar", + constructor: ƒ doSomething(), + __proto__: { + constructor: ƒ Object(), + hasOwnProperty: ƒ hasOwnProperty(), + isPrototypeOf: ƒ isPrototypeOf(), + propertyIsEnumerable: ƒ propertyIsEnumerable(), + toLocaleString: ƒ toLocaleString(), + toString: ƒ toString(), + valueOf: ƒ valueOf() + } +}</code> +</pre> + +<p>이제 <code>new</code> 연산자를 사용해서 프로토타입 기반의 <code>doSomething()</code> 인스턴스를 생성할 수 있다. new 연산자를 사용하려면 함수 호출 형식에 <code>new</code> 접두사를 붙이기만하면 된다. <code>new</code> 연산자로 함수를 호출하면 해당 함수의 인스턴스 객체를 반환받는다. 그러면 속성들을 이 객체에 추가할 수 있다.</p> + +<p>다음의 코드를 실행해보자.</p> + +<pre><code>function doSomething(){} +doSomething.prototype.foo = "bar"; // add a property onto the prototype +var doSomeInstancing = new doSomething(); +doSomeInstancing.prop = "some value"; // add a property onto the object +console.log( doSomeInstancing );</code></pre> + +<p>실행하고나면 결과는 다음과 비슷할 것이다.</p> + +<pre><code>{ + prop: "some value", + __proto__: { + foo: "bar", + constructor: ƒ doSomething(), + __proto__: { + constructor: ƒ Object(), + hasOwnProperty: ƒ hasOwnProperty(), + isPrototypeOf: ƒ isPrototypeOf(), + propertyIsEnumerable: ƒ propertyIsEnumerable(), + toLocaleString: ƒ toLocaleString(), + toString: ƒ toString(), + valueOf: ƒ valueOf() + } + } +}</code> +</pre> + +<p>위에서 본 것과 같이, doSomeInstancing 객체의 __proto__ 는 doSomething.prototype 이다.<br> + 그래서 도대체 __proto__는 무엇을 하는것인지 알아보자.<br> + 우리가 doSomeInstancing의 속성에 접근할때 브라우저는 우선 doSomeInstancing이 그 속성을 갖고있는지 확인한다.<br> + 만약 doSomeInstancing이 속성을 갖고있지 않다면, 브라우저는 doSomeInstancing의 __proto__(doSomething.prototype)가 그 속성을 갖고있는지 확인한다.<br> + 만약 doSomeInstancing의 __proto__가 브라우저가 찾던 속성을 갖고 있다면, doSomething의 __proto__가 갖고있는 그 속성을 사용한다.</p> + +<p>그렇지 않고, doSomeInstancing의 __proto__가 그 속성을 갖고있지 않을때에는<br> + doSomeInstancing의 __proto__의 __proto__가 그 속성을 갖는지 확인한다.<br> + 기본적으로, 어떠한 함수던지 그 함수의 prototype 속성의 __proto__는 window.Object.prototype이다.<br> + 그러므로 브라우저는 doSomeInstancing의 __proto__의 __proto__(doSomething.prototype의 __proto__(다시말해, Object.prototype)) 에서 그 속성을 찾아본다.<br> + 만약 그 속성을 doSomeInstancing의 __proto__의 __proto__에서 찾을 수 없다면 그다음엔 doSomeInstancing의 __proto__의 __proto__의 __proto__에서 찾을것이다.<br> + 하지만 여기서 문제가 발생한다.<br> + doSomeInstancing의 __proto__의 __proto__의 __proto__는 존재할 수 없다(window.Object.prototype의 __proto__는 null이기 때문).<br> + 그제서야, 오직 모든 프로토타입 체인이 검사 되고 브라우저가 더이상 검사할 __proto__가 없을때에서야 브라우저는 우리가 찾던 값이 undefined라고 결론짓는다.</p> + +<p>콘솔에 코드를 조금 더 추가해보자.</p> + +<pre><code>function doSomething(){} +doSomething.prototype.foo = "bar"; +var doSomeInstancing = new doSomething(); +doSomeInstancing.prop = "some value"; +console.log("doSomeInstancing.prop: " + doSomeInstancing.prop); +console.log("doSomeInstancing.foo: " + doSomeInstancing.foo); +console.log("doSomething.prop: " + doSomething.prop); +console.log("doSomething.foo: " + doSomething.foo); +console.log("doSomething.prototype.prop: " + doSomething.prototype.prop); +console.log("doSomething.prototype.foo: " + doSomething.prototype.foo);</code> +</pre> + +<p>이 코드의 결과는 아래와 같다.</p> + +<pre><code>doSomeInstancing.prop: some value +doSomeInstancing.foo: bar +doSomething.prop: undefined +doSomething.foo: undefined +doSomething.prototype.prop: undefined +doSomething.prototype.foo: bar</code> +</pre> + +<h2 id="객체를_생성하는_여러_방법과_프로토타입_체인_결과">객체를 생성하는 여러 방법과 프로토타입 체인 결과</h2> + +<h3 id="문법_생성자로_객체_생성">문법 생성자로 객체 생성</h3> + +<pre class="brush: js">var o = {a: 1}; + +// o 객체는 프로토타입으로 Object.prototype 을 가진다. +// 이로 인해 o.hasOwnProperty('a') 같은 코드를 사용할 수 있다. +// hasOwnProperty 라는 속성은 Object.prototype 의 속성이다. +// Object.prototype 의 프로토타입은 null 이다. +// o ---> Object.prototype ---> null + +var a = ["yo", "whadup", "?"]; + +// Array.prototype을 상속받은 배열도 마찬가지다. +// (이번에는 indexOf, forEach 등의 메소드를 가진다) +// 프로토타입 체인은 다음과 같다. +// a ---> Array.prototype ---> Object.prototype ---> null + +function f(){ + return 2; +} + +// 함수는 Function.prototype 을 상속받는다. +// (이 프로토타입은 call, bind 같은 메소드를 가진다) +// f ---> Function.prototype ---> Object.prototype ---> null +</pre> + +<h3 id="생성자를_이용">생성자를 이용</h3> + +<p>자바스크립트에서 생성자는 단지 <a href="/en/JavaScript/Reference/Operators/new" title="new">new 연산자</a>를 사용해 함수를 호출하면 된다.</p> + +<pre class="brush: js">function Graph() { + this.vertexes = []; + this.edges = []; +} + +Graph.prototype = { + addVertex: function(v){ + this.vertexes.push(v); + } +}; + +var g = new Graph(); +// g 'vertexes' 와 'edges'를 속성으로 가지는 객체이다. +// 생성시 g.[[Prototype]]은 Graph.prototype의 값과 같은 값을 가진다. +</pre> + +<h3 id="Object.create_이용">Object.create 이용</h3> + +<p>ECMAScript 5는 새로운 방법을 도입했다. <a href="/en/JavaScript/Reference/Global_Objects/Object/create" title="create">Object.create</a>라는 메소드를 호출하여 새로운 객체를 만들 수 있다. 생성된 객체의 프로토타입은 이 메소드의 첫 번째 인수로 지정된다.</p> + +<pre class="brush: js">var a = {a: 1}; +// a ---> Object.prototype ---> null + +var b = Object.create(a); +// b ---> a ---> Object.prototype ---> null +console.log(b.a); // 1 (상속됨) + +var c = Object.create(b); +// c ---> b ---> a ---> Object.prototype ---> null + +var d = Object.create(null); +// d ---> null +console.log(d.hasOwnProperty); // undefined이다. 왜냐하면 d는 Object.prototype을 상속받지 않기 때문이다. +</pre> + +<div> +<h3 id="class_키워드_이용"><code>class</code> 키워드 이용</h3> + +<p>ECMAScript2015에는 몇 가지 키워드가 도입되어 <a href="/en-US/docs/Web/JavaScript/Reference/Classes">class</a>를 구현하였다. 이런 생성 방식은 클래서 기반 언어의 개발자들에게 친숙하게 다가오나 동작 방식이 같지는 않다. 자바스크립트는 여전히 프로토타입 기반으로 남아있다. 새로 도입된 키워드는 {{jsxref("Statements/class", "class")}}, {{jsxref("Classes/constructor", "constructor")}}, {{jsxref("Classes/static", "static")}}, {{jsxref("Classes/extends", "extends")}}, 그리고 {{jsxref("Operators/super", "super")}}가 있다.</p> + +<pre class="brush: js">'use strict'; + +class Polygon { + constructor(height, width) { + this.height = height; + this.width = width; + } +} + +class Square extends Polygon { + constructor(sideLength) { + super(sideLength, sideLength); + } + get area() { + return this.height * this.width; + } + set sideLength(newLength) { + this.height = newLength; + this.width = newLength; + } +} + +var square = new Square(2); +</pre> + +<h3 id="성능">성능</h3> + +<p>프로토타입 체인에 걸친 속성 검색으로 성능에 나쁜 영향을 줄 수 있으며, 때때로 치명적일 수 있다. 또한 존재하지도 않는 속성에 접근하려는 시도는 항상 모든 프로토타입 체인인 전체를 탐색해서 확인하게 만든다.</p> + +<p>객체의 속성에 걸쳐 루프를 수행 하는 경우 프로토타입 체인 전체의 <strong>모든</strong> 열거자 속성에 대하여 적용된다. 객체 개인 속성인지 프로토타입 체인상 어딘가에 있는지 확인하기 위해서는 Object.prototype에서 모든 오브젝트로 상속된 <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty"><code>hasOwnProperty</code></a> 메소드를 이용할 필요가 있다. 다음 코드를 통하여 구체적인 예를 확인하여 보자.</p> + +<pre class="brush: js">console.log(g.hasOwnProperty('vertices')); +// true + +console.log(g.hasOwnProperty('nope')); +// false + +console.log(g.hasOwnProperty('addVertex')); +// false + +console.log(g.__proto__.hasOwnProperty('addVertex')); +// true +</pre> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty"><code>hasOwnProperty</code></a> 메소드만이 속성을 확인하고 프로토타입 체인 전체를 훑지 않게 할 수 있다.</p> + +<p>참고: <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined"><code>undefined</code></a>인지 여부만 확인하는 것으로는 충분하지 않다. 여전히 속성이 존재할 수도 있는데 단지 그 값에 <code>undefined</code>가 할당되어 있을 수도 있기 때문이다.</p> + +<h3 id="좋지_않은_사례_기본_프로타입의_확장_변형">좋지 않은 사례: 기본 프로타입의 확장 변형</h3> + +<p>Object.prototype 혹은 빌트인 프로토타입의 확장은 종종 이용되지만 오용이다.</p> + +<p>이 기법은 Monkey patching으로 불리며 캡슐화를 망가뜨린다. Prototype.js와 같은 유명한 프레임워크에서도 사용되지만, 빌트인 타입에 비표준 기능을 추가하는 것은 좋은 생각이 아니다.</p> + +<p>유일하게 좋은 사용 예라면, 새로운 자바스크립트 엔진에 Array.forEach등의 새로운 기능을 추가하면서 빌트인 프로토타입을 확장하는 것 정도다. </p> + +<h2 id="예">예</h2> + +<p><code>B는 A를 상속한다</code>:</p> + +<pre class="brush: js">function A(a) { + this.varA = a; +} + +// A의 정의에서 this.varA는 항상 A.prototype.varA가 가려버리는데 +// prototype에 varA를 다시 넣는 이유는 무엇인가? +A.prototype = { + varA: null, // 아무것도 안하면서 varA를 쓰는 이유가 있을까? + // 아마도 숨겨진 클래스의 할당 구조를 최적화 하려는 것인가? + // https://developers.google.com/speed/articles/optimizing-javascript#Initializing-instance-variables + // 모든 객체의 varA가 동일하게 초기화 되어야 상기 링크 내용이 유효할 수 있다. + doSomething: function() { + // ... + } +}; + +function B(a, b) { + A.call(this, a); + this.varB = b; +} +B.prototype = Object.create(A.prototype, { + varB: { + value: null, + enumerable: true, + configurable: true, + writable: true + }, + doSomething: { + value: function() { // override + A.prototype.doSomething.apply(this, arguments); // call super + // ... + }, + enumerable: true, + configurable: true, + writable: true + } +}); +B.prototype.constructor = B; + +var b = new B(); +b.doSomething(); +</pre> + +<p>중요한 점은:</p> + +<ul> + <li><code>.prototype</code>에 타입이 정의되어 있다.</li> + <li><code>Object.create()</code>을 이용하여 상속한다.</li> +</ul> + +<h2 id="prototype_그리고_Object.getPrototypeOf"><code>prototype</code> <code>그리고 Object.getPrototypeOf</code></h2> + +<p>Java나 C++에 익숙한 개발자는 클래스라는 것도 없고, 모든 것이 동적이고 실행 시 결정되는 자바스크립트의 특징 때문에 어려움을 겪을 수도 있다. 모든 것은 객체이고, 심지의 "class"를 흉내내는 방식도 단지 함수 오브젝트를 이용하는 것 뿐이다.</p> + +<p>이미 알아챘겠지만 우리의 함수 A도 특별한 속성 prototype를 가지고 있다. 이 특별한 속성은 자바스크립트의 new 연산자와 함께 쓰인다. 프로토타입 객체는 새로 만들어진 인스턴스의 내부 [[Prototype]] 속성에 복사되어 참조된다. 가령, var a1 = new A()를 수행할 때, this를 포함하고 있는 함수을 수행하기 전, 메모리에 새로 생성된 객체를 생성한 직후 자바스크립트는 a1.[[Prototype]] = A.prototype를 수행한다. 그 인스턴스의 속성에 접근하려 할 때 자바스크립트는 그 객체의 개인 속성인지 우선 확인하고 그렇지 않은 경우에 [[Prototype]]에서 찾는다. 이것은 prototype에 정의한 모든 것은 모든 인스턴스가 효과적으로 공유한다는 뜻이며, 심지어 프로토타입의 일부를 나중에 변경하다고 해도 이미 생성되어 있는 인스턴스는 필요한 경우 그 변경 사항에 접근할 수 있다.</p> + +<p>위의 예에서, 만일 <code>var a1 = new A(); var a2 = new A();</code> 그 후 <code>a1.doSomething</code>이 <code>Object.getPrototypeOf(a1).doSomething</code>를 가리키게 되는 것은<code>A.prototype.doSomething</code>으로 정의한 것과 같게 된다. 즉, <code>Object.getPrototypeOf(a1).doSomething == Object.getPrototypeOf(a2).doSomething == A.prototype.doSomething</code>.</p> + +<p>요약 하자면, prototype은 타입 정의를 위한 것이고, <code>Object.getPrototypeOf()</code>는 모든 인스턴스가 공유한다.</p> + +<p><code>[[Prototype]]</code>은 재귀적으로 탐색된다. 즉, <code>a1.doSomething</code>, <code>Object.getPrototypeOf(a1).doSomething</code>,<code>Object.getPrototypeOf(Object.getPrototypeOf(a1)).doSomething</code> 등등, 이미 발견했거나 <code>Object.getPrototypeOf</code>가 <code>null</code>을 반환할 때까지 반복된다.</p> + +<p>따라서 다음 호출에 대하여</p> + +<pre class="brush: js">var o = new Foo();</pre> + +<p>자바스크립트는 실제로 다음 작업을 수행한다.</p> + +<pre class="brush: js">var o = new Object(); +o.[[Prototype]] = Foo.prototype; +Foo.call(o);</pre> + +<p>(혹은 그런 비슷한 작업, 내부 구현은 다를 수 있다) 그리고 나중에 다음을 수행하면</p> + +<pre class="brush: js">o.someProp;</pre> + +<p>자바스크립트는 o가 속성 someProp을 가졌는지 확인하고, 아니면 <code>Object.getPrototypeOf(o).someProp</code>, 또 아니면 <code>Object.getPrototypeOf(Object.getPrototypeOf(o)).someProp</code> 등으로 계속 된다.</p> + +<h2 id="프로토타입_상속의_종류">프로토타입 상속의 종류</h2> + +<p>프로토타입 상속에는 3가지 종류가 있다 : 위임형 상속, 연결형 상속, 함수형 상속.</p> + +<h3 id="위임형_상속Delegation_inheritance">위임형 상속(Delegation inheritance)</h3> + +<p>위임형 상속에서 프로토타입 객체는 다른 객체의 기반이 된다. 위임 프로토타입을 상속받을 경우 새 객체는 해당 프로토타입에 대한 참조를 가지고 있다.</p> + +<p>새 객체의 속성에 접근할 때, 해당 객체가 직접적으로 속성을 소유하고 있는지 먼저 체크한다. 없다면 다음 순서로 <code>[[Prototype]]</code>을 체크한다. 이 과정은 프로토타입 체인을 따라서 모든 객체의 프로토타입 체인의 최상위에 있는 객체인 <code>Object.prototype</code>에 도달할 때 까지 반복된다.</p> + +<p>메소드를 위임 상속할 경우 모든 객체가 각 메소드에에 대해 하나의 코드를 공유하므로 메모리를 절약할 수 있다.</p> + +<p>Javascript에서 이를 구현하는 방법은 여러가지가 있는데 ES6에서는 아래와 같은 방식이 흔하다:</p> + +<pre class="brush: js">class Greeter { + constructor (name) { + this.name = name || 'John Doe'; + } + hello () { + return `Hello, my name is ${ this.name }`; + } +} + +const george = new Greeter('George'); +const msg = george.hello(); +console.log(msg); // Hello, my name is George +</pre> + +<p><code>Object.create(null)</code>. 을 통해 프로토타입을 {{jsxref("null")}}로 지정하여 속성 위임 없이 객체를 생성할 수 있다..</p> + +<p>이 방법의 큰 단점 중 하나는 상태를 저장하는데 그리 좋은 방법이 아니라는 것이다. 객체나 배열의 상태를 변경하게 되면 같은 프로토타입을 공유하는 모든 객체의 상태가 변경된다.</p> + +<p>상태 변경이 전파되는 것을 막으려면 각 객체마다 상태 값의 복사본을 만들어야 한다.</p> + +<h3 id="연결형_상속Concatenative_inheritance">연결형 상속(Concatenative inheritance)</h3> + +<p>연결형 상속은 한 객체의 속성을 다른 객체에 모두 복사함으로써 상속을 구현하는 방법이다.</p> + +<p>이 상속법은 Javascript 객체의 동적 확장성을 이용한 방법이다. 객체 복사는 속성의 초기값을 저장하기 위한 좋은 방법이다: 이 방식은 {{jsxref("Object.assign()")}}을 통해 구현하는 것이 보통이며 ES6 이전에 Lodash, Underscore, jQuery등의 라이브러리들이 <code>.extend()</code> 와 비슷한 메소드로 제공한 방법이다.</p> + +<pre class="brush: js">const proto = { + hello: function hello() { + return `Hello, my name is ${ this.name }`; + } +}; + +const george = Object.assign({}, proto, {name: 'George'}); +const msg = george.hello(); +console.log(msg); // Hello, my name is George +</pre> + +<p>연결형 상속은 매우 좋은 방법이며 클로져와 같이 사용한다면 훨씬 효과적인 상속 방식입니다..</p> + +<h3 id="함수형_상속Functional_inheritance">함수형 상속(Functional inheritance)</h3> + +<p>함수형 상속(Functional inheritance)이라는 단어는 Douglas Crockford가 자신의 저서 “JavaScript: The Good Parts”에서 창조한 단어이다. 이 방법은 새 속성들을 연결형 상속으로 쌓되 상속 기능을 Factory 함수로 만들어 사용하는 방식이다.</p> + +<p>기존의 객체를 확장하는데 쓰이는 함수를 일반적으로 믹스인 함수라 칭한다. 객체 확장에 함수를 사용하는 가장 큰 이점은 Private Data를 클로져를 통해 캡슐화 시킬 수 있다는 점이다.</p> + +<p>다르게 말하자면 Private 상태를 지정할 수 있다는 의미이다.</p> + +<p>특정 함수를 통할 필요 없이 public 접근이 가능한 속성에 대해 접근 제한을 거는 것은 문제가 있다. 따라서 private 클로져에 속성 값을 숨겨야 하며 이는 아래와 같이 구현한다:</p> + +<pre class="brush: js">// import Events from 'eventemitter3'; + +const rawMixin = function () { + const attrs = {}; + return Object.assign(this, { + set (name, value) { + attrs[name] = value; + this.emit('change', { + prop: name, + value: value + }); + }, + get (name) { + return attrs[name]; + } + }, Events.prototype); +}; + +const mixinModel = (target) => rawMixin.call(target); +const george = { name: 'george' }; +const model = mixinModel(george); +model.on('change', data => console.log(data)); +model.set('name', 'Sam'); +/* +{ + prop: 'name', + value: 'Sam' +} +*/ +</pre> + +<p><code>attrs</code> 을 public 속성에서 private 영역으로 옮겨서 public API를 통한 접근을 차단할 수 있다. // 접근할 수 있는 유일한 방법은 Privileged 메소드 뿐이다. Privileged 메소드는 클로져 영역에 정의된 함수로 private data에 접근 가능한 함수들을 일컫는다.</p> + +<p>위 예제를 보면 믹스인 함수 <code>rawMixin()</code>.에 대한 래퍼로 <code>mixinModel()</code> 을 선언한 것을 알 수 있다. 이는 예제에서 {{jsxref("Function.prototype.call()")}} 을 사용했듯이 함수 내에서 <code>this</code>의 값을 설정해야 하기 때문이다. Wrapper를 생략하고 호출자가 알아서 하도록 놔둘 수 있지만 그럴 경우 혼동될 가능성이 있다.</p> + +<div> +<h2 id="결론">결론</h2> + +<p>복잡한 코드를 작성하여 이용하기 전에 프로토타입 기반의 상속 모델을 이해하는 것이 <strong>중요하다</strong>. 또한 프로토타입 체인의 길이는 성능을 저해하지 않도록 줄이는 방법을 고안해야 한다. 또한 빌트인 프로토타입은 새로운 자바스크립트 기능과 호환성을 갖기 위한 이유가 아닌 이상 <strong>절대</strong> 확장해서는 안된다.</p> +</div> +</div> diff --git a/files/ko/web/javascript/guide/iterators_and_generators/index.html b/files/ko/web/javascript/guide/iterators_and_generators/index.html new file mode 100644 index 0000000000..648b898504 --- /dev/null +++ b/files/ko/web/javascript/guide/iterators_and_generators/index.html @@ -0,0 +1,193 @@ +--- +title: 반복기 및 생성기 +slug: Web/JavaScript/Guide/Iterators_and_Generators +tags: + - Guide + - Intermediate + - JavaScript +translation_of: Web/JavaScript/Guide/Iterators_and_Generators +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Using_promises", "Web/JavaScript/Guide/Meta_programming")}}</div> + +<p class="summary">컬렉션 내 각 항목 처리는 매우 흔한 연산입니다. JavaScript는 간단한 {{jsxref("Statements/for","for")}} 루프에서 {{jsxref("Global_Objects/Array/map","map()")}} 및 {{jsxref("Global_Objects/Array/filter","filter()")}}에 이르기까지, 컬렉션을 반복하는 많은 방법을 제공합니다. 반복기(iterator) 및 생성기(generator)는 반복 개념을 핵심 언어 내로 바로 가져와 {{jsxref("Statements/for...of","for...of")}} 루프의 동작(behavior)을 사용자 정의하는 메커니즘을 제공합니다.</p> + +<p>자세한 내용은, 다음을 참조하세요:</p> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Reference/Iteration_protocols">반복 프로토콜</a></li> + <li>{{jsxref("Statements/for...of","for...of")}}</li> + <li>{{jsxref("Statements/function*","function*")}} 및 {{jsxref("Generator")}}</li> + <li>{{jsxref("Operators/yield","yield")}} 및 {{jsxref("Operators/yield*","yield*")}}</li> +</ul> + +<h2 id="반복자">반복자</h2> + +<p>자바스크립트에서 <strong>반복자(Iterator)</strong>는 시퀀스를 정의하고 종료시의 반환값을 잠재적으로 정의하는 객체입니다. 더 구체적으로 말하자면, 반복자는 두 개의 속성( <code>value</code>, <code>done</code>)을 반환하는 next() 메소드 사용하여 객체의 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol">Iterator protocol</a>을 구현합니다. 시퀀스의 마지막 값이 이미 산출되었다면 <code>done</code> 값은 true 가 됩니다. 만약 <code>value</code>값이 <code>done</code> 과 함께 존재한다면, 그것은 반복자의 반환값이 됩니다.</p> + +<p>반복자를 생성하면 <code>next()</code> 메소드를 반복적으로 호출하여 명시적으로 반복시킬 수 있습니다. 반복자를 반복시키는 것은 일반적으로 한 번씩만 할 수 있기 때문에, 반복자를 소모시키는 것이라고 할 수 있습니다. 마지막 값을 산출하고나서 <code>next()</code>를 추가적으로 호출하면 <code>{done: true}</code>. 가 반환됩니다.</p> + +<p>자바스크립트에서 가장 일반적인 반복자는 배열 반복자로, 배열의 각 값을 순서대로 반환합니다. 모든 반복자가 배열로 표현될수 있다고 상상할 수 있지만 , 이것은 사실은 아닙니다. 배열은 완전히 할당되어야 하지만, 반복자는 필요한만큼만 소모되므로 무제한 시퀀스로 표현할 수 있습니다. 이를 테면 0부터 무한대사이의 정수범위처럼 말이죠.</p> + +<p>여기에 실습할 수 있는 예제가 있습니다. <code>start</code>에서 <code>end</code>까지 <code>step</code> 수 만큼 띄어진 정수 시퀀스를 정의하는 간단한 범위 반복자를 만들 수 있습니다. 최종적으로 시퀀스의 크기가 반환됩니다.</p> + +<pre class="notranslate"><code>function makeRangeIterator(start = 0, end = Infinity, step = 1) { + var nextIndex = start; + var n = 0; + + var rangeIterator = { + next: function() { + var result; + if (nextIndex < end) { + result = { value: nextIndex, done: false } + } else if (nextIndex == end) { + result = { value: n, done: true } + } else { + result = { done: true }; + } + nextIndex += step; + n++; + return result; + } + }; + return rangeIterator; +}</code> +</pre> + +<p>위의 반복자를 사용하면 아래와 같습니다:</p> + +<pre class="notranslate"><code>var it = makeRangeIterator(1, 4); + +var result = it.next(); +while (!result.done) { + console.log(result.value); // 1 2 3 + result = it.next(); +} + +console.log("Iterated over sequence of size: ", result.value);</code> +</pre> + +<div class="note"> +<p>It is not possible to know reflectively whether a particular object is an iterator. If you need to do this, use <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/Iterators_and_Generators$edit#Iterables">Iterables</a>.</p> +</div> + +<h2 id="Generator_functions">Generator functions</h2> + +<p>잘 만들어진 반복자(Iterator)는 유용한 도구인 반면, 이것을 생성할 때는 주의해서 프로그래밍을 해야 하는데, 반복자 내부에 명시적으로 상태를 유지할 필요가 있기 때문입니다. 생성자(Generator) 함수는 이에 대한 강력한 대안을 제공합니다: 실행이 연속적이지 않은 하나의 함수를 작성함으로서 개발자가 iterative algorithm을 정의할 수 있게 해줍니다. 생성자 함수는 {{jsxref("Statements/function*","function*")}} 문법을 사용하여 작성됩니다. 생성자 함수가 최초로 호출될 때, 함수 내부의 어떠한 코드도 실행되지 않고, 대신 생성자라고 불리는 반복자 타입을 반환합니다. 생성자의 <strong>next</strong> 메소드를 호출함으로서 어떤 값이 소비되면, 생성자 함수는 <strong>yield</strong> 키워드를 만날 때까지 실행됩니다. </p> + +<p>생성자 함수는 원하는 만큼 호출될 수 있고, 매번 새로운 생성자를 반환합니다다. 하지만, 각 생성자는 단 한 번만 순회될 수 있을 것입니다.</p> + +<p>위의 예제 코드에 생성자를 적용한 것입니다. 두 코드의 행위는 동일하지만, 생성자를 사용한 쪽이 쓰거나 읽기가 훨씬 쉽습니다. </p> + +<pre class="notranslate"><code>function* makeRangeIterator(start = 0, end = Infinity, step = 1) { + let n = 0; + for (let i = start; i < end; i += step) { + n++; + yield i; + } + return n; +}</code></pre> + +<h2 id="Iterables">Iterables</h2> + +<p>객체는 값이 {{jsxref("Statements/for...of", "for..of")}} 구조 내에서 반복되는 것 같은 그 반복 동작을 정의하는 경우 반복이 가능(<strong>iterable</strong>)합니다. {{jsxref("Array")}} 또는 {{jsxref("Map")}}과 같은 일부 내장 형은 기본 반복 동작이 있지만 다른 형(가령 {{jsxref("Object")}})은 없습니다.</p> + +<p><strong>반복가능</strong>하기 위해서, 객체는 <strong>@@iterator</strong> 메서드를 구현해야 합니다. 즉, 객체( 혹은 그 <a href="/ko/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain" title="prototype chain">프로토타입 체인</a>에 등장하는 객체 중 하나)가 {{jsxref("Symbol.iterator")}} 키를 갖는 속성이 있어야 함을 뜻합니다.</p> + +<p>하나의 iterable은 단 한 번, 혹은 여러번 반복가능합니다. 어떤 순간에 어떻게 사용할 지는 프로그래머에게 달려있습니다. 단 한 번 반복가능한 iterable(e.g. Generator)은 관습적으로 자신의 <strong>@@iterator</strong> 메소드로부터 <strong>this</strong>를 반환합니다. 반면, 여러 번 반복 가능한 iterables은 <strong>@@iterator </strong>메소드가 호출되는 매 회 새로운 iterator를 반드시 반환해야합니다. </p> + +<h3 id="사용자_정의_iterable">사용자 정의 iterable</h3> + +<p>이와 같이 자신의 반복가능 객체를 만들 수 있습니다:</p> + +<pre class="notranslate"><code>var myIterable = { + *[Symbol.iterator]() { + yield 1; + yield 2; + yield 3; + } +} + +for (let value of myIterable) { + console.log(value); +} +// 1 +// 2 +// 3 + +or + +[...myIterable]; // [1, 2, 3]</code></pre> + +<h3 id="내장_iterable">내장 iterable</h3> + +<p>{{jsxref("String")}}, {{jsxref("Array")}}, {{jsxref("TypedArray")}}, {{jsxref("Map")}} 및 {{jsxref("Set")}}은 모두 내장 반복가능 객체입니다, 그들의 프로토타입 객체가 모두 {{jsxref("Symbol.iterator")}} 메서드가 있기 때문입니다.</p> + +<h3 id="iterable을_기대하는_구문">iterable을 기대하는 구문</h3> + +<p>일부 문(statement) 및 식(expression)은 iterable합니다, 가령 {{jsxref("Statements/for...of","for-of")}} 루프, {{jsxref("Operators/Spread_operator","spread syntax","","true")}}, {{jsxref("Operators/yield*","yield*")}} 및 {{jsxref("Operators/Destructuring_assignment","해체 할당","","true")}}.</p> + +<pre class="brush: js notranslate">for(let value of ['a', 'b', 'c']){ + console.log(value) +} +// "a" +// "b" +// "c" + +[...'abc'] // ["a", "b", "c"] + +function* gen(){ + yield* ['a', 'b', 'c'] +} + +gen().next() // { value:"a", done:false } + +[a, b, c] = new Set(['a', 'b', 'c']) +a // "a" + + +</pre> + +<h2 id="Generator_심화">Generator 심화</h2> + +<p> 생성자 함수는 요청에 따라 그 산출된(yielded, yield 식으로 산출된) 값을 계산하고, 계산하기 비싼(힘든) 수열 또는 위에 설명한 대로 무한 수열이라도 효율적으로 나타내게 합니다.</p> + +<p>{{jsxref("Global_Objects/Generator/next","next()")}} 메서드는 또한 생성기의 내부 상태를 수정하는 데 쓰일 수 있는 값을 받습니다. <code>next()</code>에 전달되는 값은 생성기가 중단된 마지막 <code>yield</code> 식의 결과로 처리됩니다.</p> + +<p>여기 sequence(수열)을 재시작하기 위해 <code>next(x)</code>를 사용하는 피보나치 생성기가 있습니다:</p> + +<pre class="brush: js notranslate">function* fibonacci(){ + var fn1 = 0; + var fn2 = 1; + while (true){ + var current = fn1; + fn1 = fn2; + fn2 = current + fn1; + var reset = yield current; + if (reset){ + fn1 = 0; + fn2 = 1; + } + } +} + +var sequence = fibonacci(); +console.log(sequence.next().value); // 0 +console.log(sequence.next().value); // 1 +console.log(sequence.next().value); // 1 +console.log(sequence.next().value); // 2 +console.log(sequence.next().value); // 3 +console.log(sequence.next().value); // 5 +console.log(sequence.next().value); // 8 +console.log(sequence.next(true).value); // 0 +console.log(sequence.next().value); // 1 +console.log(sequence.next().value); // 1 +console.log(sequence.next().value); // 2 +</pre> + +<p>You can force a generator to throw an exception by calling its {{jsxref("Global_Objects/Generator/throw","throw()")}} method and passing the exception value it should throw. This exception will be thrown from the current suspended context of the generator, as if the <code>yield</code> that is currently suspended were instead a <code>throw<em>value</em></code> statement.</p> + +<p>If the exception is not caught from within the generator, it will propagate up through the call to <code>throw()</code>, and subsequent calls to <code>next()</code> will result in the <code>done</code> property being <code>true</code>.</p> + +<p>Generators have a {{jsxref("Global_Objects/Generator/return","return(value)")}} method that returns the given value and finishes the generator itself.</p> + +<p>{{PreviousNext("Web/JavaScript/Guide/Using_promises", "Web/JavaScript/Guide/Meta_programming")}}</p> diff --git a/files/ko/web/javascript/guide/keyed_collections/index.html b/files/ko/web/javascript/guide/keyed_collections/index.html new file mode 100644 index 0000000000..a206b6556d --- /dev/null +++ b/files/ko/web/javascript/guide/keyed_collections/index.html @@ -0,0 +1,149 @@ +--- +title: 키기반의 컬렉션 +slug: Web/JavaScript/Guide/Keyed_collections +translation_of: Web/JavaScript/Guide/Keyed_collections +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Indexed_Collections", "Web/JavaScript/Guide/Working_with_Objects")}}</div> + +<p class="summary">이번 장에서는 입력된 키값을 기준으로 정렬되는 데이터의 집합(자료 구조)에 대해 소개 할 것이다. Map과 Set은 입력된 순서대로 반복적으로 접근 가능한 요소들을 포함하고 있다. </p> + +<h2 id="Maps">Maps</h2> + +<h3 id="Map_객체"><code>Map</code> 객체</h3> + +<p>ECMAScript 6에서 값들을 매핑하기 위한 새로운 데이터 구조를 소개 하고 있다. 그중 하나인 Map객체는 간단한 키와 값을 서로 연결(매핑)시켜 저장하며 저장된 순서대로 각 요소들을 반복적으로 접근할 수 있도록 한다. </p> + +<p>다음 코드는 Map이 제공하는 기본적인 기능들을 보여 주고 있다. 더 많은 예제와 모든 기능에 대한 API를 볼려면 {{jsxref("Map")}} 페이지를 참고하면 된다. Map객체에 저장되어 있는 각 요소들을 [키, 값] 형태의 배열로 반복적으로 반환해주는 <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a></code> 를 사용할 수 있다.</p> + +<pre class="brush: js">var sayings = new Map(); +sayings.set("dog", "woof"); +sayings.set("cat", "meow"); +sayings.set("elephant", "toot"); +sayings.size; // 3 +sayings.get("fox"); // undefined +sayings.has("bird"); // false +sayings.delete("dog"); + +for (var [key, value] of sayings) { + console.log(key + " goes " + value); +} +// "cat goes meow" +// "elephant goes toot" +</pre> + +<h3 id="Object와_Map_비교"><font face="Consolas, Liberation Mono, Courier, monospace">Object와 Map 비교</font></h3> + +<p>전통적으로 {{jsxref("Object", "objects", "", 1)}} 는 문자열을 값에 매핑하는 데 사용되었다. Object는 키를 값으로 설정하고, 값을 검색하고, 키를 삭제하고, 키에 저장된 내용을 검색 할 수 있게 만들어준다. 그러나 Map 객체는 더 나은 맵이 되도록 하는 몇 가지 장점을 가지고 있다.</p> + +<ul> + <li>Object의 키는 {{jsxref("Global_Objects/String","Strings")}}이며, Map의 키는 모든 값을 가질 수 있다.</li> + <li>Object는 크기를 수동으로 추적해야하지만, Map은 크기를 쉽게 얻을 수 있다.</li> + <li>Map은 삽입된 순서대로 반복된다.</li> + <li>객체(Object)에는 prototype이 있어 Map에 기본 키들이 있다. (이것은 map = Object.create(null) 를 사용하여 우회할 수 있다. )</li> +</ul> + +<p>Object 혹은 Map중에 어느 것을 사용할지를 결정하는데 도움을 줄 두가지 팁이 있다:</p> + +<ul> + <li>실행 시까지 키를 알수 없고, 모든 키가 동일한 type이며 모든 값들이 동일한 type일 경우에는 objects를 대신해서 map을 사용해라. </li> + <li>각 개별 요소에 대해 적용해야 하는 로직이 있을 경우에는 objects를 사용해라. </li> +</ul> + +<h3 id="WeakMap_object"><code>WeakMap</code> object</h3> + +<p>{{jsxref("WeakMap")}}객체는 object만을 키로 허용하고 값은 임의의 값을 허용하는 키/값 형태의 요소의 집합이다. 키가 가지고 있는 객체에 대한 참조는 객체에 대한 참조가 더이상 존재하지 않을 경우 garbage collection(GC)의 수거 대상이 되는 약한 참조를 의미한다. <code>WeakMap</code> API는 Map API와 동일하다. </p> + +<p>단 한가지 Map객체와 다른 점은 WeakMap의 키들은 열거형이 아니라는 점이다. (즉, 키 목록을 제공해 주는 메서드가 없다는 것이다.) 만약에 키 목록을 제공한다면 garbage collection의 상태, 결과에 따라 키 목록이 변하게 될 것이다. 이는 비 결정성을 야기한다. </p> + +<p>WeakMap에 대한 더 많은 정보와 예제 코드 그리고 "왜 WeakMap을 사용하지?"를 보고 싶다면 {{jsxref("WeakMap")}} 페이지를 참고하면 된다. </p> + +<p><code>WeakMap를 사용하는 한가지 경우는 객체의 사적인 정보를 저장하기 위해서 이거나 상세 구현 내용을 숨기기 위한 것이다. 다음의 예제는 </code>Nick Fitzgerald의 블로그 글- <a href="http://fitzgeraldnick.com/weblog/53/">"Hiding Implementation Details with ECMAScript 6 WeakMaps"</a>-에서 가져온 것이다. 객체가 가지고 있는 그렇지만 외부에 공개되지 않는(private) 데이터와 메서드들은 WeakMap객체인 privates에 저장이 된다. 인스턴스를 통해 접근 가능한 모든 것들과 prototype은 public이고 다른 것들은 외부에서는 접근이 불가하다 그 이유는 privates는 모듈로부터 내보내기(export)가 되지 않기 때문이다.</p> + +<pre class="brush: js">const privates = new WeakMap(); + +function Public() { + const me = { + // Private data goes here + }; + privates.set(this, me); +} + +Public.prototype.method = function () { + const me = privates.get(this); + // Do stuff with private data in `me`... +}; + +module.exports = Public; +</pre> + +<h2 id="Sets">Sets</h2> + +<h3 id="Set_object"><code>Set</code> object</h3> + +<p>{{jsxref("Set")}}객체는 값들의 집합이다. 입력된 순서에따라 저장된 요소를 반복처리할 수 있다. Set은 중복된 값을 허용하지 않는다. 따라서 특정 값은 Set내에서 하나만 존재 하게 된다. </p> + +<p>아래의 코드는 Set의 기본적인 동작들을 보여 준다. 더 많은 예제와 모든 API는 {{jsxref("Set")}} 참조 페이지를 보면 된다. </p> + +<pre class="brush: js">var mySet = new Set(); +mySet.add(1); +mySet.add("some text"); +mySet.add("foo"); + +mySet.has(1); // true +mySet.delete("foo"); +mySet.size; // 2 + +for (let item of mySet) console.log(item); +// 1 +// "some text" +</pre> + +<h3 id="배열과_Set의_상호_변환">배열과 Set의 상호 변환</h3> + +<p>{{jsxref("Array.from")}} 혹은 <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator">spread operator</a>를 통해 Set객체를 가지고 {{jsxref("Array")}}을 생성할 수 있다. 또한 Set 생성자는 배열을 인자로 받을 수 있고 해당 배열을 Set객체의 요소로 저장한다. 한번 더 상기시키면 Set객체는 중복된 값을 저장하지 않기때문에 주어진 배열내의 중복된 요소들을 제거되어 Set으로 변환된다. </p> + +<pre class="brush: js">Array.from(mySet); +[...mySet2]; + +mySet2 = new Set([1,2,3,4]); +</pre> + +<h3 id="배열과_Set비교"><font face="Consolas, Liberation Mono, Courier, monospace">배열과 Set비교</font></h3> + +<p>일반적으로 Javascript에선 배열에 특정 요소의 집합을 저장한다. 하지만 Set객체는 몇가지 이점을 제공한다. </p> + +<ul> + <li>{{jsxref("Array.indexOf", "indexOf")}}메서드를 사용하여 배열내에 특정 요소가 존재하는지 확인하는 것은 느리다.</li> + <li>배열에선 해당 요소를 배열에서 잘라내야 하는 반면 Set객체는 요소의 값으로 해당 요소를 삭제하는 기능 제공한다.</li> + <li>{{jsxref("NaN")}}은 배열에서 indexOf메서드로 찾을 수 없다. </li> + <li>Set객체는 값의 유일성을 보장하기 때문에 직접 요소의 중복성을 확인할 필요가 없다. </li> +</ul> + +<h3 id="WeakSet_객체"><code>WeakSet</code> 객체</h3> + +<p>{{jsxref("WeakSet")}} objects are collections of objects. An object in the <code>WeakSet</code> may only occur once; it is unique in the <code>WeakSet</code>'s collection and objects are not enumerable.</p> + +<p>{{jsxref("WeakSet")}}객체는 객체를 저장하는 일종의 집합이다. <code>WeakSet내의 중복된 객체는 없으며 WeakSet내의 요소를 열거할 수는 없다. </code></p> + +<p>{{jsxref("Set")}}과 가장 큰 차이점은 다음과 같다.</p> + +<ul> + <li><code>Set과는 다르게 WeakSet은 객체의 집합이며 객체만 저장할 수 있다. 특정 type의 값을 저장할 수는 없다. </code></li> + <li><font face="Consolas, Liberation Mono, Courier, monospace">WeakSet은 약한 참조를 가진다. WeakSet내의 객체에 대한 참조는 약하게 연결이 되어 있다. WeakSet내에 저장되어 있는 객체에 대한 참조가 없게되면 garbage collection 대상이되어 수거 된다. 따라서 현재 저장되어 있는 객체에 대한 목록은 없으며 WeakSet은 열거형이 아니다. </font></li> +</ul> + +<p><code>WeakSet객체의 사용 사례는 제한되어 있다. 메모리 누수가 발생되지 않기때문에 안전하게 DOM요소를 키로 저장할 수 있고 예를 들면 추적을 위해 DOM요소들을 WeakSet에 저장할 수 있다. </code></p> + +<p> </p> + +<h2 id="Map과_Set의_키와_값의_동치성"><code>Map과 Set의 키와 값의 동치성</code></h2> + +<p>Map객체의 key에 대한 동치성 비교와 Set객체의 값에 대한 동치성 비교 모두 "<a href="https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero">same-value-zero algorithm</a>"에 근거한다. </p> + +<ul> + <li>동치성 비교는 <code>=== 비교 연산과 같이 작동한다. </code></li> + <li>-0과 +0은 같다고 간주한다. </li> + <li>{{jsxref("NaN")}}는 자기 자신하고 같다고 간주한다. (===와는 반대로)</li> +</ul> + +<p>{{PreviousNext("Web/JavaScript/Guide/Indexed_Collections", "Web/JavaScript/Guide/Working_with_Objects")}}</p> diff --git a/files/ko/web/javascript/guide/loops_and_iteration/index.html b/files/ko/web/javascript/guide/loops_and_iteration/index.html new file mode 100644 index 0000000000..4b0ac738b6 --- /dev/null +++ b/files/ko/web/javascript/guide/loops_and_iteration/index.html @@ -0,0 +1,332 @@ +--- +title: 루프와 반복 +slug: Web/JavaScript/Guide/Loops_and_iteration +translation_of: Web/JavaScript/Guide/Loops_and_iteration +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Control_flow_and_error_handling", "Web/JavaScript/Guide/Functions")}}</div> + +<p class="summary">루프는 어떤 것을 반복적으로 시행할때 빠르고 간편한 방법을 제공합니다. <a href="/en-US/docs/Web/JavaScript/Guide">JavaScript Guide</a>의 이 항목은 JavaScript 에서 사용이 가능한 서로 다른 여러가지 반복문을 소개합니다.</p> + +<p>반복문을 게임의 컴퓨터화된 버전이라고 생각해 보세요. 누군가에게 한 방향으로 X만큼 가게 시키고 다른 방향으로 Y만큼 더 가게 한다고 생각해 보십시오. 예를들어, "동쪽으로 5만큼 가세요"는 다음과 같이 반복문으로 표현 될 수 있습니다.</p> + +<pre class="brush: js notranslate">var step; +for (step = 0; step < 5; step++) { + // Runs 5 times, with values of step 0 through 4. + console.log('Walking east one step'); +} +</pre> + +<p>반복문은 매우 다양한 종류가 있습니다. 하지만 반복문이 기본적으로 하는일은 모두 같습니다. 반복문은 한 동작을 여러 번 반복합니다. (사실 0회 반복하는 것도 가능합니다.) 다양한 반복문 메커니즘은 다양한 방법으로 반복문의 시작점과 끝나는 점을 정할 수 있습니다.</p> + +<p>자바스크립트가 지원하는 반복문은 다음과 같습니다:</p> + +<ul> + <li>{{anch("for 문")}}</li> + <li>{{anch("do...while 문")}}</li> + <li>{{anch("while 문")}}</li> + <li>{{anch("레이블 문")}}</li> + <li>{{anch("break 문")}}</li> + <li>{{anch("continue 문")}}</li> + <li>{{anch("for...in 문")}}</li> + <li>{{anch("for...of 문")}}</li> +</ul> + +<h2 id="for_문"><code>for</code> 문</h2> + +<p>for 반복문은 어떤 특정한 조건이 거짓으로 판별될 때까지 반복합니다. 자바스크립트의 반복문은 C의 반복문과 비슷합니다. for 반복문은 다음과 같습니다.</p> + +<pre class="syntaxbox notranslate">for ([초기문]; [조건문]; [증감문]) + 문장 +</pre> + +<p>for문이 실행될 때, 다음과 같이 실행됩니다.:</p> + +<ol> + <li>초기화 구문인 초기문이 존재한다면 초기문이 실행됩니다. 이 표현은 보통 1이나 반복문 카운터로 초기 설정이 됩니다. 그러나 복잡한 구문으로 표현 될 때도 있습니다. 또한 변수로 선언 되기도 합니다.</li> + <li>조건문은 조건을 검사합니다. 만약 조건문이 참이라면, 그 반복문은 실행됩니다. 만약 조건문이 거짓이라면, 그 for문은 종결됩니다. 만약 그 조건문이 생략된다면, 그 조건문은 참으로 추정됩니다.</li> + <li>문장이 실행됩니다. 많은 문장을 실행할 경우엔, { } 를 써서 문장들을 묶어 줍니다.</li> + <li>갱신 구문인 증감문이 존재한다면 실행되고 2번째 단계로 돌아갑니다.</li> +</ol> + +<h3 id="예시"><strong>예시</strong></h3> + +<p>다음 함수는 스크롤링 목록(다중 선택을 허용하는 요소 {{HTMLElement("select")}}). 에서 선택된 옵션들을 세는 for문 입니다. 이 for문은 변수 i 를 선언하고 0으로 초기화 시킵니다. 이것은 i 가 <select> 요소 안의 옵션 수가 i 보다 작은지 확인 합니다. 다음의 if문을 수행하고 각 루프를 빠져나간 뒤 i 를 1 증가시킵니다.</p> + +<pre class="brush: html notranslate"><form name="selectForm"> + <p> + <label for="musicTypes">Choose some music types, then click the button below:</label> + <select id="musicTypes" name="musicTypes" multiple="multiple"> + <option selected="selected">R&B</option> + <option>Jazz</option> + <option>Blues</option> + <option>New Age</option> + <option>Classical</option> + <option>Opera</option> + </select> + </p> + <p><input id="btn" type="button" value="How many are selected?" /></p> +</form> + +<script> +function howMany(selectObject) { + var numberSelected = 0; + for (var i = 0; i < selectObject.options.length; i++) { + if (selectObject.options[i].selected) { + numberSelected++; + } + } + return numberSelected; +} + +var btn = document.getElementById("btn"); +btn.addEventListener("click", function(){ + alert('Number of options selected: ' + howMany(document.selectForm.musicTypes)) +}); +</script> + +</pre> + +<h2 id="do...while_문"><code>do...while</code> 문</h2> + +<p>do...while 문은 특정한 조건이 거짓으로 판별될 때까지 반복합니다. do...while 문은 다음과 같습니다.</p> + +<pre class="syntaxbox notranslate">do + 문장 +while (조건문); +</pre> + +<p><code>조건문을 확인하기 전에 문장은 한번 실행됩니다. 많은 문장을 실행하기 위해선 { }를 써서 문장들을 묶어줍니다. 만약 조건이 참이라면, 그 문장은 다시 실행됩니다. 매 실행 마지막마다 조건문이 확인됩니다. 만약 조건문이 거짓일 경우, 실행을 멈추고 do...while 문 바로 아래에 있는 문장으로 넘어가게 합니다.</code></p> + +<h3 id="예시_2"><strong>예시</strong></h3> + +<p>다음 예제에서, do 반복문은 최소 한번은 반복됩니다. 그리고 i 가 5보다 작지 않을 때까지 계속 반복됩니다.</p> + +<pre class="brush: js notranslate">do { + i += 1; + console.log(i); +} while (i < 5);</pre> + +<h2 id="while_문"><code>while</code> 문</h2> + +<p>while 문은 어떤 조건문이 참이기만 하면 문장을 계속해서 수행합니다. while 문은 다음과 같습니다.</p> + +<pre class="syntaxbox notranslate">while (조건문) + 문장 +</pre> + +<p>만약 조건문이 거짓이 된다면, 그 반복문 안의 문장은 실행을 멈추고 반복문 바로 다음의 문장으로 넘어갑니다.</p> + +<p>조건문은 반복문 안의 문장이 실행되기 전에 확인 됩니다. 만약 조건문이 참으로 리턴된다면, 문장은 실행되고 그 조건문은 다시 판별됩니다. 만약 조건문이 거짓으로 리턴된다면, 실행을 멈추고 while문 바로 다음의 문장으로 넘어가게 됩니다.</p> + +<p>많은 문장들을 실행하기 위해선, { }를 써서 문장들을 묶어줍니다.</p> + +<h3 id="예시_1"><strong>예시 1</strong></h3> + +<p>다음 while 반복문은 n이 3보다 작은 한, 계속 반복됩니다.</p> + +<pre class="brush: js notranslate">n = 0; +x = 0; +while (n < 3) { + n++; + x += n; +} +</pre> + +<p>매 반복과 함께, n이 증가하고 x에 더해집니다. 그러므로, x와 n은 다음과 같은 값을 갖습니다.</p> + +<ul> + <li>첫번째 경과 후: <code>n</code> = 1 and <code>x</code> = 1</li> + <li>두번째 경과 후: <code>n</code> = 2 and <code>x</code> = 3</li> + <li>세번째 경과 후: <code>n</code> = 3 and <code>x</code> = 6</li> +</ul> + +<p>세번째 경과 후에, n < 3 은 더이상 참이 아니므로, 반복문은 종결됩니다.</p> + +<h3 id="예시_2_2"><strong>예시 2</strong></h3> + +<p>조건문은 항상 거짓이 될지라도 무한 루프는 피해야 합니다. 그렇지 않으면 그 반복문은 영원히 끝나지 않을 것입니다. 아래의 while 문은 조건문이 절대 거짓이 될 수 없으므로 영원히 반복될 것입니다.</p> + +<pre class="brush: js notranslate">// 다음과 같은 코드는 피하세요. +while (true) { + console.log("Hello, world"); +}</pre> + +<h2 id="레이블_문">레이블 문</h2> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Statements/label">레이블</a>은 여러분이 프로그램에서 다른 곳으로 참조할 수 있도록 식별자로 문을 제공합니다. 예를 들어, 여러분은 루프를 식별하기 위해 레이블을 사용하고, 프로그램이 루프를 방해하거나 실행을 계속할지 여부를 나타내기 위해 break나 continue 문을 사용할 수 있습니다.</p> + +<p>레이블 문의 구문은 다음과 같습니다:</p> + +<pre class="syntaxbox notranslate">label : + statement +</pre> + +<p><em><font face="Consolas">레이블</font></em> 값은 예약어가 아닌 임의의 JavaScript 식별자일 수 있습니다. 여러분이 레이블을 가지고 식별하는 <em><font face="Consolas">문</font></em>은 어떠한 문이 될 수 있습니다.</p> + +<h3 id="예시_3"><strong>예시</strong></h3> + +<p>이 예에서, 레이블 markLoop는 while 루프를 식별합니다.</p> + +<pre class="brush: js notranslate">markLoop: +while (theMark == true) { + doSomething(); +}</pre> + +<h2 id="break_문"><code>break</code> 문</h2> + +<p>break문은 반복문, switch문, 레이블 문과 결합한 문장을 빠져나올 때 사용합니다.</p> + +<ul> + <li>레이블 없이 break문을 쓸 때: 가장 가까운 <code>while</code>, <code>do-while</code>, <code>for</code>, 또는 <code>switch</code>문을 종료하고 다음 명령어로 넘어갑니다.</li> + <li>레이블 문을 쓸 때: 특정 레이블 문에서 끝납니다.</li> +</ul> + +<p>break문의 문법은 다음과 같습니다.</p> + +<ol> + <li><code>break;</code></li> + <li><code>break <em>[레이블]</em>;</code></li> +</ol> + +<p>break문의 첫번째 형식은 가장 안쪽의 반복문이나 switch문을 빠져나옵니다. 두번째 형식는 특정한 레이블 문을 빠져나옵니다.</p> + +<h3 id="예시_1_2"><strong>예시</strong> <strong>1</strong></h3> + +<p>다음 예</p> + +<pre class="brush: js notranslate">for (i = 0; i < a.length; i++) { + if (a[i] == theValue) { + break; + } +}</pre> + +<h3 id="예시_2_Breaking_to_a_label"><strong>예시 2: </strong>Breaking to a label</h3> + +<pre class="brush: js notranslate">var x = 0; +var z = 0 +labelCancelLoops: while (true) { + console.log("Outer loops: " + x); + x += 1; + z = 1; + while (true) { + console.log("Inner loops: " + z); + z += 1; + if (z === 10 && x === 10) { + break labelCancelLoops; + } else if (z === 10) { + break; + } + } +} +</pre> + +<h2 id="continue_문">continue 문</h2> + +<p><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/continue">continue</a></code> 문은 while, do-while, for, 레이블 문을 다시 시작하기 위해 사용될 수 있습니다.</p> + +<ul> + <li>레이블없이 continue를 사용하는 경우, 그것은 가장 안쪽의 while, do-while, for 문을 둘러싼 현재 반복을 종료하고, 다음 반복으로 루프의 실행을 계속합니다. <font face="Consolas">break</font>문과 달리, continue 문은 전체 루프의 실행을 종료하지 않습니다. while 루프에서 그것은 다시 조건으로 이동합니다. for 루프에서 그것은 증가 표현으로 이동합니다.</li> + <li>레이블과 함께 continue를 사용하는 경우, continue는 그 레이블로 식별되는 루프 문에 적용됩니다.</li> +</ul> + +<p>continue 문의 구문은 다음과 같습니다:</p> + +<ol> + <li><code>continue;</code></li> + <li><code>continue </code><em><code>label;</code></em></li> +</ol> + +<h3 id="예시_1_3"><strong>예시 1</strong></h3> + +<p>다음의 예는 i 값이 3일 때 실행하는 continue 문과 함께 while 루프를 보여줍니다. 따라서, n은 값 1, 3, 7, 12를 취합니다.</p> + +<pre class="brush: js notranslate">i = 0; +n = 0; +while (i < 5) { + i++; + if (i == 3) { + continue; + } + n += i; +} +</pre> + +<h3 id="예시_2_3"><strong>예시 2</strong></h3> + +<p>checkiandj 레이블 문은 checkj 레이블 문을 포함합니다. continue가 발생하는 경우, 프로그램은 checkj의 현재 반복을 종료하고, 다음 반복을 시작합니다. 그 조건이 false를 반환 할 때까지 continue가 발생할 때마다, checkj는 반복합니다. false가 반환될 때, checkiandj 문의 나머지 부분은 완료되고, 그 조건이 false를 반환 할 때까지 checkiandj는 반복합니다. false가 반환될 때, 이 프로그램은 다음 checkiandj 문에서 계속됩니다.</p> + +<p>continue가 checkiandj의 레이블을 가지고 있다면, 프로그램은 checkiandj 문 상단에서 계속될 것입니다.</p> + +<pre class="brush: js notranslate">checkiandj: + while (i < 4) { + console.log(i); + i += 1; + checkj: + while (j > 4) { + console.log(j); + j -= 1; + if ((j % 2) == 0) { + continue checkj; + } + console.log(j + " is odd."); + } + console.log("i = " + i); + console.log("j = " + j); + }</pre> + +<h2 id="for...in_문"><code>for...in</code> 문</h2> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in"><code>for...in</code></a> 문은 객체의 열거 속성을 통해 지정된 변수를 반복합니다. 각각의 고유한 속성에 대해, JavaScript는 지정된 문을 실행합니다. for...in 문은 다음과 같습니다:</p> + +<pre class="syntaxbox notranslate">for (variable in object) { + statements +} +</pre> + +<h3 id="예시_4"><strong>예시</strong></h3> + +<p>다음 함수는 객체와 객체의 이름을 함수의 인수로 취합니다. 그런 다음 모든 객체의 속성을 반복하고 속성 이름과 값을 나열하는 문자열을 반환합니다.</p> + +<pre class="brush: js notranslate">function dump_props(obj, obj_name) { + var result = ""; + for (var i in obj) { + result += obj_name + "." + i + " = " + obj[i] + "<br>"; + } + result += "<hr>"; + return result; +} +</pre> + +<p>속성 make와 model을 가진 객체 car의 경우, 결과는 다음과 같습니다:</p> + +<pre class="brush: js notranslate">car.make = Ford +car.model = Mustang +</pre> + +<h3 id="배열"><strong>배열</strong></h3> + +<p>{{jsxref("배열")}} 요소를 반복하는 방법으로 이를 사용하도록 유도될 수 있지만, <strong>for...in</strong> 문은 숫자 인덱스에 추가하여 사용자 정의 속성의 이름을 반환합니다. 따라서 만약 여러분이 사용자 정의 속성 또는 메서드를 추가하는 등 Array 객체를 수정한다면, 배열 요소 이외에도 사용자 정의 속성을 통해 <strong>for...in</strong> 문을 반복하기 때문에, 배열을 통해 반복할 때 숫자 인덱스와 전통적인 <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for">for</a></code> 루프를 사용하는 것이 좋습니다.</p> + +<h2 id="for...of_문"><code>for...of</code> 문</h2> + +<p><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a></code> 문은 각각의 고유한 특성의 값을 실행할 명령과 함께 사용자 지정 반복 후크를 호출하여, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/iterable">반복 가능한 객체</a>({{jsxref("배열")}}, {{jsxref("Map")}}, {{jsxref("Set")}}, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments">인수</a> 객체 등을 포함)를 통해 반복하는 루프를 만듭니다.</p> + +<pre class="syntaxbox notranslate">for (<em>variable</em> of <em>object</em>) { + <em>statement +</em>}</pre> + +<p>다음 예는 for...of 루프와 <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in" title="en-US/docs/JavaScript/Reference/Statements/for...in">for...in</a></code> 루프의 차이를 보여줍니다. 속성 이름을 통해 for...in이 반복하는 동안, for...of은 속성 값을 통해 반복합니다:</p> + +<pre class="brush:js notranslate">let arr = [3, 5, 7]; +arr.foo = "hello"; + +for (let i in arr) { + console.log(i); // logs "0", "1", "2", "foo" +} + +for (let i of arr) { + console.log(i); // logs "3", "5", "7" +} +</pre> + +<p>{{PreviousNext("Web/JavaScript/Guide/Control_flow_and_error_handling", "Web/JavaScript/Guide/Functions")}}</p> diff --git a/files/ko/web/javascript/guide/modules/index.html b/files/ko/web/javascript/guide/modules/index.html new file mode 100644 index 0000000000..b52283a0fc --- /dev/null +++ b/files/ko/web/javascript/guide/modules/index.html @@ -0,0 +1,414 @@ +--- +title: JavaScript modules +slug: Web/JavaScript/Guide/Modules +translation_of: Web/JavaScript/Guide/Modules +--- +<div>{{jsSidebar("JavaScript Guide")}}{{Previous("Web/JavaScript/Guide/Meta_programming")}}</div> + +<p>이 가이드는 자바스크립트 모듈 구문을 시작하는데 필요한 모든 것을 제공합니다.</p> + +<h2 id="A_background_on_modules">A background on modules</h2> + +<p>자바스크립트 프로그램은 꽤 작게 시작되었습니다. 초기에 사용 된 대부분의 스크립트는 독립적인 작업을 수행하여, 필요한 경우 웹 페이지에 약간의 상호 작용을 제공하므로 일반적으로 큰 스크립트가 필요하지 않았습니다. 몇년 후 자바스크립트는 많은 브라우저에서 실행되고 있는 완전한 애플리케이션을 실행할 수 있을 뿐 아니라, 다른 컨텍스트에서 (예를들면 <a href="/en-US/docs/Glossary/Node.js">Node.js</a>) 자바스크립트를 사용하게 됩니다.</p> + +<p>따라서 최근 몇 년 동안 자바스크립트 프로그램을 필요에 따라 가져올 수 있는, 별도의 모듈로 분할하기 위한 매커니즘을 제공하는 것에 대해 생각하기 시작했습니다. node.js는 오랫동안 이러한 능력을 가지고 있었고, 모듈 사용을 가능하게하는 많은 자바스크립트 라이브러리와 프레임워크가 있습니다. (예를들어 <a href="https://requirejs.org/">RequireJS</a>와 같은 <a href="https://en.wikipedia.org/wiki/CommonJS">CommonJS</a> 와 <a href="https://github.com/amdjs/amdjs-api/blob/master/AMD.md">AMD</a>기반 모듈 시스템, 더 최근에는 <a href="https://webpack.github.io/">Webpack</a>과 <a href="https://babeljs.io/">Babel</a> 같은 모듈 기반 시스템이 있습니다.)</p> + +<p>좋은 소식은 최신 브라우저가 기본적으로 모듈 기능을 지원하기 시작했으며, 이것이 이 기사의 전부입니다. 브라우저는 모듈의 로딩을 최적화 할 수 있기 때문에 라이브러리를 사용하는 것보다 더 효율적이며, 클라이언트 측에서의 추가 처리와 여분의 왕복을 모두 해야하는 것 보다 효율적입니다.</p> + +<h2 id="Browser_support">Browser support</h2> + +<p>네이티브 자바스크립트 모듈은 <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/import">import</a></code>와 <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/export">export</a></code> 문(statement)에 의존적이며, 호환성은 다음과 같습니다.</p> + +<h3 id="import">import</h3> + +<p>{{Compat("javascript.statements.import")}}</p> + +<h3 id="export">export</h3> + +<p>{{Compat("javascript.statements.export")}}</p> + +<h2 id="Introducing_an_example">Introducing an example</h2> + +<p>모듈 사용법을 설명하기 위해 Github에 <a href="https://github.com/mdn/js-examples/tree/master/modules">간단한 예제 모음</a>을 만들었습니다. 이 예제들은 웹 페이지에 {{htmlelement("canvas")}} 요소(element)를 만들고, 캔버스에 다양한 도형을 그리고, 그린것에 대한 정보를 보고하는 간단한 모듈 집합입니다.</p> + +<p>이것들은 매우 사소한 것이지만, 모듈을 명확하게 설명하기 의해 의도적으로 단순하게 유지중입니다.</p> + +<div class="blockIndicator note"> +<p><strong>주의</strong>: 예제를 다운로드하여 로컬에서 실행하려면, 로컬 웹 서버를 통해 예제를 실행해야 합니다.</p> +</div> + +<h2 id="Basic_example_structure">Basic example structure</h2> + +<p>첫 번째 예제(<a href="https://github.com/mdn/js-examples/tree/master/modules/basic-modules">basic-modules</a>)를 보면 다음과 같은 파일 구조가 있습니다.</p> + +<pre class="notranslate">index.html +main.js +modules/ + canvas.js + square.js</pre> + +<div class="blockIndicator note"> +<p><strong>주의</strong>: 이 가이드의 모든 예제는 기본적으로 동일한 구조를 가집니다. 위의 내용에 익숙해지시는게 좋습니다.</p> +</div> + +<p>modules 디렉토리의 두 모듈은 다음과 같습니다.</p> + +<ul> + <li><code>canvas.js</code> — 캔버스 설정과 관련된 기능을 포함합니다. + + <ul> + <li><code>create()</code> — 지정한 ID를 가진 래퍼 {{htmlelement("div")}} 안에, 지정한 <code>width</code> 와 <code>height</code> 를 가진 캔버스를 생성합니다. 지정한 ID(첫 번째 인자)는 지정한 부모 요소(두 번째 인자)안에 추가됩니다. 캔버스의 2D 컨텍스트와 래퍼(wrapper div)의 ID가 들어있는 객체를 반환합니다.</li> + <li><code>createReportList()</code> — 데이터를 출력하는데 사용할 수 있는, 지정한 래퍼 요소(div) 안에 추가 된 정렬되지 않은 리스트(ul)를 만듭니다. 리스트의 ID를 반환합니다.</li> + </ul> + </li> + <li><code>square.js</code> — 다음을 포함합니다. + <ul> + <li><code>name</code> — 문자열 'square'를 담고있는 상수입니다.</li> + <li><code>draw()</code> — 지정된 크기, 위치, 색상을 사용하여 지정된 캔버스에 사각형을 그립니다. 사각형의 크기, 위치, 색상을 포함하는 객체를 반환합니다.</li> + <li><code>reportArea()</code> — 길이가 주어지면 사각형의 넓이를 지정한 보고서 리스트에 작성합니다.</li> + <li><code>reportPerimeter()</code> — 길이가 주어지면 사각형의 둘레를 지정한 보고서 리스트에 작성합니다.</li> + </ul> + </li> +</ul> + +<h2 id="Exporting_module_features">Exporting module features</h2> + +<p>모듈 기능을 사용하려면 먼저 함수를 export 해야 합니다. 이 작업은 <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/export">export</a></code> 문(statement)을 사용하여 수행합니다.</p> + +<p>이를 사용하는 가장 쉬운 방법은 모듈 밖으로 내보내려는 항목 앞에 (export를) 배치하는 것입니다. 예를들면 다음과 같습니다.</p> + +<pre class="brush: js notranslate">export const name = 'square'; + +export function draw(ctx, length, x, y, color) { + ctx.fillStyle = color; + ctx.fillRect(x, y, length, length); + + return { + length: length, + x: x, + y: y, + color: color + }; +}</pre> + +<p>functions, <code>var</code>, <code>let</code>, <code>const</code>, class를 내보낼 수 있지만, 최상위 항목이어야 합니다. 예를들어, 함수 안에서 <code>export</code>를 사용할 수 없습니다.</p> + +<p>여러 항목을 내보내는 더 편리한 방법은 모듈 파일 끝에 하나의 export 문을 사용하는 것입니다. 그 다음에 내보내려는 기능들을 쉼표로 구분하여 나열하고 중괄호로 묶습니다.</p> + +<pre class="brush: js notranslate">export { name, draw, reportArea, reportPerimeter };</pre> + +<h2 id="Importing_features_into_your_script">Importing features into your script</h2> + +<p>모듈에서 일부 기능을 내보낸 후에는, 이를 사용할 수 있도록 우리가 사용할 스크립트로 가져와야 합니다. 가장 간단한 방법은 다음과 같습니다.</p> + +<pre class="brush: js notranslate">import { name, draw, reportArea, reportPerimeter } from './modules/square.js';</pre> + +<p><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/import">import</a></code> 문(statement)을 사용하고, 가져올 목록을 쉼표로 구분하여 나열한 뒤 괄호로 묶습니다. 그 뒤에는 from을 쓰고 모듈 파일의 경로를 작성합니다. (사이트 루트에 연관된 경로로, 우리의 <code>basic-modules</code> 예제는 <code>/js-examples/modules/basic-modules</code> 입니다) <code><a href="https://github.com/mdn/js-examples/blob/master/modules/basic-modules/main.js">main.js</a></code>에서 이러한 코드를 볼 수 있습니다.</p> + +<p>그러나 우리는 경로를 조금 다르게 작성했습니다. 우리는 "현재 위치"를 의미하는 점(.) 구문을 사용하고 있으며, 그 다음에 찾고자하는 파일의 경로를 뒤에 써 줍니다. 이것은 상대적으로 전체 상대 경로를 작성하는 것보다 훨씬 빠르며, URL이 더 짧아 지므로 사이트 계층 구조의 다른 위치로 이동하더라도 이 예제가 계속 작동합니다.</p> + +<p>예를들면,</p> + +<pre class="notranslate"><code>/js-examples/modules/basic-modules/modules/square.js</code></pre> + +<p>이렇게 쓸 수 있습니다.</p> + +<pre class="notranslate"><code>./modules/square.js</code></pre> + +<p><code><a href="https://github.com/mdn/js-examples/blob/master/modules/basic-modules/main.js">main.js</a></code>에서 이러한 코드를 볼 수 있습니다.</p> + +<div class="blockIndicator note"> +<p><strong>주의</strong>: 일부 모듈 시스템에서는 파일 확장명을 생략할 수 있습니다. (예: <code>'/modules/square'</code>). 이것은 네이티브 자바스크립트에서는 작동하지 않습니다. 또한 앞에 슬래시를 포함해야 합니다.</p> +</div> + +<p>우리의 스크립트에 기능을 가져오면 동일한 파일 내에 정의한 것처럼 기능을 사용할 수 있습니다. 다음은 <code>main.js</code> 의 import 행 아래에 있습니다.</p> + +<pre class="brush: js notranslate">let myCanvas = create('myCanvas', document.body, 480, 320); +let reportList = createReportList(myCanvas.id); + +let square1 = draw(myCanvas.ctx, 50, 50, 100, 'blue'); +reportArea(square1.length, reportList); +reportPerimeter(square1.length, reportList); +</pre> + +<h2 id="Applying_the_module_to_your_HTML">Applying the module to your HTML</h2> + +<p>이제 <code>main.js</code> 모듈을 HTML 페이지에 적용하면 됩니다. 이는 몇 가지 주목할만한 차이점을 제외하면 HTML페이지에 일반 스크립트를 적용하는것과 매우 유사합니다.</p> + +<p>이 스크립트를 모듈로 선언하려면 {{htmlelement("script")}} 요소(element)에 <code>type="module"</code> 을 포함시켜야 합니다.</p> + +<pre class="brush: js notranslate"><script type="module" src="main.js"></script></pre> + +<p>기본적으로 모듈 기능을 가져오는 스크립트는 최상위 모듈로 작동합니다. 이를 생략하면 파이어폭스로 예를들면, "SyntaxError: import declarations may only appear at top level of a module"라는 오류를 줍니다.</p> + +<p><code>import</code> 와 <code>export</code> 문(statement)은 모듈 내에서만 사용할 수 있습니다. 정규 스크립트가 아닙니다.</p> + +<div class="blockIndicator note"> +<p><strong>주의</strong>: <code>type="module"</code>을 포함하면 인터널 스크립트에서도 import 모듈을 사용할 수 있습니다. 예: <code><script type="module"> /* 여기에 코드를 작성하세요 */ </script></code>.</p> +</div> + +<h2 id="Other_differences_between_modules_and_standard_scripts">Other differences between modules and standard scripts</h2> + +<ul> + <li>로컬 테스트에서의 주의 사항 — HTML파일을 로컬(예를들어 <code>file://</code> URL)에서 로드하려고 하면, 자바스크립트 모듈 보안 요구 사항으로 인해 CORS오류가 발생합니다. 서버를 통해 테스트 해야 합니다.</li> + <li>표준 스크립트와 달리 모듈 내부에서 정의된 스크립트 섹션과는 다르게 동작할 수 있습니다. 이는 모듈이 자동적으로 <a href="/ko/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>를 사용하기 때문입니다.</li> + <li>모듈 스크립트를 불러올 때 <code>defer</code> 속성(<a href="/ko/docs/Web/HTML/Element/script#Attributes"><code><script></code> attributes</a>)를 사용할 필요가 없습니다. 모듈은 자동으로 defer됩니다.</li> + <li>마지막으로 모듈 기능을 단일 스크립트의 스코프로 가져왔음을 분명히 해야 합니다. — 전역 스코프에서는 사용할 수 없습니다. 따라서 import한 스크립트에서 가져온 기능에만 접근할 수 있습니다. 예를들어 자바스크립트 콘솔에서 접근할 수 없습니다. DevTools에 구문 오류가 표시되지만, 사용하려고 하는 디버깅 기술 중 일부는 사용할 수 없습니다.</li> +</ul> + +<h2 id="Default_exports_versus_named_exports">Default exports versus named exports</h2> + +<p>지금까지 우리가 export 한 기능은 <strong>named exports</strong> 로 구성되었습니다. 각 항목(function, <code>const</code> 등)은 export 할 때 이름으로 참조되었으며, import 할 때에 이 이름을 참조하여 사용합니다.</p> + +<p>그 외에도 <strong>default export</strong> 라고 부르는 export 도 있습니다. 이것은 모듈이 제공하는 기본 기능을 쉽게 만들 수 있도록 설계되었습니다. 또한 자바스크립트 모듈을 기존의 CommonJS 와 AMD 모듈 시스템과 함께 사용(interpolate)하는데도 도움이 됩니다. (Jason Orendorff에 의해 작성된 <a href="https://hacks.mozilla.org/2015/08/es6-in-depth-modules/">ES6 In Depth: Modules</a> 에 설명되어있습니다. "Default exports"를 검색해보세요)</p> + +<p>예제를 가지고 어떻게 작동하는지 살펴보겠습니다. 예제 중 basic-modules 프로젝트의 <code>square.js</code> 파일에서 임의의 색상, 크기, 위치로 갖는 사각형을 만드는 <code>randomSquare()</code> 라는 함수를 찾을 수 있습니다. 이것을 기본값으로 export하려고 하므로, 파일의 맨 아래에 다음과 같이 씁니다.</p> + +<pre class="brush: js notranslate">export default randomSquare;</pre> + +<p>중괄호가 없음에 주의하세요.</p> + +<p>대신 함수 앞에 <code>export default</code> 를 추가하고, 다음과 같이 익명함수로 선언할 수 있습니다.</p> + +<pre class="brush: js notranslate">export default function(ctx) { + ... +}</pre> + +<p><code>main.js</code> 파일에서 다음 코드처럼 사용하면, default function이 import 됩니다.</p> + +<pre class="brush: js notranslate">import randomSquare from './modules/square.js';</pre> + +<p>다시 말하지만, 중괄호가 없다는 점에 유의하세요. 하나의 모듈은 하나의 default export만 허용하기 때문에 우리는 <code>randomSquare</code> 가 해당 모듈임을 알 수 있습니다. 위의 코드는 아래의 코드를 단축하여 사용한 것입니다.</p> + +<pre class="brush: js notranslate">import {default as randomSquare} from './modules/square.js';</pre> + +<div class="blockIndicator note"> +<p><strong>주의</strong>: export한 항목의 이름을 바꾸는 구문은 {{anch("Renaming imports and exports")}} 섹션에서 설명합니다.</p> +</div> + +<h2 id="Avoiding_naming_conflicts">Avoiding naming conflicts</h2> + +<p>지금까지 우리의 캔버스 도형 그리기 모듈은 제대로 작동하는 것 같습니다. 원이나 삼각형처럼 다른 도형을 그리는 모듈을 추가하려고 하면 어떻게 될까요? 이 도형(shape)에는 아마도 <code>draw()</code>, <code>reportArea()</code> 등과 같은 관련 함수가 있을 것입니다. 동일한 이름의 여러 함수를 동일한 최상위 모듈로 가져오려고 하면, 충돌과 에러가 발생합니다.</p> + +<p>다행스럽게도 이 문제를 해결할 수 있는 여러가지 방법이 있습니다. 다음 섹션에서 이 내용을 살펴보겠습니다.</p> + +<h2 id="Renaming_imports_and_exports">Renaming imports and exports</h2> + +<p><code>import</code> 와 <code>export</code> 문(statement)의 중괄호 안에 <code>as</code> 키워드를 새 함수의 이름으로 함께 사용하여, 최상위 모듈 내부의 함수들을 식별 가능한 이름으로 변경할 수 있습니다.</p> + +<p>예를들어 다음 두 가지 방법은 약간의 차이가 있지만, 두 방법 모두 동일한 작업을 수행하고 있습니다.</p> + +<pre class="brush: js notranslate">// inside module.js +export { + function1 as newFunctionName, + function2 as anotherNewFunctionName +}; + +// inside main.js +import { newFunctionName, anotherNewFunctionName } from './modules/module.js';</pre> + +<pre class="brush: js notranslate">// inside module.js +export { function1, function2 }; + +// inside main.js +import { function1 as newFunctionName, + function2 as anotherNewFunctionName } from './modules/module.js';</pre> + +<p>실제 사례를 살펴보겠습니다. <a href="https://github.com/mdn/js-examples/tree/master/modules/renaming">renaming</a> 디렉토리에서 원과 삼각형을 그리고 보고하기 위해 <code>circle.js</code> 와 <code>triangle.js</code> 모듈을 추가한다는 점만 제외하면, 앞의 예와 동일한 모듈 시스템을 볼 수 있습니다.</p> + +<p>이 모듈듈 각각에는 내부적으로 동일한 이름의 기능이 있습니다. 따라서 각각 하단에 동일한 export 문(statement)이 있습니다.</p> + +<pre class="brush: js notranslate">export { name, draw, reportArea, reportPerimeter };</pre> + +<p>이것들을 <code>main.js</code>에 가져올 때 우리는 다음과 같이 시도할 수 있습니다.</p> + +<pre class="brush: js notranslate">import { name, draw, reportArea, reportPerimeter } from './modules/square.js'; +import { name, draw, reportArea, reportPerimeter } from './modules/circle.js'; +import { name, draw, reportArea, reportPerimeter } from './modules/triangle.js';</pre> + +<p>위와같이 적으면 브라우저에서 "SyntaxError: redeclaration of import name"과 같은 오류가 발생합니다. (Firefox).</p> + +<p>대신 import가 고유하도록(식별 가능하도록) 이름을 변경해야 합니다.</p> + +<pre class="brush: js notranslate">import { name as squareName, + draw as drawSquare, + reportArea as reportSquareArea, + reportPerimeter as reportSquarePerimeter } from './modules/square.js'; + +import { name as circleName, + draw as drawCircle, + reportArea as reportCircleArea, + reportPerimeter as reportCirclePerimeter } from './modules/circle.js'; + +import { name as triangleName, + draw as drawTriangle, + reportArea as reportTriangleArea, + reportPerimeter as reportTrianglePerimeter } from './modules/triangle.js';</pre> + +<p>다음과 같이 import하는 파일 대신 모듈 파일에서 문제를 해결할 수도 있습니다.</p> + +<pre class="brush: js notranslate">// in square.js +export { name as squareName, + draw as drawSquare, + reportArea as reportSquareArea, + reportPerimeter as reportSquarePerimeter };</pre> + +<pre class="brush: js notranslate">// in main.js +import { squareName, drawSquare, reportSquareArea, reportSquarePerimeter } from './modules/square.js';</pre> + +<p>그리고 이것은 똑같이 작동 할 것입니다. 사용하는 스타일은 개인의 취향이지만, 모듈 코드를 그대로 두고 import 를 변경하는 것이 더 합리적입니다. 특히 제어 권한이 없는 써드 파티 모듈에서 import를 사용하는 경우에 특히 유용합니다.</p> + +<h2 id="Creating_a_module_object">Creating a module object</h2> + +<p>위의 방법은 정상적으로 작동하지만, 다소 지저분하고 길어질 수 있습니다. 보다 나은 해결책은 각 모듈의 기능을 모듈 객체 내부로 가져오는 것입니다. 다음과 같은 구문을 사용합니다.</p> + +<pre class="brush: js notranslate">import * as Module from './modules/module.js';</pre> + +<p>이 모듈은 <code>module.js</code> 내에서 사용할 수 있는 모든 export를 가져옵니다. 그리고 그것들을 객체 <code>Module</code> 의 멤버로 만들고 우리 임의의 효과적인 네임스페이스를 제공합니다.</p> + +<pre class="brush: js notranslate">Module.function1() +Module.function2() +etc.</pre> + +<p>다시 한 번 실제 사례를 살펴보겠습니다. <a href="https://github.com/mdn/js-examples/tree/master/modules/module-objects">module-objects</a> 디렉토리로 가면 같은 예제를 볼 수 있지만, 새로운 구문을 이용하기 위해 다시 작성합니다. 모듈에서 export는 모두 다음과 같은 간단한 형식으로 이루어집니다.</p> + +<pre class="brush: js notranslate">export { name, draw, reportArea, reportPerimeter };</pre> + +<p>반면에 import는 다음과 같습니다.</p> + +<pre class="brush: js notranslate">import * as Canvas from './modules/canvas.js'; + +import * as Square from './modules/square.js'; +import * as Circle from './modules/circle.js'; +import * as Triangle from './modules/triangle.js';</pre> + +<p>각각의 경우에, 지정한 객체 이름 아래에 있는 모듈의 import에 접근할 수 있습니다. 다음은 그 예시입니다.</p> + +<pre class="brush: js notranslate">let square1 = Square.draw(myCanvas.ctx, 50, 50, 100, 'blue'); +Square.reportArea(square1.length, reportList); +Square.reportPerimeter(square1.length, reportList);</pre> + +<p>따라서 이제는 이전과 똑같은 코드를 작성할 수 있습니다. (필요한 경우 객체 이름을 포함해야 합니다) import는 보다 깔끔해졌습니다.</p> + +<h2 id="Modules_and_classes">Modules and classes</h2> + +<p>이전에 암시 했듯이 class를 export하거나 import 할 수도 있습니다. 이것은 코드에서 충돌을 피하기 위한 또 다른 옵션으로, 모듈 코드가 이미 객체 지향 스타일로 작성된 경우에 특히 유용합니다.</p> + +<p>우리의 <a href="https://github.com/mdn/js-examples/tree/master/modules/classes">classes</a> 디렉토리에서 ES 클래스로 다시 작성된 도형 그리기 모듈의 예를 볼 수 있습니다. 예를들어 <code><a href="https://github.com/mdn/js-examples/blob/master/modules/classes/modules/square.js">square.js</a></code> 파일에는 모든 기능이 단일 클래스에 포함되어 있습니다.</p> + +<pre class="brush: js notranslate">class Square { + constructor(ctx, listId, length, x, y, color) { + ... + } + + draw() { + ... + } + + ... +}</pre> + +<p>우리는 다음과 같이 export 합니다.</p> + +<pre class="brush: js notranslate">export { Square };</pre> + +<p><code><a href="https://github.com/mdn/js-examples/blob/master/modules/classes/main.js">main.js</a></code> 에서 우리는 다음과 같이 import 합니다.</p> + +<pre class="brush: js notranslate">import { Square } from './modules/square.js';</pre> + +<p>그런다음 클래스를 이용하여 사각형을 그립니다.</p> + +<pre class="brush: js notranslate">let square1 = new Square(myCanvas.ctx, myCanvas.listId, 50, 50, 100, 'blue'); +square1.draw(); +square1.reportArea(); +square1.reportPerimeter();</pre> + +<h2 id="Aggregating_modules">Aggregating modules</h2> + +<p>모듈을 모아야 할 때가 있을 것입니다. 여러 서브 모듈을 하나의 부모 모듈로 결합하여 여러 단계의 종속성을 가질 수 있습니다. 상위 모듈에서 다음 양식의 export 구문을 사용하할 수 있습니다.</p> + +<pre class="brush: js notranslate">export * from 'x.js' +export { name } from 'x.js'</pre> + +<div class="blockIndicator note"> +<p><strong>주의</strong>: 이것은 실제로 import 의 줄임말이고, 그 뒤에 export가 옵니다. 예를들면, "나는 모듈 <code>x.js</code>를 가져온 다음, 일부 또는 전부를 export 하겠다" 라는 뜻입니다.</p> +</div> + +<p>예를들어 <a href="https://github.com/mdn/js-examples/tree/master/modules/module-aggregation">module-aggregation</a> 디렉토리를 참조하겠습니다. 이 예제에서는 이전 클래스 예제를 기반으로 <code>circle.js</code>, <code>square.js</code>, <code>triangle.js</code> 의 모든 기능을 함께 모으는 <code>shapes.js</code>라는 추가 모듈이 있습니다. 또한 우리는 <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">shapes</span></font> <code>모듈</code> 디렉토리 안에 있는 서브 디렉토리 내에서 서브 모듈을 이동 시켰습니다. 이제 모듈 구조는 다음과 같습니다.</p> + +<pre class="notranslate">modules/ + canvas.js + shapes.js + shapes/ + circle.js + square.js + triangle.js</pre> + +<p>각 하위 모듈에서 export 형태는 같습니다. 예)</p> + +<pre class="brush: js notranslate">export { Square };</pre> + +<p>다음은 집합(aggregation) 부분입니다. <code><a href="https://github.com/mdn/js-examples/blob/master/modules/module-aggregation/modules/shapes.js">shapes.js</a></code> 안에는 다음과 같은 내용이 포함되어 있습니다.</p> + +<pre class="brush: js notranslate">export { Square } from './shapes/square.js'; +export { Triangle } from './shapes/triangle.js'; +export { Circle } from './shapes/circle.js';</pre> + +<p>이 모듈은 각각의 서브 모듈의 export를 가져와서 <code>shapes.js</code> 모듈에서 효과적으로 사용할 수 있도록 합니다.</p> + +<div class="blockIndicator note"> +<p><strong>주의</strong>: <code>shapes.js</code> 에서 참조되는 export는 기본적으로 파일을 통해 리다이렉트 되고 실제로는 존재하지 않으므로, 같은 파일 내에 유용한 코드를 쓸 수 없습니다.</p> +</div> + +<p>이제 <code>main.js</code> 파일에서 우리는 세 개의 모듈 클래스를 모두 대체할 수 있습니다.</p> + +<pre class="brush: js notranslate">import { Square } from './modules/square.js'; +import { Circle } from './modules/circle.js'; +import { Triangle } from './modules/triangle.js';</pre> + +<p>다음과 같은 한 줄로 작성할 수 있습니다.</p> + +<pre class="brush: js notranslate">import { Square, Circle, Triangle } from '/js-examples/modules/module-aggregation/modules/shapes.js';</pre> + +<h2 id="Dynamic_module_loading">Dynamic module loading</h2> + +<p>브라우저에서 사용할 수 있는 자바스크립트 모듈 기능의 최신 부분은 동적 모듈 로딩 입니다. 이렇게 하면 모든 것을 최상위에서 불러오지 않고, 필요할 때만 모듈을 동적으로 불러올 수 있습니다. 이것은 몇 가지 분명한 성능 이점이 있습니다. 계속 읽어보고 어떻게 작동하는지 살펴봅시다.</p> + +<p>이 새로운 기능을 통해 <code>import()</code> 를 함수로 호출하여 모듈 경로를 매개 변수(parameter)로 전달할 수 있습니다. 모듈 객체({{anch("Creating a module object")}} 참조)를 사용하여 <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">promise</a>를 반환하면 해당 객체의 export에 접근할 수 있습니다. </p> + +<pre class="brush: js notranslate">import('/modules/myModule.js') + .then((module) => { + // Do something with the module. + });</pre> + +<p>예제를 보겠습니다. In the <a href="https://github.com/mdn/js-examples/tree/master/modules/dynamic-module-imports">dynamic-module-imports</a> 디렉토리에는 classes 예제를 기반으로 한 또 다른 예제가 있습니다. 이번에는 예제가 로딩될 때 캔버스에 아무것도 그리지 않습니다. 대신 우리는 세 개의 버튼("Circle", "Square", "Triangle")이 포함되어 있습니다. 이 버튼을 누르면 필요한 모듈을 동적으로 불러온 다음, 이를 사용하여 연관된 도형을 그립니다.</p> + +<p>이 예제에서 우리는 <a href="https://github.com/mdn/js-examples/blob/master/modules/dynamic-module-imports/index.html">index.html</a> 파일과 <a href="https://github.com/mdn/js-examples/blob/master/modules/dynamic-module-imports/main.js">main.js</a> 파일만 변경했습니다. 모듈 export는 이전과 동일하게 유지됩니다.</p> + +<p><code>main.js</code> 에서 <code><a href="/en-US/docs/Web/API/Document/querySelector">document.querySelector()</a></code> 를 사용하여 각 버튼에 대한 참조를 가져왔습니다. 예를들면 다음과 같습니다.</p> + +<pre class="brush: js notranslate">let squareBtn = document.querySelector('.square');</pre> + +<p>그런 다음 각 버튼에 이벤트 리스너를 연결하여 해당 모듈을 누르면, 동적으로 로드되어 도형을 그리는데 사용됩니다.</p> + +<pre class="brush: js notranslate">squareBtn.addEventListener('click', () => { + import('/js-examples/modules/dynamic-module-imports/modules/square.js').then((Module) => { + let square1 = new Module.Square(myCanvas.ctx, myCanvas.listId, 50, 50, 100, 'blue'); + square1.draw(); + square1.reportArea(); + square1.reportPerimeter(); + }) +});</pre> + +<p>Note that, promise fulfillment 가 모듈 객체를 반환하기 때문에 클래스는 객체의 하위 기능으로 만들어집니다. 따라서 이제 <code>Module</code> 을 사용하여 생성자(contructor)에 접근해야 합니다. 예를들어 <code>Module.Square( ... )</code> 와 같이 앞에 <code>Module</code>이 붙습니다.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="https://developers.google.com/web/fundamentals/primers/modules#mjs">Using JavaScript modules on the web</a>, by Addy Osmani and Mathias Bynens</li> + <li><a href="https://hacks.mozilla.org/2018/03/es-modules-a-cartoon-deep-dive/">ES modules: A cartoon deep-dive</a>, Hacks blog post by Lin Clark</li> + <li><a href="https://hacks.mozilla.org/2015/08/es6-in-depth-modules/">ES6 in Depth: Modules</a>, Hacks blog post by Jason Orendorff</li> + <li>Axel Rauschmayer's book <a href="http://exploringjs.com/es6/ch_modules.html">Exploring JS: Modules</a></li> +</ul> + +<p>{{Previous("Web/JavaScript/Guide/Meta_programming")}}</p> diff --git a/files/ko/web/javascript/guide/numbers_and_dates/index.html b/files/ko/web/javascript/guide/numbers_and_dates/index.html new file mode 100644 index 0000000000..6a45e1ef7f --- /dev/null +++ b/files/ko/web/javascript/guide/numbers_and_dates/index.html @@ -0,0 +1,384 @@ +--- +title: 숫자와 날짜 +slug: Web/JavaScript/Guide/Numbers_and_dates +tags: + - JavaScript +translation_of: Web/JavaScript/Guide/Numbers_and_dates +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Expressions_and_Operators", "Web/JavaScript/Guide/Text_formatting")}}</div> + +<p><span class="seoSummary">이 장에서는 JavaScript에서 숫자와 날짜를 사용하기 위한 개념과 객체, 함수에 대해 소개합니다.</span> 그리고 숫자를 10진법, 2진법, 16진법 등의 다양한 형태로 표현하는 방법과 더불어 {{jsxref("Math")}} 객체를 사용해 다양한 수학 연산을 수행하는 방법을 알 수 있습니다.</p> + +<h2 id="숫자">숫자</h2> + +<p>JavaScript에서 모든 숫자는 <a class="external external-icon" href="https://en.wikipedia.org/wiki/Double-precision_floating-point_format">double-precision 64-bit binary format IEEE 754</a> (즉, ±2<sup>−1022</sup> 과 ±2<sup>+1023</sup> 또는 대략 ±10<sup>−308</sup> to ±10<sup>+308</sup> 사이의 숫자이며 53bits의 수치정밀도 )로 구현되어 있습니다. ± 2<sup>53</sup> - 1까지의 정수 값을 정확하게 나타낼 수 있습니다.</p> + +<p>여기 부동 소수점 숫자를 나타낼 수 있으며, 숫자 형식은 세 개의 상징적인 값: <code>+</code>{{jsxref("Infinity")}}, <code>-</code>{{jsxref("Infinity")}}, and {{jsxref("NaN")}} (숫자가 아닌 값)을 갖습니다.</p> + +<p>JavaScript에 최근 추가 된 것은 {{jsxref ( "BigInt")}}로, 매우 큰 정수를 나타낼 수 있습니다. <code>BigInt</code>를사용할땐 다음을 주의해야 합니다. 예를 들면, <code>BigInt</code>와 {{jsxref ( "Number")}} 값을 같은 연산으로 혼합하고 일치시킬 수는 없으며 {{jsxref ( "Math")}} 객체를 <code>BigInt</code>값과 함께 사용할 수 없습니다.</p> + +<p>JavaScript에서 다른 기본형과 문맥에 대한 내용은 <a href="/en-US/docs/Web/JavaScript/Data_structures">JavaScript data types and structures</a>를 참조하세요.</p> + +<p>여러분은 숫자 리터럴의 네 가지 유형을 사용할 수 있습니다: 10진수, 2진수, 8진수, 16진수</p> + +<h3 id="10진수">10진수</h3> + +<pre class="brush: js notranslate">1234567890 +42 + +// 앞에 0이 붙은 숫자를 조심하세요: + +0888 // 10진수 888로 해석됩니다. +0777 // non-strict mode에서 10진수 511로 해석됩니다. +</pre> + +<p>10진수 리터럴도 영(<code>0</code>)으로 시작될 수 있다는 점에 유의하세요. 그러나 만약 영<code>0</code> 다음 숫자가 8보다 작으면, 그 숫자는 8진법으로 해석됩니다.</p> + +<h3 id="2진수">2진수</h3> + +<p>2진수 구문은 앞에 오는 0과 소문자 또는 대문자 라틴 문자 "B"(0B 또는 0b)를 사용합니다. 0b 다음의 숫자가 0 또는 1이 아니면 다음의 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError">SyntaxError</a>가 발생합니다. "0b 이후에 누락 된 2 진수"("Missing binary digits after 0b")입니다.</p> + +<pre class="brush: js notranslate">var FLT_SIGNBIT = 0b10000000000000000000000000000000; // 2147483648 +var FLT_EXPONENT = 0b01111111100000000000000000000000; // 2139095040 +var FLT_MANTISSA = 0B00000000011111111111111111111111; // 8388607</pre> + +<h3 id="8진수">8진수</h3> + +<p>8 진수 구문은 앞에 0을 사용합니다. <code>0</code> 이후의 숫자가 0에서 7까지 범위 밖에 있는 경우, 숫자는 10진수로 해석됩니다.</p> + +<pre class="brush: js notranslate">var n = 0755; // 493 +var m = 0644; // 420 +</pre> + +<p>ECMAScript 5의 Strict 모드는 8 진수 구문을 금지합니다. 8 진수 구문은 ECMAScript 5의 일부가 아니지만, <code>0644 === 420</code> 및 <code>"\ 045"=== "%"</code>의 8 진수에 접두사를 붙이면 모든 브라우저에서 지원됩니다. ECMAScript 2015에서는 접두어가 <code>0o</code>인 경우 8 진수가 지원됩니다 (예 :</p> + +<pre class="notranslate"><code>var a = 0o10; // ES2015: 8</code></pre> + +<h3 id="16진수">16진수</h3> + +<p>16진수 구문은 앞에 0 다음에 소문자나 대문자 라틴어 문자 "X"(<code>0x</code> 또는 <code>0X</code>)를 사용합니다. 0X 이후 숫자가 범위(0123456789ABCDEF) 밖에 있는 경우, 다음 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError">SyntaxError</a>가 발생합니다: "식별자는 숫자 리터럴 후 즉시 시작됩니다".</p> + +<pre class="brush: js notranslate">0xFFFFFFFFFFFFFFFFF // 295147905179352830000 +0x123456789ABCDEF // 81985529216486900 +0XA // 10 +</pre> + +<h3 id="지수_계산">지수 계산</h3> + +<pre class="notranslate"><code>1E3 // 1000 +2e6 // 2000000 +0.1e2 // 10</code> +</pre> + +<h2 id="Number_객체"><code>Number</code> 객체</h2> + +<p>{{jsxref("Number")}} 내장객체는 최대값, not-a-number, 무한대와 같은 숫자 상수를 위한 속성들이 있습니다. 여러분은 이러한 속성의 값을 변경 할 수 없고 다음과 같이 사용합니다:</p> + +<pre class="brush: js notranslate">var biggestNum = Number.MAX_VALUE; +var smallestNum = Number.MIN_VALUE; +var infiniteNum = Number.POSITIVE_INFINITY; +var negInfiniteNum = Number.NEGATIVE_INFINITY; +var notANum = Number.NaN; +</pre> + +<p>여러분은 직접 생성한 <code>Number</code> 객체의 속성이 아닌, 위와같이 항상 미리 정의된 <code>Number</code> 객체의 속성을 참조해야합니다.</p> + +<p>다음 표에서는 <code>Number</code> 객체의 속성이 요약되어 있습니다.</p> + +<table class="standard-table"> + <caption><code>Number</code> 속성들</caption> + <thead> + <tr> + <th scope="col">특성</th> + <th scope="col">묘사</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{jsxref("Number.MAX_VALUE")}}</td> + <td>표현가능한 가장 큰 수 (<code>±1.7976931348623157e+308</code>)</td> + </tr> + <tr> + <td>{{jsxref("Number.MIN_VALUE")}}</td> + <td>표현가능한 가장 작은 수(<code>±5e-324</code>)</td> + </tr> + <tr> + <td>{{jsxref("Number.NaN")}}</td> + <td>"숫자가 아닌" 특수값</td> + </tr> + <tr> + <td>{{jsxref("Number.NEGATIVE_INFINITY")}}</td> + <td>음의 무한대값; 오버 플로로 반환됨.</td> + </tr> + <tr> + <td>{{jsxref("Number.POSITIVE_INFINITY")}}</td> + <td>양의 무한대 값; 오버 플로로 반환됨.</td> + </tr> + <tr> + <td>{{jsxref("Number.EPSILON")}}</td> + <td>표현가능한 매우 작은 값{{jsxref("Number")}}.(<code>2.220446049250313e-16</code>)</td> + </tr> + <tr> + <td>{{jsxref("Number.MIN_SAFE_INTEGER")}}</td> + <td>자바스크립트에서 안전한 최소의 정수.(−2<sup>53</sup> + 1, or <code>−9007199254740991</code>)</td> + </tr> + <tr> + <td>{{jsxref("Number.MAX_SAFE_INTEGER")}}</td> + <td>자바스크립트에서 안전한 최대의 정수.(+2<sup>53</sup> − 1, or <code>+9007199254740991</code>)</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption><code>Number</code> 메소드들</caption> + <thead> + <tr> + <th>방법</th> + <th>묘사</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{jsxref("Number.parseFloat()")}}</td> + <td> + <p>문자열 인수를 파싱하고 부동 소수점 숫자를 반환합니다. 전역 {{jsxref("parseFloat", "parseFloat()")}} 함수와 동일합니다.</p> + </td> + </tr> + <tr> + <td>{{jsxref("Number.parseInt()")}}</td> + <td>문자열 라인 인수를 파싱해, 지정된 기수 또는 밑줄의 정수를 돌려줍니다. 전역 {{jsxref("parseInt", "parseInt()")}}함수와 동일합니다.</td> + </tr> + <tr> + <td>{{jsxref("Number.isFinite()")}}</td> + <td>전달된 값이 유한한 수인지 판정합니다.</td> + </tr> + <tr> + <td>{{jsxref("Number.isInteger()")}}</td> + <td>전달된 값이 정수인지 판정합니다.</td> + </tr> + <tr> + <td>{{jsxref("Number.isNaN()")}}</td> + <td>이 전달된 값 {{jsxref("Global_Objects/NaN", "Not-a-Number")}}여부를 확인합니다. 원본 글로벌 {{jsxref("Global_Objects/isNaN", "(isNaN)")}}의 더욱 강력한 버전입니다.</td> + </tr> + <tr> + <td>{{jsxref("Number.isSafeInteger()")}}</td> + <td>제공된 값이 안전한 정수인지 여부를 확인합니다.</td> + </tr> + </tbody> +</table> + +<p><code>Number</code> 프로토 타입은 다양한 형식의 <code>Number</code> 객체에서 정보를 검색하는 메소드를 제공합니다. 다음 표는 <code>Number.prototype</code>의 메소드를 요약 한 것입니다.</p> + +<table class="standard-table"> + <caption><code>Number.prototype</code>의 방법</caption> + <thead> + <tr> + <th scope="col">방법</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{jsxref("Number.toExponential", "toExponential()")}}</td> + <td>지수표기법 안에서 번호를 나타내는 문자열을 반환합니다.</td> + </tr> + <tr> + <td>{{jsxref("Number.toFixed", "toFixed()")}}</td> + <td>문자열 고정 소수 점 표기법의 수를 나타내는 문자열을 반환합니다.</td> + </tr> + <tr> + <td>{{jsxref("Number.toPrecision", "toPrecision()")}}</td> + <td>지정된 정밀에 고정 소수 점 표기법의 수를 나타내는 문자열을 반환합니다.</td> + </tr> + </tbody> +</table> + +<h2 id="Math_객체"><code>Math</code> 객체</h2> + +<p>내장 {{jsxref ( "Math")}} 객체는 수학 상수 및 함수에 대한 속성 및 메서드를 포함합니다. 예를 들어, <code>Math</code> 객체의 <code>PI</code> 속성에는 pi (3.141 ...) 값이 있습니다.이 값은 응용 프로그램에서 다음과 같이 사용합니다.</p> + +<pre class="brush: js notranslate">Math.PI +</pre> + +<p>마찬가지로 표준 수학 함수도 <code>Math</code>의 함수입니다. 여기에는 삼각 함수, 로그 함수, 지수 함수 및 기타 함수가 포함됩니다. 예를 들어 삼각 함수 sine을 사용하려면 다음과 같이 작성합니다.</p> + +<pre class="brush: js notranslate">Math.sin(1.56) +</pre> + +<p><code>Math</code>의 모든 삼각 함수에는 라디안으로 매게변수를 입력해야 합니다.</p> + +<p>다음 표에서는 <code>Math</code> 개체의 방법을 요약하였습니다.</p> + +<table class="standard-table"> + <caption><code>Math</code>의 메소드들</caption> + <thead> + <tr> + <th scope="col">방법</th> + <th scope="col">묘사</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{jsxref("Math.abs", "abs()")}}</td> + <td>절대 값</td> + </tr> + <tr> + <td>{{jsxref("Math.sin", "sin()")}}, {{jsxref("Math.cos", "cos()")}}, {{jsxref("Math.tan", "tan()")}}</td> + <td>표준 삼각 함수; 라디안에서의 인수</td> + </tr> + <tr> + <td>{{jsxref("Math.asin", "asin()")}}, {{jsxref("Math.acos", "acos()")}}, {{jsxref("Math.atan", "atan()")}}, {{jsxref("Math.atan2", "atan2()")}}</td> + <td>역삼각 함수; 라디안에 반환 값</td> + </tr> + <tr> + <td>{{jsxref("Math.sinh", "sinh()")}}, {{jsxref("Math.cosh", "cosh()")}}, {{jsxref("Math.tanh", "tanh()")}}</td> + <td>쌍곡삼각함수; 라디안에 반환 값.</td> + </tr> + <tr> + <td>{{jsxref("Math.asinh", "asinh()")}}, {{jsxref("Math.acosh", "acosh()")}}, {{jsxref("Math.atanh", "atanh()")}}</td> + <td>역쌍곡삼각함수; 라디안에 반환 값.</td> + </tr> + <tr> + <td> + <p>{{jsxref("Math.pow", "pow()")}}, {{jsxref("Math.exp", "exp()")}}, {{jsxref("Math.expm1", "expm1()")}}, {{jsxref("Math.log10", "log10()")}}, {{jsxref("Math.log1p", "log1p()")}}, {{jsxref("Math.log2", "log2()")}}</p> + </td> + <td>지수와 로그 기능.</td> + </tr> + <tr> + <td>{{jsxref("Math.floor", "floor()")}}, {{jsxref("Math.ceil", "ceil()")}}</td> + <td> 가장큰/가장작은 정수 보다 적은/많은 또는 그와 동등한 원칙으로 반환해라.</td> + </tr> + <tr> + <td>{{jsxref("Math.min", "min()")}}, {{jsxref("Math.max", "max()")}}</td> + <td>더적거나 더많은 쉼표의 (각각) 숫자 인수의 나뉜목록으로 반환해라.</td> + </tr> + <tr> + <td>{{jsxref("Math.random", "random()")}}</td> + <td>0과 1사이의 난수를 반환해라.</td> + </tr> + <tr> + <td>{{jsxref("Math.round", "round()")}}, {{jsxref("Math.fround", "fround()")}}, {{jsxref("Math.trunc", "trunc()")}},</td> + <td>반올림과 절단 기능들.</td> + </tr> + <tr> + <td>{{jsxref("Math.sqrt", "sqrt()")}}, {{jsxref("Math.cbrt", "cbrt()")}}, {{jsxref("Math.hypot", "hypot()")}}</td> + <td>제곱 근, 세 제곱 근, 평방 인수의 합의 제곱 근.</td> + </tr> + <tr> + <td>{{jsxref("Math.sign", "sign()")}}</td> + <td>그 수가 양수인지 음수인지 0인지를 가르키는 숫자의 표시.</td> + </tr> + <tr> + <td>{{jsxref("Math.clz32", "clz32()")}},<br> + {{jsxref("Math.imul", "imul()")}}</td> + <td>32비트 이진 표시의 주요 제로 비트 수.<br> + 그 두 인수의 C-like 32비트 곱셈의 결과.</td> + </tr> + </tbody> +</table> + +<p>다른 많은 객체와 달리 자신의 <code>Math</code> 개체를 만들필요가 없습니다. 언제든 내장 된 <code>Math</code> 객체 바로 사용할 수 있습니다.</p> + +<h2 id="Date_객체"><code><font face="Consolas, Monaco, Andale Mono, monospace">Date</font></code><font face="Consolas, Monaco, Andale Mono, monospace"> 객체</font></h2> + +<p>자바스크립트에는 날짜 데이터 타입이 없습니다. 그러나, {{jsxref ( "Date")}} 객체와 그 메소드를 사용하여 응용 프로그램에서 날짜와 시간을 처리 할 수 있습니다. <code>Date</code> 객체에는 날짜 설정, 가져 오기 및 조작을위한 많은 메소드가 있습니다. 속성(properties)이 없습니다.</p> + +<p>자바스크립트는 자바와 비슷하게 날짜를 처리합니다. 두 언어에는 동일한 날짜 메소드가 많으며 두 언어 모두 1970 년 1 월 1 일 00:00:00 이후의 밀리 초 수로 날짜를 저장합니다. 유닉스 타임 스탬프는 1970 년 1 월 1 일 00:00:00 이후의 초 수입니다.</p> + +<p>Date 개체 범위는 UTC 1970 년 1 월 1 일을 기준으로 -100,000,000 일에서 100,000,000 일입니다.</p> + +<p>Date 객체를 만들려면 :</p> + +<pre class="brush: js notranslate">var dateObjectName = new Date([parameters]); +</pre> + +<p>여기서 <code>dateObjectName</code>은 만들려는 <code>Date</code> 객체의 이름입니다. 새로운 객체 또는 기존 객체의 속성 일 수 있습니다.</p> + +<p><code>new</code> 키워드없이 <code>Date</code>를 호출하면 현재 날짜와 시간을 나타내는 문자열이 반환됩니다.</p> + +<p>앞 구문에서 <code>parameters</code>는 아래 규칙을 따릅니다.</p> + +<ul> + <li>아무것도없을때: 오늘의 날짜와 시간을 만듭니다. 예를 들어, <code>today = new Date();</code>.</li> + <li>날짜를 나타내는 문자열의 형식: "Month day, year hours:minutes:seconds."예를 들어, <code>var Xmas95 = new Date("December 25, 1995 13:30:00")</code>.만약 당신이 시간, 분, 또는 초를 빠뜨린다면, 값은 0이 됩니다.</li> + <li>정수 값의 연도, 월, 날의 집합입니다. 예를 들어, <code>var Xmas95 = new Date(1995, 11, 25)</code>.</li> + <li>연도, 월, 일, 시, 분,초 동안 정수 값의 집합입니다.. 예를 들어, <code>var Xmas95 = new Date(1995, 11, 25, 9, 30, 0);</code>.</li> +</ul> + +<h3 id="Data_개체의_표현_방법"><code>Data</code> 개체의 표현 방법</h3> + +<p>날짜와 시간을 조절하는 <code>Date</code>객체표현 방법은 아래 종류로 나뉩니다:</p> + +<ul> + <li>"set" 함수, 날짜 개체 안에서의 날짜 및 시간 값을 설정합니다.</li> + <li>"get" 함수, 날짜 개체 안에서의 날짜 및 시간 값을 얻습니다.</li> + <li>"to" 함수, 날짜 개체로부터 문자열 값을 반환합니다.</li> + <li><code>Date</code> 문자열을 분석하기위해 parse와 UTC함수를 사용합니다.</li> +</ul> + +<p>"get"및 "set"메소드를 사용하여 초, 분,시, 일, 요일, 월 및 연도를 별도로 가져 와서 설정할 수 있습니다. 요일이 자동적으로 설정되기 (위해) 때문에, 요일을 돌려주는 getDay 메소드가 있습니다만, 대응하는 setDay 메소드는 없습니다. 이러한 메서드는 정수를 사용하여 다음과 같이 값을 나타냅니다.</p> + +<ul> + <li>초와 분: 0 to 59</li> + <li>시간: 0 to 23</li> + <li>요일: 0 (Sunday) to 6 (Saturday)</li> + <li>날짜: 1 to 31 (day of the month)</li> + <li>월: 0 (January) to 11 (December)</li> + <li>연도: years since 1900</li> +</ul> + +<p>예를 들어, 아래와 같이 값들을 정의해봅시다 :</p> + +<pre class="brush: js notranslate">var Xmas95 = new Date("December 25, 1995"); +</pre> + +<p>그러면 <code>Xmas95.getMonth()</code>는 11을 반환합니다, 그리고 <code>Xmas95.getFullYear()</code>는 1995를 반환합니다.</p> + +<p><code>getTime</code>과 <code>setTime</code>방법들은 날짜를 나눌때 유용합니다. <code>getTime</code>함수는 <code>Date</code>객체에 대해 1970년 1월 1일 00:00시부터 밀리초단위로 리턴합니다.</p> + +<p>예를 들어, 다음 코드는 현재 년도에 남아 수를 표시합니다:</p> + +<pre class="brush: js notranslate">var today = new Date(); +var endYear = new Date(1995, 11, 31, 23, 59, 59, 999); // Set day and month +endYear.setFullYear(today.getFullYear()); // Set year to this year +var msPerDay = 24 * 60 * 60 * 1000; // Number of milliseconds per day +var daysLeft = (endYear.getTime() - today.getTime()) / msPerDay; +var daysLeft = Math.round(daysLeft); //returns days left in the year +</pre> + +<p>이 예제에는 오늘 날짜가 포함된 <code>today</code>라는 명칭을 가진 <code>Date</code>객체를 만듭니다. 그리고 나서 <code>endYear</code>라는 <code>Date</code>객체를 만들고 현재연도를 설정합니다. 그런 다음 하루에 밀리 초 수를 사용하여 <code>getTime</code>을 사용하고 전체 일 수를 반올림하여 <code>today</code>와 <code>endYear</code> 사이의 일 수를 계산합니다.</p> + +<p><code>Parse</code> 함수는 날짜문자열부터 기존의 <code>Date</code>객체까지의 값을 할당하기에 유용합니다. 예를 들어, 다음 코드는 그 <code>IPOdate</code> 객체에 날짜값을 할당하기위해 <code>parse</code>와 <code>setTime</code>을 사용합니다;</p> + +<pre class="brush: js notranslate">var IPOdate = new Date(); +IPOdate.setTime(Date.parse("Aug 9, 1995")); +</pre> + +<h3 id="예제">예제</h3> + +<p>다음 예제 에서 <code>JSClock()</code>는 digital 시계형식의 시간을 반환합니다.</p> + +<pre class="brush: js notranslate">function JSClock() { + var time = new Date(); + var hour = time.getHours(); + var minute = time.getMinutes(); + var second = time.getSeconds(); + var temp = "" + ((hour > 12) ? hour - 12 : hour); + if (hour == 0) + temp = "12"; + temp += ((minute < 10) ? ":0" : ":") + minute; + temp += ((second < 10) ? ":0" : ":") + second; + temp += (hour >= 12) ? " P.M." : " A.M."; + return temp; +} +</pre> + +<p><code>JSClock</code> 함수는 먼저 time이라는 새 <code>Date</code> 객체를 만듭니다. 인수가 없으므로 현재 날짜와 시간으로 시간이 생성됩니다. 그런 다음 <code>getHours</code>, <code>getMinutes</code> 및 <code>getSeconds</code> 메소드를 호출하면 현재 시간, 분 및 초 값이<code>hour</code>, <code>minute</code>, <code>second</code>로 할당됩니다.</p> + +<p>다음 네 문장은 시간을 기준으로 문자열 값을 만듭니다. 첫 번째 명령문은 변수 temp를 작성하고 조건식을 사용하여 값을 할당합니다. hour가 12보다 큰 경우 (hour - 12), 그렇지 않은 경우 시간이 0이 아닌 경우 시간이 12 일 경우 시간이 12가됩니다.</p> + +<p>다음 명령문은 <code>temp</code> 값에 <code>minute</code> 값을 추가합니다. 분(<code>minute</code>)의 값이 10보다 작 으면 조건식은 앞에 0이 있는 문자열을 추가합니다. 그렇지 않으면 콜론을 구분하는 문자열을 추가합니다. 그런 다음 같은 방법으로 temp에 초 값을 추가합니다.</p> + +<p>마지막으로 조건부 표현식에 "P.M."이 추가됩니다. 시간(<code>hour</code>)이 12 시간 이상이면 임시(<code>temp</code>)로; 그렇지 않으면 "A.M."을 <code>temp</code>에 추가합니다.</p> + +<p>{{PreviousNext("Web/JavaScript/Guide/Expressions_and_Operators", "Web/JavaScript/Guide/Text_formatting")}}</p> diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/about/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/about/index.html new file mode 100644 index 0000000000..05deb2017f --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/about/index.html @@ -0,0 +1,109 @@ +--- +title: About +slug: Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/About +--- +<h3 id=".EC.9D.B4.EB.B2.88_.EB.A6.B4.EB.A6.AC.EC.A6.88.EC.9D.98_.EC.83.88_.EA.B8.B0.EB.8A.A5" name=".EC.9D.B4.EB.B2.88_.EB.A6.B4.EB.A6.AC.EC.A6.88.EC.9D.98_.EC.83.88_.EA.B8.B0.EB.8A.A5"> 이번 릴리즈의 새 기능 </h3> +<p>JavaScript 버전 1.5는 다음과 같은 개선과 새 기능을 제공합니다: +</p><p><b>런타임 오류</b><br> +런타임 오류가 예외로서 보고됩니다. +</p><p><b>숫자 표현 서식 개선</b><br> +숫자를 표현하는 서식이 Number.prototype.toExponential, Number.prototype.toFixed, Number.prototype.toPrecision 메소드를 포함함으로서 개선되었습니다. <a href="ko/Core_JavaScript_1.5_Guide/Predefined_Core_Objects/Number_Object">Number 개체</a> 페이지를 보십시오. +</p><p><b>정규 표현식 개선</b><br> +정규표현식이 다음과 같이 개선되었습니다: +</p> +<ul><li> 한정자 — +, *, ?, {} — 뒤에 ?를 붙여서 greedy하지 않도록 할 수 있습니다. <a href="ko/Core_JavaScript_1.5_Guide/Writing_a_Regular_Expression_Pattern#Using_Special_Characters">정규 표현식 패턴 쓰기</a> 페이지에서 ?에 대한 항목을 보십시오. +</li><li> Non-capturing parentheses, (?:x) can be used instead of capturing parentheses(x). When non-capturing parentheses are used, matched subexpressions are not available as back-references. See the entry for (?:x) on page <a href="ko/Core_JavaScript_1.5_Guide/Writing_a_Regular_Expression_Pattern#Using_Special_Characters">Writing a Regular Expression Pattern</a>. +</li><li> Positive and negative lookahead assertions are supported. Both assert a match depending on what follows the string being matched. See the entries for x(?=y) and x(?!y) on page <a href="ko/Core_JavaScript_1.5_Guide/Writing_a_Regular_Expression_Pattern#Using_Special_Characters">Writing a Regular Expression Pattern</a>. +</li><li> The m flag has been added to specify that the regular expression should match over multiple lines. See the <a href="ko/Core_JavaScript_1.5_Guide/Working_with_Regular_Expressions/Executing_a_Global_Search%2c_Ignoring_Case%2c_and_Considering_Multiline_Input">Executing a Global Search, Ignoring Case, and Considering Multiline Input</a> page. +</li></ul> +<p><b>조건부 함수 선언</b><br> +함수를 if 조건안에서 선언할 수 있습니다. <a href="ko/Core_JavaScript_1.5_Guide/Defining_Functions">함수 정의</a> 페이지를 참고하세요. +</p><p><b>함수 표현식</b> <br> +함수를 표현식 안에서 선언할 수 있습니다. <a href="ko/Core_JavaScript_1.5_Guide/Defining_Functions">함수 정의</a> 페이지를 참고하세요. +</p><p><b>Multiple catch clauses</b><br> +Multiple catch clauses in a try...catch statement are supported. See <a href="ko/Core_JavaScript_1.5_Guide/Exception_Handling_Statements/try...catch_Statement#The_catch_Block">The catch Block</a> page. +</p><p><b>Getters와 Setters</b><br> +JavaScript writers can now add getters and setters to their objects. This feature is available only in the C implementation of JavaScript. See the <a href="ko/Core_JavaScript_1.5_Guide/Creating_New_Objects/Defining_Getters_and_Setters">Defining Getters and Setters</a> page. +</p><p><b>상수</b> <br> +읽기전용의 상수가 지원됩니다. This feature is available only in the C implementation of JavaScript. See the <a href="ko/Core_JavaScript_1.5_Guide/Constants">Constants</a> page. +</p> +<h3 id=".EB.AF.B8.EB.A6.AC_.EC.95.8C.EA.B3.A0_.EC.9E.88.EC.96.B4.EC.95.BC_.ED.95.A0_.EA.B2.83" name=".EB.AF.B8.EB.A6.AC_.EC.95.8C.EA.B3.A0_.EC.9E.88.EC.96.B4.EC.95.BC_.ED.95.A0_.EA.B2.83"> 미리 알고 있어야 할 것 </h3> +<p>이 안내서는 당신이 다음과 같은 배경지식을 지녔다고 가정합니다: +</p> +<ul><li> 인터넷과 World Wide Web (WWW)에 대한 상식적인 이해 +</li><li> HyperText Markup Language (HTML)에 대한 충분한 지식<br> +</li></ul> +<p>C 혹은 Visual Basic에 대한 프로그래밍 경험이 있으면 좋지만, 필수사항은 아닙니다. +</p> +<h3 id="JavaScript_.EB.B2.84.EC.A0.84" name="JavaScript_.EB.B2.84.EC.A0.84"> JavaScript 버전 </h3> +<table class="fullwidth-table"> +<tbody><tr> +<th>JavaScript 버전</th> +<th>Navigator 버전</th> +</tr> +<tr> +<td>JavaScript 1.0</td> +<td>Navigator 2.0</td> +</tr> +<tr> +<td>JavaScript 1.1</td> +<td>Navigator 3.0</td> +</tr> +<tr> +<td>JavaScript 1.2</td> +<td>Navigator 4.0-4.05</td> +</tr> +<tr> +<td>JavaScript 1.3</td> +<td>Navigator 4.06-4.7x</td> +</tr> +<tr> +<td>JavaScript 1.4</td> +<td> </td> +</tr> +<tr> +<td>JavaScript 1.5</td> +<td>Navigator 6.0<br>모질라 (오픈소스 브라우저)</td> +</tr> +</tbody></table> +<p><small><b>표1: JavaScript와 Navigator 버전</b></small><br> +<br> +Each version of the Netscape Enterprise Server also supports a different version of JavaScript. To help you write scripts that are compatible with multiple versions of the Enterprise Server, this manual uses an abbreviation to indicate the server version in which each feature was implemented. +</p> +<table class="fullwidth-table"> +<tbody><tr> +<th>Abbreviation</th> +<th>Enterprise Server version</th> +</tr> +<tr> +<td>NES 2.0</td> +<td>Netscape Enterprise Server 2.0</td> +</tr> +<tr> +<td>NES 3.0</td> +<td>Netscape Enterprise Server 3.0</td> +</tr> +</tbody></table> +<p><small><b>Table 2: Abbreviations of Netscape Enterprise Server versions</b></small> +</p> +<h3 id="JavaScript_.EC.A0.95.EB.B3.B4.EB.A5.BC_.EC.B0.BE.EC.9D.84_.EC.88.98_.EC.9E.88.EB.8A.94_.EA.B3.B3" name="JavaScript_.EC.A0.95.EB.B3.B4.EB.A5.BC_.EC.B0.BE.EC.9D.84_.EC.88.98_.EC.9E.88.EB.8A.94_.EA.B3.B3"> JavaScript 정보를 찾을 수 있는 곳 </h3> +<p>The core JavaScript documentation includes the following books: +</p> +<ul><li> <a href="ko/Core_JavaScript_1.5_Guide">The Core JavaScript Guide</a> (this guide) provides information about the core JavaScript language and its objects. +</li><li> <a href="ko/Core_JavaScript_1.5_Reference">The Core JavaScript Reference</a> provides reference material for the core JavaScript language. +</li></ul> +<p>If you are new to JavaScript, start with the <a href="ko/Core_JavaScript_1.5_Guide">Core JavaScript Guide</a>. Once you have a firm grasp of the fundamentals, you can use the <a href="ko/Core_JavaScript_1.5_Reference">Core JavaScript Reference</a> to get more details on individual objects and statements. +</p> +<h3 id=".EB.AC.B8.EC.84.9C_.EA.B7.9C.EC.95.BD" name=".EB.AC.B8.EC.84.9C_.EA.B7.9C.EC.95.BD"> 문서 규약 </h3> +<p>JavaScript 응용프로그램은 많은 운영체제에서 실행됩니다. 이 책에 있는 정보는 모든 운영체제에 적용됩니다. 파일과 디렉토리 경로는 Windows 형식(디렉토리 이름을 구분하는데 역슬래시를 사용)으로 썼습니다. Unix에서는 역슬래시를 슬래시로 바꾸어 사용하면 됩니다. +</p><p>이 안내서에서 URL은 다음과 같은 형태로 씁니다. +</p><p><code><span class="nowiki">http://server.domain/path/file.html</span></code> +</p><p>이 URL에서 "server"는 우리가 응용프로그램을 실행하는 서버 이름(research1이나 www 등)이고, "domain"은 인터넷 도메인 이름(netscape.com이나 uiuc.edu 등)입니다. "path"는 서버의 디렉토리 구조를 나타내고, "file.html"은 파일 이름입니다. 일반적으로 URL에서 이탤릭체로 쓴 부분은 알맞은 내용으로 바꿔써야 할 내용(placeholder)이고, 평범한 고정폭 글꼴은 그대로 쓰면 되는 내용입니다. Secure Socket Layer(SSL)을 사용하는 서버라면 http 대신 https를 쓰면 됩니다. +</p><p>이 안내서는 다음과 같은 관례를 따릅니다. +</p> +<ul><li> <code>고정폭 글꼴</code>은 샘플 코드, API, 언어 요소(메소드 이름, 속성 이름 등), 파일 이름, 경로, 디렉토리 이름, HTML 태그, 화면에 입력해야 할 텍스트를 나타내는 데 쓰입니다. (고정폭 이탤릭체는 코드 내용 중에서 적당히 알맞은 내용으로 바꿔써야 할 부분을 나타내는 데 씁니다.) +</li><li> <i>이탤릭체</i>는 책 제목, 강조, 변수, 뜻 그대로 쓰인 단어(words in the literal sense)에 씁니다. +</li><li> <b>굵은 글씨</b>는 용어에 씁니다. +</li></ul> +<p>{{ PreviousNext("Core_JavaScript_1.5_Guide", "Core_JavaScript_1.5_Guide:JavaScript_Overview") }} +</p>{{ languages( { "en": "en/Core_JavaScript_1.5_Guide/About", "fr": "fr/Guide_JavaScript_1.5/\u00c0_propos", "ja": "ja/Core_JavaScript_1.5_Guide/About", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/O" } ) }} diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/class-based_vs._prototype-based_languages/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/class-based_vs._prototype-based_languages/index.html new file mode 100644 index 0000000000..20601a0e81 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/class-based_vs._prototype-based_languages/index.html @@ -0,0 +1,26 @@ +--- +title: Class-Based vs. Prototype-Based Languages +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Class-Based_vs._Prototype-Based_Languages +--- +<h3 id=".E3.82.AF.E3.83.A9.E3.82.B9.E3.83.99.E3.83.BC.E3.82.B9.E8.A8.80.E8.AA.9E.E3.81.A8.E3.83.97.E3.83.AD.E3.83.88.E3.82.BF.E3.82.A4.E3.83.97.E3.83.99.E3.83.BC.E3.82.B9.E8.A8.80.E8.AA.9E" name=".E3.82.AF.E3.83.A9.E3.82.B9.E3.83.99.E3.83.BC.E3.82.B9.E8.A8.80.E8.AA.9E.E3.81.A8.E3.83.97.E3.83.AD.E3.83.88.E3.82.BF.E3.82.A4.E3.83.97.E3.83.99.E3.83.BC.E3.82.B9.E8.A8.80.E8.AA.9E">클래스 기반언어와 프로토타입 기반언어</h3> +<p>Java와 C++이라는 클래스 기반의 객체지향언어는 클래스와 인스턴스라는 2개의 다른 실체가 있다는 개념에 기초하고 있습니다.</p> +<ul> <li>클래스는 어떤 객체의 집합을 특징짓는 모든 속성(Java에서는 메소드와 필드를, C++에서는 멤버를 프로퍼티로 간주)을 정의합니다. 클래스란 그것이 나타내는 객체집합의 특정멤버가 아닌, 추상적인것입니다. 예를들어, Employee클래스는 모든 종업원의 집합을 나타냅니다.</li> <li>한편, 인스턴스는 클래스를 실례로 한것입니다. 즉, 그 멤버중 하나인것입니다. 예를들어, Victoria는 Employee클래스의 인스턴스가 될 수 있습니다. 이 클래스는 특정 개인을 종업원으로서 표현하고 있는것입니다. 인스턴스는 그 부모클래스의 속성을 정확하게 유지하고 있습니다.</li> +</ul> +<p>JavaScript のようなプロトタイプベース言語はこの区別がありません。単にオブジェクトがあるだけです。プロトタイプベース言語には原型的なオブジェクトという概念があります。このオブジェクトは新しいオブジェクトの初期プロパティを取得する元になるテンプレートとして使用されます。どのオブジェクトもそれ独自のプロパティを指定できます。オブジェクト作成時にも実行時にも可能です。さらに、どのオブジェクトも別のオブジェクトに対するプロトタイプとして関連付けることができます。2 つ目のオブジェクトが 1 つ目のオブジェクトのプロトタイプを共有するということもできます。</p> +<h4 id=".E3.82.AF.E3.83.A9.E3.82.B9.E3.81.AE.E5.AE.9A.E7.BE.A9" name=".E3.82.AF.E3.83.A9.E3.82.B9.E3.81.AE.E5.AE.9A.E7.BE.A9">クラスの定義</h4> +<p>クラスベース言語ではクラス定義ごとにクラスを定義します。定義では特殊なメソッドを指定してそのクラスのインスタンスを作成することができます。そのようなメソッドはコンストラクタと呼びます。コンストラクタメソッドはインスタンスのプロパティに対する初期値を指定することができます。また、作成時に他の適当な処理を実行することもできます。new 演算子をコンストラクタメソッドと一緒に用いることでクラスのインスタンスを作成できます。</p> +<p>JavaScript は同様のモデルに従っていますが、コンストラクタと別になっているクラス定義がありません。その代わりに、プロパティと値からなる特定の初期的なセットを持つオブジェクトを作成するコンストラクタ関数を定義します。どの JavaScript 関数もコンストラクタとして使用できます。new 演算子をコンストラクタ関数とともに使用することで新しいオブジェクトを作成します。</p> +<h4 id=".E3.82.B5.E3.83.96.E3.82.AF.E3.83.A9.E3.82.B9.E3.81.A8.E7.B6.99.E6.89.BF" name=".E3.82.B5.E3.83.96.E3.82.AF.E3.83.A9.E3.82.B9.E3.81.A8.E7.B6.99.E6.89.BF">サブクラスと継承</h4> +<p>クラスベース言語ではクラス定義を通じてクラスの階層を作ります。クラス定義では新しいクラスがある既存のクラスのサブクラスになるように指定することができます。サブクラスはスーパークラスの全プロパティを継承します。さらに新しくプロパティを追加したり継承したものを変更することもできます。例えば、Employee クラスが name および dept プロパティのみを含んでおり、Manager は reports プロパティを追加する Employee のサブクラスであるとします。この場合、Manager クラスのインスタンスは name、dept、reports という 3 つのプロパティをすべて持つことになります。</p> +<p>JavaScript では、原型的なオブジェクトをどのコンストラクタ関数にも結びつけることができるようにして継承を実装しています。そのため、全く同じような Employee と Manager の例を作成することができますが、使用する用語が若干異なります。まず、Employee コンストラクタ関数を定義します。これは name および dept プロパティを指定します。次に Manager コンストラクタ関数を定義します。これは reports プロパティを指定します。最後に新しい Employee オブジェクトを Manager コンストラクタ関数に対するプロトタイプとして代入します。そして新しい Manager を作成すると、このオブジェクトは Employee オブジェクトから name および dept プロパティを継承します。</p> +<h4 id=".E3.83.97.E3.83.AD.E3.83.91.E3.83.86.E3.82.A3.E3.81.AE.E8.BF.BD.E5.8A.A0.E3.81.A8.E5.89.8A.E9.99.A4" name=".E3.83.97.E3.83.AD.E3.83.91.E3.83.86.E3.82.A3.E3.81.AE.E8.BF.BD.E5.8A.A0.E3.81.A8.E5.89.8A.E9.99.A4">プロパティの追加と削除</h4> +<p>クラスベース言語では一般的にクラスをコンパイル時に生成し、コンパイル時または実行時にクラスのインスタンスを作成します。クラス定義後にそのクラスのプロパティの数や型を変更することはできません。しかし、JavaScript ではどんなオブジェクトでも実行時にプロパティを追加したり削除したりすることができます。あるオブジェクトのセットでプロトタイプとして使用されているオブジェクトにプロパティを追加すると、そのプロトタイプの使用元であるオブジェクトにも新しいプロパティが追加されます。</p> +<h4 id=".E9.81.95.E3.81.84.E3.81.AE.E6.A6.82.E8.A6.81" name=".E9.81.95.E3.81.84.E3.81.AE.E6.A6.82.E8.A6.81">違いの概要</h4> +<p>次の表でこれらの違いをいくつか短くまとめてみます。この章の残りで、JavaScript のコンストラクタとプロトタイプを用いてオブジェクト階層を作成することについての詳細を説明していきます。また、この方法が Java ではどう変わるかという比較もします。</p> +<table class="fullwidth-table"> <tbody> <tr> <th>クラスベース (Java)</th> <th>プロトタイプベース (JavaScript)</th> </tr> <tr> <td>クラスとインスタンスは異なる実体である。</td> <td>すべてのオブジェクトはインスタンスである。</td> </tr> <tr> <td>クラス定義を用いてクラスを定義する。また、コンストラクタメソッドを用いてクラスをインスタンス化する。</td> <td>コンストラクタ関数を用いてオブジェクトのセットを定義し、作成する。</td> </tr> <tr> <td><code>new</code> 演算子を用いて単一のオブジェクトを作成する。</td> <td>同じ。</td> </tr> <tr> <td>既存のクラスのサブクラスを定義するクラス定義を用いてオブジェクト階層を構築する。</td> <td>コンストラクタ関数に結びつけられたプロトタイプとしてオブジェクトを代入することでオブジェクト階層を構築する。</td> </tr> <tr> <td>クラスチェーンに従ってプロパティを継承する。</td> <td>プロトタイプチェーンに従ってプロパティを継承する。</td> </tr> <tr> <td>クラス定義がクラスの全インスタンスの全プロパティを指定する。実行時に動的にプロパティを追加することはできない。</td> <td>コンストラクタ関数またはプロトタイプがプロパティの初期セットを指定する。個々のオブジェクトやオブジェクトの全体のセットに動的にプロパティを追加したり、それらからプロパティを除去したりできる。</td> </tr> </tbody> +</table> +<div class="noinclude"> +<p>{{ PreviousNext("Core_JavaScript_1.5_Guide:Predefined_Core_Objects:String_Object", "Core_JavaScript_1.5_Guide:The_Employee_Example") }}</p> +</div> +<p>{{ languages( { "zh-tw": "zh_tw/Core_JavaScript_1.5_教學/以類別為基礎的語言_vs._以原型為基礎的語言", "en": "en/Core_JavaScript_1.5_Guide/Class-Based_vs._Prototype-Based_Languages", "es": "es/Gu\u00eda_JavaScript_1.5/Lenguajes_basados_en_clases_frente_a_basados_en_prototipos", "fr": "fr/Guide_JavaScript_1.5/Langages_bas\u00e9s_sur_les_classes_et_langages_bas\u00e9s_sur_les_prototypes", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/J\u0119zyki_oparte_na_klasach_vs._oparte_na_prototypach", "zh-cn": "cn/Core_JavaScript_1.5_Guide/Class-Based_vs._Prototype-Based_Languages" } ) }}</p> diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/constants/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/constants/index.html new file mode 100644 index 0000000000..48a697fdc2 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/constants/index.html @@ -0,0 +1,28 @@ +--- +title: Constants +slug: Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Constants +translation_of: Web/JavaScript/Guide/Grammar_and_types +--- +<h3 id=".EC.83.81.EC.88.98" name=".EC.83.81.EC.88.98"> 상수 </h3> +<p><code><a href="ko/Core_JavaScript_1.5_Reference/Statements/const">const</a></code> 키워드를 이용하면 읽기 전용의 이름 있는 상수를 만들 수 있습니다. 상수 식별자(const identifier)는 변수의 식별자와 동일합니다. 문자나 밑줄로 시작해야 하고, 알파벳, 숫자, 밑줄 문자를 사용할 수 있습니다. +</p> +<pre class="eval">const prefix = '212'; +</pre> +<p>상수는 스크립트 실행 중에 값을 대입하거나 다시 선언하여 값을 바꿀 수 없습니다. +</p><p>전역 상수인 경우에도 항상 <code>const</code> 키워드를 붙여야 한다는 점만 제외하면, 상수의 범위 규칙은 변수의 경우와 동일합니다. const 키워드가 없으면 변수라고 판정됩니다. +</p><p>같은 범위에 있는 함수나 변수의 이름과 같은 이름으로 상수를 만들 수 없습니다. 예를 들어, +</p> +<pre>//이 코드는 에러를 낼 것입니다 +function f() {}; + const f = 5; + +//이 코드 또한 에러를 냅니다. +function f() { + const g = 5; + var g; + + //그 외 코드... + +}</pre> +<p>{{ PreviousNext("Core_JavaScript_1.5_Guide:Variables", "Core_JavaScript_1.5_Guide:Literals") }} +</p>{{ languages( { "en": "en/Core_JavaScript_1.5_Guide/Constants", "fr": "fr/Guide_JavaScript_1.5/Constantes", "ja": "ja/Core_JavaScript_1.5_Guide/Constants", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Sta\u0142e" } ) }} diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_a_regular_expression/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_a_regular_expression/index.html new file mode 100644 index 0000000000..d969b378f4 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_a_regular_expression/index.html @@ -0,0 +1,35 @@ +--- +title: Creating a Regular Expression +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Creating_a_Regular_Expression +--- +<h3 id=".EC.A0.95.EA.B7.9C.ED.91.9C.ED.98.84.EC.8B.9D_.EB.A7.8C.EB.93.A4.EA.B8.B0" name=".EC.A0.95.EA.B7.9C.ED.91.9C.ED.98.84.EC.8B.9D_.EB.A7.8C.EB.93.A4.EA.B8.B0">정규표현식 만들기</h3> +<p>정규표현식은 다음의 두 가지 방법으로 만들 수 있습니다.</p> +<ul> + <li>정규표현식 상수값을 이용하여 만들기</li> +</ul> +<pre> re = /ab+c/; </pre> +<dl> + <dd> + <dl> + <dd> + 정규표현식 상수값은 스크립트가 실행될 때 컴파일됩니다. 따라서 정규표현식의 값이 변하지 않을 경우, 이 방법을 사용하면 좀 더 나은 성능을 얻을 수 있습니다.</dd> + </dl> + </dd> +</dl> +<ul> + <li><a href="ko/Core_JavaScript_1.5_Reference/Global_Objects/RegExp">RegExp</a> 객체의 생성자를 호출하여 만들기</li> +</ul> +<pre> re = new RegExp("ab+c"); </pre> +<dl> + <dd> + <dl> + <dd> + 생성자를 이용하면 실행 시간에 정규표현식이 컴파일됩니다. 정규표현식 패턴이 바뀔 것을 알고 있거나, 또는 패턴을 사용자의 입력 등을 통해 외부에서 가져오려고 할 때 이 방법을 사용하십시오.</dd> + </dl> + </dd> +</dl> +<div class="noinclude"> + <p>{{ PreviousNext("Core_JavaScript_1.5_Guide:Operators:Special_Operators", "Core_JavaScript_1.5_Guide:Writing_a_Regular_Expression_Pattern") }}</p> +</div> +<p> </p> diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/defining_getters_and_setters/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/defining_getters_and_setters/index.html new file mode 100644 index 0000000000..3238e19b0f --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/defining_getters_and_setters/index.html @@ -0,0 +1,84 @@ +--- +title: Defining Getters and Setters +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Creating_New_Objects/Defining_Getters_and_Setters +--- +<h3 id="getter.2Fsetter_.EC.A0.95.EC.9D.98.ED.95.98.EA.B8.B0" name="getter.2Fsetter_.EC.A0.95.EC.9D.98.ED.95.98.EA.B8.B0">getter/setter 정의하기</h3> + +<p>getter는 속성의 값을 얻어오는 메소드이고, setter는 속성의 값을 설정하는 메소드입니다. 우리는 언어에서 미리 정의한 핵심 개체들과 사용자 정의 개체에 getter/setter를 정의할 수 있습니다. getter와 setter를 정의할 때 쓰이는 문법은 개체 상수값 문법입니다.</p> + +<p>다음의 JS 쉘 세션은 사용자가 정의한 개체 o에 대해서 getter와 setter가 어떻게 동작하는지 보여줍니다. JS 쉘은 JavaScript를 한 번에 실행(batch)하거나 대화식으로(interactively) 실행할 수 있게 해주는 응용프로그램입니다.</p> + +<p><code>o</code> 개체에는 이런 속성이 있습니다.</p> + +<ul> + <li>o.a - 수</li> + <li>o.b - o.a 더하기 1을 반환하는 getter</li> + <li>o.c - 받은 값을 2로 나누어서 o.a에 설정하는 setter</li> +</ul> + +<pre>js> o = new Object; +[object Object] +js> o = {a:7, get b() {return this.a+1; }, set c(x) {this.a = x/2}}; +[object Object] +js> o.a +7 +js> o.b +8 +js> o.c = 50 +js> o.a +25 +js> +</pre> + +<p>다음 JavaScript 쉘 세션은 이미 정의된 <code>Date</code> 모든 인스턴스에 year 속성을 추가하기 위해서 getter/setter가 어떻게 Date 프로토타입을 확장하는지 보여줍니다. 이 세션에서는 year 속성의 getter와 setter를 지원하기 위해서 <code>Date</code>에 있는 <code>getFullYear</code> 메소드와 <code>setFullYear</code> 메소드를 사용하고 있습니다.</p> + +<p>이 문장들은 year 속성에 대한 getter와 setter를 정의합니다.</p> + +<pre>js> var d = Date.prototype; +js> d.__defineGetter__("year", function() { return this.getFullYear(); }); +js> d.__defineSetter__("year", function(y) { this.setFullYear(y); }); +</pre> + +<p>이 문장들은 <code>Date</code>의 getter/setter를 사용합니다.</p> + +<pre>js> var now = new Date; +js> print(now.year); +2000 +js> now.year=2001; +987617605170 +js> print(now); +Wed Apr 18 11:13:25 GMT-0700 (Pacific Daylight Time) 2001 +</pre> + +<div class="note">JavaScript 1.5를 개발하는 동안 이미 존재하는 개체에 getter/setter를 추가할 때 <code>getter =</code>, <code>setter =</code>이라는 식의 문법을 사용하던 때가 잠깐 있었습니다. 이 문법은 이제 사용하지 말아야 합니다. 현재의 JS 1.5 엔진에서는 경고를 발생시키고, 더 나중의 버전에서는 문법 에러를 발생시키게 될 것입니다.</div> + +<p> </p> + +<h3 id=".EC.9A.94.EC.95.BD" name=".EC.9A.94.EC.95.BD">요약</h3> + +<p>getter/setter를</p> + +<ul> + <li><a href="ko/Core_JavaScript_1.5_Guide/Creating_New_Objects/Using_Object_Initializers">개체 초기화 지정자</a>를 이용해서 정의하거나,</li> + <li>개체가 만들어진 이후에 getter/setter 추가 메소드를 이용해서 언제든지 추가할 수 있습니다.</li> +</ul> + +<p><a href="ko/Core_JavaScript_1.5_Guide/Creating_New_Objects/Using_Object_Initializers">개체 초기화 지정자</a>를 이용할 때는 단순히 getter 메소드 앞에는 <code>get</code>을 써주고 setter 메소드 앞에는 <code>set</code>을 써주기만 하면됩니다. 물론 getter 메소드에는 매개변수가 없어야 하고 setter에는 정확히 하나만 있어야 합니다. 다음 예제에서와 같이 말입니다.</p> + +<pre class="eval">o = { + a:7, + <strong>get</strong> b() { return this.a+1; }, + <strong>set</strong> c(x) { this.a = x/2; } +}; +</pre> + +<p>개체가 생성된 이후에 어느 때라도 <code>__defineGetter__</code>와 <code>__defineSetter__</code>라는 메소드를 이용하면 getter/setter를 정의할 수 있습니다. 두 메소드 모두 첫 번째 매개변수에 getter/setter 이름을 나타내는 문자열을 받습니다. 두 번째 매개변수는 getter/setter로서 호출될 함수를 받습니다. 예제를 보십시오.</p> + +<pre class="eval">o.__defineGetter__("b", function() { return this.a+1; }); +o.__defineSetter__("c", function(x) { this.a = x/2; }); +</pre> + +<p>두 가지 중에서 어떤 방식을 택할지는 프로그래밍 스타일이나 해야할 작업에 달려있습니다. 프로토타입을 정의하는데 이미 개체 초기화 지정자를 사용하고 있다면 거의 첫 번째 방식을 사용할 것입니다. 첫 번째가 좀 더 단순하고 자연스러운 방식입니다. 그러나 우리가 직접 프로토토입을 만들거나 개체를 생성할 수 없어서 나중에 getter/setter를 추가해야 하는 상황이라면 두 번째 방식을 사용할 수 밖에 없습니다. 두 번째 방식은 JavaScript의 동적인 특성을 잘 보여주는 방식입니다. 하지만 코드를 읽고 이해하기 어렵게 만들 수도 있습니다.</p> + +<p>{{ PreviousNext("Core_JavaScript_1.5_Guide:Creating_New_Objects:Using_this_for_Object_References", "Core_JavaScript_1.5_Guide:Creating_New_Objects:Deleting_Properties") }}</p> diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/defining_methods/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/defining_methods/index.html new file mode 100644 index 0000000000..8e91a2007f --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/defining_methods/index.html @@ -0,0 +1,43 @@ +--- +title: Defining Methods +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Creating_New_Objects/Defining_Methods +--- +<h3 id=".EB.A9.94.EC.86.8C.EB.93.9C_.EC.A0.95.EC.9D.98" name=".EB.A9.94.EC.86.8C.EB.93.9C_.EC.A0.95.EC.9D.98">메소드 정의</h3> +<p> + <i> + 메소드</i> + 는 개체와 연관되어 있는 함수입니다. 일반적인 함수를 정의하는 것과 같은 방법으로 메소드를 정의합니다. 그 후에, 존재하는 개체와 함수를 연관시키기 위해서 다음과 같은 문법을 사용합니다.</p> +<pre>object.methodname = function_name +</pre> +<p><code>object</code>는 존재하는 개체중에 하나이고, <code>methodname</code>은 지금 추가하려는 메소드 이름이며, <code>function_name</code>은 함수 이름입니다.</p> +<p>이제 우리는 개체의 메소드를 호출할 때 다음과 같이 할 수 있습니다.</p> +<pre>object.methodname(params); +</pre> +<p>개체 생성자 함수에 메소드 정의를 포함시켜서 개체 타입에 대한 메소드를 정의할 수 있습니다. 예를 들어, 미리 정의된 car 개체의 속성을 출력해주는 함수를 정의할 수 있습니다.</p> +<pre>function displayCar() { + var result = "A Beautiful " + this.year + " " + this.make + + " " + this.model; + pretty_print(result); +} +</pre> +<p><code>pretty_print</code>는 가로선과 문자열을 출력하는 함수입니다. 이 메소드가 포함된 개체를 참조하기 위해서 <code>this</code>를 사용하고 있다는 것을 주의해서 보십시오.</p> +<p>아래 문장을 개체 정의에 추가함으로써 이 함수를 car의 메소드로 만들 수 있습니다.</p> +<pre>this.displayCar = displayCar; +</pre> +<p>그러므로 <code>car</code> 개체의 완벽한 정의는 아래와 같은 모습이 될 것입니다.</p> +<pre>function car(make, model, year, owner) { + this.make = make; + this.model = model; + this.year = year; + this.owner = owner; + this.displayCar = displayCar; +} +</pre> +<p>그러면 우리는 모든 car 개체에 대해서 이런 식으로 <code>displayCar</code> 메소드를 호출할 수 있게됩니다.</p> +<pre>car1.displayCar() +car2.displayCar() +</pre> +<p>이 코드는 다음 그림과 같은 내용을 만들어냅니다.</p> +<p><img alt="Image:obja.gif"> <small><b>그림 7.1: 메소드 출력 결과</b></small></p> +<p>{{ PreviousNext("Core_JavaScript_1.5_Guide:Creating_New_Objects:Defining_Properties_for_an_Object_Type", "Core_JavaScript_1.5_Guide:Creating_New_Objects:Using_this_for_Object_References") }}</p> diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/defining_properties_for_an_object_type/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/defining_properties_for_an_object_type/index.html new file mode 100644 index 0000000000..17c2aa7de8 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/defining_properties_for_an_object_type/index.html @@ -0,0 +1,11 @@ +--- +title: Defining Properties for an Object Type +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Creating_New_Objects/Defining_Properties_for_an_Object_Type +--- +<h3 id=".EA.B0.9C.EC.B2.B4_.ED.98.95.EC.8B.9D.EC.97.90_.EC.86.8D.EC.84.B1_.EC.A0.95.EC.9D.98.ED.95.98.EA.B8.B0" name=".EA.B0.9C.EC.B2.B4_.ED.98.95.EC.8B.9D.EC.97.90_.EC.86.8D.EC.84.B1_.EC.A0.95.EC.9D.98.ED.95.98.EA.B8.B0">개체 형식에 속성 정의하기</h3> +<p><code>prototype</code> 속성을 이용하면 이미 정의해 놓은 개체 형식에 속성을 추가할 수 있습니다. 이 방법을 사용하면 개체의 인스턴스 하나에만 속성이 추가되는 것이 아니라 같은 타입의 모든 개체가 공유하는 속성을 정의합니다. 다음 코드는 <code>car</code> 형식의 모든 개체에 <code>color</code> 속성을 추가하고, <code>car1</code> 개체의 <code>color</code> 속성에 값을 할당하는 코드입니다.</p> +<pre>Car.prototype.color=null; +car1.color="black"; +</pre> +<p>더 많은 정보를 얻으려면 <a href="ko/Core_JavaScript_1.5_Reference">기본 JavaScript 레퍼런스</a>에 있는 Function 개체의 <a href="ko/Core_JavaScript_1.5_Reference/Objects/Function#Properties"><code>prototype</code> 속성</a>을 보십시오. {{ PreviousNext("Core_JavaScript_1.5_Guide:Creating_New_Objects:Indexing_Object_Properties", "Core_JavaScript_1.5_Guide:Creating_New_Objects:Defining_Methods") }}</p> diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/deleting_properties/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/deleting_properties/index.html new file mode 100644 index 0000000000..1b6f50cc11 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/deleting_properties/index.html @@ -0,0 +1,20 @@ +--- +title: Deleting Properties +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Creating_New_Objects/Deleting_Properties +--- +<h3 id=".EC.86.8D.EC.84.B1_.EC.A0.9C.EA.B1.B0" name=".EC.86.8D.EC.84.B1_.EC.A0.9C.EA.B1.B0">속성 제거</h3> +<p><code>delete</code> 연산자를 사용하여 속성을 제거할 수 있습니다. 어떻게 속성을 제거하는지 코드를 보십시오.</p> +<pre>//a와 b라는 속성을 가지는 새 개체를 만듭니다. +myobj = new Object; +myobj.a = 5; +myobj.b = 12; + +//myobj가 속성 b만을 가지도록 속성 a를 지웁니다. +delete myobj.a; +</pre> +<p>전역 변수를 선언할 때 <code>var</code> 키워드를 사용하지 않았다면 그 전역 변수를 제거하는데 <code>delete</code> 연산자를 사용할 수 있습니다.</p> +<pre>g = 17; +delete g; +</pre> +<p>더 많은 정보를 얻으려면 <a href="ko/Core_JavaScript_1.5_Guide/Operators/Special_Operators#delete">delete</a>를 보십시오. {{ PreviousNext("Core_JavaScript_1.5_Guide:Creating_New_Objects:Defining_Getters_and_Setters", "Core_JavaScript_1.5_Guide:Predefined_Core_Objects") }}</p> diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/index.html new file mode 100644 index 0000000000..8345ba1478 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/index.html @@ -0,0 +1,6 @@ +--- +title: Creating New Objects +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Creating_New_Objects +--- +{{wiki.localize('System.API.page-generated-for-subpage')}} diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/indexing_object_properties/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/indexing_object_properties/index.html new file mode 100644 index 0000000000..84b9df2c2d --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/indexing_object_properties/index.html @@ -0,0 +1,9 @@ +--- +title: Indexing Object Properties +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Creating_New_Objects/Indexing_Object_Properties +--- +<h3 id=".EA.B0.9C.EC.B2.B4_.EC.86.8D.EC.84.B1_.EC.A0.91.EA.B7.BC.ED.95.98.EA.B8.B0" name=".EA.B0.9C.EC.B2.B4_.EC.86.8D.EC.84.B1_.EC.A0.91.EA.B7.BC.ED.95.98.EA.B8.B0">개체 속성 접근하기</h3> +<p>JavaScript 1.0에서는 개체의 속성을 참조할 때 개체 이름이나 순서 인덱스를 사용할 수 있습니다. 그러나 JavaScript 1.1과 그 이후 버전에서는 처음에 속성을 정의할 때 이름으로 정의했으면 항상 이름으로만 참조해야 하고, 인덱스로 정의했으면 인덱스로만 참조해야 합니다.</p> +<p>이런 제한은 앞 페이지 예제의 car 개체 형식처럼 생성자 함수로 개체와 개체 속성을 만들 때나 명시적으로 개별 속성을 만들 때(예를 들어 <code>myCar.color = "red"</code> 같은 식으로 속성을 추가할 때) 모두 적용됩니다. 그러므로 <code>myCar{{ mediawiki.external(5) }} = "25 mpg"</code>라고 인덱스를 이용해서 속성을 정의하면 그 이후로는 항상 <code>myCar{{ mediawiki.external(5) }}</code>로 참조할 수 있습니다.</p> +<p>이 규칙은 <code>forms</code> 배열 같이 HTML을 반영하여 생성된 개체에는 예외입니다. 이 배열에 있는 개체를 참조할 때는 순서(문서에 기록된 순서)를 나타내는 숫자나 이름(이름을 정의한 경우에만)을 이용하여 참조할 수 있습니다. 예를 들어, 문서에 있는 두 번째 <code><FORM></code> 태그가 "myForm"이라는 값을 가진 <code>NAME</code> 속성을 갖고 있다면 이 폼은 <code>document.forms{{ mediawiki.external(1) }}</code>, <code>document.forms{{ mediawiki.external('\"myForm\"') }}</code>, <code>document.myForm</code>으로 접근할 수 있습니다. {{ PreviousNext("Core_JavaScript_1.5_Guide:Creating_New_Objects:Using_a_Constructor_Function", "Core_JavaScript_1.5_Guide:Creating_New_Objects:Defining_Properties_for_an_Object_Type") }}</p> diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/using_a_constructor_function/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/using_a_constructor_function/index.html new file mode 100644 index 0000000000..552347b70e --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/using_a_constructor_function/index.html @@ -0,0 +1,58 @@ +--- +title: Using a Constructor Function +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Creating_New_Objects/Using_a_Constructor_Function +--- +<h3 id=".EC.83.9D.EC.84.B1.EC.9E.90_.ED.95.A8.EC.88.98_.EC.82.AC.EC.9A.A9.ED.95.98.EA.B8.B0" name=".EC.83.9D.EC.84.B1.EC.9E.90_.ED.95.A8.EC.88.98_.EC.82.AC.EC.9A.A9.ED.95.98.EA.B8.B0">생성자 함수 사용하기</h3> +<p>다른 방법으로, 다음 두 단계를 거쳐서 개체를 만들 수도 있습니다.</p> +<ol> + <li>생성자 함수를 작성함으로써 개체를 정의합니다.</li> + <li>new 키워드를 사용하여 개체의 인스턴스를 만듭니다.</li> +</ol> +<p>개체 형식을 정의하기 위해서, 개체의 이름, 속성, 메소드를 지정하는 함수를 만듭니다. 자동차를 나타내기 위한 개체를 만들고 싶다고 해봅시다. 그렇다면 이 형식이 <code>car</code>라고 불리길 원할 것이고, make, model, year라는 속성이 있기를 원할 것입니다. 원하는 것을 이루기 위해서 이런 함수를 작성합니다.</p> +<pre>function car(make, model, year) { + this.make = make; + this.model = model; + this.year = year; +} +</pre> +<p>함수의 인자로 전달받은 값을 개체의 속성에 할당하기 위해서 <code>this</code>를 사용했다는 것을 명심하십시오.</p> +<p>이제 우리는 <code>mycar</code>라는 개체를 이렇게 만들 수 있습니다.</p> +<pre>mycar = new car("Eagle", "Talon TSi", 1993); +</pre> +<p>이 문장은 <code>mycar</code>를 만들고, 지정된 값을 mycar의 속성에 할당합니다. 그러면 <code>mycar.make</code>는 "Eagle"이라는 문자열 값을 가지고, <code>mycar.year</code>는 1993이라는 정수를 가질 것입니다.</p> +<p>우리는 <code>new</code>를 써서 <code>car</code> 개체를 몇 개라도 만들 수 있습니다.</p> +<pre>kenscar = new car("Nissan", "300ZX", 1992); +vpgscar = new car("Mazda", "Miata", 1990); +</pre> +<p>개체는 다른 개체를 속성으로 가질 수 있습니다. 예를 들어, <code>person</code> 개체를 다음과 같이 정의했다고 합시다.</p> +<pre>function person(name, age, sex) { + this.name = name; + this.age = age; + this.sex = sex; +} +</pre> +<p>그리고나서 person 개체의 인스턴스 두 개를 만듭니다.</p> +<pre>rand = new person("Rand McKinnon", 33, "M"); +ken = new person("Ken Jones", 39, "M"); +</pre> +<p>이제 우리는 car가 owner라는 속성으로 <code>person</code> 개체를 가지도록 car의 정의를 바꿀 수 있습니다.</p> +<pre>function car(make, model, year, owner) { + this.make = make; + this.model = model; + this.year = year; + this.owner = owner; +} +</pre> +<p>새 개체 인스턴스를 만들 때 이렇게 쓸 수 있습니다.</p> +<pre>car1 = new car("Eagle", "Talon TSi", 1993, rand); +car2 = new car("Nissan", "300ZX", 1992, ken); +</pre> +<p>위 문장에서 owner 인자로 문자열 상수값이나 정수값을 전달하는 대신 <code>rand</code>와 <code>ken</code>이라는 개체를 전달했다는 사실에 주의하십시오. 이제 car2의 소유자 이름을 알고 싶으면 이런식으로 접근할 수 있습니다.</p> +<pre>car2.owner.name +</pre> +<p>정의된 개체에 아무때나 속성을 추가할 수 있다는 사실을 기억하십시오.</p> +<pre>car1.color = "black" +</pre> +<p>이 문장은 car1에 <code>color</code> 속성을 추가하고 "black"이라는 값을 할당합니다. 그러나 이 문장이 다른 개체에 영향을 미치지는 않습니다. 같은 형식을 가지는 모든 개체에 새 속성을 추가하고 싶으면 car 개체 형식의 정의에 속성을 추가해야 합니다.</p> +<p>{{ PreviousNext("Core_JavaScript_1.5_Guide:Creating_New_Objects:Using_Object_Initializers", "Core_JavaScript_1.5_Guide:Creating_New_Objects:Indexing_Object_Properties") }}</p> diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/using_this_for_object_references/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/using_this_for_object_references/index.html new file mode 100644 index 0000000000..0ed663ae1f --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/using_this_for_object_references/index.html @@ -0,0 +1,25 @@ +--- +title: Using this for Object References +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Creating_New_Objects/Using_this_for_Object_References +--- +<h3 id="this.EB.A5.BC_.EC.82.AC.EC.9A.A9.ED.95.9C_.EA.B0.9C.EC.B2.B4_.EC.B0.B8.EC.A1.B0" name="this.EB.A5.BC_.EC.82.AC.EC.9A.A9.ED.95.9C_.EA.B0.9C.EC.B2.B4_.EC.B0.B8.EC.A1.B0">this를 사용한 개체 참조</h3> +<p>JavaScript에는 <code>this</code>라는 키워드가 있는데, 메소드 안에서 현재 개체를 참조하기 위해서 이 키워드를 사용할 수 있습니다. 예를 들어, 개체의 값 속성을 검증하는 <code>validate</code>라는 함수가 있다고 해봅시다.</p> +<pre>function validate(obj, lowval, hival) { + if ((obj.value < lowval) || (obj.value > hival)) + alert("Invalid Value!"); +} +</pre> +<p>그러면 폼의 각 요소의 <code>onchange</code> 이벤트 핸들러에서 <code>validate</code>를 호출할 때, 다음 예제와 같은 방법으로 this를 사용해서 폼 요소를 <code>validate</code>에 전달할 수 있습니다.</p> +<pre><input type="text" name="age" size="3" + onChange="validate(this, 18, 99)"> +</pre> +<p><code>form</code> 속성과 같이 사용하면, <code>this</code>는 현재 개체의 부모 폼을 참조할 수 있습니다. 다음 예제에서, <code>myForm</code>이라는 폼은 <code>Text</code> 개체와 버튼을 포함하고 있습니다. 사용자가 버튼을 클릭하면 <code>Text</code> 개체의 값을 폼 이름으로 바꿉니다. 버튼의 <code>onclick</code> 이벤트 핸들러에서 부모 폼인 <code>myForm</code>을 참조하기 위해서 <code>this.form</code>을 사용하고 있습니다.</p> +<pre><form name="myForm"> +<p><label>Form name:<input type="text" name="text1" value="Beluga"></label> +<p><input name="button1" type="button" value="Show Form Name" + onclick="this.form.text1.value=this.form.name"> +</p> +</form> +</pre> +<p>{{ PreviousNext("Core_JavaScript_1.5_Guide:Creating_New_Objects:Defining_Methods", "Core_JavaScript_1.5_Guide:Creating_New_Objects:Defining_Getters_and_Setters") }}</p> diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/expressions/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/expressions/index.html new file mode 100644 index 0000000000..d9f8bb0bf9 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/expressions/index.html @@ -0,0 +1,16 @@ +--- +title: Expressions +slug: Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Expressions +--- +<h3 id=".ED.91.9C.ED.98.84.EC.8B.9D" name=".ED.91.9C.ED.98.84.EC.8B.9D"> 표현식 </h3> +<p><i>표현식</i>은 상수(literals), 변수, 연산자 그리고 단일값을 반환하는 계산식(값은 숫자, 문자열, 논리값이 가능)이 알맞게 조합된 집합체다. +</p><p>개념적으로 보면 표현식에는 두가지 타입이 있다: 하나는 변수에 값을 할당하는 것이고 다른 하나는 단순히 값을 가지고 있는 것이다. 예를 들어, x = 7 이라는 표현식은 x 에 7이라는 값을 할당하는 표현식이다. 이 표현식은 스스로 7이라는 값을 부여한다. 이런 표현식들은 <i>할당 연산자</i>를 사용한다. 반면에, 3 + 4 라는 표현식은 단순히 7이라는 값을 계산할 뿐이다; 할당하지 않는다. 이런 표현식에서 사용되는 연산자는 그냥 단순히 <i>연산자</i>라고만 한다. +</p><p>JavaScript에는 다음과 같은 타입의 표현식이 있다: +</p> +<ul><li> 산술형 : 3.14159와 같이 숫자를 표현(evaluate). (일반적으로 <a href="ko/Core_JavaScript_1.5_Guide/Operators/Arithmetic_Operators">산술 연산자</a>를 사용) +</li><li> 문자열형: "Fred"나 "234"와 같이 문자열을 표현(evaluate). (일반적으로 <a href="ko/Core_JavaScript_1.5_Guide/Operators/String_Operators">문자열 연산자</a>를 사용) +</li><li> 논리형: 참(true) 혹은 거짓(false)을 표현(evaluate). (종종 <a href="ko/Core_JavaScript_1.5_Guide/Operators/Logical_Operators">논리 연산자</a>와 함께 사용) +</li><li> 객체형: 객체를 표현(evaluate). (객체표현식에 사용하는 다양한 연산자는 <a href="ko/Core_JavaScript_1.5_Guide/Operators/Special_Operators">특수 연산자</a>를 참고) +</li></ul> +<p>{{ PreviousNext("Core_JavaScript_1.5_Guide:Unicode", "Core_JavaScript_1.5_Guide:Operators") }} +</p>{{ languages( { "en": "en/Core_JavaScript_1.5_Guide/Expressions", "fr": "fr/Guide_JavaScript_1.5/Expressions", "ja": "ja/Core_JavaScript_1.5_Guide/Expressions", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Wyra\u017cenia" } ) }} diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/javascript_overview/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/javascript_overview/index.html new file mode 100644 index 0000000000..310ab25c67 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/javascript_overview/index.html @@ -0,0 +1,44 @@ +--- +title: JavaScript Overview +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/JavaScript_Overview +--- +<h3 id="JavaScript.EB.9E.80_.EB.AC.B4.EC.97.87.EC.9D.B8.EA.B0.80.3F" name="JavaScript.EB.9E.80_.EB.AC.B4.EC.97.87.EC.9D.B8.EA.B0.80.3F">JavaScript란 무엇인가?</h3> +<p>JavaScript는 크로스 플랫폼, 객체 지향 스크립트 언어입니다. JavaScript는 작고, 가벼운 언어입니다; JavaScript는 단독으로 쓰이는 언어로는 유용하지 않지만, 웹 브라우져 같은 다른 제품이나 프로그램에 포함하기 쉽습니다. 호스트 환경에서 JavaScript는 그 환경의 다른 개체(object)들을 프로그램적으로 제어하기 위해서 그들과 연결될 수 있습니다.</p> +<p>기본 JavaScript(core JavaScript)는 <code>Array</code>, <code>Date</code>, <code>Math</code>등 기본이 되는 개체들(core set of objects)과 연산자, 제어 구조, 문장등 언어의 기본 요소들(core set of language elements)을 포함하고 있습니다. 기본 JavaScript는 다른 개체를 추가함으로써 다양한 목적을 위해 확장될 수 있습니다. 예를 들면 다음과 같은 것들입니다.</p> +<ul> <li>"클라이언트쪽 JavaScript"는 브라우저(Navigatore 또는 다른 브라우저들)와 브라우저의 Document Object Model(DOM)을 제어할 수 있는 개체들을 제공함으로써 기본 언어를 확장합니다. 예를 들어, 클라이언트쪽 확장 기능은 응용프로그램이 HTML 폼에 요소를 두어 마우스 클릭이나 폼 입력, 페이지 이동 같은 사용자 이벤트에 반응할 수 있게 합니다.</li> <li>"서버쪽 JavaScript"는 서버에서 JavaScript를 실행하는 데 연관되는 개체들을 제공함으로써 기본 언어를 확장합니다. 예를 들어, 서버쪽 확장 기능은 응용프로그램이 관계형 데이터베이스와 통신할 수 있게 하고, 응용프로그램의 호출들 사이에 연속성을 제공하거나, 서버에서 파일 조작을 수행할 수 있도록 해줍니다.</li> +</ul> +<p>JavaScript의 LiveConnect 기능을 통해서, Java와 JavaScript 코드가 서로 통신할 수 있습니다. JavaScript에서 Java 개체를 초기화하여 개체의 공개 메소드와 필드에 접근할 수 있습니다. Java에서 JavaScript 개체, 속성(property), 메소드에 접근할 수 있습니다.</p> +<p>Netscape가 JavaScript를 개발했고 Netscape 브라우저에서 JavaScript가 가장 먼저 사용되었습니다.</p> +<h3 id="JavaScript.EC.99.80_Java" name="JavaScript.EC.99.80_Java">JavaScript와 Java</h3> +<p>JavaScript 와 Java 는 여러가지 면에서 비슷하지만 본질적으로 다릅니다. JavaScript는 Java 와 공통점이 있지만 Java 처럼 형(type)을 검사하지 않습니다. JavaScript는 Java 문법의 대부분과 제어흐름의 기본적인 개념들을 지원합니다.</p> +<p>Java의 클래스 선언으로 이루어지는 컴파일 타임 시스템에 대조적으로, JavaScript는 수, 불리언, 문자열 값을 나타내는 작은 규모의 자료형에 기반한 런타임 시스템을 지원합니다. JavaScript는 클래스 기반 개체 모델이 아닌 프로토타입 기반(prototype-based) 개체 모델을 갖고 있습니다. 프로토타입 기반 개체 모델은 동적인 상속을 제공합니다. 즉, 각각의 개체를 상속할 수 있는 것입니다. JavaScript는 또 특별히 선언시의 요구사항이 없는 함수도 지원합니다. 함수는 느슨하게 타입된 메소드로 실행됨으로써 개체의 속성이 될 수 있습니다.(Functions can be properties of objects, executing as loosely typed methods.)</p> +<p>Java에 비해 JavaScript는 형식이 자유로운 언어입니다. 모든 변수, 클래스, 메소드들을 꼭 선언 할 필요는 없습니다. 메소드가 public, private, protected 인지 고민해야할 필요가 없고, interface를 구현할 필요도 없습니다. 변수, 매개변수(parameter), 함수의 반환 형식도 명시적으로 지정할 필요가 없습니다.</p> +<p>Java는 클래스 기반 프로그래밍 언어로서, 빠른 실행과 형 안정성(type safety)을 위해 설계되었습니다. 형 안정성이란 예를 들면 Java에서 정수를 개체 참조로 변환할 수 없고, Java 바이트코드에 오류를 일으켜서 사적인(private) 메모리 공간에 접근할 수 없다는 말입니다. 자바의 클래스 기반 모델은 프로그램이 클래스와 클래스의 메소드로만 이루어진다는 의미입니다. Java의 클래스 상속과 엄격한 형 검사(strong typing)는 일반적으로 단단히 결합된 개체의 계층 구조를 필요로 합니다. 이런 요구사항이 JavaScript 프로그래밍에 비해 Java 프로그래밍을 더 복잡하게 만듭니다.</p> +<p>반면 JavaScript는 HyperTalk나 dBASE 같이 적은 줄수의 동적 타입 언어를 계승한 것입니다. 이런 스크립트 언어는 더 많은 사람들을 위한 프로그래밍 도구로서 제공되는데, 이 언어들이 문법이 쉽고, 내장되기에 쉬우며, 개체 생성에 요구 사항이 단순하기 때문입니다.</p> +<table class="fullwidth-table"> <tbody> <tr> <th>JavaScript</th> <th>Java</th> </tr> <tr> <td>개체 지향. 개체의 형식 사이에 구분이 없음. 프로토타입 메커니즘을 통해 상속을 지원하고, 어떤 개체에든지 동적으로 속성과 메소드를 추가할 수 있습니다.</td> <td>클래스 기반. 개체는 클래스 계층 구조를 관통하는 상속을 통해서 클래스와 인스턴스(instance)로 나뉩니다. 클래스와 인스턴스에는 동적으로 속성과 메소드를 추가할 수 없습니다.</td> </tr> <tr> <td>변수의 자료형을 선언하지 않음(동적 형 검사)</td> <td>변수의 자료형을 반드시 선언해야 함(정적 형 검사)</td> </tr> <tr> <td>Cannot automatically write to hard disk.</td> <td>Cannot automatically write to hard disk.</td> </tr> </tbody> +</table> +<p><small><strong>표(Table) 1.1: JavaScript 와 Java 비교</strong></small><br> +<br> +Java와 JavaScript 사이의 차이점에 대해서 더 알고 싶으시면 <a href="/ko/Core_JavaScript_1.5_Guide#.EA.B0.9C.EC.B2.B4_.EB.AA.A8.EB.8D.B8.EC.9D.98_.EC.83.81.EC.84.B8_.EB.82.B4.EC.9A.A9" title="ko/Core_JavaScript_1.5_Guide#.EA.B0.9C.EC.B2.B4_.EB.AA.A8.EB.8D.B8.EC.9D.98_.EC.83.81.EC.84.B8_.EB.82.B4.EC.9A.A9">개체 모델의 상세 내용</a>을 보시기 바랍니다.</p><h3 id="JavaScript.EC.99.80_ECMAScript_.EB.AA.85.EC.84.B8" name="JavaScript.EC.99.80_ECMAScript_.EB.AA.85.EC.84.B8">JavaScript와 ECMAScript 명세</h3> +<p>Netscape가 JavaScript를 개발했고, Netscape 브라우저에서 가장 처음으로 사용되었습니다. 그러나 <a class="external" href="http://www.ecma-international.org/">Ecma International</a> - 정보와 통신 시스템을 표준화하기 위한 유럽 기구(공식적으로 ECMA - the European Computer Manufacturers Association으로 알려짐) - 과 Netscape가 공동으로 작업하여 기본 JavaScript에 기반하여 표준화되고 국제적인 프로그래밍 언어를 만들어냈습니다. JavaScript의 표준화된 버전은 ECMAScript라고 부르고, 표준을 지원하는 응용프로그램에서는 모두 동일하게 동작합니다. 회사들은 그들의 JavaScript 구현을 개발하기 위해서 공개된 표준 언어를 사용할 수 있습니다. ECMAScript 표준은 ECMA-262 명세에 문서화되어 있습니다.</p> +<p>ECMA-262 표준은 <a class="external" href="http://www.iso.ch/">ISO</a> (International Organization for Standardization, 국제 표준화기구)의 승인을 받아 ISO-16262가 되었습니다. Mozilla 웹사이트에서 <a class="external" href="http://www.mozilla.org/js/language/E262-3.pdf">ECMA-262의 PDF 문서</a>를 얻을 수 있습니다. <a class="external" href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">the Ecma International 웹사이트</a> 에서도 명세를 찾을 수 있습니다. ECMAScript 명세는 <a class="external" href="http://www.w3.org/">World Wide Web Consortium (W3C)</a>에서 표준화 한 Document Object Model(DOM)에 대해서는 설명하지 않습니다. DOM은 HTML 문서 개체들이 스크립트에 노출되는 방식을 정의합니다.</p> +<h4 id="JavaScript_.EB.B2.84.EC.A0.84.EA.B3.BC_ECMAScript_.ED.8C.90.EB.B3.B8_.EC.82.AC.EC.9D.B4.EC.9D.98_.EA.B4.80.EA.B3.84" name="JavaScript_.EB.B2.84.EC.A0.84.EA.B3.BC_ECMAScript_.ED.8C.90.EB.B3.B8_.EC.82.AC.EC.9D.B4.EC.9D.98_.EA.B4.80.EA.B3.84">JavaScript 버전과 ECMAScript 판본 사이의 관계</h4> +<p>Netscape는 ECMA와 밀접하게 작업하여 ECMAScript Specification(ECMA-262)를 만들었습니다. JavaScript 버전과 ECMAScript 판본(edition)들 사이의 관계가 아래 표에 설명되어 있습니다.</p> +<table class="fullwidth-table"> <tbody> <tr> <th>JavaScript 버전</th> <th>ECMAScript 판본과의 관계</th> </tr> <tr> <td>JavaScript 1.1</td> <td>ECMA-262, 1판은 JavaScript 1.1에 기초합니다.</td> </tr> <tr> <td>JavaScript 1.2</td> <td>JavaScript 1.2가 발표됐을 때 ECMA-262가 아직 완성되지 않았습니다. 다음과 같은 이유때문에 JavaScript 1.2는 ECMA-262 1판과 완벽하게 호환되지 않습니다. <ul> <li>Netscape는 JavaScript 1.2에 몇 가지 기능을 추가했으나, ECMA-262에서 고려하지 못했습니다.</li> <li>ECMA-262는 두 가지 새 기능을 추가했습니다. 유니코드를 이용한 국제화, 모든 플랫폼에서의 동일한 동작. Date 개체 같은 JavaScript 1.2의 몇 가지 기능이 플랫폼에 의존적이었습니다.</li> </ul> </td> </tr> <tr> <td> <p>JavaScript 1.3</p> </td> <td> <p>JavaScript 1.3은 ECMA-262 1판과 완벽하게 호환됩니다.</p> <p>JavaScript 1.3은 ==와 !=연산자를 제외하고는 JavaScript 1.2의 추가적인 기능을 그대로 유지하면서 JavaScript 1.2가 ECMA-262와 어긋나던 점들을 해결했습니다. ==, != 연산자는 ECMA-262에 맞추기 위해 수정되었습니다.</p> </td> </tr> <tr> <td> <p>JavaScript 1.4</p> </td> <td> <p>JavaScript 1.4는 ECMA-262 1판과 완벽하게 호환됩니다.</p> <p>JavaScript 1.4가 발표되었을 때 ECMAScript 명세의 세 번째 버전이 아직 완성되지 않았습니다.</p> </td> </tr> <tr> <td>JavaScript 1.5</td> <td>JavaScript 1.5는 ECMA-262 3판과 완벽하게 호환됩니다.</td> </tr> </tbody> +</table> +<p><small><strong>표 1.2: JavaScript 버전과 ECMAScript 판본</strong></small><br> +<br> +참고: ECMA-262 2판은 1판에 편집상 사소한 변경과 버그 수정을 가한 판본입니다. 현재 ECMA의 TC39 워킹그룹에서 ECMAScript 4판을 작업하고 있습니다. 4판은 JavaScript 2.0과 대응될 것입니다.</p> +<p><a href="/ko/Core_JavaScript_1.5_Guide" title="ko/Core_JavaScript_1.5_Guide">JavaScript 기본 레퍼런스</a>에서 ECMAScript 호환 기능을 보여줍니다.</p> +<p>JavaScript는 항상 ECMAScript Specification에 포함되지 않은 기능들을 포함할 것입니다. JavaScript는 추가적인 기능을 제공하지만 ECMAScript와 호환됩니다.</p> +<h4 id="JavaScript_.EB.AC.B8.EC.84.9C_vs_ECMAScript_.EB.AA.85.EC.84.B8.EC.84.9C" name="JavaScript_.EB.AC.B8.EC.84.9C_vs_ECMAScript_.EB.AA.85.EC.84.B8.EC.84.9C">JavaScript 문서 vs ECMAScript 명세서</h4> +<p>ECMAScript 명세는 ECMAScript를 구현하는데 필요한 요구사항을 모아놓은 것입니다. 이것은 우리가 JavaScript의 한 기능이 다른 ECMAScript 구현에서도 지원될 것인지 결정하는데 유용합니다. ECMAScript에서 지원하는 기능만을 사용하는 JavaScript 코드를 작성할 계획이라면 ECMAScript 명세를 살펴볼 필요가 있을 것입니다.</p> +<p>ECMAScript 문서는 스크립트 프로그래머를 돕기위해 작성된 것이 아닙니다. 스크립트 작성에 대한 정보를 얻으려면 JavaScript 문서를 보십시오.</p> +<h4 id="JavaScript.EC.99.80_ECMAScript_.EC.9A.A9.EC.96.B4" name="JavaScript.EC.99.80_ECMAScript_.EC.9A.A9.EC.96.B4">JavaScript와 ECMAScript 용어</h4> +<p>ECMAScript 명세는 JavaScript 프로그래머에게는 친숙하지 않은 용어와 문법을 사용하여 작성되었습니다. 비록 ECMAScript의 언어 설명이 다르긴 하지만 언어는 똑같습니다. JavaScript는 ECMAScript 명세에서 설명하는 모든 기능을 지원합니다.</p> +<p>JavaScript 문서는 JavaScript 프로그래머에게 적당한 언어의 측면을 설명합니다. 예를 들면 이렇습니다.</p> +<ul> <li>전역 개체(Global Object)는 JavaScript 문서에서는 논의되지 않는데, 그것은 우리가 그 개체를 직접 사용할 일이 없기 때문입니다. 전역 개체에서 우리가 사용할 만한 메소드와 속성은 JavaScript 문서에서 논의되고 있기는 하지만 최상위(top-level) 함수와 속성이라고 부릅니다.</li> <li>JavaScript 문서에서 매개변수가 없는 <code>Number</code>와 <code>String</code> 개체 생성자는 논의되지 않고 있는데, 그것은 거의 사용할 일이 없기 때문입니다. <code>Number</code>의 인자없는 생성자는 +0을 반환하고, <code>String</code>의 인자없는 생성자는 ""(빈 문자열)을 반환합니다.</li> +</ul> +<p>{{ PreviousNext("Core_JavaScript_1.5_Guide:About", "Core_JavaScript_1.5_Guide:Values") }}</p> +<p>{{ languages( { "en": "en/Core_JavaScript_1.5_Guide/JavaScript_Overview", "fr": "fr/Guide_JavaScript_1.5/Aper\u00e7u_de_JavaScript", "ja": "ja/Core_JavaScript_1.5_Guide/JavaScript_Overview", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Podgl\u0105d_JavaScriptu" } ) }}</p> diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/literals/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/literals/index.html new file mode 100644 index 0000000000..dfaff2c586 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/literals/index.html @@ -0,0 +1,174 @@ +--- +title: Literals +slug: Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Literals +translation_of: Web/JavaScript/Guide/Grammar_and_types +--- +<h3 id=".EC.83.81.EC.88.98.EA.B0.92.28Literal.29" name=".EC.83.81.EC.88.98.EA.B0.92.28Literal.29">상수값(Literal)</h3> +<p>JavaScript에서 값을 표현하기 위해 상수값을 사용할 수 있습니다. 그것은 변수가 아니라 고정된 값으로서 "문자 그대로(literally)" 스크립트에 값을 제공하는 것입니다. 이 절에서 다음과 같은 상수값에 대해서 설명하겠습니다.</p> +<ul> + <li>{{ Anch("배열 상수값") }}</li> + <li>{{ Anch("불리언 상수값") }}</li> + <li>{{ Anch("소수 상수값") }}</li> + <li>{{ Anch("정수") }}</li> + <li>{{ Anch("개체 상수값") }}</li> + <li>{{ Anch("문자열 상수값") }}</li> +</ul> +<h4 id=".EB.B0.B0.EC.97.B4_.EC.83.81.EC.88.98.EA.B0.92" name=".EB.B0.B0.EC.97.B4_.EC.83.81.EC.88.98.EA.B0.92">배열 상수값</h4> +<p>배열 상수값은 대괄호([])안에 배열의 원소(element)를 0개 이상 나열한 것입니다. 배열 상수값으로 배열을 만드면 배열은 지정된 원소를 가지도록 초기화되고, 지정된 원소의 개수만큼의 길이를 갖게 됩니다.</p> +<p>다음 예제는 세 개의 원소를 가지고 길이가 3인 <code>coffees</code> 배열을 만드는 예제입니다.</p> +<pre>coffees = ["French Roast", "Colombian", "Kona"]</pre> +<p><b>참고</b> 배열 상수값은 개체 초기화지정자(object initializer) 중의 하나입니다. <a href="ko/Core_JavaScript_1.5_Guide/Creating_New_Objects/Using_Object_Initializers">개체 초기화지정자 사용하기</a>를 보십시오.</p> +<p>최상위 스크립트에서 상수값을 이용하여 배열을 만들면 JavaScript는 배열 상수값을 포함하는 표현식을 평가(evaluate)할 때마다 배열을 만듭니다. 또한, 함수 안에서 사용된 상수값은 함수가 호출될 때마다 생성됩니다.</p> +<p>배열 상수값은 Array 개체입니다. Array 개체에 대한 상세한 내용은 <a href="ko/Core_JavaScript_1.5_Guide/Predefined_Core_Objects/Array_Object">Array 개체</a>를 보십시오.</p> +<p><b>배열 상수값의 추가적인 쉼표</b></p> +<p>배열 상수값에 모든 원소를 지정할 필요는 없습니다. 쉼표만 찍어 두면 값이 할당되지 않은 빈 공간을 가진 배열이 만들어집니다. 다음 예제는 <code>fish</code> 배열을 만듭니다.</p> +<pre>fish = ["Lion", , "Angel"]</pre> +<p>이 배열은 값을 가진 원소 두 개와 빈 원소 하나를 갖게됩니다. (<code>fish{{ mediawiki.external(0) }}</code>은 "Lion", <code>fish{{ mediawiki.external(1) }}</code>은 <code>undefined</code>, <code>fish{{ mediawiki.external(2) }}</code>는 "Angel"이라는 값을 가집니다.)</p> +<p>원소 목록 끝에 남겨둔 쉼표는 무시됩니다. 다음 예제에서 배열 길이는 3입니다. <code>myList{{ mediawiki.external(3) }}</code>은 만들어지지 않습니다. 그외에 목록에 있는 다른 쉼표들은 각각 새로운 원소를 나타냅니다.</p> +<pre>myList = ['home', , 'school', ];</pre> +<p>다음 예제에서 배열 길이는 4이고, <code>myList{{ mediawiki.external(0) }}</code>과 <code>myList{{ mediawiki.external(2) }}</code>는 비게 됩니다.</p> +<pre>myList = [ , 'home', , 'school'];</pre> +<p>다음 예제에서 배열 길이는 4이고 <code>myList{{ mediawiki.external(1) }}</code>과 <code>myList{{ mediawiki.external(3) }}</code>이 비게 됩니다. 오직 마지막 쉼표만 무시됩니다.</p> +<pre>myList = ['home', , 'school', , ];</pre> +<h4 id=".EB.B6.88.EB.A6.AC.EC.96.B8_.EC.83.81.EC.88.98.EA.B0.92" name=".EB.B6.88.EB.A6.AC.EC.96.B8_.EC.83.81.EC.88.98.EA.B0.92">불리언 상수값</h4> +<p>불리언 형은 두 가지 상수값을 가질 수 있는데, 그것은 <code>true</code>와 <code>false</code>입니다.</p> +<p><code>true</code>, <code>false</code>라는 기본(primitive) 불리언 값과 true, false 값의 불리언 개체를 혼동하지 마십시오. 불리언 개체는 기본 불리언 데이터 형을 감싸는 역할을 할 뿐입니다. 더 많은 정보는 <a href="ko/Core_JavaScript_1.5_Guide/Predefined_Core_Objects/Boolean_Object">불리언 개체</a>를 참조하십시오.</p> +<h4 id=".EC.A0.95.EC.88.98" name=".EC.A0.95.EC.88.98">정수</h4> +<p>10진수, 16진수, 8진수 정수를 쓸 수 있습니다. 10진수 정수 상수값은 0(영)으로 시작하지 않는 숫자의 나열입니다. 0(영)으로 시작하는 정수 상수값은 8진수입니다. 0x(또는 0X)로 시작하면 16진수입니다. 16진수는 0부터 9까지의 숫자와 a부터 f나 A부터 F까지의 문자를 포함할 수 있습니다. 8진수에는 0부터 7까지만 쓸 수 있습니다.</p> +<p>8진수 정수 상수값은 사용하지 말기를 추천하고 있으며, ECMA-262 표준 3판에서는 아예 제거되었습니다. 하위 호환성을 위해 JavaScript 1.5에서는 여전히 8진수 정수 상수값을 지원하고 있습니다.</p> +<p>몇 가지 정수 상수값을 예를 보여드리겠습니다.</p> +<pre class="eval">0, 117, -345 (10진수) +015, 0001, -077 (8진수) +0x1123, 0x00111, -0xF1A7 (16진수 또는 "hex") +</pre> +<h4 id=".EC.86.8C.EC.88.98_.EC.83.81.EC.88.98.EA.B0.92" name=".EC.86.8C.EC.88.98_.EC.83.81.EC.88.98.EA.B0.92">소수 상수값</h4> +<p>소수 상수값은 이런 부분으로 이뤄집니다.</p> +<ul> + <li>부호를 가질 수 있는(즉, "+"나 "-"로 시작할 수 있는) 10진수 정수,</li> + <li>소수점("."),</li> + <li>소수 부분(10진수),</li> + <li>지수 부분</li> +</ul> +<p>지수 부분은 "e"나 "E" 뒤에 숫자가 붙은 형태입니다. 숫자 앞에는 부호("+"나 "-")를 붙일 수도 있습니다. 소수 상수값은 적어도 하나의 숫자에 소수점 또는 지수 부분을 가져야 합니다.</p> +<p>소수 상수값의 몇 가지 예제를 보여드리겠습니다. 3.1415, -3.1E12, .1e12, 2E-12</p> +<h4 id=".EA.B0.9C.EC.B2.B4_.EC.83.81.EC.88.98.EA.B0.92" name=".EA.B0.9C.EC.B2.B4_.EC.83.81.EC.88.98.EA.B0.92">개체 상수값</h4> +<p>개체 상수값은 중괄호({}) 안에 특성(property) 이름과 그에 해당하는 값의 쌍을 나열한 것입니다. 문장(statement)의 시작 부분에 개체 상수값을 사용해서는 안됩니다. { 가 블럭의 시작을 나타내기 때문에, 에러가 나거나 의도하지 않은 동작을 보일 것입니다.</p> +<p>다음은 개체 상수값의 예입니다. <code>car</code> 개체의 첫 번째 원소는 <code>myCar</code>라는 특성을 정의하고 있습니다. 두 번째 원소는 <code>getCar</code> 특성을 정의하는데, <code>(CarTypes("Honda"));</code>라는 함수를 호출하고 있습니다. 세 번째 원소는 <code>special</code> 특성을 정의하는데에 <code>Sales</code>라는 변수를 사용합니다.</p> +<pre>var Sales = "Toyota"; + +function CarTypes(name) { + if(name == "Honda") + return name; + else + return "Sorry, we don't sell " + name + "."; +} + +car = {myCar: "Saturn", getCar: CarTypes("Honda"), special: Sales} + +document.write(car.myCar); // Saturn +document.write(car.getCar); // Honda +document.write(car.special); // Toyota</pre> +<p>개체 특성 이름에 정수 상수값이나 문자열 상수값을 사용할 수 있고, 개체 안에 다른 개체를 포함시킬 수도 있습니다. 다음 예제를 보십시오.</p> +<pre>car = {manyCars: {a: "Saab", b: "Jeep"}, 7: "Mazda"} + +document.write(car.manyCars.b); // Jeep +document.write(car[7]); // Mazda +</pre> +<p>다음 사항을 참고하십시오.</p> +<pre class="eval">foo = {a: "alpha", 2: "two"} +document.write (foo.a) // alpha +document.write (foo[2]) // two +//document.write (foo.2) // Error: missing ) after argument list +//document.write (foo[a]) // Error: a is not defined +document.write (foo["a"]) // alpha +document.write (foo["2"]) // two +</pre> +<h4 id=".EB.AC.B8.EC.9E.90.EC.97.B4_.EC.83.81.EC.88.98.EA.B0.92" name=".EB.AC.B8.EC.9E.90.EC.97.B4_.EC.83.81.EC.88.98.EA.B0.92">문자열 상수값</h4> +<p>문자열 상수값은 큰따옴표(")나 작은따옴표(')로 둘러싸인 0개 이상의 문자들 입니다. 문자열은 같은 종류의 따옴표로 묶어야 합니다. 즉, 작은따옴표 둘로 묶거나, 큰따옴표 둘로 묶어야 한다는 말입니다. 문자열 상수값의 예를 보여드리겠습니다.</p> +<ul> + <li>"blah"</li> + <li>'blah'</li> + <li>"1234"</li> + <li>"one line \n another line"</li> + <li>"John's cat"</li> +</ul> +<p>우 리는 문자열 상수값에 String 개체의 모든 메소드를 호출할 수 있습니다. JavaScript는 자동으로 문자열 상수값을 임시 String 개체로 만들어서 메소드를 호출한 후, 임시 String 개체를 제거합니다. 문자열 상수값에 <code>String.length</code> 특성을 사용할 수도 있습니다. 이렇게 말입니다.</p> +<ul> + <li>"John's cat".length</li> +</ul> +<p>우리가 특별하게 String 개체를 필요로 하는 경우가 아니라면 문자열 상수값을 사용해야만 합니다. String 개체에 대한 자세한 내용은 <a href="ko/Core_JavaScript_1.5_Guide/Predefined_Core_Objects/String_Object">String 개체</a>를 보십시오.</p> +<h5 id=".EB.AC.B8.EC.9E.90.EC.97.B4.EC.97.90.EC.84.9C_.ED.8A.B9.EC.88.98.EB.AC.B8.EC.9E.90_.EC.82.AC.EC.9A.A9.ED.95.98.EA.B8.B0" name=".EB.AC.B8.EC.9E.90.EC.97.B4.EC.97.90.EC.84.9C_.ED.8A.B9.EC.88.98.EB.AC.B8.EC.9E.90_.EC.82.AC.EC.9A.A9.ED.95.98.EA.B8.B0">문자열에서 특수문자 사용하기</h5> +<p>다음 예제에서 볼 수 있듯이 일반적인 문자뿐만 아니라 특수문자도 문자열에 쓸 수 있습니다.</p> +<pre>"one line \n another line"</pre> +<p>JavaScript 문자열에 사용할 수 있는 특수문자를 표로 나타낸 것입니다.</p> +<table class="fullwidth-table"> + <tbody> + <tr> + <th>문자</th> + <th>의미</th> + </tr> + <tr> + <td>\b</td> + <td>Backspace</td> + </tr> + <tr> + <td>\f</td> + <td>Form feed</td> + </tr> + <tr> + <td>\n</td> + <td>New line</td> + </tr> + <tr> + <td>\r</td> + <td>Carriage return</td> + </tr> + <tr> + <td>\t</td> + <td>Tab</td> + </tr> + <tr> + <td>\v</td> + <td>Vertical tab</td> + </tr> + <tr> + <td>\'</td> + <td>Apostrophe or single quote</td> + </tr> + <tr> + <td>\"</td> + <td>Double quote</td> + </tr> + <tr> + <td>\\</td> + <td>Backslash character (\).</td> + </tr> + <tr> + <td>\<i>XXX</i></td> + <td>세 자리 까지의 8진수 "XXX"로 지정하는 Latin-1 인코딩의 문자. 0부터 377 사이. 예를 들어, \251은 저작권 기호의 8진수 표현입니다.</td> + </tr> + <tr> + <td>\x<i>XX</i></td> + <td>두 자리 까지의 16진수 "XX"로 지정하는 Latin-1 인코딩의 문자. 00부터 FF 사이. 예를 들어, \xA9는 저작권 기호의 16진수 표현입니다.</td> + </tr> + <tr> + <td>\u<i>XXXX</i></td> + <td>네 자리의 16진수 "XXXX"로 지정하는 유니코드 문자. 예를 들어, \u00A9는 저작권 기호의 유니코드 표현입니다. <a href="ko/Core_JavaScript_1.5_Guide/Unicode#.EC.9C.A0.EB.8B.88.EC.BD.94.EB.93.9C_.EC.9D.B4.EC.8A.A4.EC.BC.80.EC.9D.B4.ED.94.84_.EC.8B.9C.ED.80.80.EC.8A.A4">유니코드 이스케이프 시퀀스</a>를 보십시오.</td> + </tr> + </tbody> +</table> +<p><small><b>표 2.1: JavaScript 특수문자</b></small></p> +<h5 id=".EB.AC.B8.EC.9E.90_.EC.9D.B4.EC.8A.A4.EC.BC.80.EC.9D.B4.ED.94.84" name=".EB.AC.B8.EC.9E.90_.EC.9D.B4.EC.8A.A4.EC.BC.80.EC.9D.B4.ED.94.84">문자 이스케이프</h5> +<p>표 2.1에 없는 문자에 대해서는 역슬래시가 무시됩니다. 그러나 이러한 기능은 사용하지 않기를 권장하므로 사용을 피해야만 합니다.</p> +<p>역슬래시를 앞에 붙이면 문자열 안에 따옴표를 넣을 수 있습니다. 이것은 따옴표 "이스케이프(escaping)"라고 알려져 있습니다.</p> +<pre>var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service." +document.write(quote) +</pre> +<p>이 코드의 결과는 다음과 같습니다.</p> +<pre>He read "The Cremation of Sam McGee" by R.W. Service. +</pre> +<p>문자열 안에 역슬래시 문자를 넣고 싶으면 역슬래시 문자를 이스케이프시켜야 합니다. 예를 들어, <code>c:\temp</code> 라는 경로를 문자열에 할당하고 싶으면 다음과 같이 하면 됩니다.</p> +<pre>var home = "c:\\temp" +</pre> +<p>{{ PreviousNext("Core_JavaScript_1.5_Guide:Constants", "Core_JavaScript_1.5_Guide:Unicode") }}</p> +<p>{{ languages( { "en": "en/Core_JavaScript_1.5_Guide/Literals", "fr": "fr/Guide_JavaScript_1.5/Constantes_litt\u00e9rales", "ja": "ja/Core_JavaScript_1.5_Guide/Literals", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Litera\u0142y" } ) }}</p> diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/objects_and_properties/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/objects_and_properties/index.html new file mode 100644 index 0000000000..abe9ff83f4 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/objects_and_properties/index.html @@ -0,0 +1,39 @@ +--- +title: Objects and Properties +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Objects_and_Properties +--- +<h3 id=".EA.B0.9D.EC.B2.B4.EC.99.80_.EC.86.8D.EC.84.B1" name=".EA.B0.9D.EC.B2.B4.EC.99.80_.EC.86.8D.EC.84.B1"> 객체와 속성 </h3> +<p>자바스크립트 객체는 객체를 구성하는 속성을 가지고 있습니다. 속성에는 간단한 방법으로 접근할 수 있습니다.: +</p> +<pre>객체이름.속성이름 +</pre> +<p>객체 이름과 속성 이름 두 가지 모두에 대해 알기쉬운 예가 있습니다. 속성은 값을 지정하여 정의합니다. 예를 들어 <code>myCar</code>라는 객체가 있다면(객체가 이미 존재한다고 가정합니다.), <code>make</code>, <code>model</code>, <code>year</code>라는 속성에 다음과 같이 값을 지정할 수 있습니다. +</p> +<pre>myCar.make = "Ford"; +myCar.model = "Mustang"; +myCar.year = 1969; +</pre> +<p>배열은 한 가지 변수 이름으로 결합되어 있는 연속된 값의 집합입니다. 자바스크립트에서 속성과 배열은 밀접한 관련이 있습니다; 말하자면 그 두 가지는 같은 데이터 구조에 다른 인터페이스라는 뜻입니다. 예를 들면 <code>myCar</code> 객체에 다음과 같이 접근할 수도 있습니다: +</p> +<pre>myCar["make"] = "Ford"; +myCar["model"] = "Mustang"; +myCar["year"] = 1967; +</pre> +<p>이러한 배열의 종류는 <i>연관 배열</i>이라고 부릅니다. 왜냐하면 각각의 인덱스 요소가 문자열 값과 연관되어 있기 때문입니다. 이러한 방식에 대한 설명은 다음의 함수에 객체와 객체의 이름을 입력했을 때 객체의 속성을 표시해주는 다음과 같은 함수에서 알아볼 수 있습니다: +</p> +<pre>function show_props(obj, obj_name) { + var result = ""; + for (var i in obj) + result += obj_name + "." + i + " = " + obj[i] + "\n"; + return result; +} +</pre> +<p>결과적으로 <code>call show_props(myCar, "myCar")</code>라는 함수 호출은 다음과 같은 값을 반환합니다: +</p> +<pre>myCar.make = Ford +myCar.model = Mustang +myCar.year = 1967 +</pre> +<p>{{ PreviousNext("Core_JavaScript_1.5_Guide:Predefined_Functions:escape_and_unescape_Functions", "Core_JavaScript_1.5_Guide:Creating_New_Objects") }} +</p>{{ languages( { "fr": "fr/Guide_JavaScript_1.5/Objets_et_propri\u00e9t\u00e9s", "ja": "ja/Core_JavaScript_1.5_Guide/Objects_and_Properties", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Obiekty_i_w\u0142a\u015bciwo\u015bci" } ) }} diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/arithmetic_operators/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/arithmetic_operators/index.html new file mode 100644 index 0000000000..ce55c0e3f2 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/arithmetic_operators/index.html @@ -0,0 +1,44 @@ +--- +title: Arithmetic Operators +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Operators/Arithmetic_Operators +translation_of: Web/JavaScript/Guide/Expressions_and_Operators +--- +<h3 id=".EC.82.B0.EC.88.A0_.EC.97.B0.EC.82.B0.EC.9E.90" name=".EC.82.B0.EC.88.A0_.EC.97.B0.EC.82.B0.EC.9E.90"> 산술 연산자 </h3> +<p>산술 연산자는 수(상수값이든지 변수든지)를 받아서 하나의 수를 반환합니다. 표준 산술 연산자는 더하기(+), 빼기(-), 곱하기(*), 나누기(/)입니다. 이 연산자들은 대부분의 다른 프로그래밍 언어에서 처럼 동작합니다. 예외적으로 / 연산자는 JavaScript에서 소수를 반환합니다. C나 Java 같은 다른 언어에서는 / 연산자가 소수 부분은 잘라버립니다. 예를 들면 이렇습니다. +</p> +<pre>1/2 //returns 0.5 in JavaScript +1/2 //returns 0 in Java +</pre> +<p>JavaScript는 다음 표에 나오는 산술 연산자를 제공합니다. +</p> +<table class="fullwidth-table"> +<tbody><tr> +<th>연산자</th> +<th>설명</th> +<th>예제</th> +</tr> +<tr> +<td>%<br>(나머지)</td> +<td>2항(binary) 연산자. 두 피연산자의 나눗셈에서 나온 나머지를 반환합니다.</td> +<td>12 % 5 returns 2.</td> +</tr> +<tr> +<td>++<br>(증가)</td> +<td>단항(unary) 연산자. 피연산자에 1을 더함. 전위 연산자(++x)를 사용하면 피연산자에 1을 더한 후 그 값을 반환합니다. 후위 연산자(x++)를 사용하면 피연산자에 1을 더하기 전에 피연산자의 값을 반환합니다.</td> +<td><code>x</code>가 3일 때, <code>++x</code>는 <code>x</code>를 4로 만들고 4를 반환합니다. 반면 <code>x++</code>는 <code>x</code>를 4로 만들고 3을 반환합니다.</td> +</tr> +<tr> +<td>--<br>(감소)</td> +<td>단항 연산자. 피연산자에서 1을 뺌. 반환값은 증가 연산자와 동일한 방식으로 결정됩니다.</td> +<td><code>x</code>가 3일 때, <code>--x</code>는 <code>x</code>를 2로 만들고 2를 반환합니다. 반면 <code>x--</code>는 <code>x</code>를 2로 만들고 3을 반환합니다.</td> +</tr> +<tr> +<td>-<br>(단항 부정)</td> +<td>단항 연산자. 피연산자의 부호를 바꾼 값을 반환합니다.</td> +<td><code>x</code>가 3이면 <code>-x</code>는 -3을 반환합니다.</td> +</tr> +</tbody></table> +<p><small><b>표 3.4: 산술 연산자</b></small> +</p><p>{{ PreviousNext("Core_JavaScript_1.5_Guide:Operators:Comparison_Operators", "Core_JavaScript_1.5_Guide:Operators:Bitwise_Operators") }} +</p>{{ languages( { "en": "en/Core_JavaScript_1.5_Guide/Operators/Arithmetic_Operators", "fr": "fr/Guide_JavaScript_1.5/Op\u00e9rateurs/Op\u00e9rateurs_arithm\u00e9tiques", "ja": "ja/Core_JavaScript_1.5_Guide/Operators/Arithmetic_Operators", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Operatory/Operatory_arytmetyczne" } ) }} diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/assignment_operators/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/assignment_operators/index.html new file mode 100644 index 0000000000..dbc284f12f --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/assignment_operators/index.html @@ -0,0 +1,62 @@ +--- +title: Assignment Operators +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Operators/Assignment_Operators +--- +<h3 id=".ED.95.A0.EB.8B.B9_.EC.97.B0.EC.82.B0.EC.9E.90" name=".ED.95.A0.EB.8B.B9_.EC.97.B0.EC.82.B0.EC.9E.90">할당 연산자</h3> +<p>할당 연산자는 왼쪽 피연산자에 오른쪽 피연산자의 값을 할당합니다. 가장 기본적인 할당 연산자에는 등호(=)가 있는데, 왼쪽 피연산자의 값을 오른쪽 연산자에 할당합니다. 즉, x = y 라고 하면 y의 값이 x에 할당되는 것입니다.</p> +<p>다른 할당 연산자는 다음 표에서 보듯이 표준연산을 약식으로 쓰는 것입니다.</p> +<table class="fullwidth-table"> + <tbody> + <tr> + <th>약식 연산자</th> + <th>의미</th> + </tr> + <tr> + <td>x += y</td> + <td>x = x + y</td> + </tr> + <tr> + <td>x -= y</td> + <td>x = x - y</td> + </tr> + <tr> + <td>x *= y</td> + <td>x = x * y</td> + </tr> + <tr> + <td>x /= y</td> + <td>x = x / y</td> + </tr> + <tr> + <td>x %= y</td> + <td>x = x % y</td> + </tr> + <tr> + <td>x <<= y</td> + <td>x = x << y</td> + </tr> + <tr> + <td>x >>= y</td> + <td>x = x >> y</td> + </tr> + <tr> + <td>x >>>= y</td> + <td>x = x >>> y</td> + </tr> + <tr> + <td>x &= y</td> + <td>x = x & y</td> + </tr> + <tr> + <td>x ^= y</td> + <td>x = x ^ y</td> + </tr> + <tr> + <td>x |= y</td> + <td>x = x | y</td> + </tr> + </tbody> +</table> +<p><small><b>표: 할당 연산자</b></small></p> +<p>{{ PreviousNext("Core_JavaScript_1.5_Guide:Operators", "Core_JavaScript_1.5_Guide:Operators:Comparison_Operators") }}</p> diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/bitwise_operators/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/bitwise_operators/index.html new file mode 100644 index 0000000000..860e6787e9 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/bitwise_operators/index.html @@ -0,0 +1,101 @@ +--- +title: Bitwise Operators +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Operators/Bitwise_Operators +translation_of: Web/JavaScript/Guide/Expressions_and_Operators +--- +<p><br> +</p> +<h3 id=".EB.B9.84.ED.8A.B8_.EC.97.B0.EC.82.B0.EC.9E.90" name=".EB.B9.84.ED.8A.B8_.EC.97.B0.EC.82.B0.EC.9E.90"> 비트 연산자 </h3> +<p>비트 연산자는 피연산자를 10진수나 16진수, 8진수로 다루지 않고 32개의 비트 집합으로 다룹니다. 예를 들어, 10진수 9는 2진수로 1001입니다. 비트 연산자는 2진수 표현으로 연산을 하지만 반환값은 JavaScript 표준 수 값으로 반환합니다. +</p><p>JavaScript의 비트 연산자를 다음 표에 요약했습니다. +</p> +<table class="fullwidth-table"> +<tbody><tr> +<th>연산자</th> +<th>사용법</th> +<th>설명</th> +</tr> +<tr> +<td>비트 AND</td> +<td><code>a & b</code></td> +<td>두 피연산자의 대응되는 비트가 모두 1이면 1을 반환.</td> +</tr> +<tr> +<td>비트 OR</td> +<td><code>a | b</code></td> +<td>두 피연산자의 대응되는 비트에서 둘 중 하나가 1이거나 모두 1인 경우 1을 반환.</td> +</tr> +<tr> +<td>비트 XOR</td> +<td><code>a ^ b</code></td> +<td>두 피연산자의 대응되는 비트에서 둘 중 하나가 1이고, 둘 다 1이 아닐 경우 1을 반환.</td> +</tr> +<tr> +<td>비트 NOT</td> +<td><code>~ a</code></td> +<td>피연산자의 비트를 뒤집음.</td> +</tr> +<tr> +<td>왼쪽으로 이동</td> +<td><code>a << b</code></td> +<td>a의 2진수 표현을 b 비트만큼 왼쪽으로 이동함. 오른쪽은 0으로 채움.</td> +</tr> +<tr> +<td>부호 비트로 채우는 오른쪽 이동</td> +<td><code>a >> b</code></td> +<td>a의 2진수 표현을 b 비트만큼 오른쪽으로 이동함. 오른쪽 남는 비트는 버림.</td> +</tr> +<tr> +<td>0으로 채우는 오른쪽 이동</td> +<td><code>a >>> b</code></td> +<td>a의 2진수 표현을 b 비트만큼 오른쪽으로 이동함. 오른쪽 남는 비트는 버리고, 왼쪽은 0으로 채움.</td> +</tr> +</tbody></table> +<p><small><b>표 3.5: 비트 연산자</b></small> +</p> +<h4 id=".EB.B9.84.ED.8A.B8_.EB.85.BC.EB.A6.AC_.EC.97.B0.EC.82.B0.EC.9E.90" name=".EB.B9.84.ED.8A.B8_.EB.85.BC.EB.A6.AC_.EC.97.B0.EC.82.B0.EC.9E.90"> 비트 논리 연산자 </h4> +<p>개념적으로 비트 논리 연산자는 다음과 같이 동작합니다. +</p> +<ul><li> 피연산자는 32비트 정수로 변환되어 비트의 나열로 표현됩니다. +</li><li> 두 피연산자의 비트를 같은 위치에 있는 것 끼리 짝을 짓습니다. +</li><li> 짝 지어진 각각의 쌍에 대해서 연산자를 적용하여 결과를 만들어냅니다. +</li></ul> +<p>예를 들어, 9를 2진수로 쓰면 1001이고 15를 2진수로 표현하면 1111입니다. 두 값에 비트 연산을 적용하면 결과는 다음과 같습니다. +</p> +<ul><li> 15 & 9 yields 9 (1111 & 1001 = 1001) +</li><li> 15 | 9 yields 15 (1111 | 1001 = 1111) +</li><li> 15 ^ 9 yields 6 (1111 ^ 1001 = 0110) +</li></ul> +<h4 id=".EB.B9.84.ED.8A.B8_.EC.9D.B4.EB.8F.99_.EC.97.B0.EC.82.B0.EC.9E.90" name=".EB.B9.84.ED.8A.B8_.EC.9D.B4.EB.8F.99_.EC.97.B0.EC.82.B0.EC.9E.90"> 비트 이동 연산자 </h4> +<p>비트 이동 연산자는 피연산자 두 개를 받습니다. 첫 번째는 이동하려는 수이고, 두 번째는 첫 번째 피연산자를 몇 비트나 이동시킬지 나타내는 비트 수입니다. 이동 방향은 사용된 연산자에 따라 다릅니다. +</p><p>이동 연산자는 피연산자를 32비트 정수로 변환하여 연산하고, 왼쪽 연산자와 같은 자료형으로 반환합니다. +</p><p>이동 연산자는 다음 표에 있습니다. +</p> +<table class="fullwidth-table"> +<tbody><tr> +<th>연산자</th> +<th>설명</th> +<th>예제</th> +</tr> +<tr> +<td><<<br> +(왼쪽 이동)</td> +<td>이 연산자는 첫 번째 피연산자의 비트를 지정된 수만큼 왼쪽으로 옮깁니다. 왼쪽으로 넘친 비트는 버립니다. 오른쪽 빈 자리는 0으로 채웁니다.</td> <td>9<<2는 36을 반환합니다. 1001을 왼쪽으로 2비트 이동하면 100100이 되고 이것은 36이기 때문입니다.</td> +</tr> +<tr> +<td>>><br> +(부호 비트로 채우는 오른쪽 이동)</td> +<td>이 연산자는 첫 번째 피연산자의 비트를 지정된 수 만큼 오른쪽으로 옮깁니다. 오른쪽으로 넘친 비트는 버립니다. 왼쪽 빈 자리는 원래 가장 왼쪽에 있던 비트 값으로 채웁니다.</td> +<td>9>>2는 2를 반환합니다. 1001을 2비트 오른쪽으로 이동하면 10이 되는데 이것은 2이기 때문입니다. 비슷하게 -9>>2는 -3을 반환하는데, 부호가 유지되기 때문입니다.</td> +</tr> +<tr> +<td>>>><br> +(0으로 채우는 오른쪽 이동)</td> +<td>이 연산자는 첫 번째 피연산자의 비트를 지정된 수 만큼 오른쪽으로 옮깁니다. 오른쪽으로 넘친 비트는 버립니다. 왼쪽 빈 자리는 0으로 채웁니다.</td> +<td>19>>>2는 4를 반환합니다. 10011을 2비트 오른쪽으로 이동하면 100이 되기 때문입니다. 음수가 아닌 수에 대해서는 0을 채우는 오른쪽 이동이나 부호 비트로 채우는 오른쪽 이동이 똑같은 결과를 반환합니다.</td> +</tr> +</tbody></table> +<p><small><b>표 3.6: 비트 이동 연산자</b></small> +</p><p>{{ PreviousNext("Core_JavaScript_1.5_Guide:Operators:Arithmetic_Operators", "Core_JavaScript_1.5_Guide:Operators:Logical_Operators") }} +</p>{{ languages( { "en": "en/Core_JavaScript_1.5_Guide/Operators/Bitwise_Operators", "fr": "fr/Guide_JavaScript_1.5/Op\u00e9rateurs/Op\u00e9rateurs_bit-\u00e0-bit", "ja": "ja/Core_JavaScript_1.5_Guide/Operators/Bitwise_Operators", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Operatory/Operatory_bitowe" } ) }} diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/index.html new file mode 100644 index 0000000000..53b8e67492 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/index.html @@ -0,0 +1,108 @@ +--- +title: Operators +slug: Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Operators +--- +<h3 id=".EC.97.B0.EC.82.B0.EC.9E.90" name=".EC.97.B0.EC.82.B0.EC.9E.90"> 연산자 </h3> +<p>JavaScript에는 다음과 같은 연산자 타입이 있습니다. 이 섹션은 연산자에 대해 기술하고 연산자 우선순위에 대한 정보를 제공합니다. +</p> +<ul><li> <a href="ko/Core_JavaScript_1.5_Guide/Operators/Assignment_Operators">할당 연산자</a> +</li><li> <a href="ko/Core_JavaScript_1.5_Guide/Operators/Comparison_Operators">비교 연산자</a> +</li><li> <a href="ko/Core_JavaScript_1.5_Guide/Operators/Arithmetic_Operators">산술 연산자</a> +</li><li> <a href="ko/Core_JavaScript_1.5_Guide/Operators/Bitwise_Operators">비트 연산자</a> +</li><li> <a href="ko/Core_JavaScript_1.5_Guide/Operators/Logical_Operators">논리 연산자</a> +</li><li> <a href="ko/Core_JavaScript_1.5_Guide/Operators/String_Operators">문자열 연산자</a> +</li><li> <a href="ko/Core_JavaScript_1.5_Guide/Operators/Special_Operators">특수 연산자</a> +</li></ul> +<p>JavaScript는 이항연산자와 단항연산자를 모두 사용할 수 있습니다. 이항연산자는 두개의 피연산자(operand)를 가지며, 하나의 피연산자는 연산자 앞에 나머지 하나는 뒤에 위치합니다: +</p> +<pre>operand1 operator operand2 +</pre> +<p>예를 들자면, <code>3+4</code> 혹은 <code>x*y</code>와 같은 것입니다. +</p><p>단항연산자는 연산자 앞 혹은 뒤쪽에 하나의 피연산자만 있으면 됩니다: +</p> +<pre>operator operand +</pre> +<p>혹은 +</p> +<pre>operand operator +</pre> +<p>예를 들자면, <code>x++</code> 혹은 <code>++x</code>와 같은 것입니다. +</p><p>덧붙여, JavaScript는 한개의 삼항연산자, 조건 연산자를 가지고 있습니다. 삼항 연산자는 세개의 피연산자가 필요합니다. +</p> +<h4 id=".EC.97.B0.EC.82.B0.EC.9E.90_.EC.9A.B0.EC.84.A0.EC.88.9C.EC.9C.84" name=".EC.97.B0.EC.82.B0.EC.9E.90_.EC.9A.B0.EC.84.A0.EC.88.9C.EC.9C.84"> 연산자 우선순위 </h4> +<p><small><i><a>관련된 논의</a>에 따라서, 아래의 표는 우선순위 순으로 <b>내림차순</b> 정렬되었습니다.</i></small> +</p> +<table class="fullwidth-table"> +<tbody><tr> +<th>연산자 타입</th> +<th>사용하는 연산자</th> +</tr> +<tr> +<td>멤버 </td> +<td>. []</td> +</tr> +<tr> +<td>호출 / 인스턴스 생성 </td> +<td>() new</td> +</tr> +<tr> +<td>부정/증감 </td> +<td>! ~ - + ++ -- typeof void delete</td> +</tr> +<tr> +<td>곱하기/나누기 </td> +<td>* / %</td> +</tr> +<tr> +<td>더하기/빼기 </td> +<td>+ -</td> +</tr> +<tr> +<td>비트 이동 </td> +<td><< >> >>></td> +</tr> +<tr> +<td>관계 </td> +<td>< <= > >= in instanceof</td> +</tr> +<tr> +<td>같음 </td> +<td>== != === !==</td> +</tr> +<tr> +<td>비트연산-and </td> +<td>&</td> +</tr> +<tr> +<td>비트연산-xor </td> +<td>^</td> +</tr> +<tr> +<td>비트연산-or </td> +<td>|</td> +</tr> +<tr> +<td>논리연산-and </td> +<td>&&</td> +</tr> +<tr> +<td>논리연산-or </td> +<td>||</td> +</tr> +<tr> +<td>조건 </td> +<td>?:</td> +</tr> +<tr> +<td>할당 </td> +<td>= += -= *= /= %= <<= >>= >>>= &= ^= |=</td> +</tr> +<tr> +<td>컴마</td> +<td>,</td> +</tr> +</tbody></table> +<p><small><b>표: 연산자 우선순위</b></small> +</p><p>이 표의 보다 자세한 버전은 <a href="ko/Core_JavaScript_1.5_Reference/Operators/Operator_Precedence#Table">레퍼런스 섹션</a>에 있는 각 연산자별 상세한 추가 설명 링크를 참고하세요. +</p><p>{{ PreviousNext("Core_JavaScript_1.5_Guide:Expressions", "Core_JavaScript_1.5_Guide:Operators:Assignment_Operators") }} +</p>{{ languages( { "en": "en/Core_JavaScript_1.5_Guide/Operators", "fr": "fr/Guide_JavaScript_1.5/Op\u00e9rateurs", "ja": "ja/Core_JavaScript_1.5_Guide/Operators", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Operatory" } ) }} diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/logical_operators/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/logical_operators/index.html new file mode 100644 index 0000000000..6b30493f83 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/logical_operators/index.html @@ -0,0 +1,68 @@ +--- +title: Logical Operators +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Operators/Logical_Operators +translation_of: Web/JavaScript/Guide/Expressions_and_Operators +--- +<h3 id=".EB.85.BC.EB.A6.AC_.EC.97.B0.EC.82.B0.EC.9E.90" name=".EB.85.BC.EB.A6.AC_.EC.97.B0.EC.82.B0.EC.9E.90"> 논리 연산자 </h3> +<p>논리 연산자는 주로 불리언(논리적) 값과 함께 사용됩니다. 그때 논리 연산자는 불리언 값을 반환합니다. 그러나 &&와 || 연산자는 실제로는 피연산자 중에 하나의 값을 반환하기 때문에, 이 연산자가 불리언 값이 아닌 값과 함께 사용되면 불리언 값이 아닌 값을 반환할 것입니다. 다음 표에 논리 연산자에 대해서 설명했습니다. +</p> +<table class="fullwidth-table"> +<tbody><tr> +<th>연산자</th> +<th>사용법</th> +<th>설명</th> +</tr> +<tr> +<td>&&</td> +<td>expr1 && expr2</td> +<td>(논리적 AND) expr1이 false로 변환될 수 있으면 expr1을 반환하고, 그렇지 않으면 expr2를 반환합니다. 그러므로 불리언 값과 같이 사용하면 피연산자 둘 모두가 true일 때 &&는 true를 반환하고 그렇지 않을 때는 false를 반환합니다.</td> +</tr> +<tr> +<td>||</td> +<td>expr1 || expr2</td> +<td>(논리적 OR) expr1이 true로 변환될 수 있으면 expr1을 반환하고 그렇지 않으면 expr2를 반환합니다. 그러므로 불리언 값과 같이 사용하면 ||는 피연산자 중에서 하나만 true이면 true를 반환합니다. 둘 다 false이면 false를 반환합니다.</td> +</tr> +<tr> +<td>!</td> +<td>!expr</td> +<td>(논리적 NOT) 피연산자가 true로 변환될 수 있으면 false를 반환합니다. 그렇지 않으면 true를 반환합니다.</td> +</tr> +</tbody></table> +<p><small><b>표 3.7: 논리 연산자</b></small> +</p><p>false로 변환될 수 있는 표현식은 null, 0, 빈 문자열(""), undefined로 평가될 수 있는 표현식들입니다. +</p><p>다음 코드는 && 연산자를 사용하는 예를 보여줍니다. +</p> +<pre>a1=true && true // t && t returns true +a2=true && false // t && f returns false +a3=false && true // f && t returns false +a4=false && (3 == 4) // f && f returns false +a5="Cat" && "Dog" // t && t returns Dog +a6=false && "Cat" // f && t returns false +a7="Cat" && false // t && f returns false +</pre> +<p>다음 코드는 || 연산자를 사용하는 예를 보여줍니다. +</p> +<pre>o1=true || true // t || t returns true +o2=false || true // f || t returns true +o3=true || false // t || f returns true +o4=false || (3 == 4) // f || f returns false +o5="Cat" || "Dog" // t || t returns Cat +o6=false || "Cat" // f || t returns Cat +o7="Cat" || false // t || f returns Cat +</pre> +<p>다음 코드는 ! 연산자를 사용하는 예를 보여줍니다. +</p> +<pre>n1=!true // !t returns false +n2=!false // !f returns true +n3=!"Cat" // !t returns false +</pre> +<h4 id=".EB.8B.A8.EC.B6.95_.ED.8F.89.EA.B0.80" name=".EB.8B.A8.EC.B6.95_.ED.8F.89.EA.B0.80"> 단축 평가 </h4> +<p>논리 표현식이 왼쪽부터 오른쪽으로 평가되기 때문에 다음 규칙을 이용해서 "단축(short-circuit)" 평가를 할 수 있습니다. +</p> +<ul><li> <code>false</code> && <i>아무 표현식</i>은 false로 단축 평가 됩니다. +</li><li> <code>true</code> || <i>아무 표현식</i>은 true로 단축 평가 됩니다. +</li></ul> +<p>이 규칙을 따라 평가를 수행한다고 해서 피연산자를 모두 평가할 때와 결과가 달라지지 않습니다. <i>아무 표현식</i> 부분은 평가되지 않기 때문에 아무런 부수 효과(side effect)도 일어나지 않는다는 것에 주의하십시오. +</p><p>{{ PreviousNext("Core_JavaScript_1.5_Guide:Operators:Bitwise_Operators", "Core_JavaScript_1.5_Guide:Operators:String_Operators") }} +</p>{{ languages( { "en": "en/Core_JavaScript_1.5_Guide/Operators/Logical_Operators", "fr": "fr/Guide_JavaScript_1.5/Op\u00e9rateurs/Op\u00e9rateurs_logiques", "ja": "ja/Core_JavaScript_1.5_Guide/Operators/Logical_Operators", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Operatory/Operatory_logiczne" } ) }} diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/special_operators/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/special_operators/index.html new file mode 100644 index 0000000000..aa66b296fc --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/special_operators/index.html @@ -0,0 +1,228 @@ +--- +title: Special Operators +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Operators/Special_Operators +translation_of: Web/JavaScript/Guide/Expressions_and_Operators +--- +<h3 id=".ED.8A.B9.EC.88.98_.EC.97.B0.EC.82.B0.EC.9E.90" name=".ED.8A.B9.EC.88.98_.EC.97.B0.EC.82.B0.EC.9E.90"> 특수 연산자 </h3> +<p>JavaScript 다음과 같은 특별한 연산자를 제공합니다. +</p> +<ul><li> {{ Anch("조건 연산자") }} +</li><li> {{ Anch("쉼표 연산자") }} +</li><li> {{ Anch("delete") }} +</li><li> {{ Anch("in") }} +</li><li> {{ Anch("instanceof") }} +</li><li> {{ Anch("new") }} +</li><li> {{ Anch("this") }} +</li><li> {{ Anch("typeof") }} +</li><li> {{ Anch("void") }} +</li></ul> +<h4 id=".EC.A1.B0.EA.B1.B4_.EC.97.B0.EC.82.B0.EC.9E.90" name=".EC.A1.B0.EA.B1.B4_.EC.97.B0.EC.82.B0.EC.9E.90"> 조건 연산자 </h4> +<p>조건 연산자는 JavaScript에서 유일하게 세 개의 피연산자를 사용하는 연산자입니다. 연산자는 조건에 따라 둘 중에 하나의 값을 가질 수 있습니다. 문법은 이렇습니다. +</p> +<pre>condition ? val1 : val2 +</pre> +<p><code>condition</code>이 true이면 연산자는 <code>val1</code>의 값을 갖습니다. 그렇지 않으면 <code>val2</code>의 값을 갖습니다. 다른 표준 연산자를 사용할 수 있는 곳이면 어디든지 조건 연산자를 사용할 수 있습니다. +</p> +<pre>status = (age >= 18) ? "adult" : "minor" +</pre> +<p>이 문장은 <code>age</code>가 18이거나 더 큰 경우에 <code>status</code> 변수에 "adult"라는 값을 할당합니다. 그렇지 않으면 "minor"라는 값을 할당합니다. +</p> +<h4 id=".EC.89.BC.ED.91.9C_.EC.97.B0.EC.82.B0.EC.9E.90" name=".EC.89.BC.ED.91.9C_.EC.97.B0.EC.82.B0.EC.9E.90"> 쉼표 연산자 </h4> +<p>쉼표 연산자(,)는 단순히 피연산자 둘을 모두 평가하고 두 번째 피연산자의 값을 반환하는 연산자입니다. 이 연산자는 주로 <code>for</code> 반복문에서 변수 여러 개가 매번 업데이트 되게 하는데 쓰입니다. +</p><p>예를 들어 <code>a</code>가 각각 10줄의 원소를 가지는 2차원 배열일 때, 다음 코드에서는 변수 두 개를 한 번에 바꾸기 위해서 쉼표 연산자를 사용하고 있습니다. 이 코드는 배열의 대각선 원소를 출력합니다. +</p> +<pre>for (var i=0, j=9; i <= 9; i++, j--) + document.writeln("a["+i+"]["+j+"]= " + a[i][j]) +</pre> +<h4 id="delete" name="delete"> delete </h4> +<p>delete는 개체(object), 개체의 속성(property), 배열의 특정 인덱스에 있는 원소(element)를 지우는 연산자입니다. 문법은 이렇습니다. +</p> +<pre>delete objectName +delete objectName.property +delete objectName[index] +delete property // with 문장 안에서만 유효합니다 +</pre> +<p><code>objectName</code>은 개체 이름이고, <code>property</code>는 개체에 존재하는 속성이고, <code>index</code>는 배열의 원소 위치를 나타내는 정수입니다. +</p><p>네 번째 형식은 개체의 속성을 지우는 코드인데, <code>with</code> 문장 안에서만 사용할 수 있습니다. +</p><p>암시적으로 선언된 변수를 지울 때는 <code>delete</code> 연산자를 사용할 수 있지만 <code>var</code> 문장을 이용해서 선언된 변수는 지울 수 없습니다. +</p><p><code>delete</code> 연산자 실행이 성공하면, 속성이나 원소가 <code>undefined</code>로 설정됩니다. <code>delete</code> 연산자는 실행이 가능하면 true를 반환하고, 불가능하면 false를 반환합니다. +</p> +<pre>x=42 +var y= 43 +myobj=new Number() +myobj.h=4 // h라는 속성을 만듭니다 +delete x // returns true (암시적으로 선언된 변수는 지울 수 있습니다) +delete y // returns false (var로 선언한 변수는 지울 수 없습니다) +delete Math.PI // returns false (미리 정의된 속성은 지울 수 없습니다) +delete myobj.h // returns true (사용자 정의 속성은 지울 수 있습니다) +delete myobj // returns true (암시적으로 선언되었으므로 지울 수 있습니다) +</pre> +<p><b>배열의 원소를 지우기</b><br> +배열의 원소를 지울 때, 배열의 길이에는 변화가 없습니다. 예를 들어, a{{ mediawiki.external(3) }}, a{{ mediawiki.external(4) }}를 지우더라도 a{{ mediawiki.external(4) }}와 a{{ mediawiki.external(3) }}은 여전히 정의되지 않습니다. +</p><p><code>delete</code> 연산자가 배열 원소를 제거할 때 원소는 더이상 배열에 존재하지 않습니다. 아래 예제에서 trees{{ mediawiki.external(3) }}은 <code>delete</code>로 제거되었습니다. +</p> +<pre>trees=new Array("redwood","bay","cedar","oak","maple") +delete trees[3] +if (3 in trees) { + // 이 블록은 실행되지 않습니다. +} +</pre> +<p>배열 원소가 존재하긴 하지만 정의되지 않은 값을 가지도록 하고 싶다면 <code>delete</code> 연산자 대신 <code>undefined</code> 키워드를 사용하십시오. 다음 예제에서 <code>trees{{ mediawiki.external(3) }}</code>에 <code>undefined</code> 값을 할당했지만 배열 요소는 여전히 존재합니다. +</p> +<pre>trees=new Array("redwood","bay","cedar","oak","maple") +trees[3]=undefined +if (3 in trees) { + // 이 블록은 실행됩니다. +} +</pre> +<h4 id="in" name="in"> in </h4> +<p><code>in</code> 연산자는 지정된 속성이 지정된 개체에 있으면 true를 반환합니다. 문법은 이렇습니다. +</p> +<pre>propNameOrNumber in objectName +</pre> +<p><code>propNameOrNumber</code>은 속성 이름을 나타내는 문자열이나 배열 인덱스를 나타내는 수이고, <code>objectName</code>은 개체 이름입니다. +</p><p>다음 예제는 <code>in</code> 연산자의 몇 가지 사용법을 보여줍니다. +</p> +<pre>// 배열 +trees=new Array("redwood","bay","cedar","oak","maple") +0 in trees // returns true +3 in trees // returns true +6 in trees // returns false +"bay" in trees // returns false (원하는 인덱스를 지정해야 하는데, + // 그 인덱스에 있는 값을 지정하면 안됩니다.) +"length" in trees // returns true (length는 배열의 속성입니다.) + +// 미리 정의된 개체 +"PI" in Math // returns true +myString=new String("coral") +"length" in myString // returns true + +// 사용자 개체 +mycar = {make:"Honda",model:"Accord",year:1998} +"make" in mycar // returns true +"model" in mycar // returns true +</pre> +<h4 id="instanceof" name="instanceof"> instanceof </h4> +<p><code>instanceof</code>는 지정된 개체가 지정된 개체 형식이면 true를 반환합니다. 문법은 이렇습니다. +</p> +<pre>objectName instanceof objectType +</pre> +<p><code>objectName</code>은 <code>objectType</code>과 비교할 개체의 이름이고, <code>objectType</code>은 개체 형식으로 <code>Date</code>나 <code>Array</code> 같은 것입니다. +</p><p>실행중에 개체의 형식을 알고 싶으면 <code>instanceof</code>를 사용하면 됩니다. 예를 들어 예외를 처리할 때, 발생한 예외의 형식에 따라 서로 다른 예외 처리 코드를 실행할 수 있습니다. +</p><p>다음 코드에서 <code>theDay</code>가 <code>Date</code> 개체인지 결정하기 위해서 <code>instanceof</code>를 사용합니다. <code>theDay</code>는 <code>Date</code> 개체이기 때문에 <code>if</code>문 안에 있는 문장이 실행됩니다. +</p> +<pre>theDay=new Date(1995, 12, 17) +if (theDay instanceof Date) { + // 실행할 문장 +} +</pre> +<h4 id="new" name="new"> new </h4> +<p>사용자 정의 개체 형식이나 <code>Array, Boolean, Date, Function, Image, Number, Object, Option, RegExp, String</code> 같이 미리 정의된 개체 형식의 인스턴스를 만들 때 <code>new</code> 연산자를 사용합니다. 서버에서는 <code>DbPool, Lock, File, SendMail</code> 등을 만들 때 사용할 수 있습니다. <code>new</code>는 다음과 같이 사용합니다. +</p> +<pre>objectName = new objectType ( param1 [,param2] ...[,paramN] ) +</pre> +<p><a href="ko/Core_JavaScript_1.5_Guide/Creating_New_Objects/Using_Object_Initializers">개체 초기화 지정자 사용하기</a>에 설명한 것처럼 개체 초기화 지정자를 이용해서 개체를 만들 수도 있습니다. +</p><p>더 많은 정보를 얻으려면 JavaScript 레퍼런스의 <a href="ko/Core_JavaScript_1.5_Reference/Operators/Special_Operators/new_Operator">new 연산자</a> 페이지를 보시기 바랍니다. +</p> +<h4 id="this" name="this"> this </h4> +<p>현재 개체를 참조할 때 <code>this</code> 키워드를 사용합니다. 일반적으로 <code>this</code>는 메소드를 호출하는 개체를 참조합니다. 다음과 같이 사용하면 됩니다. +</p> +<pre>this[.propertyName] +</pre> +<p><b>예제 1.</b><br> +개체의 <code>value</code> 속성이 높거나 낮은 값을 가지는지 검증하는 <code>validate</code>라는 함수가 있다고 가정합시다. +</p> +<pre>function validate(obj, lowval, hival) { + if ((obj.value < lowval) || (obj.value > hival)) + alert("Invalid Value!") +} +</pre> +<p>이제 우리는 폼의 각 요소의 <code>onChange</code> 이벤트 핸들러에서 <code>validate</code> 함수를 호출하면서, <code>this</code>를 이용하여 스스로를 함수에 전달할 수 있습니다. +</p> +<pre><B>Enter a number between 18 and 99:</B> +<INPUT TYPE = "text" NAME = "age" SIZE = 3 + onChange="validate(this, 18, 99)"> +</pre> +<p><b>예제 2.</b><br> +<code>form</code> 속성과 결합되면, <code>this</code>는 현재 개체가 포함된 폼을 참조할 수 있습니다. 다음 예제에서 <code>myForm</code> 폼은 <code>Text</code> 개체와 버튼을 포함하고 있습니다. 사용자가 버튼을 클릭하면 <code>Text</code> 개체의 값이 폼 이름으로 설정됩니다. 버튼의 <code>onClick</code> 이벤트 핸들러는 부모 폼인 <code>myForm</code>을 참조하기 위해서 <code>this.form</code>을 사용하고 있습니다. +</p> +<pre><FORM NAME="myForm"> +Form name:<INPUT TYPE="text" NAME="text1" VALUE="Beluga"> +<P> +<INPUT NAME="button1" TYPE="button" VALUE="Show Form Name" + onClick="this.form.text1.value=this.form.name"> +</FORM> +</pre> +<h4 id="typeof" name="typeof"> typeof </h4> +<p><code>typeof</code> 연산자는 둘 중 한 가지 방법으로 사용할 수 있습니다. +</p> +<pre>1. typeof operand +2. typeof (operand) +</pre> +<p><code>typeof</code> 연산자는 피연산자의 평가되지 않은 형식을 나타내는 문자열을 반환합니다. <code>피연산자</code>는 string, variable, keyword, object 등의 타입을 반환하게 됩니다. 괄호는 선택적입니다. +</p><p>우리가 이런 변수를 정의했다고 해봅시다. +</p> +<pre>var myFun = new Function("5+2") +var shape="round" +var size=1 +var today=new Date() +</pre> +<p><code>typeof</code>는 이 변수들에 대해서 다음과 같은 결과를 반환할 것입니다. +</p> +<pre>typeof myFun is function +typeof shape is string +typeof size is number +typeof today is object +typeof dontExist is undefined +</pre> +<p><code>true</code>와 <code>null</code> 키워드에 대해서 <code>typeof</code> 연산자는 다음과 같은 결과를 반환합니다. +</p> +<pre>typeof true is boolean +typeof null is object +</pre> +<p>수와 문자열에 대해서 <code>typeof</code> 연산자는 다음과 같은 결과를 반환합니다. +</p> +<pre>typeof 62 is number +typeof 'Hello world' is string +</pre> +<p>속성 값에 대해서 <code>typeof</code> 연산자는 속성이 포함하고 있는 값의 형식을 반환합니다. +</p> +<pre>typeof document.lastModified is string +typeof window.length is number +typeof Math.LN2 is number +</pre> +<p>메소드와 함수에 사용하면 <code>typeof</code> 연산자는 다음과 같은 결과를 반환합니다. +</p> +<pre>typeof blur is function +typeof eval is function +typeof parseInt is function +typeof shape.split is function +</pre> +<p>미리 정의된 개체들에 대해서 <code>typeof</code> 연산자는 다음과 같은 결과를 반환합니다. +</p> +<pre>typeof Date is function +typeof Function is function +typeof Math is function +typeof Option is function +typeof String is function +</pre> +<h4 id="void" name="void"> void </h4> +<p><code>void</code> 연산자는 다음과 같이 사용할 수 있습니다. +</p> +<pre>1. void (expression) +2. void expression +</pre> +<p><code>void</code> 연산자는 표현식이 값을 반환하지 않으면서 평가되어야 한다고 지정하는데 사용됩니다. <code>expression</code>은 평가하려는 JavaScript 표현식입니다. 표현식을 감싸는 괄호는 선택적이지만 사용하는 쪽이 더 좋은 스타일입니다. +</p><p>표현식을 하이퍼텍스트 링크로 지정하기 위해서 <code>void</code> 연산자를 사용할 수 있습니다. 표현식이 평가되기는 하지만 현재 문서 대신 로드되지는 않습니다. +</p><p>아래 코드는 사용자가 클릭할 때 아무 동작도 하지 않는 하이퍼텍스트 링크를 만듭니다. 사용자가 링크를 클릭하면 <code>void(0)</code>는 정의되지 않은 것(undefined)으로 평가되고 JavaScript에서 아무런 효과가 없습니다. +</p> +<pre><A HREF="javascript:void(0)">Click here to do nothing</A> +</pre> +<p>다음 코드는 클릭하면 폼을 제출하는 하이퍼텍스트 링크를 만듭니다. +</p> +<pre><A HREF="javascript:void(document.form.submit())"> +Click here to submit</A> +</pre> +<p>{{ PreviousNext("Core_JavaScript_1.5_Guide:Operators:String_Operators", "Core_JavaScript_1.5_Guide:Creating_a_Regular_Expression") }} +</p>{{ languages( { "en": "en/Core_JavaScript_1.5_Guide/Operators/Special_Operators", "fr": "fr/Guide_JavaScript_1.5/Op\u00e9rateurs/Op\u00e9rateurs_sp\u00e9ciaux", "ja": "ja/Core_JavaScript_1.5_Guide/Operators/Special_Operators", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Operatory/Operatory_specjalne" } ) }} diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/string_operators/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/string_operators/index.html new file mode 100644 index 0000000000..41c6c07286 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/string_operators/index.html @@ -0,0 +1,11 @@ +--- +title: String Operators +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Operators/String_Operators +translation_of: Web/JavaScript/Guide/Expressions_and_Operators +--- +<h4 id=".EB.AC.B8.EC.9E.90.EC.97.B4_.EC.97.B0.EC.82.B0.EC.9E.90" name=".EB.AC.B8.EC.9E.90.EC.97.B4_.EC.97.B0.EC.82.B0.EC.9E.90"> 문자열 연산자 </h4> +<p>문자열 값에 사용할 수 있는 비교 연산자 외에도 연결 연산자(+)가 있는데, 이 연산자는 두 문자열 값을 연결한 새로운 문자열 값을 반환합니다. 예를 들어, <code>"my " + "string"</code>는 <code>"my string"</code>라는 문자열을 반환합니다. +</p><p>축약된 할당 연산자인 += 또한 문자열 연결에 사용할 수 있습니다. 예를 들어 <code>mystring</code> 변수가 "alpha"라는 값을 가지고 있을 때, <code>mystring += "bet"</code>은 "alphabet"으로 평가되고, 그 값이 <code>mystring</code>에 할당됩니다. +</p><p>{{ PreviousNext("Core_JavaScript_1.5_Guide:Operators:Logical_Operators", "Core_JavaScript_1.5_Guide:Operators:Special_Operators") }} +</p>{{ languages( { "en": "en/Core_JavaScript_1.5_Guide/Operators/String_Operators", "fr": "fr/Guide_JavaScript_1.5/Op\u00e9rateurs/Op\u00e9rateurs_li\u00e9s_aux_cha\u00eenes", "ja": "ja/Core_JavaScript_1.5_Guide/Operators/String_Operators", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Operatory/Operacje_na_\u0142a\u0144cuchach" } ) }} diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/predefined_core_objects/array_object/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/predefined_core_objects/array_object/index.html new file mode 100644 index 0000000000..1f6ef48f3a --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/predefined_core_objects/array_object/index.html @@ -0,0 +1,133 @@ +--- +title: Array Object +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Predefined_Core_Objects/Array_Object +--- +<h3 id="Array_.EA.B0.9C.EC.B2.B4" name="Array_.EA.B0.9C.EC.B2.B4">Array 개체</h3> +<p>JavaScript에는 명시적인 배열 자료형이 없습니다. 하지만 배열을 다루기 위해서 <code>Array</code> 개체와 그 개체의 메소드를 이용할 수 있습니다. <code>Array</code> 개체에는 다양한 방법으로 배열을 다루기 위한 메소드들이 있는데, 배열을 합치거나, 순서를 뒤집거나, 정렬하는 등의 작업을 할 수 있습니다. 배열 길이를 알 수 있는 속성과 정규 표현식에 사용할 수 있는 속성들이 있습니다. + <i> + 배열</i> + 은 이름이나 색인으로 참조할 수 있는 값들을 모아놓은, 값의 순서가 유지되는 집합입니다. 예를 들어, 우리는 고용 번호로 색인된 고용인의 이름을 담고 있는 <code>emp</code>라는 배열을 만들 수 있습니다. 이 때 <code>emp{{ mediawiki.external(1) }}</code>는 1번 고용인, <code>emp{{ mediawiki.external(2) }}</code> 2번 고용인이 되는 것입니다.</p> +<p> </p> +<h4 id=".EB.B0.B0.EC.97.B4_.EB.A7.8C.EB.93.A4.EA.B8.B0" name=".EB.B0.B0.EC.97.B4_.EB.A7.8C.EB.93.A4.EA.B8.B0">배열 만들기</h4> +<p><code>Array</code> 개체는 이렇게 만들 수 있습니다.</p> +<pre>1. arrayObjectName = new Array(element0, element1, ..., elementN) +2. arrayObjectName = new Array(arrayLength) +</pre> +<p><code>arrayObjectName</code>은 새 개체의 이름이거나 존재하는 다른 개체의 속성 이름입니다. <code>Array</code> 개체의 속성이나 메소드를 이용할 때는 arrayObjectName은 존재하는 <code>Array</code> 개체 이름이거나 존재하는 다른 개체의 속성입니다.</p> +<p><code>element0, element1, ..., elementN</code>는 배열의 원소(element)가 될 값들입니다. 이런 식으로 지정하면, 나열한 값들을 원소로 가지고, 길이는 값의 개수인 배열이 만들어집니다.</p> +<p><code>arrayLength</code>는 배열의 초기 길이입니다. 다음 코드는 원소 다섯 개를 가지는 배열을 만듭니다.</p> +<pre>billingMethod = new Array(5) +</pre> +<p>배열 상수값 또한 <code>Array</code> 개체입니다. 예를 들어, 다음과 같은 상수값은 <code>Array</code> 개체입니다. 배열 상수값에 대한 자세한 내용은 <a href="ko/Core_JavaScript_1.5_Guide/Literals#.EB.B0.B0.EC.97.B4_.EC.83.81.EC.88.98.EA.B0.92">배열 상수값</a>을 보시기 바랍니다.</p> +<pre>coffees = ["French Roast", "Columbian", "Kona"] +</pre> +<h4 id=".EB.B0.B0.EC.97.B4.EC.97.90_.EC.9B.90.EC.86.8C_.EB.84.A3.EA.B8.B0" name=".EB.B0.B0.EC.97.B4.EC.97.90_.EC.9B.90.EC.86.8C_.EB.84.A3.EA.B8.B0">배열에 원소 넣기</h4> +<p>원소에 값을 할당함으로써 배열에 값을 넣을 수 있습니다.</p> +<pre>emp[1] = "Casey Jones" +emp[2] = "Phil Lesh" +emp[3] = "August West" +</pre> +<p>배열을 만들 때 값을 넣을 수도 있습니다.</p> +<pre>myArray = new Array("Hello", myVar, 3.14159) +</pre> +<h4 id=".EB.B0.B0.EC.97.B4_.EC.9B.90.EC.86.8C_.EC.B0.B8.EC.A1.B0.ED.95.98.EA.B8.B0" name=".EB.B0.B0.EC.97.B4_.EC.9B.90.EC.86.8C_.EC.B0.B8.EC.A1.B0.ED.95.98.EA.B8.B0">배열 원소 참조하기</h4> +<p>배열 원소의 순서를 나타내는 숫자로 원소를 참조할 수 있습니다. 예를 들어 다음과 같은 배열을 만들었다고 해봅시다.</p> +<pre>myArray = new Array("Wind","Rain","Fire") +</pre> +<p>그러면 첫 번째 원소는 <code>myArray{{ mediawiki.external(0) }}</code>으로 참조할 수 있고, 두 번째 원소는 <code>myArray{{ mediawiki.external(1) }}</code>로 참조할 수 있습니다.</p> +<p>원소의 색인은 영(0)부터 시작하지만 배열 길이(예를 들면 <code>myArray.length</code>)는 배열의 원소 개수를 나타냅니다.</p> +<p> </p> +<h4 id="Array_.EA.B0.9C.EC.B2.B4.EC.9D.98_.EB.A9.94.EC.86.8C.EB.93.9C" name="Array_.EA.B0.9C.EC.B2.B4.EC.9D.98_.EB.A9.94.EC.86.8C.EB.93.9C">Array 개체의 메소드</h4> +<p><code>Array</code> 개체는 다음과 같은 메소드들을 가지고 있습니다.</p> +<ul> + <li><code>concat</code> 메소드는 두 배열을 합쳐서 새 배열 하나를 반환합니다.</li> +</ul> +<pre>myArray = new Array("1","2","3") +myArray = myArray.concat("a", "b", "c"); // myArray는 ["1", "2", "3", "a", "b", "c"]이 되었습니다. +</pre> +<ul> + <li><code>join(deliminator = ",")</code> 메소드는 배열의 모든 원소를 문자열로 바꿔서 하나의 문자열을 만들어줍니다.</li> +</ul> +<pre>myArray = new Array("Wind","Rain","Fire") +list = myArray.join(" - "); // list는 "Wind - Rain - Fire"입니다. +</pre> +<ul> + <li><code>pop</code> 메소드는 배열의 마지막 원소를 배열에서 제거하고 그 원소를 반환합니다.</li> +</ul> +<pre>myArray = new Array("1", "2", "3"); +last=myArray.pop(); // MyArray는 ["1", "2"], last = "3"이 되었습니다. +</pre> +<ul> + <li><code>push</code> 메소드는 하나 또는 그 이상의 원소를 배열 끝에 추가하고, 추가된 마지막 원소를 반환합니다.</li> +</ul> +<pre>myArray = new Array("1", "2"); +myArray.push("3"); // MyArray는 ["1", "2", "3"]이 되었습니다. +</pre> +<ul> + <li><code>reverse</code> 메소드는 원소의 순서를 뒤집어서 첫 번째 원소가 마지막 원소가 되고, 마지막 원소가 첫 번째 원소가 되도록 합니다.</li> +</ul> +<pre>myArray = new Array ("1", "2", "3"); +myArray.reverse(); // myArray = [ "3", "2", "1" ]이 되었습니다. +</pre> +<ul> + <li><code>shift</code> 메소드는 첫 번째 요소를 배열에서 제거하고, 그 원소를 반환합니다.</li> +</ul> +<pre>myArray = new Array ("1", "2", "3"); +first=myArray.shift(); // MyArray는 ["2", "3"], first는 "1"이 되었습니다. +</pre> +<ul> + <li><code>slice (start_index, upto_index)</code> 메소드는 배열의 일부분을 추출하여 새 배열을 반환합니다.</li> +</ul> +<pre>myArray = new Array ("a", "b", "c", "d", "e"); +myArray = myArray.slice(1,4); //색인 1부터 색인 4 바로 앞까지의 원소를 추출해서 [ "b", "c", "d" ]를 반환합니다. +</pre> +<ul> + <li><code>splice(index, count_to_remove, addelement1, addelement2, ...)</code> 메소드는 배열에 원소를 추가하거나 배열에서 원소를 제거합니다.</li> +</ul> +<pre>myArray = new Array ("1", "2", "3", "4", "5"); +myArray.splice(1,3,"a","b","c", "d"); // MyArray는 ["1", "a", "b", "c", "d", "5"]가 되었습니다. +// 이 코드는 색인 1(즉 "2")부터 원소 세 개를 제거하고, 그 자리에 원소를 추가합니다. +</pre> +<ul> + <li><code>sort</code> 메소드는 원소를 정렬합니다.</li> +</ul> +<pre>myArray = new Array("Wind","Rain","Fire") +myArray.sort(); // 배열을 정렬했으므로 myArrray = [ "Fire", "Rain", "Wind" ]가 되었습니다. +</pre> +<p><code>sort</code> 메소드에 배열을 어떻게 정렬할지 결정하는 콜백 함수를 전해줄 수 있습니다. 그 함수는 두 값을 비교해서 다음 셋 중 하나를 반환해야 합니다.</p> +<ul> + <li>정렬할 때 a가 b보다 작다면 -1(또는 임의의 음수)를 반환</li> + <li>정렬할 때 a가 b보다 크다면 1(또는 임의의 양수)를 반환</li> + <li>a와 b가 같으면 0을 반환</li> +</ul> +<p>예를 들어 다음 코드는 원소의 마지막 글자를 기준으로 배열을 정렬합니다.</p> +<pre>var sortFn = function(a,b){ + if (a[a.length - 1] < b[b.length - 1]) return -1; + if (a[a.length - 1] > b[b.length - 1]) return 1; + if (a[a.length - 1] == b[b.length - 1]) return 0; + } +myArray.sort(sortFn); // 배열을 정렬했으므로 myArray = ["Wind","Fire","Rain"]가 되었습니다. +</pre> +<ul> + <li><code>unshift</code> 메소드는 하나 또는 그 이상의 원소를 배열 앞에 추가하고 배열의 새 길이를 반환합니다.</li> +</ul> +<h4 id="2.EC.B0.A8.EC.9B.90_.EB.B0.B0.EC.97.B4" name="2.EC.B0.A8.EC.9B.90_.EB.B0.B0.EC.97.B4">2차원 배열</h4> +<p>다음 코드는 2차원 배열을 만듭니다.</p> +<pre>a = new Array(4) +for (i=0; i < 4; i++) { + a[i] = new Array(4) + for (j=0; j < 4; j++) { + a[i][j] = "["+i+","+j+"]" + } +} +</pre> +<p>바로 위 코드는 이런 배열을 만들어냅니다.</p> +<pre>Row 0:[0,0][0,1][0,2][0,3] +Row 1:[1,0][1,1][1,2][1,3] +Row 2:[2,0][2,1][2,2][2,3] +Row 3:[3,0][3,1][3,2][3,3] +</pre> +<h4 id=".EB.B0.B0.EC.97.B4.EA.B3.BC_.EC.A0.95.EA.B7.9C_.ED.91.9C.ED.98.84.EC.8B.9D" name=".EB.B0.B0.EC.97.B4.EA.B3.BC_.EC.A0.95.EA.B7.9C_.ED.91.9C.ED.98.84.EC.8B.9D">배열과 정규 표현식</h4> +<p>배열이 정규 표현식과 문자열을 매치한 결과로 생성되었을 때, 그 배열은 매치에 대한 정보를 제공하는 속성과 원소를 포함하고 있습니다. <code>RegExp.exec</code>, <code>String.match</code>, <code>String.split</code>의 반환 값은 배열입니다. 정규 표현식과 관련된 배열 사용에 대한 정보를 얻으려면 4장 <a href="ko/Core_JavaScript_1.5_Guide#.EC.A0.95.EA.B7.9C_.ED.91.9C.ED.98.84.EC.8B.9D">정규 표현식</a>을 보십시오.</p> +<p>{{ PreviousNext("Core_JavaScript_1.5_Guide:Predefined_Core_Objects", "Core_JavaScript_1.5_Guide:Predefined_Core_Objects:Boolean_Object") }}</p> diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/predefined_core_objects/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/predefined_core_objects/index.html new file mode 100644 index 0000000000..9306e0ea94 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/predefined_core_objects/index.html @@ -0,0 +1,20 @@ +--- +title: Predefined Core Objects +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Predefined_Core_Objects +translation_of: Web/JavaScript/Guide +--- +<h3 id=".EB.AF.B8.EB.A6.AC_.EC.A0.95.EC.9D.98.EB.90.9C_.EA.B8.B0.EB.B3.B8_.EA.B0.9C.EC.B2.B4" name=".EB.AF.B8.EB.A6.AC_.EC.A0.95.EC.9D.98.EB.90.9C_.EA.B8.B0.EB.B3.B8_.EA.B0.9C.EC.B2.B4"> 미리 정의된 기본 개체 </h3> +<p>이 절에서는 기본 JavaScrip에 미리 정의된 개체에 대해서 설명하겠습니다. +</p> +<ul><li> <a href="ko/Core_JavaScript_1.5_Guide/Predefined_Core_Objects/Array_Object">Array 개체</a> +</li><li> <a href="ko/Core_JavaScript_1.5_Guide/Predefined_Core_Objects/Boolean_Object">Boolean 개체</a> +</li><li> <a href="ko/Core_JavaScript_1.5_Guide/Predefined_Core_Objects/Date_Object">Date 개체</a> +</li><li> <a href="ko/Core_JavaScript_1.5_Guide/Predefined_Core_Objects/Function_Object">Function 개체</a> +</li><li> <a href="ko/Core_JavaScript_1.5_Guide/Predefined_Core_Objects/Math_Object">Math 개체</a> +</li><li> <a href="ko/Core_JavaScript_1.5_Guide/Predefined_Core_Objects/Number_Object">Number 개체</a> +</li><li> <a href="ko/Core_JavaScript_1.5_Guide/Predefined_Core_Objects/RegExp_Object">RegExp 개체</a> +</li><li> <a href="ko/Core_JavaScript_1.5_Guide/Predefined_Core_Objects/String_Object">String 개체</a> +</li></ul> +<p>{{ PreviousNext("Core_JavaScript_1.5_Guide:Creating_New_Objects:Deleting_Properties", "Core_JavaScript_1.5_Guide:Predefined_Core_Objects:Array_Object") }} +</p>{{ languages( { "en": "en/Core_JavaScript_1.5_Guide/Predefined_Core_Objects", "fr": "fr/Guide_JavaScript_1.5/Objets_pr\u00e9d\u00e9finis", "ja": "ja/Core_JavaScript_1.5_Guide/Predefined_Core_Objects", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Obiekty_predefiniowane" } ) }} diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/unicode/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/unicode/index.html new file mode 100644 index 0000000000..562b7a53a0 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/unicode/index.html @@ -0,0 +1,109 @@ +--- +title: Unicode +slug: Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Unicode +translation_of: Web/JavaScript/Guide/Grammar_and_types +--- +<h3 id=".EC.9C.A0.EB.8B.88.EC.BD.94.EB.93.9C" name=".EC.9C.A0.EB.8B.88.EC.BD.94.EB.93.9C"> 유니코드 </h3> +<p>유니코드는 세계의 주요한 문자 언어를 교환하고 표현하기 위한 문자-코딩 표준입니다. 유니코드는 아메리카, 유럽, 중동, 아프리카, 인도, 아시아, 태평양 지역(Pacifica)의 언어를 포함하며 고문자와 기술 분야 기호들도 포함합니다. 유니코드는 공통적인 기술 분야, 수학 분야 기호 뿐만 아니라 여러 언어를 포함한 텍스트의 교환, 처리, 표현을 지원합니다. 유니코드는 나라마다 서로 다른 문자 표준으로 인해서 여러 언어를 포함했을 때 발생하는 국제화 문제를 해결할 수 있기를 희망합니다. 하지만 아직은 모든 현대 문자, 고대 문자를 지원하지는 못합니다. +</p><p>유니코드 문자 집합은 알려진 모든 인코딩을 위해 사용될 수 있습니다. 유니코드는 ASCII (American Standard Code for Information Interchange, 정보 교환을 위한 미국 표준 코드) 문자 집합을 본떠 만들어졌습니다. 각각의 문자에 숫자와 이름을 부여한 것입니다. 문자 인코딩은 문자의 정체성(identity)과 숫자 값(코드 위치)와 함께 숫자 값의 비트 표현을 명시합니다. 16비트 숫자 값(코드 값)은 U+0041처럼 접두어 U뒤에 16진수를 붙여서 표시합니다. 이 값의 유일한 이름은 LATIN CAPITAL LETTER A입니다. +</p><p><b>JavaScript 1.3 이전 버전은 유니코드를 지원하지 않습니다.</b> +</p> +<h4 id=".EC.9C.A0.EB.8B.88.EC.BD.94.EB.93.9C.EC.99.80_ASCII_.EB.B0.8F_ISO_.EC.82.AC.EC.9D.B4.EC.9D.98_.ED.98.B8.ED.99.98.EC.84.B1" name=".EC.9C.A0.EB.8B.88.EC.BD.94.EB.93.9C.EC.99.80_ASCII_.EB.B0.8F_ISO_.EC.82.AC.EC.9D.B4.EC.9D.98_.ED.98.B8.ED.99.98.EC.84.B1"> 유니코드와 ASCII 및 ISO 사이의 호환성 </h4> +<p>유니코드는 ISO 10646의 부분집합인 국제 표준 ISO/IEC 10646-1; 1993과 완벽하게 호환됩니다. +</p><p>몇몇 인코딩 표준(UTF-8, UTF-16, ISO UCS-2를 포함하는)들이 실제 비트 값으로 유니코드를 표현하기 위해 사용됩니다. +</p><p>UTF-8 인코딩은 ASCII 문자와 호환되며 많은 프로그램이 UTF-8을 지원합니다. 앞쪽 128개의 유니코드 문자는 ASCII 문자에 대응되며 같은 바이트 값을 가지고 있습니다. U+0020부터 U+007E 까지의 유니코드 문자는 ASCII 문자 0x20 부터 0x7E 까지와 동일합니다. 라틴 알파벳을 지원하고 7비트 문자 집합을 사용하는 ASCII와는 달리, UTF-8은 한 문자를 위해서 한 개부터 네 개 사이의 8진수(octet)를 사용합니다. ("8진수"는 바이트 또는 8비트를 의미합니다.) 이 방법으로 수백만개의 문자를 표현할 수 있습니다. 다른 인코딩 표준인 UTF-16은 유니코드 문자를 표현하기 위해 2바이트를 사용합니다. 이스케이프 시퀀스를 이용하여 UTF-16은 4바이트를 써서 모든 유니코드 범위를 표현합니다. ISO UCS-2 (Universal Character Set, 세계 문자 집합)은 2바이트를 사용합니다. +</p><p>JavaScript와 Navigator가 UTF-8/유니코드를 지원한다는 것은 우리가 비 라틴 문자와 국제화되고 지역화된 문자에다 특수한 기술 분야 기호까지 JavaScript 프로그램에 쓸 수 있다는 것을 의미합니다. 유니코드는 여러 언어를 포함한 텍스트를 인코딩할 수 있는 표준적인 방법을 제공합니다. UTF-8 인코딩이 ASCII와 호환되기 때문에, ASCII 문자를 프로그램에 사용할 수 있습니다. 우리는 JavaScript의 주석, 문자열 리터럴, 식별자(identifier), 정규 표현식에 비 ASCII 유니코드 문자를 쓸 수 있습니다. +</p> +<h4 id=".EC.9C.A0.EB.8B.88.EC.BD.94.EB.93.9C_.EC.9D.B4.EC.8A.A4.EC.BC.80.EC.9D.B4.ED.94.84_.EC.8B.9C.ED.80.80.EC.8A.A4" name=".EC.9C.A0.EB.8B.88.EC.BD.94.EB.93.9C_.EC.9D.B4.EC.8A.A4.EC.BC.80.EC.9D.B4.ED.94.84_.EC.8B.9C.ED.80.80.EC.8A.A4"> 유니코드 이스케이프 시퀀스 </h4> +<p>우리는 문자열 리터럴, 정규 표현식, 식별자에 유니코드 이스케이프 시퀀스를 사용할 수 있습니다. 이스케이프 시퀀스는 ASCII 문자 여섯 개로 이루어지는데, \u 뒤에 16진수를 표현하는 숫자 네 개가 붙은 모양입니다. 예를 들어 \u00A9는 저작권 기호를 나타냅니다. JavaScript에서 모든 유니코드 이스케이프 시퀀스는 문자 한 개로 인식됩니다. +</p><p>다음의 코드는 저작권 문자와 "Netscape Communications"라는 문자열을 반환합니다. +</p> +<pre>x="\u00A9 Netscape Communications"</pre> +<p>다음의 표는 자주 사용되는 특수 문자의 유니코드 값을 모은 것입니다. +</p> +<table class="fullwidth-table"> +<tbody><tr> +<th>분류</th> +<th>유니코드 값</th> +<th>이름</th> +<th>형식화된 이름(Format name)</th> +</tr> +<tr> +<td>공백 문자</td> +<td>\u0009</td> +<td>Tab</td> +<td><TAB></td> +</tr> +<tr> +<td> </td> +<td>\u000B</td> +<td>Vertical Tab</td> +<td><VT></td> +</tr> +<tr> +<td> </td> +<td>\u000C</td> +<td>Form Feed</td> +<td><FF></td> +</tr> +<tr> +<td> </td> +<td>\u0020</td> +<td>Space</td> +<td><SP></td> +</tr> +<tr> +<td>줄 끝 문자</td> +<td>\u000A</td> +<td>Line Feed</td> +<td><LF></td> +</tr> +<tr> +<td> </td> +<td>\u000D</td> +<td>Carriage Return</td> +<td><CR></td> +</tr> +<tr> +<td>그 외 유니코드 이스케이프 시퀀스</td> +<td>\u0008</td> +<td>Backspace</td> +<td><BS></td> +</tr> +<tr> +<td> </td> +<td>\u0009</td> +<td>Horizontal Tab</td> +<td><HT></td> +</tr> +<tr> +<td> </td> +<td>\u0022</td> +<td>Double Quote</td> +<td>"</td> +</tr> +<tr> +<td> </td> +<td>\u0027</td> +<td>Single Quote</td> +<td>'</td> +</tr> +<tr> +<td> </td> +<td>\u005C</td> <td>Backslash</td> +<td>\</td> +</tr> +</tbody></table> +<p><small><b>표 2.2: 특수 문자의 유니코드 값</b></small> +</p><p>JavaScript에서 유니코드 이스케이프 시퀀스는 Java와 다릅니다. JavaScript에서, 이스케이프 시퀀스가 특수 문자로 먼저 해석되지 않습니다. 예를 들어, 줄 끝 이스케이프 시퀀스가 문자열에 포함되어 있어도 함수에 의해 해석되기 전까지는 문자열을 자르지 않습니다. 주석에 포함된 이스케이프 시퀀스는 모두 무시됩니다. Java에서는 한 줄 주석에 이스케이프 시퀀스가 있으면 유니코드 문자로 해석됩니다. 문자열 리터럴에서 Java 컴파일러는 이스케이프 시퀀스를 먼저 해석합니다. 예를 들어 줄 끝 이스케이프 문자(즉 \u000A)가 Java에서 사용되면 문자열 리터럴을 끝나게 합니다. Java에서는 줄 끝 문자가 문자열 리터럴에 포함될 수 없으므로, 에러가 발생합니다. 문자열 리터럴에 개행 문자를 넣으려면 반드시 \n을 사용해야 합니다. JavaScript에서 이스케이프 시퀀스는 \n과 같은 방식으로 동작합니다. +</p> +<div class="note">참고: 긴 문자열을 변환하는 웹 프로그램 <a class="external" href="http://www.hot-tips.co.uk/useful/unicode_converter.HTML">Hot-Tips' Unicode Converter</a>, by Bob Foley.</div> +<h4 id="JavaScript_.ED.8C.8C.EC.9D.BC.EC.97.90.EC.84.9C_.EC.9C.A0.EB.8B.88.EC.BD.94.EB.93.9C_.EB.AC.B8.EC.9E.90" name="JavaScript_.ED.8C.8C.EC.9D.BC.EC.97.90.EC.84.9C_.EC.9C.A0.EB.8B.88.EC.BD.94.EB.93.9C_.EB.AC.B8.EC.9E.90"> JavaScript 파일에서 유니코드 문자 </h4> +<p>초기 버전의 <a href="ko/Gecko">Gecko</a>는 XUL에서 로드되는 JavaScript 파일의 인코딩이 Latin-1일 것이라고 가정했습니다. Gecko 1.8부터는 XUL 파일의 인코딩으로 부터 JavaScript 파일의 인코딩을 유추하도록 변경되었습니다. 더 많은 정보는 <a href="ko/International_characters_in_XUL_JavaScript">International characters in XUL JavaScript</a> 페이지를 참고하시기 바랍니다. +</p> +<h4 id=".EC.9C.A0.EB.8B.88.EC.BD.94.EB.93.9C.EB.A1.9C_.EB.AC.B8.EC.9E.90_.ED.91.9C.EC.8B.9C.ED.95.98.EA.B8.B0" name=".EC.9C.A0.EB.8B.88.EC.BD.94.EB.93.9C.EB.A1.9C_.EB.AC.B8.EC.9E.90_.ED.91.9C.EC.8B.9C.ED.95.98.EA.B8.B0"> 유니코드로 문자 표시하기 </h4> +<p>우리는 다른 언어나 기술 분야 기호를 표시하기 위해서 유니코드를 사용할 수 있습니다. 문자를 제대로 표시하기 위해서는 Mozilla Firefox나 Netscape 같은 클라이언트가 유니코드를 지원해야 합니다. 게다가 클라이언트에서 사용할 수 있는 적절한 유니코드 글꼴이 필요하고, 클라이언트 플랫폼이 유니코드를 지원해야 합니다. 종종 유니코드 글꼴이 모든 유니코드 문자를 표시하지 못하는 경우가 있습니다. Windows 95 같은 몇몇 플랫폼은 유니코드를 부분적으로만 지원합니다. +</p><p>비 ASCII 문자 입력을 받기 위해서는 클라이언트가 유니코드로 입력을 보내야 합니다. 표준 확장 키보드(standard enhanced keyborad)를 사용하면 클라이언트에서 유니코드가 지원하는 추가적인 문자를 쉽게 입력할 수 없습니다. 때때로 유니코드 문자를 입력하려면 유니코드 이스케이프를 사용하는 방법 밖에 없을 때도 있습니다. +</p><p>유니코드에 대한 더 많은 정보를 얻으려면 <a class="external" href="http://www.unicode.org/">유니코드 홈페이지</a>나 The Unicode Standard, Version 2.0, published by Addison-Wesley, 1996 를 보시기 바랍니다. +</p><p>{{ PreviousNext("Core_JavaScript_1.5_Guide:Literals", "Core_JavaScript_1.5_Guide:Expressions") }} +</p>{{ languages( { "en": "en/Core_JavaScript_1.5_Guide/Unicode", "fr": "fr/Guide_JavaScript_1.5/Unicode", "ja": "ja/Core_JavaScript_1.5_Guide/Unicode", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Unicode" } ) }} diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/values/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/values/index.html new file mode 100644 index 0000000000..8fcd0070e9 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/values/index.html @@ -0,0 +1,39 @@ +--- +title: Values +slug: Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Values +translation_of: Web/JavaScript/Guide/Grammar_and_types +--- +<h3 id=".EA.B0.92" name=".EA.B0.92"> 값 </h3> +<p>JavaScript는 다음과 같은 값 형식을 인식합니다. +</p> +<ul><li> <a href="ko/Core_JavaScript_1.5_Reference/Global_Objects/Number">수</a>, 42나 3.14159 +</li><li> <a href="ko/Core_JavaScript_1.5_Reference/Global_Objects/Boolean">논리적(불리언)</a> 값, <code>true</code>와 <code>false</code> +</li><li> <a href="ko/Core_JavaScript_1.5_Reference/Global_Objects/String">문자열</a>, "안녕!" +</li><li> <code>null</code>, null 값을 나타내는 특별한 키워드. <code>null</code>은 또한 기본(primitive) 값이기도 합니다. JavaScript는 대소문자를 구분하므로, <code>null</code>은 <code>Null</code>이나 <code>NULL</code>과는 다릅니다. +</li><li> <code><a href="ko/Core_JavaScript_1.5_Reference/Global_Properties/undefined">undefined</a></code>, 값이 정의되지 않은 최상위 속성. <code>undefined</code>도 기본(primitive) 값입니다. +</li></ul> +<p>이렇게 조금 적어보이는 값 형식 또는 "자료형"이지만 훌륭한 기능을 작성할 수 있습니다. 정수와 실수 사이에 엄격한 구분은 없습니다. JavaScript에는 명시적인 날짜 자료형은 없습니다. 하지만 <code><a href="ko/Core_JavaScript_1.5_Reference/Global_Objects/Date">Date</a></code> 개체를 이용하면 됩니다. +<a href="ko/Core_JavaScript_1.5_Reference/Global_Objects/Object">Object</a>와 <a href="ko/Core_JavaScript_1.5_Reference/Global_Objects/Function">함수</a>는 언어의 또다른 기초 요소입니다. 개체는 값을 포함할 수 있는 이름 붙은 어떤 것이라고 생각하면 되고, 함수는 프로그램이 수행할 수 있는 실행 절차라고 생각하면 됩니다. +</p> +<h4 id=".EC.9E.90.EB.A3.8C.ED.98.95_.EB.B3.80.ED.99.98" name=".EC.9E.90.EB.A3.8C.ED.98.95_.EB.B3.80.ED.99.98"> 자료형 변환 </h4> +<p>JavaScript는 동적 타입 언어입니다. 이 말은 변수를 선언할 때 타입을 지정하지 않아도 되고, 스크립트 실행중에 필요에 따라 자동으로 자료형이 바뀐다는 말입니다. 예를 들어 다음과 같이 변수를 선언할 수 있습니다. +</p> +<pre class="eval">var answer = 42 +</pre> +<p>그 후에 이 변수에 문자열 값을 할당할 수 있습니다. +</p> +<pre class="eval">answer = "Thanks for all the fish..." +</pre> +<p>JavaScript는 동적 타입 언어이기 때문에, 이렇게 대입하더라도 에러를 내지 않습니다. +</p><p>숫자와 문자열 값을 + 연산자로 계산하는 표현식에서, JavaScript는 숫자를 문자열로 변환합니다. 예를 들어 다음과 같은 문장을 생각해봅시다. +</p> +<pre class="eval">x = "The answer is " + 42 // returns "The answer is 42" +y = 42 + " is the answer" // returns "42 is the answer" +</pre> +<p>다른 연산자를 사용하는 문장에서는 숫자를 문자열로 변환하지 않습니다. +</p> +<pre class="eval">"37" - 7 // returns 30 +"37" + 7 // returns "377" +</pre> +<p>{{ PreviousNext("Core_JavaScript_1.5_Guide:JavaScript_Overview", "Core_JavaScript_1.5_Guide:Variables") }} +</p>{{ languages( { "en": "en/Core_JavaScript_1.5_Guide/Values", "fr": "fr/Guide_JavaScript_1.5/Valeurs", "ja": "ja/Core_JavaScript_1.5_Guide/Values", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Warto\u015bci" } ) }} diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/variables/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/variables/index.html new file mode 100644 index 0000000000..f31c37bc9c --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/variables/index.html @@ -0,0 +1,64 @@ +--- +title: Variables +slug: Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Variables +translation_of: Web/JavaScript/Guide/Grammar_and_types +--- +<h3 id=".EB.B3.80.EC.88.98" name=".EB.B3.80.EC.88.98"> 변수 </h3> +<p>우리는 프로그램 내에서 값에 이름을 부여하기 위해서 변수를 사용할 수 있습니다. 변수의 이름은 "식별자(identifier)"라고 불리며, 몇 가지 규칙을 따라야 합니다. +</p><p>JavaScript 의 식별자는 문자(letter)나 밑줄(_)이나 달러 기호($)로 시작해야 합니다. 그 뒤에는 숫자(0-9)도 올 수 있습니다. JavaScript는 대소문자를 구별하기 때문에, 문자는 대문자 "A"부터 "Z"까지와 소문자 "a"부터 "z"까지를 사용할 수 있습니다. +</p><p>JavaScript 1.5부터, 식별자에 å나 ü같은 ISO 8859-1이나 유니코드 문자를 사용할 수 있습니다. 또한 <a href="ko/Core_JavaScript_1.5_Guide/Unicode#.EC.9C.A0.EB.8B.88.EC.BD.94.EB.93.9C_.EC.9D.B4.EC.8A.A4.EC.BC.80.EC.9D.B4.ED.94.84_.EC.8B.9C.ED.80.80.EC.8A.A4">유니코드 이스케이프 시퀀스</a> 페이지에 나열된 \uXXXX 형식 유니코드 이스케이프 시퀀스를 식별자에 쓸 수도 있습니다. +</p><p>규칙에 맞는 이름 몇 가지는 이런 것입니다. <code>Number_hits</code>, <code>temp99</code>, <code>_name</code>. +</p> +<h4 id=".EB.B3.80.EC.88.98_.EC.84.A0.EC.96.B8" name=".EB.B3.80.EC.88.98_.EC.84.A0.EC.96.B8"> 변수 선언 </h4> +<p>변수를 선언하는 방법에는 두 가지가 있습니다. +</p> +<ul><li> <a href="ko/Core_JavaScript_1.5_Reference/Statements/var">var</a> 키워드를 이용하는 방법. 예를 들면 <code>var x = 42</code> 같은 식입니다. 이 문법은 <a href="#.EB.B3.80.EC.88.98_.EB.B2.94.EC.9C.84">지역, 전역</a> 변수를 선언하는데 모두 사용할 수 있습니다. +</li><li> 그냥 값을 대입하는 방법. <code>x = 42</code> 같은 식입니다. 이 방법은 항상 <a href="#.EC.A0.84.EC.97.AD_.EB.B3.80.EC.88.98">전역 변수</a>를 선언하고, strict JavaScript 경고를 냅니다. 이 방법은 절대 사용하지 맙시다. +</li></ul> +<h4 id=".EB.B3.80.EC.88.98.EB.A5.BC_.ED.8F.89.EA.B0.80.ED.95.98.EA.B8.B0.28Evaluating.29" name=".EB.B3.80.EC.88.98.EB.A5.BC_.ED.8F.89.EA.B0.80.ED.95.98.EA.B8.B0.28Evaluating.29"> 변수를 평가하기(Evaluating) </h4> +<p>초기값을 지정하지 않고 <code>var</code> 문장을 이용해서 선언한 변수는 <a href="ko/Core_JavaScript_1.5_Reference/Global_Properties/undefined">undefined</a>라는 값을 갖습니다. +</p><p>선언하지 않은 변수에 접근하려고 하면 ReferenceError 예외가 발생합니다. +</p> +<pre class="eval">var a; +print("The value of a is " + a); // prints "The value of a is undefined" +print("The value of b is " + b); // throws ReferenceError exception +</pre> +<p>변수가 값을 갖고 있는지 결정하기 위해서 <code>undefined</code>를 사용할 수 있습니다. 다음 코드에서 <code>input</code>에는 값을 할당하지 않아서 <code><a href="ko/Core_JavaScript_1.5_Reference/Statements/if...else">if</a></code>문은 <code>true</code>로 평가됩니다. +</p> +<pre>var input; +if(input === undefined){ + doThis(); +} else { + doThat(); +}</pre> +<p><span class="comment">Not sure how the following is related to "Variables" section</span> +<code>undefined</code>값을 참/거짓을 판별하는 구문에 쓰면 <code>false</code>로 평가됩니다. 예를 들어 다음 코드에서는 <code>myArray</code>의 원소가 정의되지 않았기 때문에 <code>myFunction</code> 함수가 실행됩니다. +</p> +<pre>myArray=new Array() +if (!myArray[0]) + myFunction();</pre> +<p>숫자가 필요한 문맥에서 null 변수를 평가하면 null 값은 0으로 평가되고, 참/거짓이 필요한 문맥에서는 false로 평가됩니다. +When you evaluate a null variable, the null value behaves as 0 in numeric contexts and as false in boolean contexts. For example: +</p> +<pre>var n = null; +n * 32; //0을 반환합니다</pre> +<h4 id=".EB.B3.80.EC.88.98_.EB.B2.94.EC.9C.84" name=".EB.B3.80.EC.88.98_.EB.B2.94.EC.9C.84"> 변수 범위 </h4> +<p>함 수 외부에서 선언한 변수는 "전역(global)" 변수라고 부릅니다. 그 변수는 현재 문서의 모든 코드에서 접근할 수 있기 때문입니다. 함수 안에서 선언한 변수는 "지역(local)" 변수라고 부릅니다. 그 변수는 함수 안에서만 접근할 수 있기 때문입니다. +</p><p>JavaScript에는 <a href="ko/Core_JavaScript_1.5_Guide/Block_Statement#.EB.B8.94.EB.A1.9D_.EB.AC.B8.EC.9E.A5">블록 문장</a> 범위가 없습니다. 대신 그 블록이 포함된 코드의 지역 범위에 포함됩니다. 예를 들어 다음 코드에서는 <code>condition</code>이 <code>false</code>이면 예외를 발생시키는 대신 0을 출력합니다. +</p> +<pre class="eval">if (condition) { + var x = 5; +} +print(x ? x : 0); +</pre> +<p>JavaScript의 변수와 관련해서 또다른 색다른 점은 나중에 선언될 변수에 예외 발생없이 접근할 수 있다는 것입니다. +</p> +<pre class="eval">print(x === undefined); // prints "true" +var x = 3; +</pre> +<h4 id=".EC.A0.84.EC.97.AD_.EB.B3.80.EC.88.98" name=".EC.A0.84.EC.97.AD_.EB.B3.80.EC.88.98"> 전역 변수 </h4> +<p><span class="comment">need links to pages discussing scope chains and the global object</span> +전역 변수는, 실제로는 "전역 개체(global object)"의 속성(property)입니다. 웹 페이지에서 전역 개체는 <a href="ko/DOM/window">window</a>이므로, <code>window.<i>variable</i></code> 문장을 이용해서 전역 변수에 접근할 수 있습니다. +</p><p>그러므로, window나 frame 이름을 이용하면 다른 window나 frame에 정의된 전역 변수에 접근할 수 있습니다. 예를 들어 <code>phoneNumber</code>라는 변수를 <code>FRAMESET</code> 문서에 정의했다면, 자식 frame에서 <code>parent.phoneNumber</code>로 그 변수에 접근할 수 있습니다. +</p><p>{{ PreviousNext("Core_JavaScript_1.5_Guide:Values", "Core_JavaScript_1.5_Guide:Constants") }} +</p>{{ languages( { "en": "en/Core_JavaScript_1.5_Guide/Variables", "fr": "fr/Guide_JavaScript_1.5/Variables", "ja": "ja/Core_JavaScript_1.5_Guide/Variables", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Zmienne" } ) }} diff --git a/files/ko/web/javascript/guide/text_formatting/index.html b/files/ko/web/javascript/guide/text_formatting/index.html new file mode 100644 index 0000000000..027e92c262 --- /dev/null +++ b/files/ko/web/javascript/guide/text_formatting/index.html @@ -0,0 +1,275 @@ +--- +title: 텍스트 서식 +slug: Web/JavaScript/Guide/Text_formatting +translation_of: Web/JavaScript/Guide/Text_formatting +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Numbers_and_dates", "Web/JavaScript/Guide/Regular_Expressions")}}</div> + +<p class="summary">이 장에서는 JavaScript에서 문자열과 텍스트로 작업하는 방법을 소개합니다.</p> + +<h2 id="문자열">문자열</h2> + +<p> JavaScript의 {{Glossary("문자열")}} 유형은 원문의 데이터를 나타내는데 사용됩니다. 이는 16비트 부호 없는 정수 값(UTF-16 code units)의 "요소" 집합입니다. String의 각 요소(문자)는 String에서 하나의 위치를 차지합니다. 첫 번째 요소는 인덱스 0 다음은 인덱스 1 등등... 문자열의 길이는 요소의 수와 같습니다. 문자열 리터럴 또는 문자열 객체를 사용하여 문자열을 만들 수 있습니다.</p> + +<p> </p> + +<p>주의 : 이페이지를 수정한다면 MDN bug 857438이 해결될 때 까지 U+FFFF이상의 문자를 포함하지 마세요. ( <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=857438">https://bugzilla.mozilla.org/show_bug.cgi?id=857438</a> ).</p> + +<h3 id="문자열_리터럴">문자열 리터럴</h3> + +<p>작은따옴표나 큰따옴표를 사용하여 간단한 문자열을 만들 수 있습니다:</p> + +<pre class="brush: js">'foo' +"bar"</pre> + +<p>보다 많은 문자열을 이스케이프 시퀀스를 사용하여 만들 수 있습니다</p> + +<h4 id="16진수_이스케이프_시퀀스">16진수 이스케이프 시퀀스</h4> + +<p>\x 뒤에 수는 <a href="https://en.wikipedia.org/wiki/Hexadecimal">16진수</a>로 해석(interpreted)됩니다.</p> + +<pre class="brush: js">'\xA9' // "©" +</pre> + +<h4 id="유니코드_이스케이프_시퀀스">유니코드 이스케이프 시퀀스</h4> + +<p>유니코드 이스케이프 시퀀스는 \u 다음에 적어도 네 개의 16진수 숫자(digit)를 필요로 합니다.</p> + +<pre class="brush: js">'\u00A9' // "©"</pre> + +<h4 id="유니코드_코드_포인트_이스케이프">유니코드 코드 포인트 이스케이프</h4> + +<p>ECMAScript 6의 새로운 기능. 유니 코드 포인트 이스케이프를 사용하면 16 진수를 사용하여 모든 문자를 이스케이프 처리 할 수 있으므로 최대 <code>0x10FFFF</code>의 유니 코드 코드 포인트를 사용할 수 있습니다. 간단한 유니 코드 이스케이프를 사용하면 동일한 결과를 얻기 위해서 서로 게이트를 별도로 작성해야하는 경우가 있습니다.</p> + +<p>{{jsxref("String.fromCodePoint()")}} 나 {{jsxref("String.prototype.codePointAt()")}}를 참고하세요.</p> + +<pre class="brush: js">'\u{2F804}' + +// the same with simple Unicode escapes +'\uD87E\uDC04'</pre> + +<h3 id="문자열_개체">문자열 개체</h3> + +<p>{{jsxref("문자열")}} 개체<span>는 문자열 기본 데이터 형식의 래퍼입니다.</span></p> + +<pre class="brush: js">var s = new String("foo"); // Creates a String object +console.log(s); // Displays: { '0': 'f', '1': 'o', '2': 'o'} +typeof s; // Returns 'object' +</pre> + +<p>여러분은 문자열 리터럴 값에 문자열 개체의 방법 중 하나를 호출 할 수 있습니다.—JavaScript가 자동으로 문자열 리터럴을 임시 문자열 개체로 변환하고, 메서드를 호출하고, 그리고나서 임시 문자열 개체를 삭제합니다. 또한, <code>String.length</code> 속성을 문자열 리터럴과 함께 사용할 수 있습니다.</p> + +<p>특별히 <code>String</code> 개체를 사용할 필요가 없지 않는 한, <code>String</code> 개체는 직관에 반하는 행동을 할 수 있기 때문에 여러분은 string 리터럴을 사용해야합니다. 예를들어:</p> + +<pre class="brush: js">var s1 = "2 + 2"; // Creates a string literal value +var s2 = new String("2 + 2"); // Creates a String object +eval(s1); // Returns the number 4 +eval(s2); // Returns the string "2 + 2"</pre> + +<p><span class="atn">문자열 개체</span><span>는</span> <span class="atn hps">문자열</span><span>의 문자 수를</span> <span class="hps">나타내는</span> <span class="atn hps">하나의 속성</span><span>,</span> <span class="atn hps">길이</span><span class="atn">를 갖습니다</span><span>.</span> 예를 들어, "Hello, World!"가 13자 이므로 다음 코드는 <span class="hps">x를 값 13으로 할당합니다. <code>String</code> 객체는 문자열에있는 UTF-16 코드 단위의 수를 나타내는 길이가 하나의 속성을 가집니다. 예를 들어, 다음 코드에서는 "Hello, World!"가 UTF-16 코드 단위로 표현되는 13개의 문자를 가지고 있기 때문에 x 값이 13이 됩니다. 배열 브래킷 스타일을 사용하여 각 코드 단위에 액세스 할 수 있습니다. 문자열은 변경 불가능한 배열과 같은 객체이기 때문에 개별 문자를 변경할 수 없습니다.</span></p> + +<pre><code>var mystring = 'Hello, World!'; +var x = mystring.length; +mystring[0] = 'L'; // This has no effect, because strings are immutable +mystring[0]; // This returns "H"</code></pre> + +<p>유니 코드 스칼라 값이 U + FFFF (희귀 한 중국어 / 일본어 / 한국어 / 베트남어 문자 및 일부 이모티콘)보다 큰 문자는 각각 서로 다른 두 개의 코드 단위로 UTF-16에 저장됩니다. 예를 들어, 단일 문자 U + 1F600 "Emoji grinning face"를 포함하는 문자열은 길이가 2입니다. 대괄호를 사용하여 이러한 문자열의 개별 코드 단위에 액세스하면 일치하지 않는 대리 코드 단위가있는 문자열이 만들어지는 등의 바람직하지 않은 결과가 발생할 수 있습니다. 유니 코드 표준 위반 MDN 버그 857438이 수정 된 후에 예제가 이 페이지에 추가되어야합니다. {{jsxref ( "String.fromCodePoint ()")}} 또는 {{jsxref ( "String.prototype.codePointAt ()")}}도 참조하십시오.</p> + +<p><code>String</code> 객체는 다양한 메서드가 있습니다: 문자열 자체의 변경된 결과를 반환하는 <code>substring</code>과 <code>toUpperCase</code>가 그것!</p> + +<p>다음 표는 {{jsxref("문자열")}} 개체의 메서드를 요약한 것입니다.</p> + +<table class="standard-table"> + <caption> + <h4 id="문자열_메서드">문자열 메서드</h4> + </caption> + <thead> + <tr> + <th scope="col">Method</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{jsxref("String.charAt", "charAt")}}, {{jsxref("String.charCodeAt", "charCodeAt")}}, {{jsxref("String.codePointAt", "codePointAt")}}</td> + <td> + <p>문자열에서 지정된 위치에 있는 문자나 문자 코드를 반환합니다.</p> + </td> + </tr> + <tr> + <td>{{jsxref("String.indexOf", "indexOf")}}, {{jsxref("String.lastIndexOf", "lastIndexOf")}}</td> + <td> + <p>문자열에서 지정된 부분 문자열의 위치나 지정된 부분 문자열의 마지막 위치를 각각 반환합니다.</p> + </td> + </tr> + <tr> + <td>{{jsxref("String.startsWith", "startsWith")}}, {{jsxref("String.endsWith", "endsWith")}}, {{jsxref("String.includes", "includes")}}</td> + <td> + <p>문자열 시작하고, 끝나고, 지정된 문자열을 포함하는지의 여부를 반환합니다.</p> + </td> + </tr> + <tr> + <td>{{jsxref("String.concat", "concat")}}</td> + <td> + <p>두 문자열의 텍스트를 결합하고 새로운 문자열을 반환합니다.</p> + </td> + </tr> + <tr> + <td>{{jsxref("String.fromCharCode", "fromCharCode")}}, {{jsxref("String.fromCodePoint", "fromCodePoint")}}</td> + <td> + <p>유니코드 값의 지정된 시퀀스로부터 문자열을 구축합니다. 문자열 인스턴스가 아닌 문자열 클래스의 메서드입니다.</p> + </td> + </tr> + <tr> + <td>{{jsxref("String.split", "split")}}</td> + <td> + <p>부분 문자열로 문자열을 분리하여 문자열 배열로 문자열 개체를 분할합니다.</p> + </td> + </tr> + <tr> + <td>{{jsxref("String.slice", "slice")}}</td> + <td> + <p>문자열의 한 부분을 추출하고 새 문자열을 반환합니다.</p> + </td> + </tr> + <tr> + <td>{{jsxref("String.substring", "substring")}}, {{jsxref("String.substr", "substr")}}</td> + <td> + <p><span class="hps">어느</span> <span class="hps">시작 및 종료</span> <span class="hps">인덱스</span> <span class="hps">또는</span> <span class="hps">시작 인덱스</span> <span class="hps">및</span> <span class="atn hps">길이</span><span class="atn">를 지정하여, </span><span class="hps">문자열의</span> <span class="hps">지정된</span> <span class="hps">일부를</span> <span class="hps">반환합니다.</span></p> + </td> + </tr> + <tr> + <td>{{jsxref("String.match", "match")}}, {{jsxref("String.replace", "replace")}}, {{jsxref("String.search", "search")}}</td> + <td> + <p><span class="atn hps">정규 표현식</span><span>으로</span> <span class="hps">작업합니다.</span></p> + </td> + </tr> + <tr> + <td>{{jsxref("String.toLowerCase", "toLowerCase")}},<br> + {{jsxref("String.toUpperCase", "toUpperCase")}}</td> + <td> + <p>.<span class="hps">모든</span><span class="hps"> 소문자</span> <span class="hps">또는</span><span class="atn hps"> 대문자에서 각각 문자열을 반환합니다.</span></p> + </td> + </tr> + <tr> + <td>{{jsxref("String.normalize", "normalize")}}</td> + <td><span class="hps">호출</span> <span class="atn hps">문자열 값</span><span>의</span> <span class="hps">유니 코드 표준화</span> <span class="atn hps">양식</span><span>을 반환합니다.</span></td> + </tr> + <tr> + <td>{{jsxref("String.repeat", "repeat")}}</td> + <td> + <p>주어진 회를 반복하는 개체 요소로 이루어진 문자열을 반환합니다.</p> + </td> + </tr> + <tr> + <td>{{jsxref("String.trim", "trim")}}</td> + <td><span class="atn hps">문자열</span><span class="atn">의 시작과 끝</span><span>에서</span> <span class="hps">공백을</span> <span class="atn hps">자릅니다</span><span>.</span></td> + </tr> + </tbody> +</table> + +<h3 id="다중_선_템플릿_문자열">다중 선 템플릿 문자열</h3> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/template_strings">템플릿 문자열</a>은 포함 식을 용납하는 문자열 리터럴입니다. 여러분은 그것들과 함께 다중 선 문자열 및 문자열 보간 기능을 사용할 수 있습니다.</p> + +<p>템플릿 문자열은 작은따옴표나 큰따옴표 대신에 back-tick (` `) (<a class="external external-icon" href="https://en.wikipedia.org/wiki/Grave_accent">grave accent</a>)문자로 묶습니다.<span> </span><span class="hps">템플릿</span> <span class="hps">문자열은</span> <span class="hps">자리 표시자를 </span><span>포함 할 수 있습니다</span>. <span class="hps">이들은</span> <span class="atn hps">달러 기호</span><span>와</span> <span class="atn hps">중괄호</span><span>로 표시됩니다</span>. (<code>${expression}</code>)</p> + +<h4 id="다중_선">다중 선</h4> + +<p>소스에 삽입하는 새로운 선 문자는 템플릿 문자열의 일부입니다. 정상적인 문자열을 사용하면, 여러분은 다중 선 문자열을 얻기 위해 다음과 같은 구문을 사용해야합니다:</p> + +<pre class="brush: js">console.log("string text line 1\n\ +string text line 2"); +// "string text line 1 +// string text line 2"</pre> + +<p>다중 선 문자열과 같은 효과를 얻기 위해, 여러분은 이제 쓸 수 있습니다:</p> + +<pre class="brush: js">console.log(`string text line 1 +string text line 2`); +// "string text line 1 +// string text line 2"</pre> + +<h4 id="포함식">포함식</h4> + +<p>일반 문자열 내에서 표현식을 포함하기 위해, 다음과 같은 구문을 사용합니다:</p> + +<pre class="brush: js">var a = 5; +var b = 10; +console.log("Fifteen is " + (a + b) + " and\nnot " + (2 * a + b) + "."); +// "Fifteen is 15 and +// not 20."</pre> + +<p>이제, 템플릿 문자열을 가지고, 여러분은 읽기와 같이 대체를 만드는 syntactic sugar의 사용을 할 수 있습니다:</p> + +<pre class="brush: js">var a = 5; +var b = 10; +console.log(`Fifteen is ${a + b} and\nnot ${2 * a + b}.`); +// "Fifteen is 15 and +// not 20."</pre> + +<p>자세한 내용은 <a href="/en-US/docs/Web/JavaScript/Reference">JavaScript 참조</a>에서 <a href="/en-US/docs/Web/JavaScript/Reference/template_strings">템플릿 문자열</a>에 대해 읽어보세요.</p> + +<h2 id="국제화">국제화</h2> + +<p>{{jsxref("Intl")}} 개체는 ECMA스크립트 국제 API에 언어와 문자열과 숫자서식과 날짜와 시간서식을 제공하는 명칭공간입니다. {{jsxref("Collator")}}, {{jsxref("NumberFormat")}}, 와 {{jsxref("DateTimeFormat")}} 개체들을 위한 생성자들은 <code>Intl</code> 개체의 특성들입니다.</p> + +<h3 id="날짜와_시간서식">날짜와 시간서식</h3> + +<p>{{jsxref("DateTimeFormat")}} 개체는 날짜와 시간을 서식하기에 유용합니다. 다음 코드는 미국에서 쓰이는 영어로 날짜를 서식합니다. (결과는 다른 시간대와 다릅니다)</p> + +<pre class="brush: js">var msPerDay = 24 * 60 * 60 * 1000; + +// July 17, 2014 00:00:00 UTC. +var july172014 = new Date(msPerDay * (44 * 365 + 11 + 197)); + +var options = { year: "2-digit", month: "2-digit", day: "2-digit", + hour: "2-digit", minute: "2-digit", timeZoneName: "short" }; +var americanDateTime = new Intl.DateTimeFormat("en-US", options).format; + +console.log(americanDateTime(july172014)); // 07/16/14, 5:00 PM PDT +</pre> + +<h3 id="숫자_서식">숫자 서식</h3> + +<p>{{jsxref("NumberFormat")}}개체는 통화를 위해 숫자를 서식하는것에 대해 유용하다.</p> + +<pre class="brush: js">var gasPrice = new Intl.NumberFormat("en-US", + { style: "currency", currency: "USD", + minimumFractionDigits: 3 }); + +console.log(gasPrice.format(5.259)); // $5.259 + +var hanDecimalRMBInChina = new Intl.NumberFormat("zh-CN-u-nu-hanidec", + { style: "currency", currency: "CNY" }); + +console.log(hanDecimalRMBInChina.format(1314.25)); // ¥ 一,三一四.二五 +</pre> + +<h3 id="조합">조합</h3> + +<p>{{jsxref("Collator")}}개체는 문자열을 비교하고 구분하는 것에 대해 유용합니다.</p> + +<p>예를 들어, 실제로 독일에선 phonebook과 dictionary라는 2개의 다른 종류의 명령어들이 있습니다. 전화기록부류는 소리를 강조합니다. 그리고 구분에 앞서 다른것들은 “ä”, “ö”인것처럼 "ae", "oe"로 확장됐습니다. </p> + +<pre class="brush: js">var names = ["Hochberg", "Hönigswald", "Holzman"]; + +var germanPhonebook = new Intl.Collator("de-DE-u-co-phonebk"); + +// as if sorting ["Hochberg", "Hoenigswald", "Holzman"]: +console.log(names.sort(germanPhonebook.compare).join(", ")); +// logs "Hochberg, Hönigswald, Holzman" +</pre> + +<p>어떤 독일말들은 여분의 변모음과 함께 활용한다. 그래서 사전안에서 이것은 변모음을 무시하라고 명령하기에 실용적이다.</p> + +<pre class="brush: js">var germanDictionary = new Intl.Collator("de-DE-u-co-dict"); + +// as if sorting ["Hochberg", "Honigswald", "Holzman"]: +console.log(names.sort(germanDictionary.compare).join(", ")); +// logs "Hochberg, Holzman, Hönigswald" +</pre> + +<p>{{jsxref("Intl")}}API에 대한 자세한 내용은 <a href="https://hacks.mozilla.org/2014/12/introducing-the-javascript-internationalization-api/">Introducing the JavaScript Internationalization API</a>를 참조하세요.</p> + +<p>{{PreviousNext("Web/JavaScript/Guide/Numbers_and_dates", "Web/JavaScript/Guide/Regular_Expressions")}}</p> diff --git a/files/ko/web/javascript/guide/using_promises/index.html b/files/ko/web/javascript/guide/using_promises/index.html new file mode 100644 index 0000000000..bc847e561a --- /dev/null +++ b/files/ko/web/javascript/guide/using_promises/index.html @@ -0,0 +1,361 @@ +--- +title: Using promises +slug: Web/JavaScript/Guide/Using_promises +tags: + - Promise + - Promises +translation_of: Web/JavaScript/Guide/Using_promises +--- +<div>{{jsSidebar("JavaScript Guide")}}{{PreviousNext("Web/JavaScript/Guide/Details_of_the_Object_Model", "Web/JavaScript/Guide/Iterators_and_Generators")}}</div> + +<p class="summary">{{jsxref("Promise")}}는 비동기 작업의 최종 완료 또는 실패를 나타내는 객체입니다. 대부분 여러분은 이미 만들어진 promise를 사용했었기 때문에 이 가이드에서는 어떻게 promise를 만드는지 설명하기에 앞서 promise의 사용법에 대해 설명합니다.</p> + +<p>기본적으로 promise는 함수에 콜백을 전달하는 대신에, 콜백을 첨부하는 방식의 객체입니다.<br> + </p> + +<p>비동기로 음성 파일을 생성해주는 <code>createAudioFileAsync()</code>라는 함수가 있었다고 생각해보세요. 해당 함수는 음성 설정에 대한 정보를 받고, 두 가지 콜백 함수를 받습니다. 하나는 음성 파일이 성공적으로 생성되었을때 실행되는 콜백, 그리고 다른 하나는 에러가 발생했을때 실행되는 콜백입니다.</p> + +<p><code>createAudioFileAsync()</code>는 함수는 아래와 같이 사용됩니다. </p> + +<pre class="notranslate"><code>function successCallback(result) { + console.log("Audio file ready at URL: " + result); +}</code> + +<code>function failureCallback(error) { + console.log("Error generating audio file: " + error); +}</code> + +<code>createAudioFileAsync(audioSettings, successCallback, failureCallback);</code></pre> + +<p>…모던한 함수들은 위와 같이 콜백들을 전달지 않고 콜백을 붙여 사용할 수 있게 Promise를 반환해줍니다.</p> + +<p>만약 <code>createAudioFileAsync()</code> 함수가 Promise를 반환해주도록 수정해본다면, 다음과 같이 간단하게 사용되어질 수 있습니다.</p> + +<pre class="notranslate"><code><span style='background-color: rgba(220, 220, 220, 0.5); font-family: consolas,"Liberation Mono",courier,monospace; font-style: inherit; font-weight: inherit;'>createAudioFileAsync(audioSettings).then(successCallback, failureCallback);</span></code></pre> + +<p>…조금 더 간단하게 써보자면:</p> + +<pre class="notranslate"><code>const promise = createAudioFileAsync(audioSettings); +promise.then(successCallback, failureCallback);</code></pre> + +<p>우리는 이와 같은 것을 <em>비동기 함수 호출</em>이라고 부릅니다. 이런 관례는 몇 가지 장점을 갖고 있습니다. 각각에 대해 한번 살펴보도록 합시다.</p> + +<h2 id="Guarantees">Guarantees</h2> + +<p>콜백 함수를 전달해주는 고전적인 방식과는 달리, Promise는 아래와 같은 특징을 보장합니다.</p> + +<ul> + <li>콜백은 자바스크립트 Event Loop이 <a href="/en-US/docs/Web/JavaScript/EventLoop#Run-to-completion">현재 실행중인 콜 스택을 완료</a>하기 이전에는 절대 호출되지 않습니다.</li> + <li>비동기 작업이 성공하거나 실패한 뒤에 <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then">then()</a></code> 을 이용하여 추가한 콜백의 경우에도 위와 같습니다.</li> + <li><code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then">then()</a></code>을 여러번 사용하여 여러개의 콜백을 추가 할 수 있습니다. 그리고 각각의 콜백은 주어진 순서대로 하나 하나 실행되게 됩니다.</li> +</ul> + +<p>Promise의 가장 뛰어난 장점 중의 하나는 <strong>chaining</strong>입니다.</p> + +<h2 id="Chaining">Chaining</h2> + +<p>보통 하나나 두 개 이상의 비동기 작업을 순차적으로 실행해야 하는 상황을 흔히 보게 됩니다. 순차적으로 각각의 작업이 이전 단계 비동기 작업이 성공하고 나서 그 결과값을 이용하여 다음 비동기 작업을 실행해야 하는 경우를 의미합니다. 우리는 이런 상황에서 <strong>promise chain</strong>을 이용하여 해결하기도 합니다.</p> + +<p><code>then()</code> 함수는 새로운 promise를 반환합니다. 처음에 만들었던 promise와는 다른 새로운 promise입니다.</p> + +<pre class="brush: js notranslate">const promise = doSomething(); +const promise2 = promise.then(successCallback, failureCallback); +</pre> + +<p>또는</p> + +<pre class="brush: js notranslate">const promise2 = doSomething().then(successCallback, failureCallback); +</pre> + +<p>두 번째 promise는 <code>doSomething()</code> 뿐만 아니라 <code>successCallback</code> or <code>failureCallback</code> 의 완료를 의미합니다. <code>successCallback</code> or <code>failureCallback</code> 또한 promise를 반환하는 비동기 함수일 수도 있습니다. 이 경우 <code>promise2</code>에 추가 된 콜백은 <code>successCallback</code>또는 <code>failureCallback</code>에 의해 반환된 promise 뒤에 대기합니다.</p> + +<p>기본적으로, 각각의 promise는 체인 안에서 서로 다른 비동기 단계의 완료를 나타냅니다.</p> + +<p>예전에는 여러 비동기 작업을 연속적으로 수행하면 고전적인 '지옥의 콜백 피라미드'가 만들어 졌었습니다.</p> + +<pre class="brush: js notranslate">doSomething(function(result) { + doSomethingElse(result, function(newResult) { + doThirdThing(newResult, function(finalResult) { + console.log('Got the final result: ' + finalResult); + }, failureCallback); + }, failureCallback); +}, failureCallback); +</pre> + +<p>모던한 방식으로 접근한다면, 우리는 콜백 함수들을 반환된 promise에 promise chain을 형성하도록 추가할 수 있습니다:</p> + +<pre class="brush: js notranslate">doSomething().then(function(result) { + return doSomethingElse(result); +}) +.then(function(newResult) { + return doThirdThing(newResult); +}) +.then(function(finalResult) { + console.log('Got the final result: ' + finalResult); +}) +.catch(failureCallback); +</pre> + +<p><code>then</code> 에 넘겨지는 인자는 선택적(optional)입니다. 그리고 <code>catch(failureCallback)</code> 는 <code>then(null, failureCallback)</code> 의 축약입니다. 이 표현식을 <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">화살표 함수</a>로 나타내면 다음과 같습니다.</p> + +<pre class="brush: js notranslate">doSomething() +.then(result => doSomethingElse(result)) +.then(newResult => doThirdThing(newResult)) +.then(finalResult => { + console.log(`Got the final result: ${finalResult}`); +}) +.catch(failureCallback); +</pre> + +<p><strong>중요:</strong> 반환값이 반드시 있어야 합니다, 만약 없다면 콜백 함수가 이전의 promise의 결과를 받지 못합니다.<br> + (화살표 함수 () => x는 () => {return x;}와 같습니다).</p> + +<h3 id="Chaining_after_a_catch">Chaining after a catch</h3> + +<p>chain에서 작업이 실패한 후에도 새로운 작업을 수행하는 것이 가능하며 매우 유용합니다. (예 : <code>catch</code>) 다음 예를 읽으십시오:</p> + +<pre class="brush: js notranslate">new Promise((resolve, reject) => { + console.log('Initial'); + + resolve(); +}) +.then(() => { + throw new Error('Something failed'); + + console.log('Do this'); +}) +.catch(() => { + console.log('Do that'); +}) +.then(() => { + console.log('Do this, whatever happened before'); +}); +</pre> + +<p>그러면 다음 텍스트가 출력됩니다.</p> + +<pre class="notranslate">Initial +Do that +Do this, whatever happened before +</pre> + +<p><strong>참고:</strong> "Do this" 텍스트가 출력되지 않은 것을 주의깊게 보십시오. "Something failed" 에러가 rejection을 발생시켰기 때문입니다.</p> + +<h2 id="Error_propagation">Error propagation</h2> + +<p>'콜백 지옥'에서 <code>failureCallback</code>이 3번 발생한 것을 기억 할 것입니다. promise chain에서는 단 한 번만 발생하는것과 비교되죠.</p> + +<pre class="notranslate"><code>doSomething() +.then(result => doSomethingElse(result)) +.then(newResult => doThirdThing(newResult)) +.then(finalResult => console.log(`Got the final result: ${finalResult}`)) +.catch(failureCallback);</code></pre> + +<p>기본적으로 promise chain은 예외가 발생하면 멈추고 chain의 아래에서 catch를 찾습니다. 이것은 동기 코드가 어떻게 동작 하는지 모델링 한 것입니다.</p> + +<pre class="notranslate"><code>try { + const result = syncDoSomething(); + const newResult = syncDoSomethingElse(result); + const finalResult = syncDoThirdThing(newResult); + console.log(`Got the final result: ${finalResult}`); +} catch(error) { + failureCallback(error); +}</code></pre> + +<p>비동기 코드를 사용한 이러한 대칭성은 ECMAScript 2017에서 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function"><code>async</code>/<code>await</code></a> 구문(Syntactic sugar) 에서 최고로 느낄 수 있습니다.</p> + +<pre class="notranslate"><code>async function foo() { + try { + const result = await doSomething(); + const newResult = await doSomethingElse(result); + const finalResult = await doThirdThing(newResult); + console.log(`Got the final result: ${finalResult}`); + } catch(error) { + failureCallback(error); + } +}</code></pre> + +<p>이것은 promise를 기반으로 합니다. <code>doSomething()</code>은 이전 함수와 같습니다. 문법은 <a href="https://developers.google.com/web/fundamentals/getting-started/primers/async-functions">이곳</a>에서 확인 할 수 있습니다.</p> + +<p>Promise는 모든 오류를 잡아내어, 예외 및 프로그래밍 오류가 발생해도 콜백 지옥의 근본적인 결함을 해결합니다. 이는 비동기 작업의 기능 구성에 필수적입니다.</p> + +<h2 id="Promise_rejection_events">Promise rejection events</h2> + +<p>Promise가 reject될 때마다 두 가지 이벤트 중 하나가 전역 범위에 발생합니다.(일반적으로, 전역 범위는 {{domxref("window")}}거나, 웹 워커에서 사용되는 경우, {{domxref("Worker")}}, 혹은 워커 기반 인터페이스입니다.) 두 가지 이벤트는 다음과 같습니다.</p> + +<dl> + <dt>{{domxref("Window.rejectionhandled_event", "rejectionhandled")}}</dt> + <dd>executor의 <code>reject</code>함수에 의해 reject가 처리 된 후 promise가 reject 될 때 발생합니다.</dd> + <dt>{{domxref("Window.unhandledrejection_event", "unhandledrejection")}}</dt> + <dd>promise가 reject되었지만 사용할 수 있는 reject 핸들러가 없을 때 발생합니다.</dd> +</dl> + +<p>({{domxref("PromiseRejectionEvent")}} 유형인) 두 이벤트에는 멤버 변수인 promise와 reason 속성이 있습니다. {{domxref ( "PromiseRejectionEvent.promise", "promise")}}는 reject된 promise를 가리키는 속성이고, {{domxref ( "PromiseRejectionEvent.reason", "reason")}}은 promise가 reject된 이유를 알려 주는 속성입니다.</p> + +<p>이들을 이용해 프로미스에 대한 에러 처리를 대체(fallback)하는 것이 가능해지며, 또한 프로미스 관리시 발생하는 이슈들을 디버깅하는 데 도움을 얻을 수 있습니다. 이 핸들러들은 모든 맥락에서 전역적(global)이기 때문에, 모든 에러는 발생한 지점(source)에 상관없이 동일한 핸들러로 전달됩니다.</p> + +<p>특히 유용한 사례 : {{Glossary("Node.js")}}로 코드를 작성할 때, 흔히 프로젝트에서 사용하는 모듈이 reject된 프로미스를 처리하지 않을 수 있습니다. 이런 경우 노드 실행시 콘솔에 로그가 남습니다. 이를 수집에서 분석하고 직접 처리할 수도 있습니다. 아니면 그냥 콘솔 출력을 어지럽히는 것을 막기 위해 그럴 수도 있죠. 이런 식으로 {{domxref("Window.unhandledrejection_event", "unhandledrejection")}}(<a href="/en-US/docs/Web/API/Window/unhandledrejection_event">영어</a>) 이벤트를 처리하는 핸들러를 추가하면 됩니다.</p> + +<pre class="notranslate"><code>window.addEventListener("unhandledrejection", event => { + /* You might start here by adding code to examine the + promise specified by event.promise and the reason in + event.reason */ + + event.preventDefault(); +}, false);</code></pre> + +<p>이벤트의 {{domxref("Event.preventDefault", "preventDefault()")}} 메서드를 호출하면 reject 된 프로미스가 처리되지 않았을 때 JavaScript 런타임이 기본 동작을 수행하지 않습니다. 이 기본 동작은 대개 콘솔에 오류를 기록하는 것이기 때문에, 이것은 확실히 NodeJS를 위한 것이죠.</p> + +<p>제대로 하려면, 당연한 말이지만, 이 이벤트를 그냥 무시해버리기 전에 reject된 프로미스 코드에 실제로 버그가 없는지 확실히 검사해야 합니다.</p> + +<h2 id="오래된_콜백_API를_사용하여_Promise만들기">오래된 콜백 API를 사용하여 Promise만들기</h2> + +<p>{{jsxref ( "Promise")}}는 생성자를 사용하여 처음부터 생성 될 수 있습니다. 이것은 오래된 API를 감쌀 때만 필요합니다.</p> + +<p>이상적인 프로그래밍 세계에서는 모든 비동기 함수는 promise을 반환해야 하지만. 불행히도 일부 API는 여전히 success 및 / 또는 failure 콜백을 전달하는 방식일거라 생각합니다.. 예를 들면 {{domxref ( "WindowTimers.setTimeout", "setTimeout ()")}} 함수가 있습니다.</p> + +<pre class="notranslate"><code>setTimeout(() => saySomething("10 seconds passed"), 10000);</code> +</pre> + +<p>예전 스타일의 콜백과 Promise를 합치는것 문제가 있습니다. 함수 <code>saySomething()</code>이 실패하거나 프로그래밍 오류가 있으면 아무 것도 잡아 내지 않습니다. <code>setTimeout</code>의 문제점 입니다.</p> + +<p>다행히도 우리는 <code>setTimeout</code>을 Promise로 감쌀 수 있습니다. 가장 좋은 방법은 가능한 가장 낮은 수준에서 문제가되는 함수를 래핑 한 다음 다시는 직접 호출하지 않는 것입니다.</p> + +<pre class="notranslate"><code>const wait = ms => new Promise(resolve => setTimeout(resolve, ms)); + +wait(10000).then(() => saySomething("10 seconds")).catch(failureCallback);</code> +</pre> + +<p>기본적으로 promise constructor는 promise를 직접 해결하거나 reject 할 수 있는 실행자 함수를 사용합니다. <code>setTimeout()</code>은 함수에서 fail이 일어나거나 error가 발생하지 않기 때문에 이 경우 reject를 사용하지 않습니다.</p> + +<h2 id="Composition">Composition</h2> + +<p>{{jsxref ( "Promise.resolve ()")}}와 {{jsxref ( "Promise.reject ()")}}는 각각 이미 resolve되거나 reject 된 promise를 여러분이 직접 생성하기위한 바로 가기입니다. 가끔 유용하게 사용됩니다.</p> + +<p>{{jsxref("Promise.all()")}}와 {{jsxref("Promise.race()")}}는 비동기 작업을 병렬로 실행하기위한 두 가지 구성 도구입니다.</p> + +<p>우리는 병렬로 작업을 시작하고 모든 작업이 다음과 같이 끝날 때까지 기다릴 수 있습니다.</p> + +<pre class="notranslate"><code>Promise.all([func1(), func2(), func3()]) +.then(([result1, result2, result3]) => { /* use result1, result2 and result3 */ });</code></pre> + +<p>Sequential composition is possible using some clever JavaScript:</p> + +<p>고급진 JavaScript를 사용하여 순차적 구성이 가능합니다.</p> + +<pre class="notranslate"><code>[func1, func2, func3].reduce((p, f) => p.then(f), Promise.resolve()) +.then(result3 => { /* use result3 */ });</code> +</pre> + +<p>기본적으로 <code>Promise.resolve().then(func1).then(func2).then(func3);</code>과 같은 약속 체인으로 비동기 함수 배열을 축소합니다.</p> + +<p>이것은 재사용 가능한 작성 기능으로 만들 수 있는데, 이는 함수형 프로그래밍에서 일반적인 방식입니다.</p> + +<pre class="notranslate"><code>const applyAsync = (acc,val) => acc.then(val); +const composeAsync = (...funcs) => x => funcs.reduce(applyAsync, Promise.resolve(x));</code> +</pre> + +<p><code>composeAsync()</code> 함수는 여러 함수를 인수로 받아들이고 composition 파이프 라인을 통해 전달되는 초기 값을 허용하는 새 함수를 반환합니다.</p> + +<pre class="notranslate"><code>const transformData = composeAsync(func1, func2, func3); +const result3 = transformData(data);</code> +</pre> + +<p>ECMAScript 2017에서는 async / await를 사용하여 순차적 구성을보다 간단하게 수행 할 수 있습니다.</p> + +<pre class="notranslate"><code>let result; +for (const f of [func1, func2, func3]) { + result = await f(result); +} +/* use last result (i.e. result3) */</code></pre> + +<h2 id="Timing">Timing</h2> + +<p>To avoid surprises, functions passed to <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then">then()</a></code> will never be called synchronously, even with an already-resolved promise:</p> + +<p>놀라움(역자 주. 에러가 난다거나, 코드가 문제가 생긴다거나..했을때의 그 놀라움..)을 피하기 위해 <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then">then()</a></code>에 전달 된 함수는 already-resolved promise에 있는 경우에도 동기적으로 호출되지 않습니다.</p> + +<pre class="notranslate"><code>Promise.resolve().then(() => console.log(2)); +console.log(1); // 1, 2</code> +</pre> + +<p>즉시 실행되는 대신 전달 된 함수는 마이크로 태스크 대기열에 저장됩니다. 즉, 자바 스크립트 이벤트 루프의 현재 실행이 끝날 때 대기열이 비면 나중에 실행됩니다.</p> + +<pre class="notranslate"><code>const wait = ms => new Promise(resolve => setTimeout(resolve, ms)); + +wait().then(() => console.log(4)); +Promise.resolve().then(() => console.log(2)).then(() => console.log(3)); +console.log(1); // 1, 2, 3, 4</code></pre> + +<h2 id="Nesting">Nesting</h2> + +<div class="blockIndicator note"> +<p>역자 주. 아래부분에 대한 번역이 미흡합니다. 원문을 참고해 주세요</p> +</div> + +<p>간단한 promise 체인은 중첩이 부주의 한 구성의 결과 일 수 있으므로 중첩하지 않고 평평하게 유지하는 것이 가장 좋습니다. <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/Using_promises#Common_mistakes">common mistakes</a>를 참조하십시오.</p> + +<p>(Simple promise chains are best kept flat without nesting, as nesting can be a result of careless composition. See <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/Using_promises#Common_mistakes">common mistakes</a>.)</p> + +<p>중첩은 <code>catch</code> 문 범위를 제한하는 제어 구조입니다. 특히, 중첩 된 <code>catch</code>는 중첩 된 범위 외부의 체인에있는 오류가 아닌 범위 및 그 이하의 오류 만 잡습니다. 올바르게 사용하면 오류 복구에서보다 정확한 결과를 얻을 수 있습니다.</p> + +<pre class="notranslate"><code>doSomethingCritical() +.then(result => doSomethingOptional(result) + .then(optionalResult => doSomethingExtraNice(optionalResult)) + .catch(e => {})) // Ignore if optional stuff fails; proceed. +.then(() => moreCriticalStuff()) +.catch(e => console.log("Critical failure: " + e.message));</code> +</pre> + +<p>여기에 있는 선택적 단계는 들여 쓰기가 아닌 중첩되어 있지만 주위의 바깥 쪽 <code>(</code> 및 <code>)</code> 의 규칙적이지 않은 배치를 하지않도록 조심하세요.</p> + +<p>inner neutralizing <code>catch</code> 문은 <code>doSomethingOptional()</code>및 <code>doSomethingExtraNice()</code>에서 발생한 오류를 catch 한 후에 코드가 <code>moreCriticalStuff()</code>로 다시 시작됩니다. 중요하게도 <code>doSomethingCritical()</code>이 실패하면 해당 오류는 최종 (외부) <code>catch</code>에 의해서만 포착됩니다.</p> + +<h2 id="Common_mistakes">Common mistakes</h2> + +<p>promise chains을 작성할 때 주의해야 할 몇 가지 일반적인 실수는 다음과 같습니다. 이러한 실수 중 몇 가지는 다음 예제에서 나타납니다.</p> + +<pre class="notranslate"><code>// Bad example! Spot 3 mistakes! + +doSomething().then(function(result) { + doSomethingElse(result) // Forgot to return promise from inner chain + unnecessary nesting + .then(newResult => doThirdThing(newResult)); +}).then(() => doFourthThing()); +// Forgot to terminate chain with a catch!</code> +</pre> + +<p>첫 번째 실수는 제대로 체인을 연결하지 않는 것입니다. 이것은 우리가 새로운 promise를 만들었지 만 그것을 반환하는 것을 잊었을때 일어납니다. 결과적으로 체인이 끊어 지거나 오히려 두 개의 독립적 인 체인이 경쟁하게됩니다. 즉, <code>doFourthThing()</code>은 <code>doSomethingElse()</code> 또는 <code>doThirdThing()</code>이 완료 될 때까지 기다리지 않고 의도하지 않은 것처럼 병렬로 실행됩니다. 별도의 체인은 별도의 오류 처리 기능을 가지고있어서 잡기 어려운 오류가 발생합니다.</p> + +<p>두 번째 실수는 불필요하게 중첩되어 첫 번째 실수를 가능하게 만드는 것입니다. 중첩은 내부 오류 처리기의 범위를 제한합니다. 의도하지 않은 경우 에러가 캐치되지 않는 오류가 발생할 수 있습니다. 이 변형은 <a href="https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it">promise constructor anti-pattern</a>입니다.이 패턴은 이미 약속을 사용하는 코드를 감싸기 위해 promise 생성자의 중복 사용과 중첩을 결합합니다.</p> + +<p>세 번째 실수는 <code>catch</code>로 체인을 종료하는 것을 잊는 것입니다. 약속되지 않은 약속 체인은 대부분의 브라우저에서 예상하지 못한 약속 거부를 초래합니다.</p> + +<p>좋은 경험 법칙은 항상 약속의 사슬을 반환하거나 종결하는 것이며, 새로운 약속을 얻 자마자 즉각적으로 돌려서 물건을 평평하게하는 것입니다.</p> + +<pre class="notranslate"><code>doSomething() +.then(function(result) { + return doSomethingElse(result); +}) +.then(newResult => doThirdThing(newResult)) +.then(() => doFourthThing()) +.catch(error => console.log(error));</code></pre> + +<p><code>() => x</code> 은 <code>() => { return x; }</code>.의 축약형임을 참고하세요</p> + +<p>이제는 적절한 오류 처리 기능을 갖춘 결정성있는 단일 체인이 있습니다.</p> + +<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function"><code>async</code>/<code>await</code></a>를 사용하면 대부분의 문제를 해결할 수 있습니다. 이러한 문법의 가장 흔한 실수는 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function"><code>await</code></a>키워드를 빼먹는 것입니다.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Promise.then()")}}</li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function"><code>async</code>/<code>await</code></a> </li> + <li><a href="http://promisesaplus.com/">Promises/A+ specification</a></li> + <li><a href="https://medium.com/@ramsunvtech/promises-of-promise-part-1-53f769245a53">Venkatraman.R - JS Promise (Part 1, Basics)</a></li> + <li><a href="https://medium.com/@ramsunvtech/js-promise-part-2-q-js-when-js-and-rsvp-js-af596232525c#.dzlqh6ski">Venkatraman.R - JS Promise (Part 2 - Using Q.js, When.js and RSVP.js)</a></li> + <li><a href="https://tech.io/playgrounds/11107/tools-for-promises-unittesting/introduction">Venkatraman.R - Tools for Promises Unit Testing</a></li> + <li><a href="http://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html">Nolan Lawson: We have a problem with promises — Common mistakes with promises</a></li> +</ul> + +<p>{{PreviousNext("Web/JavaScript/Guide/Details_of_the_Object_Model", "Web/JavaScript/Guide/Iterators_and_Generators")}}</p> diff --git a/files/ko/web/javascript/guide/values,_variables,_and_literals/index.html b/files/ko/web/javascript/guide/values,_variables,_and_literals/index.html new file mode 100644 index 0000000000..629cbd069a --- /dev/null +++ b/files/ko/web/javascript/guide/values,_variables,_and_literals/index.html @@ -0,0 +1,708 @@ +--- +title: 문법과 자료형 +slug: 'Web/JavaScript/Guide/Values,_variables,_and_literals' +tags: + - Guide + - JavaScript + - 'l10n:priority' +translation_of: Web/JavaScript/Guide/Grammar_and_types +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/소개", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}</div> + +<p class="summary">이 장은 JavaScript의 기본 문법과 변수 선언, 자료형 및 리터럴을 다룹니다.</p> + +<h2 id="기본">기본</h2> + +<p>JavaScript는 문법의 대부분을 Java와 C, C++로부터 차용하고 있으며, Awk, Perl, Python의 영향도 받았습니다.</p> + +<p>JavaScript는 <strong>대소문자를 구별</strong>하며 <strong>유니코드</strong> 문자셋을 이용합니다. 따라서 다음과 같은 코드도 유효합니다.</p> + +<pre class="brush: js">var 갑을 = "병정"; +var Früh = "foobar"; // Früh: 독일어로 "이른" +</pre> + +<p>하지만 <code>Früh</code>는 <code>früh</code>와 다릅니다. 대소문자를 구분하기 때문입니다.</p> + +<p>JavaScript에서는 명령을 {{Glossary("Statement", "명령문(statement)")}}이라고 부르며, 세미콜론(<code>;</code>)으로 구분합니다.</p> + +<p>명령문이 한 줄을 다 차지할 경우에는 세미콜론이 필요하지 않습니다. 그러나 한 줄에 두 개 이상의 명령문이 필요하다면 세미콜론으로 구분해야 합니다. ECMAScript는 세미콜론을 자동으로 삽입해 명령문을 끝내는 규칙(ASI)도 가지고 있습니다. (더 많은 정보는 JavaScript의 <a href="/ko/docs/Web/JavaScript/Reference/Lexical_grammar">어휘 문법 에 대한 자세한 참고서</a>를 참고하세요) 하지만, 세미콜론이 필요하지 않은 경우라도 항상 세미콜론으로 끝마치는 편이 버그 예방 차원에서 더 좋은 습관이라고 여겨집니다.</p> + +<p>JavaScript의 스크립트 소스는 왼쪽에서 오른쪽으로 탐색하면서 토큰, 제어 문자, 줄바꿈 문자, 주석이나 공백으로 이루어진 입력 element의 시퀀스로 변환됩니다. 스페이스, 탭, 줄바꿈 문자는 공백으로 간주됩니다.</p> + +<h2 id="주석">주석</h2> + +<p><strong>주석</strong>의 구문은 C++ 및 다른 많은 언어와 똑같습니다.</p> + +<pre class="brush: js">// 한 줄 주석 + +/* 이건 더 긴, + * 여러 줄 주석입니다. + */ + +/* 그러나, /* 중첩된 주석은 쓸 수 없습니다 */ SyntaxError */</pre> + +<p>주석은 공백처럼 행동하며 스크립트 실행 시 버려집니다.</p> + +<div class="blockIndicator note"> +<p><strong>참고</strong>: 몇몇 자바스크립트 파일의 시작부에 <code>#!/usr/bin/env node</code>와 같은 형태의 주석 문법이 쓰이는 것을 볼 수 있습니다. 이것은 <strong>해시백 주석</strong> 문법이라고 하는데, 이 특별한 주석은 스크립트를 실행할 때 쓸 특별한 자바스크립트 인터프리터의 경로를 설정할 때 쓰입니다. <a href="https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Hashbang_comments">해시백 주석</a>을 참고하여 자세한 내용을 확인할 수 있습니다.</p> +</div> + +<h2 id="선언">선언</h2> + +<p>JavaScript의 선언에는 3가지 방법이 있습니다.</p> + +<dl> + <dt>{{jsxref("Statements/var", "var")}}</dt> + <dd>변수를 선언. 추가로 동시에 값을 초기화.</dd> + <dt>{{jsxref("Statements/let", "let")}}</dt> + <dd>블록 범위(scope) 지역 변수를 선언. 추가로 동시에 값을 초기화.</dd> + <dt>{{jsxref("Statements/const", "const")}}</dt> + <dd>블록 범위 읽기 전용 상수를 선언.</dd> +</dl> + +<h3 id="변수">변수</h3> + +<p>어플리케이션에서 값에 상징적인 이름으로 변수를 사용합니다. 변수명은 {{Glossary("식별자(identifier)")}}라고 불리며 특정 규칙을 따릅니다.</p> + +<p>JavaScript 식별자는 문자, 밑줄(_) 혹은 달러 기호($)로 시작해야 하는 반면 이후는 숫자(0-9)일 수도 있습니다. JavaScript가 대소문자를 구분하기에, 문자는 "A"부터 "Z"(대문자)와 "a"부터 "z"(소문자)까지 모두 포함합니다.</p> + +<p>ISO 8859-1 혹은 Unicode 문자(가령 å 나 ü)도 식별자에 사용할 수 있습니다(좀 더 상세한 내용은 <a href="https://mathiasbynens.be/notes/javascript-identifiers-es6">이 블로그 글</a>을 참고). 또한 <a href="/ko/docs/Web/JavaScript/Reference/Lexical_grammar#String_literals">Unicode escape sequences</a>도 식별자에 문자로 사용할 수 있습니다.</p> + +<p>적절한 이름으로는 <code>Number_hits</code>, <code>temp99, $credit</code> 및 <code>_name</code>등입니다.</p> + +<h3 id="변수_선언">변수 선언</h3> + +<p>변수 선언은 아래 3가지 방법으로 가능합니다.</p> + +<ul> + <li>{{jsxref("Statements/var", "var")}} 키워드로. 예를 들어, <code>var x = 42</code>. 이 구문은 지역 및 전역 변수를 선언하는데 모두 사용될 수 있습니다.</li> + <li>{{jsxref("Statements/let", "let")}} 키워드로. 예를 들어, <code>let y = 13</code>. 이 구문은 블록 범위 지역 변수를 선언하는데 사용될 수 있습니다. 아래 <a href="/ko/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#변수_범위">변수 범위</a> 참고하세요.</li> +</ul> + +<p>간단히 변수에 값을 할당 할 수도 있습니다. 예를 들어, <code>x = 42 </code>와 같은 구문은 <strong><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#Description">선언되지 않는 전역변수 </a></strong>를 만듭니다. 뿐만 아니라, 자바스크립트의 엄격한 경고를 만들어냅니다. 선언되지 않은 전역변수는 의도되지 않은 동작을 만들어내고는 합니다. 따라서 선언되지 않는 전역변수를 사용하면 안됩니다.</p> + +<h3 id="변수_할당">변수 할당</h3> + +<p>지정된 초기값 없이 <code>var</code> 혹은 <code>let</code> 문을 사용해서 선언된 변수는 {{jsxref("undefined")}} 값을 갖습니다.</p> + +<p>선언되지 않은 변수에 접근을 시도하는 경우 {{jsxref("ReferenceError")}} 예외가 발생합니다.</p> + +<pre class="brush: js">var a; +console.log("a 값은 " + a); // "a 값은 undefined"로 로그가 남음. + +console.log('b 값은 ' + b); // b 값은 undefined +var b; + +console.log("c 값은 " + c); // ReferenceError 예외 던짐 + +let x; +console.log('x 값은 ' + x); // x 값은 undefined + +console.oog('y 값은 ' + y); // ReferenceError 예외 던짐 +let y; +</pre> + +<p><code>undefined</code>를 사용하여 변수값이 있는지 확인할 수 있습니다. 아래 코드에서, <code>input</code> 변수는 값이 할당되지 않았고 <code><a href="/ko/docs/Web/JavaScript/Reference/Statements/if...else">if</a></code>문은 <code>true</code>로 평가합니다.</p> + +<pre class="brush: js">var input; +if(input === undefined) { + doThis(); +} else { + doThat(); +} +</pre> + +<p><code>undefined</code> 값은 <code>boolean</code> 문맥(context)에서 사용될 때 <code>false</code>로 동작합니다. 예를 들어, 아래 코드는 <code>myArray</code> 요소가 <code>undefined</code>이므로 <code>myFunction</code> 함수를 실행합니다.</p> + +<pre class="brush: js">var myArray = []; +if (!myArray[0]) myFunction(); +</pre> + +<p><code>undefined</code> 값은 수치 문맥에서 사용될 때 <code>NaN</code>으로 변환됩니다.</p> + +<pre class="brush: js">var a; +a + 2; // NaN으로 평가</pre> + +<p>{{jsxref("null")}} 값을 평가할 때, 수치 문맥에서는 0으로, <code>boolean</code> 문맥에서는 <code>false</code>로 동작합니다. 예를 들면,</p> + +<pre class="brush: js">var n = null; +console.log(n * 32); // 콘솔에 0 으로 로그가 남음. +</pre> + +<h3 id="변수_범위">변수 범위</h3> + +<p>어떤 함수의 바깥에 변수를 선언하면, 현재 문서의 다른 코드에 해당 변수를 사용할 수 있기에 <em>전역</em> 변수라고 합니다. 만약 함수 내부에 변수를 선언하면, 오직 그 함수 내에서만 사용할 수 있기에 <em>지역</em> 변수라고 부릅니다.</p> + +<p>ECMAScript 6 이전의 JavaScript는 <a href="/ko/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#Block_문">block 문</a> 범위가 없습니다. 그래서 오히려, 블록 내에 선언된 변수는 그 블록 내에 존재하는 <em>함수(혹은 전역 범위)</em>에 지역적입니다. 예를 들어서 아래의 코드는 5라는 로그를 남깁니다. <code>x</code>의 범위가 이 경우 <code>if</code>문 블록이 아니라 x가 선언된 함수(나 전역 문맥)이기 때문입니다.</p> + +<pre class="brush: js">if (true) { + var x = 5; +} +console.log(x); // 5 +</pre> + +<p>ECMAScript 6에 도입된 <code>let</code> 선언을 사용했을 때, 이 동작은 바뀌었습니다.</p> + +<pre class="brush: js">if (true) { + let y = 5; +} +console.log(y); // ReferenceError: y is not defined</pre> + +<h3 id="변수_호이스팅">변수 호이스팅</h3> + +<p>또 다른 JavaScript 변수의 특이한 점은 예외를 받지 않고도, 나중에 선언된 변수를 참조할 수 있다는 것입니다. 이 개념은 <strong>호이스팅</strong>(hoisting)으로 알려져 있습니다. 즉 JavaScript 변수가 어떤 의미에서 "끌어올려지거"나 함수나 문의 최상단으로 올려지는 것을 말합니다. 하지만, 끌어올려진 변수는 <code>undefined</code> 값을 반환합니다. 그래서 심지어 이 변수를 사용 혹은 참조한 후에 선언 및 초기화하더라도, 여전히 <code>undefined</code>를 반환합니다.</p> + +<pre class="brush: js">/** + * Example 1 + */ +console.log(x === undefined); // logs "true" +var x = 3; + + +/** + * Example 2 + */ +// undefined 값을 반환함. +var myvar = "my value"; + +(function() { + console.log(myvar); // undefined + var myvar = "local value"; +})(); +</pre> + +<p>위 예제는 아래 예제와 동일하게 볼 수 있습니다.</p> + +<pre class="brush: js">/** + * Example 1 + */ +var x; +console.log(x === undefined); // logs "true" +x = 3; + +/** + * Example 2 + */ +var myvar = "my value"; + +(function() { + var myvar; + console.log(myvar); // undefined + myvar = "local value"; +})();</pre> + +<p>호이스팅 때문에, 함수 내의 모든 <code>var</code> 문은 가능한 함수 상단 근처에 두는 것이 좋습니다. 이 방법은 코드를 더욱 명확하게 만들어줍니다.</p> + +<p>ECMAScript 2015의 let (const)는 변수를 블록의 상단으로 올리지 않습니다.<br> + 변수가 선언되기 전에 블록 안에서 변수를 참조하게 되면 {{jsxref("ReferenceError")}}를 발생시키게 됩니다.<br> + 변수는 블록 시작부터 선언이 처리될 때까지 'temporal dead zone'에 위치하게 됩니다.</p> + +<pre><code>console.log(x); // ReferenceError +let x = 3;</code> +</pre> + +<h3 id="함수_호이스팅">함수 호이스팅</h3> + +<p>함수에서는 단지 함수 선언만 상단으로 끌어올려집니다. 함수 표현식은 그렇지 않습니다.</p> + +<pre class="brush: js">/* 함수 선언 */ + +foo(); // "bar" + +function foo() { + console.log('bar'); +} + + +/* 함수 표현식 */ + +baz(); // TypeError: baz is not a function + +var baz = function() { + console.log('bar2'); +};</pre> + +<h3 id="전역_변수">전역 변수</h3> + +<p>전역 변수는 사실 <em>global 객체</em>의 속성(property)입니다. 웹 페이지에서 global 객체는 {{domxref("window")}} 이므로, <code>windows.<em>variable</em></code> 구문을 통해 전역 변수를 설정하고 접근할 수 있습니다.</p> + +<p>그 결과, window 혹은 frame의 이름을 지정하여 한 window 혹은 frame에서 다른 window 혹은 frame에 선언된 전역 변수에 접근할 수 있습니다. 예를 들어, <code>phoneNumber</code> 라는 변수가 문서에 선언된 경우, iframe에서 <code>parent.phoneNumber</code>로 이 변수를 참조할 수 있습니다.</p> + +<h2 id="상수">상수</h2> + +<p>{{jsxref("Statements/const", "const")}} 키워드로 읽기 전용 상수를 만들 수 있습니다. 상수 식별자의 구문은 변수 식별자와 같습니다. 문자, 밑줄이나 달러 기호로 시작해야 하고 문자, 숫자나 밑줄을 포함할 수 있습니다.</p> + +<pre class="brush: js">const PI = 3.14; +</pre> + +<p>상수는 스크립트가 실행 중인 동안 대입을 통해 값을 바꾸거나 재선언될 수 없습니다. 값으로 초기화해야 합니다.</p> + +<p>상수에 대한 범위 규칙은 <code>let</code> 블록 범위 변수와 동일합니다. 만약 <code>const</code> 키워드가 생략된 경우에는, 식별자는 변수를 나타내는 것으로 간주됩니다.</p> + +<p>상수는 같은 범위에 있는 함수나 변수와 동일한 이름으로 선언할 수 없습니다. 예를 들어,</p> + +<pre class="brush: js">// 오류가 발생합니다 +function f() {}; +const f = 5; + +// 역시 오류가 발생합니다 +function f() { + const g = 5; + var g; + + //statements +} +</pre> + +<p>그러나, 상수에 할당된 객체의 속성은 보호되지 않아서 다음의 문은 문제없이 실행됩니다.</p> + +<pre class="brush: js">const MY_OBJECT = {'key': 'value'}; +MY_OBJECT.key = 'otherValue'; +</pre> + +<p>또한, 배열의 내용도 보호되지 않아서 다음의 문도 문제없이 실행됩니다.</p> + +<pre class="brush: js">const MY_ARRAY = ['HTML','CSS']; +MY_ARRAY.push('JAVASCRIPT'); +console.log(MY_ARRAY); //logs ['HTML','CSS','JAVASCRIPT']; +</pre> + +<h2 id="데이터_구조_및_형">데이터 구조 및 형</h2> + +<h3 id="데이터_형">데이터 형</h3> + +<p>최신 ECMAScript 표준은 7가지 데이터 형을 정의합니다.</p> + +<ul> + <li>6가지 {{Glossary("Primitive", "원시")}} 데이터 형 + <ul> + <li>{{Glossary("Boolean")}}. true와 false</li> + <li>{{Glossary("null")}}. null 값을 나타내는 특별한 키워드. JavaScript는 대소문자를 구분하므로, null은 Null, NULL 혹은 다른 변형과도 다릅니다.</li> + <li>{{Glossary("undefined")}}. 값이 저장되어 있지 않은 최상위 속성.</li> + <li>{{Glossary("Number")}}. 정수 또는 실수형 숫자. 예:42 혹은 3.14159.</li> + <li>{{Glossary("String")}}. 문자열. 예:"안녕"</li> + <li>{{Glossary("Symbol")}}. (ECMAScript 6에 도입) 인스턴스가 고유하고 불변인 데이터 형.</li> + </ul> + </li> + <li>그리고 {{Glossary("Object")}}</li> +</ul> + +<p>이 데이터 형이 비교적 많지 않지만, 어플리케이션에 유용한 기능을 수행할 수 있습니다. {{jsxref("Object", "객체")}}와 {{jsxref("Function", "함수")}}는 언어의 다른 기본 요소입니다. 객체는 값을 위한 컨테이너, 함수는 어플리케이션이 수행할 수 있는 절차(procedure)로 생각할 수 있습니다.</p> + +<h3 id="자료형_변환">자료형 변환</h3> + +<p>JavaScript는 동적 형지정(정형) 언어입니다. 이는 변수를 선언할 때 데이터 형을 지정할 필요가 없음을 의미합니다. 또한 데이터 형이 스크립트 실행 도중 필요에 의해 자동으로 변환됨을 뜻합니다. 그래서, 예를 들어, 다음과 같이 변수를 정의할 수 있습니다.</p> + +<pre class="brush: js">var answer = 42;</pre> + +<p>그리고 나중에, 동일한 변수에 문자열 값을 할당할 수도 있습니다. 아래와 같이,</p> + +<pre class="brush: js">answer = "Thanks for all the fish..."; +</pre> + +<p>JavaScript는 동적 형지정 언어이므로, 이 할당은 오류 메시지가 발생하지 않습니다.</p> + +<p>숫자와 문자열 값 사이에 + 연산자를 포함한 식에서, JavaScript는 숫자 값을 문자열로 변환합니다. 예를 들어, 아래와 같은 문이 있습니다.</p> + +<pre class="brush: js">x = "The answer is " + 42 // "The answer is 42" +y = 42 + " is the answer" // "42 is the answer"</pre> + +<p>다른 연산자를 포함한 식의 경우, JavaScript는 숫자 값을 문자열로 변환하지 않습니다. 예를 들면,</p> + +<pre class="brush: js">"37" - 7 // 30 +"37" + 7 // 377 +</pre> + +<h3 id="문자열을_숫자로_변환하기">문자열을 숫자로 변환하기</h3> + +<p>숫자를 나타내는 값이 문자열로 메모리에 있는 경우, 변환을 위한 메서드가 있습니다.</p> + +<ul> + <li>{{jsxref("parseInt", "parseInt()")}}</li> + <li>{{jsxref("parseFloat", "parseFloat()")}}</li> +</ul> + +<p><code>parseInt</code>는 오직 정수만 반환하므로, 소수에서는 사용성이 떨어집니다. 게다가 <code>parseInt</code>를 잘 사용하기 위해서는 항상 진법(Radix) 매개변수를 포함해야 합니다. 진법 매개변수는 변환에 사용될 진법을 지정하는데 사용됩니다.</p> + +<p>문자열을 숫자로 변환하는 대안은 +(단항 더하기) 연산자입니다.</p> + +<pre class="brush: js">"1.1" + "1.1" = "1.11.1" +(+"1.1") + (+"1.1") = 2.2 +// 참고: 괄호는 명확성을 위해 추가, 필요한 것은 아닙니다. +</pre> + +<h2 id="리터럴">리터럴</h2> + +<p>JavaScript에서 값을 나타내기 위해 리터럴을 사용합니다. 이는 말 그대로 스크립트에 부여한 고정값으로, 변수가 아닙니다. 이 절에서는 다음과 같은 형태의 리터럴을 설명합니다.</p> + +<ul> + <li>{{anch("배열_리터럴", "배열 리터럴")}}</li> + <li>{{anch("불린_리터럴", "불린 리터럴")}}</li> + <li>{{anch("부동_소수점_리터럴", "부동 소수점 리터럴")}}</li> + <li>{{anch("정수", "정수")}}</li> + <li>{{anch("객체_리터럴", "객체 리터럴")}}</li> + <li>{{anch("정규식_리터럴", "정규식 리터럴")}}</li> + <li>{{anch("문자열_리터럴", "문자열 리터럴")}}</li> +</ul> + +<h3 id="배열_리터럴">배열 리터럴</h3> + +<p>배열 리터럴은 0개 이상의 식(expression) 목록입니다. 각 식은 배열 요소를 나타내고 대괄호(<code>[]</code>)로 묶입니다. 배열 리터럴을 사용하여 배열을 만들 때, 그 요소로 지정된 값으로 초기화되고, 그 길이는 지정된 인수의 갯수로 설정됩니다.</p> + +<p>아래 예제는 요소가 3개로 길이가 3인 coffees 배열을 만듭니다.</p> + +<pre class="brush: js">var coffees = ["French Roast", "Colombian", "Kona"]; +</pre> + +<div class="note"> +<p><strong>참고:</strong> 배열 리터럴은 일종의 객체 이니셜라이저(initialiizer)입니다. <a href="/ko/docs/Web/JavaScript/Guide/Working_with_Objects#Using_object_initializers">Using Object Initializers</a> 참고.</p> +</div> + +<p>배열이 최상단 스크립트에서 리터럴을 사용하여 만들어진 경우, JavaScript는 배열 리터럴을 포함한 식을 평가할 때마다 배열로 해석합니다. 게다가, 함수에서 사용되는 리터럴은 함수가 호출될 때마다 생성됩니다.</p> + +<p>배열 리터럴은 배열 객체입니다. 배열 객체에 대한 자세한 내용은 {{jsxref("Array")}}와 <a href="/ko/docs/Web/JavaScript/Guide/Indexed_collections">Indexed collections</a> 참고.</p> + +<h4 id="배열_리터럴의_추가_쉼표">배열 리터럴의 추가 쉼표</h4> + +<p>배열 리터럴에서 모든 요소를 지정할 필요는 없습니다. 만약 잇달아 두 개의 쉼표를 두면, 배열은 지정되지 않은 요소를 <code>undefined</code>로 만듭니다. 다음 예제는 <code>fish</code> 배열을 만듭니다.</p> + +<pre class="brush: js">var fish = ["Lion", , "Angel"]; +</pre> + +<p>이 배열은 값이 있는 두 요소와 빈 요소 하나를 가집니다(<code>fish[0]</code>은 "Lion", <code>fish[1]</code>은 <code>undefined</code>, <code>fish[2]</code>는 "Angel").</p> + +<p>만약 요소 목록을 후행(trailing) 쉼표로 끝낸다면, 그 쉼표는 무시됩니다. 다음 예제에서, 배열의 길이는 3입니다. <code>myList[3]</code>은 없습니다. 목록의 다른 모든 쉼표는 새로운 요소를 나타냅니다.</p> + +<div class="note"> +<p><strong>참고:</strong> 후행 쉼표는 구버전 브라우저에서 오류를 유발할 수 있으므로 제거하는게 최선입니다.</p> +</div> + +<pre class="brush: js">var myList = ['home', , 'school', ]; +</pre> + +<p>아래 예제에서, 배열의 길이는 4이며, <code>myList[0]</code>과 <code>myList[2]</code>는 값이 빠졌습니다.</p> + +<pre class="brush: js">var myList = [ , 'home', , 'school']; +</pre> + +<p>아래 예제에서, 배열의 길이는 4이며, <code>myList[1]</code>과 <code>myList[3]</code>은 값이 빠졌습니다. 마지막 쉼표는 무시됩니다.</p> + +<pre class="brush: js">var myList = ['home', , 'school', , ]; +</pre> + +<p>추가 쉼표의 동작을 이해하는 것은 JavaScript를 언어로서 이해하는데 중요하지만, 코드를 작성할 때는 빠진 요소의 값을 명시적으로 undefined로 선언하는 것이 코드의 명확성과 유지보수성을 높입니다.</p> + +<h3 id="불리언_리터럴">불리언 리터럴</h3> + +<p>불리언 형은 <code>true</code>와 <code>false</code>의 리터럴 값을 가집니다.</p> + +<p>원시 불린 값 <code>true</code> 및 <code>false</code>와 Boolean 객체의 true 및 false 값을 혼동하지 마세요. Boolean 객체는 원시 불린 데이터 형을 감싸는 래퍼(wrapper)입니다. 더 많은 정보는 {{jsxref("Boolean")}}을 참고하세요.</p> + +<h3 id="정수_리터럴">정수 리터럴</h3> + +<p>정수는 10진, 16진, 8진 및 2진수로 표현될 수 있습니다.</p> + +<ul> + <li>10진 정수 리터럴은 선행 0(zero)이 아닌 숫자열로 이루어집니다.</li> + <li>정수 리터럴에서 선행 0(zero)이나 선행 0o(혹은 0O)은 8진수임을 나타냅니다. 8진 정수는 오직 숫자 0-7만 포함할 수 있습니다.</li> + <li>선행 0x(나 0X)는 16진수임을 나타냅니다. 16진 정수는 숫자 0-9 및 문자 a-f, A-F를 포함할 수 있습니다.</li> + <li>선행 0b(나 0B)는 2진수임을 나타냅니다. 2진 정수는 오직 숫자 0과 1만 포함할 수 있습니다.</li> +</ul> + +<p>다음은 정수 리터럴 예제입니다.</p> + +<pre class="eval">0, 117 및 -345 (10진수) +015, 0001 및 -0o77 (8진수) +0x1123, 0x00111 및 -0xF1A7 (16진수) +0b11, 0b0011 및 -0b11 (2진수) +</pre> + +<p>더 많은 정보는 <a href="/ko/docs/Web/JavaScript/Reference/Lexical_grammar#Numeric_literals">Lexical grammar reference의 Numeric literals</a>를 참고하세요.</p> + +<h3 id="부동_소수점_리터럴">부동 소수점 리터럴</h3> + +<p>부동 소수점 리터럴은 아래와 같은 부분으로 이루어집니다.</p> + +<ul> + <li>부호("+"나 "-")가 달릴 수 있는 10진 정수,</li> + <li>소수점("."),</li> + <li>소수(또 다른 10진수),</li> + <li>지수.</li> +</ul> + +<p>지수부는 "e"나 "E" 다음에 오며 부호("+"나 "-")가 달릴 수 있는 정수입니다. 부동 소수점 리터럴은 적어도 숫자 하나와 소수점 혹은 "e"(나 "E")가 있어야 합니다.</p> + +<p>더 간결하게 설명하면, 구문은 다음과 같습니다.</p> + +<pre class="eval">[(+|-)][digits][.digits][(E|e)[(+|-)]digits] +</pre> + +<p>예를 들면,</p> + +<pre class="eval">3.1415926 +-.123456789 +-3.1E+12 +.1e-23 +</pre> + +<h3 id="객체_리터럴">객체 리터럴</h3> + +<p>객체 리터럴은 중괄호({})로 묶인 0개 이상인 객체의 속성명과 관련 값 쌍 목록입니다. 문의 시작에 객체 리터럴을 사용해서는 안됩니다. 이는 {가 블록의 시작으로 해석되기 때문에 오류를 이끌거나 의도한 대로 동작하지 않습니다.</p> + +<p>아래는 객체 리터럴의 예제입니다. <code>car</code> 객체의 첫째 요소는 <code>myCar</code> 속성을 정의하고 문자열 <code>"Saturn"</code>을 할당합니다. 반면 둘째 요소인 <code>getCar</code> 속성은 <code>function (carTypes("Honda"))</code>을 호출한 결과가 즉시 할당됩니다. 셋째 요소 <code>special</code> 속성은 기존 변수 <code>sales</code>를 사용합니다.</p> + +<pre class="brush: js">var sales = "Toyota"; + +function carTypes(name) { + if (name === "Honda") { + return name; + } else { + + } + return "Sorry, we don't sell " + name + "."; +} + +var car = { myCar: "Saturn", getCar: carTypes("Honda"), special: sales }; + +console.log(car.myCar); // Saturn +console.log(car.getCar); // Honda +console.log(car.special); // Toyota +</pre> + +<p>게다가, 속성명으로 숫자나 문자열 리터럴을 사용하거나 또다른 객체 리터럴 내부에 객체를 중첩할 수도 있습니다. 아래 예제는 이 옵션을 사용합니다.</p> + +<pre class="brush: js">var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" }; + +console.log(car.manyCars.b); // Jeep +console.log(car[7]); // Mazda +</pre> + +<p>객체 속성명은 빈 문자열 포함 어떤 문자열도 될 수 있습니다. 속성명이 유효한 JavaScript {{Glossary("식별자")}}나 숫자가 아닌 경우, 따옴표로 묶여야 합니다. 또한 유효한 식별자가 아닌 속성명은 점(<code>.</code>) 속성으로 접근할 수 없습니다. 대신 배열 같은 표기법("<code>[]</code>")으로 접근하고 값을 설정할 수 있습니다.</p> + +<pre class="bursh: js">var unusualPropertyNames = { + "": "An empty string", + "!": "Bang!" +} +console.log(unusualPropertyNames.""); // SyntaxError: Unexpected string +console.log(unusualPropertyNames[""]); // An empty string +console.log(unusualPropertyNames.!); // SyntaxError: Unexpected token ! +console.log(unusualPropertyNames["!"]); // Bang! +</pre> + +<h4 id="향상된_객체_리터럴">향상된 객체 리터럴</h4> + +<p>ES2015에서, 객체 리터럴은 구성에서 프로토타입 설정, foo: foo 할당을 위한 단축 표기, 메서드 정의, super 클래스 호출 및 식으로 동적인 속성명 계산을 지원하기 위해 확장됐습니다. 그에 따라 객체 리터럴 및 클래스 선언이 함께 더 가까워지고, 객체 기반 설계는 같은 일부 편의기능으로 득을 볼 수 있습니다.</p> + +<pre class="bursh: js">var obj = { + // __proto__ + __proto__: theProtoObj, + // ‘handler: handler’의 단축 표기 + handler, + // Methods + toString() { + // Super calls + return "d " + super.toString(); + }, + // Computed (dynamic) property names + [ 'prop_' + (() => 42)() ]: 42 +};</pre> + +<p>아래를 참고하세요.</p> + +<pre class="brush: js">var foo = {a: "alpha", 2: "two"}; +console.log(foo.a); // alpha +console.log(foo[2]); // two +//console.log(foo.2); // Error: missing ) after argument list +//console.log(foo[a]); // Error: a is not defined +console.log(foo["a"]); // alpha +console.log(foo["2"]); // two +</pre> + +<h3 id="정규식_리터럴">정규식 리터럴</h3> + +<p>정규식 리터럴은 (<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions">정규식 상세</a>) 슬래시 사이에 감싸인 패턴입니다. 다음은 정규식 리터럴 예제입니다.</p> + +<pre class="brush: js">var re = /ab+c/;</pre> + +<h3 id="문자열_리터럴">문자열 리터럴</h3> + +<p>문자열 리터럴은 큰 따옴표(<code>"</code>) 혹은 작은 따옴표(<code>'</code>)로 묶인 0개 이상의 문자입니다. 문자열은 같은 형 따옴표, 즉 큰 따옴표 쌍이나 작은 따옴표 쌍으로 구분되어야 합니다. 아래는 문자열 리터럴의 예제입니다.</p> + +<pre class="brush: js">"foo" +'bar' +"1234" +"one line \n another line" +"John's cat" +</pre> + +<p>문자열 리터럴 값은 문자열 객체의 모든 메서드를 호출할 수 있습니다. JavaScript는 자동으로 문자열 리터럴을 임시 문자열 객체로 변환, 메서드를 호출하고 나서 임시 문자열 객체를 폐기합니다. 또한 문자열 리터럴에서도 <code>String.length</code> 속성을 사용할 수 있습니다.</p> + +<pre class="brush: js">console.log("John's cat".length) +// 공백을 포함한 문자열 내 심볼 갯수가 출력됩니다. +// 여기서는, 10. +</pre> + +<p>ES2015에서는, 템플릿 리터럴도 사용할 수 있습니다. 템플릿 문자열은 문자열 구성을 위한 달콤한 구문을 제공합니다. 이는 Perl, Python 등에 있는 문자열 삽입(interpolation) 기능과 비슷합니다. 마음대로, 문자열 구성을 사용자 정의하고 인젝션 공격을 피하거나 문자열 콘텐츠로 더 고레벨 데이터 구조를 구성하기 위한 태그가 추가될 수 있습니다.</p> + +<pre class="brush: js">// 기본적인 문자열 리터럴 생성 +`In JavaScript '\n' is a line-feed.` + +// 여러 줄 문자열 +`In JavaScript this is + not legal.` + +// 문자열 삽입 +var name = "Bob", time = "today"; +`Hello ${name}, how are you ${time}?` + +// Construct an HTTP request prefix is used to interpret the replacements and construction +POST`http://foo.org/bar?a=${a}&b=${b} + Content-Type: application/json + X-Credentials: ${credentials} + { "foo": ${foo}, + "bar": ${bar}}`(myOnReadyStateChangeHandler);</pre> + +<p>꼭 문자열 객체를 사용할 필요가 없는 경우 문자열 리터럴을 사용해야 합니다. 문자열 객체에 대해 자세한 사항은 {{jsxref("String")}}을 참고하세요.</p> + +<h4 id="문자열에서_특수_문자_사용">문자열에서 특수 문자 사용</h4> + +<p>보통 문자에 더해서, 문자열에 아래 예제와 같이 특수 문자도 포함할 수 있습니다.</p> + +<pre class="brush: js">"one line \n another line" +</pre> + +<p>다음 표는 JavaScript 문자열에 사용할 수 있는 특수 문자 목록입니다.</p> + +<table> + <caption>표: JavaScript 특수 문자</caption> + <thead> + <tr> + <th scope="col">문자</th> + <th scope="col">뜻</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>\0</code></td> + <td>Null Byte</td> + </tr> + <tr> + <td><code>\b</code></td> + <td>Backspace</td> + </tr> + <tr> + <td><code>\f</code></td> + <td>Form feed</td> + </tr> + <tr> + <td><code>\n</code></td> + <td>New line</td> + </tr> + <tr> + <td><code>\r</code></td> + <td>Carriage return</td> + </tr> + <tr> + <td><code>\t</code></td> + <td>Tab</td> + </tr> + <tr> + <td><code>\v</code></td> + <td>Vertical tab</td> + </tr> + <tr> + <td><code>\'</code></td> + <td>Apostrophe 혹은 작은 따옴표</td> + </tr> + <tr> + <td><code>\"</code></td> + <td>큰 따옴표</td> + </tr> + <tr> + <td><code>\\</code></td> + <td>백슬래시</td> + </tr> + <tr> + <td><code>\<em>XXX</em></code></td> + <td>Latin-1 인코딩 문자는 0 - 377 사이 8진수 3자리까지 지정될 수 있습니다. 예를 들어, \251은 copyright 심볼을 표현하는 8진수 시퀀스입니다.</td> + </tr> + <tr> + </tr> + <tr> + <td><code>\x<em>XX</em></code></td> + <td>Latin-1 인코딩 문자는 00 - FF 사이의 16진수 2자리로 지정될 수 있습니다. 예를 들어, \xA9는 copyright 심볼을 표현하는 16진수 시퀀스입니다.</td> + </tr> + <tr> + </tr> + <tr> + <td><code>\u<em>XXXX</em></code></td> + <td>유니코드 문자는 16진수 4자리로 지정될 수 있습니다. 예를 들어, \u00A9는 copyright 심볼을 표현하는 유니코드 열입니다. <a href="/ko/docs/Web/JavaScript/Reference/Lexical_grammar#String_literals">Unicode escape sequences</a>를 참고하세요.</td> + </tr> + <tr> + <td><code>\u<em>{XXXXX}</em></code></td> + <td>유니코드 코드 포인트 이스케이프. 예를 들어, \u{2F804}는 간단한 유니코드 이스케이프 \uD87E\uDC04와 같습니다.</td> + </tr> + </tbody> +</table> + +<h4 id="문자_이스케이프">문자 이스케이프</h4> + +<p>표에 없는 문자의 경우 전행 백슬래시는 무시되지만, 이 용법은 더 이상 사용되지 않으며, 사용을 피해야 합니다.</p> + +<p>전행 백슬래시와 함께 문자열 안에 따옴표를 사용할 수 있습니다. 이것을 따옴표 <em>이스케이프</em>라고 합니다. 예를 들어,</p> + +<pre class="brush: js">var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service."; +console.log(quote); +</pre> + +<p>이 코드의 결과는,</p> + +<pre class="eval">He read "The Cremation of Sam McGee" by R.W. Service. +</pre> + +<p>백슬래시를 문자열 내에 포함시키기 위해서는, 백슬래시 문자를 이스케이프 해야 합니다. 예를 들어, 파일 경로 <code>c:\temp</code>를 문자열에 할당하기 위해서는 아래와 같이 사용합니다.</p> + +<pre class="brush: js">var home = "c:\\temp"; +</pre> + +<p>또한 줄바꿈 역시 전행 백슬래시로 이스케이프할 수 있습니다. 백슬래시와 줄바꿈 모두 문자열 값에서는 사라집니다.</p> + +<pre class="brush: js">var str = "this string \ +is broken \ +across multiple\ +lines." +console.log(str); // this string is broken across multiplelines. +</pre> + +<p>JavaScript에는 "heredoc" 구문은 없지만, 줄바꿈 이스케이프와 각 줄 끝 이스케이프된 줄바꿈을 추가하여 흉내낼 수 있습니다.</p> + +<pre class="brush: js">var poem = +"Roses are red,\n\ +Violets are blue.\n\ +I'm schizophrenic,\n\ +And so am I." +</pre> + +<p>ECMAScript 2015에서는 템플릿 리터럴(<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings"><strong>template literals</strong></a>)이라는 새로운 리터럴이 소개되었습니다. 이 것은 다중 문자열을 포함한 많은 새로운 기능을 가지고 있습니다!</p> + +<pre dir="rtl"><code>var poem = +`Roses are red, +Violets are blue. +Sugar is sweet, +and so is foo.`</code> +</pre> + +<h2 id="추가_정보">추가 정보</h2> + +<p>이 장은 선언과 형에 대한 기본 구문에 초점을 맞춥니다. JavaScript 언어 구조에 대해 더 많이 배우려면, 다음 장을 참고하세요.</p> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Guide/Control_flow_and_error_handling">흐름 제어와 오류 처리</a></li> + <li><a href="/ko/docs/Web/JavaScript/Guide/Loops_and_iteration">루프와 반복</a></li> + <li><a href="/ko/docs/Web/JavaScript/Guide/%ED%95%A8%EC%88%98">함수</a></li> + <li><a href="/ko/docs/Web/JavaScript/Guide/Expressions_and_Operators">식과 연산자</a></li> +</ul> + +<p>다음 장에서는, 흐름 제어 구조와 오류 처리를 살핍니다.</p> + +<p>{{PreviousNext("Web/JavaScript/Guide/소개", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}</p> diff --git a/files/ko/web/javascript/guide/working_with_objects/index.html b/files/ko/web/javascript/guide/working_with_objects/index.html new file mode 100644 index 0000000000..192e22604c --- /dev/null +++ b/files/ko/web/javascript/guide/working_with_objects/index.html @@ -0,0 +1,500 @@ +--- +title: Working with objects +slug: Web/JavaScript/Guide/Working_with_Objects +translation_of: Web/JavaScript/Guide/Working_with_Objects +--- +<p>자바스크립트는 간단한 객체기반 패러다임 상에서 만들어졌다. 객체는 프로퍼티의 모음이며, 프로퍼티는 "이름"(name 또는 key)과 "값"(value)의 연결로 이루어진다 . 프로퍼티의 값으로 함수가 될 수 있는데, 이런 프로퍼티는 메소드라고 불린다. 브라우저 안에 미리 정의 된 객체뿐 아니라 사용자들이 직접 자신만의 객체를 정의할 수도 있다.</p> + +<p class="summary">이 절에서는 객체, 프로퍼티, 함수, 메소드가 어떻게 사용되는지, 그리고 사용자를 위한 새로운 객체를 생성하는 방법을 설명한다</p> + +<h2 id="개요">개요</h2> + +<p>자바스크립트에서의 객체는 다른 프로그래밍 언어에서와 비슷하게 현실 세계에서의 사물(objects)과 비교해 볼 수 있다. 자바스크립트에서의 객체의 개념은 실세계상에서의 인식 가능한 사물로 이해할 수 있다.</p> + +<p>객체는 단독으로 존재 가능한 개체(entity)이며, 프로퍼티(property)과 타입(type)을 가진다. 예를 들어 컵과 비교를 해 본다면 컵은 사물 객체인데 색깔, 모양, 무게, 재료 등의 속성(프로퍼티)을 가지고 있다. 비슷하게 자바스크립트의 객체는 그 특징을 결정짓는 여러 프로퍼티를 가진다.</p> + +<h2 id="객체와_프로퍼티">객체와 프로퍼티</h2> + +<p><span style="font-size: 14px; line-height: 1.5;">자바스크립트의 객체에는 그와 연관된 프로퍼티가 있다. 프로퍼티는 객체에 붙은 변수(variable)라고 설명할 수 있겠다. 객체의 프로퍼티는 일반 자바스크립의 변수와 기본적으로 똑같은데, 다만 객체에 속해있다는 차이만 있을 뿐이다. 객체의 프로퍼티들이 객체의 특징을 규정한다. 프로퍼티에 접근할 때는 도트(점) 표기법을 사용한다.</span></p> + +<pre class="brush: js">objectName.propertyName +</pre> + +<p><span style="font-size: 14.39px; line-height: 16.79px;">자바스크립트의 모든 변수가 그렇듯이, 객체의 이름과 프로퍼티 이름은 모두 대소문자를 구별한다. 프로퍼티를 새로 정의하려면 그냥 이름과 값을 추가하면 된다. 예를 들어</span><span style="font-size: 14px; line-height: 1.5;"> </span><code style="line-height: 1.5; font-size: 14px; font-style: normal;">myCar</code><span style="font-size: 14px; line-height: 1.5;"> </span><span style="font-size: 14.39px; line-height: 16.79px;">라는 이름의 객체를 생성하고, 거기에</span><span style="font-size: 14px; line-height: 1.5;"> </span><code style="line-height: 1.5; font-size: 14px; font-style: normal;">make</code><span style="font-size: 14px; line-height: 1.5;">, </span><code style="line-height: 1.5; font-size: 14px; font-style: normal;">model</code><span style="font-size: 14px; line-height: 1.5;">, and </span><code style="line-height: 1.5; font-size: 14px; font-style: normal;">year</code><span style="font-size: 14px; line-height: 1.5;"> </span><span style="font-size: 14.39px; line-height: 16.79px;">라는 프로퍼티들을 추가해보자:</span></p> + +<pre class="brush: js">var myCar = new Object(); +myCar.make = "Ford"; +myCar.model = "Mustang"; +myCar.year = 1969; +</pre> + +<p><span style="font-size: 14px; line-height: 1.5;">대괄호 표기법을 사용하여 객체의 프로퍼티에 접근할 수 있다. 객체는 연관배열(</span><em>associative arrays</em><span style="font-size: 14px; line-height: 1.5;">)이라고도 불리는데, 각 프로퍼티는 하나의 문자열 이름과 연관되어(associated) 이것을 통해 접근할 수 있기 때문이다. 예를 들면 </span><span style="font-family: courier new,andale mono,monospace; font-size: 14.39px; line-height: 16.79px;">myCar</span><span style="font-size: 14px; line-height: 1.5;"> 객체의 프로퍼티에 다음과 같이 접근할 수 있다.</span></p> + +<pre class="brush: js">myCar["make"] = "Ford"; +myCar["model"] = "Mustang"; +myCar["year"] = 1969; +</pre> + +<p><span style="font-size: 14px; line-height: 1.5;">객체의 프로퍼티 이름은 유효한 자바스크립트 문자열이거나 문자열로 변환이 가능한 것이면 어떤 것이든 가능하며, 심지어 빈 문자열도 된다. 하지만 자바스크립트 식별자(identifier)로 적합하지 않으면 (예 : 하이픈, 빈칸을 포함하거나 숫자로 시작하는 이름), 대괄호를 이용한 표기법으로만 접근이 가능하다. 이 표기법은 프로퍼티 이름이 사전에 미리 결정되지 않고 런타임 시점에 결정되는 경우에 특히 유용하다. 아래의 예를 보자.</span></p> + +<pre class="brush: js">var myObj = new Object(), + str = "myString", + rand = Math.random(), + obj = new Object(); // 변수 4개를 콤마를 사용하여 한번에 생성하고 할당. + +myObj.type = "Dot syntax"; +myObj["date created"] = "String with space"; +myObj[str] = "String value"; +myObj[rand] = "Random Number"; +myObj[obj] = "Object"; +myObj[""] = "Even an empty string"; + +console.log(myObj); +</pre> + +<p><span style="font-size: 14px; line-height: 1.5;">변수에 저장된 문자열을 이용해서도 프로퍼티에 접근할 수 있다.</span></p> + +<div style="width: auto;"> +<pre class="brush: js">var propertyName = "make"; +myCar[propertyName] = "Ford"; + +propertyName = "model"; +myCar[propertyName] = "Mustang"; +</pre> +</div> + +<p>대괄호 표기법을 <a class="internal" href="/ko/docs/JavaScript/Guide/Statements#for...in_Statement" title="ko/docs/JavaScript/Guide/Statements#for...in Statement">for...in</a> 과 함께 사용하면 객체의 열거가능한 프로퍼티를 나열할 수 있다. 이것이 어떻게 작동하는지 알기 위해 아래의 함수를 보자. 이 함수는 객체와 객체 이름을 함수의 인자로 전달받아서 객체의 프로퍼티들을 출력해 준다.</p> + +<pre class="brush: js">function showProps(obj, objName) { + var result = ""; + for (var i in obj) { + if (obj.hasOwnProperty(i)) { + result += objName + "." + i + " = " + obj[i] + "\n"; + } + } + return result; +} +</pre> + +<p><code>showProps(myCar, "myCar")</code> 함수를 호출하면 다음과 같은 문자열을 반환한다.</p> + +<pre>myCar.make = Ford +myCar.model = Mustang +myCar.year = 1969</pre> + +<h2 id="모든_것이_객체">모든 것이 객체</h2> + +<p><span style="font-size: 14px; line-height: 1.5;">자바스크립트 세상에서는 거의 모든 것들이 객체이다. </span><code style="line-height: 16.79px; font-size: 14.39px; font-style: normal;">null</code><span style="font-size: 14.39px; line-height: 16.79px;"> 과 </span><code style="line-height: 16.79px; font-size: 14.39px; font-style: normal;">undefined</code><span style="font-size: 14.39px; line-height: 16.79px;"> 를 제외한 모든 </span><span style="font-size: 14px; line-height: 1.5;">원시 타입도 객체로 취급된다. 이러한 원시 타입들에도 프로퍼티가 추가될 수 있고 (설명 필요: </span><span style="font-size: 14.39px; line-height: 16.79px;">assigned properties of some types are not persistent), 모두 객체로서의 특징을 갖는다.</span></p> + +<h2 id="객체의_프로퍼티_나열하기">객체의 프로퍼티 나열하기</h2> + +<p><a href="/ko/docs/JavaScript/ECMAScript_5_support_in_Mozilla" title="ko/docs/JavaScript/ECMAScript 5 support in Mozilla">ECMAScript 5</a> 를 기준으로 객체의 프로퍼티를 나열/순회하는 방법이 세 가지 있다.</p> + +<ul> + <li><a href="/ko/docs/JavaScript/Reference/Statements/for...in" title="ko/docs/JavaScript/Reference/Statements/for...in">for...in</a> 루프<br> + 이 방법은 객체와 객체의 프로토타입 체인 상의 열거 가능한 모든 프로퍼티를 순회한다.</li> + <li><a href="/ko/docs/JavaScript/Reference/Global_Objects/Object/keys" title="ko/docs/JavaScript/Reference/Global Objects/Object/keys">Object.keys(o)</a><br> + 이 메소드는 객체 <span style="font-family: courier new,andale mono,monospace; font-size: 14.39px; line-height: 16.79px;">o</span><span style="font-size: 14.39px; line-height: 16.79px;"> </span> 자체에 속한(즉 프로토타입 체인 상에 있는 것은 제외) 열거 가능한 프로퍼티 이름들("keys")의 배열을 반환한다.</li> + <li><a href="/ko/docs/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames" title="ko/docs/JavaScript/Reference/Global Objects/Object/getOwnPropertyNames">Object.getOwnPropertyNames(o)</a><br> + 이 메소드는 객체 <span style="font-family: courier new,andale mono,monospace; font-size: 14.39px; line-height: 16.79px;">o</span> 자체의 모든 프로퍼티(열거 가능 여부에 무관) 이름들의 배열을 반환한다.</li> +</ul> + +<p>ECMAScript 5 이전 버전에서는 객체의 모든 프로퍼티를 나열하는 자체적인 방법이 제공되지 않았다. 하지만 아래 함수를 이용하면 가능하다.</p> + +<pre class="brush: js">function listAllProperties(o){ + var objectToInspect; + var result = []; + + for(objectToInspect = o; objectToInspect !== null; objectToInspect = Object.getPrototypeOf(objectToInspect)){ + result = result.concat(Object.getOwnPropertyNames(objectToInspect)); + } + + return result; +} +</pre> + +<p>이 트릭은 객체의 "숨겨진" 프로퍼티를 알아내는 데 유용하다. (숨겨진 프로퍼티란 프로토타입 체인 상의 프로퍼티 중 객체를 통해 접근이 불가능한 것들을 말하는데 동일 이름의 다른 프로퍼티가 프로퍼티 체인 상에서 먼저 존재하는 경우에 발생한다). 만약 접근 가능한 프로퍼티만 나열하고 싶다면 배열에서 중복되는 프로퍼티들을 제거하면 된다.</p> + +<h2 id="객체_생성하기">객체 생성하기</h2> + +<p>자바스크립트에는 미리 정의된 객체가 몇 개 존재한다. 사용자는 여기에 추가적으로 자신의 객체를 생성할 수 있다. 자바스크립트 1.2 부터는 객체 이니셜라이저(initializer) 를 이용하여 객체를 생성할 수 있다. 또 다른 방법으로는 먼저 생성자 함수를 정의한 후 이 함수와 <code style="font-style: normal;">new</code> 연산자를 이용하여 인스턴스를 만들수 있다.</p> + +<p><span style="font-size: 1.71rem; letter-spacing: -0.5px; line-height: 24px;">객체 이니셜라이저</span></p> + +<p>생성자 함수를 사용하는 방법 대신, 객체 이니셜라이저를 사용하여 객체를 생성할 수 있다. 이 방식은 때때로 "리터럴 표기에 의한 객체 생성"(creating objects with literal notation) 이라고도 불린다. 객체 이니셜라이저라는 단어는 C++ 에서도 비슷한 의미로 사용된다.</p> + +<p><span style="line-height: 1.5;">객체 이니셜라이저를 이용한 객체 생성의 문법은 다음과 같다.</span></p> + +<pre class="brush: js">var obj = { property_1: value_1, // property_# may be an identifier... + 2: value_2, // or a number... + // ..., + "property n": value_n }; // or a string </pre> + +<p><code>obj</code>는 새로 만들어질 객체 이름이고, <code>property_<em>i</em></code>는 식별자 (이름, 숫자, 또는 스트링 리터럴), <code style="font-style: normal;">value_<em>i</em></code> 는 수식인데 이 값이 <code>property_<em>i</em></code> 에 할당 된다. <code>obj</code> 변수에 할당 (assignment =) 하는 것은 선택 사항이다; 이 생성된 객체를 다른 곳에서 참조할 필요가 없다면 변수에 할당하지 않아도 된다. (만약 이 생성된 객체를 변수를 사용하지 않고 구문 안에서 바로 사용하려면 블럭 구문과 혼돈되지 않도록 리터널을 괄호로 감싸줄 필요가 있다.)</p> + +<p>객체 이니셜라이저는 수식이고, 각각의 이니셜라이저가 포함된 구문이 실행될 때 마다 이니셜라이저 수식에 의해 새로운 객체가 하나씩 생성이 된다. 똑같은 이니셜라이저에 의해 생성된 객체라도 서로 별개이며 비교 결과는 동일하지 않음 (not equal) 이 된다. 객체는 마치 <code>new Object()</code> 호출이 실행된 것 처럼 생성이 된다; 즉, 객체 이니셜라이저 수식에 의해 만들어진 객체들은 <code>Object</code>의 인스턴스들이 된다.</p> + +<p>다음 문장은 수식<code>cond</code>가 참일 경우 객체를 만들어서 변수 <code>x</code> 에 할당한다:</p> + +<pre class="brush: js">if (cond) var x = {hi: "there"}; +</pre> + +<p>다음 예제는 <code>myHonda</code>을 생성하고 세개의 속성을 추가한다. <code>engine</code> 속성 역시 자신의 속성들을 가지고 있는 객체이다.</p> + +<pre class="brush: js">var myHonda = {color: "red", wheels: 4, engine: {cylinders: 4, size: 2.2}}; +</pre> + +<p>객체 이니셜라이저를 이용하여 배열을 만들 수 있다. <a href="/ko/docs/Web/JavaScript/Guide/Values%2C_variables%2C_and_literals#Array_literals">array literals</a> 를 참조하기 바란다.</p> + +<p>JavaScript 1.1 과 그 이전 버전에서는, 객체 이니셜라이저를 사용할 수 없었다. 항상 생성자 함수를 쓰거나 생성 목적으로 제공되는 별도 함수를 사용했어야 했다. <a href="/ko/docs/Web/JavaScript/Guide/Working_with_Objects#Using_a_constructor_function">Using a constructor function</a> 참고.</p> + +<h3 id="생성자_함수_사용하기">생성자 함수 사용하기</h3> + +<p>다른 방법으로는 다음 두 단계에 따라 객체를 생성할 수 있다:</p> + +<ol> + <li>생성자 함수를 작성하여 객체 타입을 정의한다. 객체 타입 이름의 첫 글자는 반드시 대문자를 사용하는 좋은 관례가 있으므로 따르기를 권장한다.</li> + <li><code>new</code>를 이용하여 객체의 인스턴스를 생성한다.</li> +</ol> + +<p>객체의 타입을 정의하려면 타입의 이름, 속성(프로퍼티), 메소드 등을 기술하는 함수를 하나 만들어야 한다. 예를 들면, 여러분이 자동차를 위한 객체 타입을 만들기 원한다면, 이 객체의 타입의 이름은 <code>car</code>이고, 이 타입은 제조사, 모델, 생산연도를 위한 속성을 포함하길 원할 것이다. 아마도 다음과 같은 함수를 작성하게 될 것이다:</p> + +<pre class="brush: js">function Car(make, model, year) { + this.make = make; + this.model = model; + this.year = year; +} +</pre> + +<p>함수 인자로 전달 받은 값을 객체의 속성에 할당하기 위해서 <code>this</code>를 사용 한 것에 주목하기 바란다.</p> + +<p>이제 다음과 같이 하여 <code>mycar</code>라는 이름의 객체를 생성할 수 있다:</p> + +<pre class="brush: js">var mycar = new Car("Eagle", "Talon TSi", 1993); +</pre> + +<p>이 문장은 <code>mycar</code>를 만들고 특정 값들을 속성으로 할당하고 있다. 이렇게 하면 <code>mycar.make</code>의 값은 문자열 "Eagle" 이 되고, <code>mycar.year</code>는 정수 1993 이 된다.</p> + +<p><code>new</code>를 이용하면 어떤 갯수의 <code>car</code> 객체도 만들 수 있다. 예를 들면 다음과 같다.</p> + +<pre class="brush: js">var kenscar = new Car("Nissan", "300ZX", 1992); +var vpgscar = new Car("Mazda", "Miata", 1990); +</pre> + +<p>객체는 또 다른 객체를 속성으로 가질 수 있다. 예를 들어 여러분이 <code>person</code> 이라는 객체를 다음과 같이 정의를 했고:</p> + +<pre class="brush: js">function Person(name, age, sex) { + this.name = name; + this.age = age; + this.sex = sex; +} +</pre> + +<p>그리고 두 개의 새 <code>person</code> 객체의 인스턴스를 만들었다고 하면:</p> + +<pre class="brush: js">var rand = new Person("Rand McKinnon", 33, "M"); +var ken = new Person("Ken Jones", 39, "M"); +</pre> + +<p><code>car</code>의 정의에 <code>person</code> 객체의 값을 갖는 <code>owner</code> 속성을 추가하도록 수정할 수 있다:</p> + +<pre class="brush: js">function Car(make, model, year, owner) { + this.make = make; + this.model = model; + this.year = year; + this.owner = owner; +} +</pre> + +<p>수정된 새 객체의 인스턴스를 만들려면 다음과 같이 하면 된다:</p> + +<pre class="brush: js">var car1 = new Car("Eagle", "Talon TSi", 1993, rand); +var car2 = new Car("Nissan", "300ZX", 1992, ken); +</pre> + +<p>위 문장은 문자열 리터럴이나 정수를 넘기는 대신 객체 <code>rand</code> 와 <code>ken</code>을 owners를 위한 인자로 전달하고 있다. car2의 소유자 이름을 찾고 싶다면 다음과 같은 속성을 사용할 수 있다.:</p> + +<pre class="brush: js">car2.owner.name +</pre> + +<p>이미 정의 된 객체에도 새로운 속성을 추가할 수 있다.</p> + +<pre class="brush: js">car1.color = "black"; +</pre> + +<p>위 문장은 속성 <code>color</code>를 car1 에 추가하고, 그 값으로는 "black"을 지정하고 있다. 그러나 이것은 다른 객체들에는 영향을 주지 않는다. 새 속성을 해당 타입의 모든 객체들에 다 추가하고 싶다면, 이 속성을 <code>car</code> 객체 타입의 정의에 추가해야 한다.</p> + +<h3 id="Object.create_메서드_사용하기">Object.create 메서드 사용하기</h3> + +<p>객체는 <code>Object.create</code> 메서드를 이용해서 생성될 수 있다. 이 메서드는 사용할 프로토타입 객체를 사용자가 직접 선택할 수 있기 때문에 상당히 유용하다. (객체 생성시 생성자 함수가 없어도 가능하다). 이 메서드에 대한 더 자세한 정보는 {{jsxref("Object.create()")}} 를 참고하도록 하자.</p> + +<pre class="brush: js">// Animal properties and method encapsulation +var Animal = { + type: "Invertebrates", // Default value of properties + displayType : function(){ // Method which will display type of Animal + console.log(this.type); + } +} + +// Create new animal type called animal1 +var animal1 = Object.create(Animal); +animal1.displayType(); // Output:Invertebrates + +// Create new animal type called Fishes +var fish = Object.create(Animal); +fish.type = "Fishes"; +fish.displayType(); // Output:Fishes</pre> + +<h2 id="상속">상속</h2> + +<p>JavaScript 에서의 모든 객체들은 최소한 하나의 다른 객체로부터 상속을 받는다. 상속을 제공하는 객체를 프로토타입이라고 부르며, 상속되는 속성들은 <code>prototype</code> 이라는 생성자 객체에서 찾을 수 있다.</p> + +<h2 id="객체_프로퍼티의_인덱싱">객체 프로퍼티의 인덱싱</h2> + +<p>JavaScript 1.0에서는 객체의 속성을 참조할 때 속성 이름을 이용하거나 또는 숫자 인덱스를 이용할 수 있었다. 하지만 JavaScript 1.1과 그 이후 부터는 처음에 프로퍼티를 이름으로 정의하면 항상 이름으로만 참조를 할 수 있고, 처음에 인덱스를 이용하여 정의하면 인덱스를 이용해서만 참조할 수 있다.</p> + +<p>이 제약 사항은 생성자 함수를 이용하여 객체와 프로퍼티를 생성할 때 (앞에서 <code>Car</code> 객체 타입의 예)에도 동일하게 적용되고, 개개의 속성을 명시적으로 지정할 때 (예: <code>myCar.color = "red"</code>)에도 마찬가지이다. 만약 처음에 객체 속성을 정의할 때 <code>myCar[5] = "25 mpg"</code> 처럼 인덱스 방식을 사용하면, 그 이후에도 계속 <code>myCar[5]</code> 방식으로만 참조할 수 있다.</p> + +<p><code>forms</code> 배열과 같이 HTML 로부터 얻어지는 객체들에는 이 규칙이 적용되지 않는다. 숫자를 이용하거나 (이 객체가 문서 상에 존재하는 순서에 따라) 또는 태그의 attribute 이름으로 참조가 가능하다. 예를 들면 HTML 문서에서 두 번째 <code><FORM></code> 태그가 "myForm" 이라는 값의 <code>NAME</code> attribute 를 가지고 있다면, 이 form을 <code>document.forms[1]</code> 또는 <code>document.forms["myForm"]</code> 또는 <code>document.myForm</code> 와 같이 접근할 수 있다.</p> + +<h2 id="객체의_프로퍼티_정의">객체의 프로퍼티 정의</h2> + +<p><code>prototype</code> 프로퍼티를 사용하여 미리 정의된 객체 타입에 속성을 추가할 수 있다. 이렇게 정의된 속성은 해당 객체 타입의 한 인스턴스에만 적용되는 것이 아니라 해당 객체 타입의 모든 인스턴스가 갖게 된다. 다음 코드에서는 <code>car</code> 타입의 객체 전체에 <code>color</code> 프로퍼티를 추가한 후, <code>car1</code> 인스턴스의 <code>color</code> 프로퍼티에 값을 할당하는 것을 보여준다.</p> + +<pre class="brush: js">Car.prototype.color = null; +car1.color = "black"; +</pre> + +<p>더 많은 정보는 <a href="/en-US/docs/JavaScript/Reference" title="en-US/docs/JavaScript/Reference">JavaScript Reference</a>에서 <code>Function</code> 객체의 <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype">prototype 속성</a>을 참조</p> + +<h2 id="메소드_정의">메소드 정의</h2> + +<p><em>메소드</em>는 한 객체와 연관된(associated) 함수이며, 간단하게 말해 객체의 프로퍼티 중에서 함수인 것을 메소드라고 한다. 메소드를 정의하는 방식은 일반 함수를 정의하는 것과 동일하고, 다만 어떤 객체의 프로퍼티로 할당되어야 한다는 점이 차이가 난다. 자세한 것은 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions">method definitions</a>를 참조하자. 다음은 메소드 정의의 한 예이다.</p> + +<pre class="brush: js">objectName.methodname = function_name; + +var myObj = { + myMethod: function(params) { + // ...do something + } +}; +</pre> + +<p>첫번째 줄은 이미 존재하는 <code>objectName</code>이라는 객체에 <code>methodname</code>이라는 이름의 메소드를 추가하는 것이다. <code>function_name</code> 은 메소드로 사용될 함수의 이름이다. 두번째 줄부터는 객체를 정의할 때 메소드를 같이 정의하는 예이다.</p> + +<p>그러고 나면 다음과 같이 해당 객체의 문맥(context)에서 메소드를 호출할 수 있다.</p> + +<pre class="brush: js">object.methodname(params); +</pre> + +<p>객체 생성자 함수에 메소드 정의를 포함시킴으로써 해당 객체 타입의 메소드를 정의할 수 있다. 한 예로 이전에 정의한 car 객체의 프로퍼티를 형식에 맞춰 출력하는 함수를 정의할 수 있는데, 다음과 같다.</p> + +<pre class="brush: js">function displayCar() { + var result = "A Beautiful " + this.year + " " + this.make + + " " + this.model; + pretty_print(result); +} +</pre> + +<p>위에서 <code>pretty_print</code>는 수평 규칙과 문자열을 나타내 주는 함수이다. 여기서 사용한 <code>this</code>는 해당 메소드가 속한 객체를 가리킨다는 점을 기억하자.</p> + +<p>아래와 같은 코드를 <code>car</code>객체의 정의에 추가함으로써 해당 함수를 <code>car</code>객체의 메소드로 만들 수 있다.</p> + +<pre class="brush: js">this.displayCar = displayCar; +</pre> + +<p>따라서 <code>car객체의 전체 정의는 아래와 같이 됩니다.</code></p> + +<pre class="brush: js">function Car(make, model, year, owner) { + this.make = make; + this.model = model; + this.year = year; + this.owner = owner; + this.displayCar = displayCar; +} +</pre> + +<p>그리고 각각의 객체(인스턴스)를 가지고 <code>displayCar메서드를 아래와 같이 호출 할 수 있습니다:</code></p> + +<pre class="brush: js">car1.displayCar(); +car2.displayCar(); +</pre> + +<h2 id="객체_참조를_위해_this_를_사용하기">객체 참조를 위해 <code>this</code> 를 사용하기</h2> + +<p>자바스크립트는 특별한 키워드를 가지고 잇습니다. 바로 <code>this</code>라는 키워드이다. 메서드 내부에서 <code>this 키워드를 사용하게 되면 해당 메서드를 포함한 객체를 가리키게 된다. 예를 들어 특정 객체의 속성값의 상한과 하한 값의 범위에 있는지를 확인하는 validate라는 함수를 아래와 같이 작성한다고 했을 때, </code></p> + +<pre class="brush: js">function validate(obj, lowval, hival) { + if ((obj.value < lowval) || (obj.value > hival)) + alert("Invalid Value!"); +} +</pre> + +<p><code>validate메서드를 각각의 form 요소들의 onchange 이벤트 핸들러에서 호출할 수 있다. 그 때, 다음 예제처럼 this 키워드를 사용해서 해당 form요소를 인자로 넘길 수 있다. </code></p> + +<pre class="brush: html"><input type="text" name="age" size="3" + onChange="validate(this, 18, 99)"> +</pre> + +<p>일반적으로 <code>this는 메서드를 호출하는 객체를 지칭합니다. </code></p> + +<p> <code>myForm</code>. <code>form속성과 함께 사용할때, this키워드는 현재 객체의 부모 form을 지칭한다. 다음의 예제에서, myForm form은 텍스트 객체와 버튼 객체를 가지고 있다. 사용자가 해당 버튼을 클릭했을때, myForm form안에 있는 텍스트 객체의 값을 myForm form의 이름으로 설정한다. 해당 버튼의 onclick 이벤트 처리자는 부모 form인 myForm을 지칭하기 위해 this.form를 사용한다. </code></p> + +<pre class="brush: html"><form name="myForm"> +<p><label>Form name:<input type="text" name="text1" value="Beluga"></label> +<p><input name="button1" type="button" value="Show Form Name" + onclick="this.form.text1.value = this.form.name"> +</p> +</form></pre> + +<h2 id="getters_와_setters_정의">getters 와 setters 정의</h2> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Functions/get">getter</a> 메서드는 특정 속성의 값을 받아 오기 위한 메서드 입니다. <a href="/en-US/docs/Web/JavaScript/Reference/Functions/set">setter</a>메서드는 특정 속성의 값을 설정하기 위한 메서드 입니다. 새로운 속성을 추가 하기 위해 getter와 setter 메서드들을 미리 정의된 객체 혹은 사용자 정의 객체에 정의 하 수 있습니다. getter와 setter메서드들을 정의 하기 위한 문법은 객체 구문 문법을 사용합니다.</p> + +<p>자바스크립트 1.8.1버전부터, 객체와 배열 초기화에서 속성들을 설정하고자 할 경우 setter메서드들은 더이상 사용이 불가합니다.</p> + +<p>다음의 <a href="/en-US/docs/SpiderMonkey/Introduction_to_the_JavaScript_shell" title="en-US/docs/SpiderMonkey/Introduction to the JavaScript shell">JS 쉘</a>은 getter와 setter메서드들이 사용자 정의객체인 o에서 어떻게 작동하는지를 보여 줍니다. JS쉘은 개발자가 배치 모드 혹은 대화형 모드에서 자바스크립트 코드를 테스트하기위한 하나의 어플리케이션입니다. </p> + +<pre class="brush: js">js> var o = {a: 7, get b() {return this.a + 1;}, set c(x) {this.a = x / 2}}; +[object Object] +js> o.a; +7 +js> o.b; +8 +js> o.c = 50; +js> o.a; +25 +</pre> + +<p>o 객체의 속성이 다음과 같을 때,</p> + +<ul> + <li><code>o.a</code> — 숫자</li> + <li><code>o.b</code> — o.a에 1을 더한 값을 반환하는 getter 메서드</li> + <li><code>o.c</code> — <code>o.a에 주어진 인자 값의 반에 해당 하는 값을 설정하는 setter 메서드</code></li> +</ul> + +<p><code>[gs]et <em>속성명</em>()</code> 문법이 실제 사용되는 메서드명이라고 생각이 될지라도, "[gs]et <em>속성명</em>()" 문법(<code>__define[GS]etter__와는 반대로</code>)을 사용한 객체 구문 문법으로 정의된 getter와 setter메서드들의 이름들은 실제 getter 메서드들의 이름이 아니라는 점에 유의 하세요. "[gs]et <em>속성명</em>()" 문법을 사용하여 getter, setter메서드내의 함수명을 작성하기 위해서는, <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineProperty" title="en-US/docs/Core JavaScript 1.5 Reference/Global +Objects/Object/defineProperty">Object.defineProperty</a></code> (혹은 <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineGetter" title="en-US/docs/Core JavaScript 1.5 Reference/Global +Objects/Object/defineGetter">Object.prototype.__defineGetter__</a> 레거시 콜백</code>)을 사용하여 프로그램적으로 분명한 이름의 함수명을 사용하세요. </p> + +<p>아래의 자바스크립트 쉡은 이미 정의된 Date 클래스의 모든 인스턴스들에 년도 속성을 추가 하기 위해 getter와 setter 메서드들이 Date 프로토타입을 확장하는 방법을 보여 줍니다. </p> + +<p>아래의 구문들은 년도 속성 추가를 위한 getter와 setter메서드를 정의합니다:</p> + +<pre class="brush: js">js> var d = Date.prototype; +js> Object.defineProperty(d, "year", { + get: function() {return this.getFullYear() }, + set: function(y) { this.setFullYear(y) } +}); +</pre> + +<p>아래의 구문들은 Date객체에서 getter와 setter메서드를 사용하는 법을 보여 줍니다:</p> + +<pre class="brush: js">js> var now = new Date; +js> print(now.year); +2000 +js> now.year = 2001; +987617605170 +js> print(now); +Wed Apr 18 11:13:25 GMT-0700 (Pacific Daylight Time) 2001 + +</pre> + +<p>원칙적으로, getter와 setter는 둘 중 하나가 될 수 있다.</p> + +<ul> + <li>object initializers 를 사용하여 정의하거나, </li> + <li>getter와 setter메서드 추가 방법을 사용하여 언제든지 특정 객체에 나중에 추가하는 방법</li> +</ul> + +<p>object initializers를 사용해서 getter와 setter메서드들을 정의할 경우, getter메서드는 get, setter메서드는 set이라는 접두사만 추가하면 됩니다. 물론 getter메서드는 인자를 받지 않는 반면, setter 메서드는 정확히 하나의 인자(설정할 새로운 값)만을 받습니다. </p> + +<pre class="brush: js">var o = { + a: 7, + get b() { return this.a + 1; }, + set c(x) { this.a = x / 2; } +}; +</pre> + +<p><code>Object.defineProperties 메서드를 사용하면 객체 생성이후라도 언제든지 </code>getter and setter메서드들을 객체에 추가할 수 있습니다. <code>Object.defineProperties 메서드의 첫번째 인자는 </code>getter and setter메서드들을 추가할 객체이고, 두번째 인자는 getter and setter메서드들의 이름과 getter and setter메서드들의 정의를 가지고 있는 객체가 되어야 합니다. 이전 예제와 동일하게 사용된 getter and setter메서드들을 정의하고 있는 예제는 아래와 같습니다:</p> + +<pre class="brush: js">var o = { a:0 } + +Object.defineProperties(o, { + "b": { get: function () { return this.a + 1; } }, + "c": { set: function (x) { this.a = x / 2; } } +}); + +o.c = 10 // Runs the setter, which assigns 10 / 2 (5) to the 'a' property +console.log(o.b) // Runs the getter, which yields a + 1 or 6 +</pre> + +<p>당신의 프로그래밍 스타일과 현재 진행 중인 작업에 따라 getter and setter메서드들을 정의할 수 있는 두가지 양식 중 하나를 선택하여 사용할 수 있습니다. prototype을 정의 할때 object initializer를 사용했다면 앞으로도 대부분 첫번째 양식을 선택 하여 작성을 할 것입니다. 이 양식이 보다 간결하고 자연스럽기 때문입니다. 하지만 prototype 혹은 특정 객체를 작성하지 않고서 나중에 getter and setter 메서드를 추가하고자 한다면 두번째 양식만이 가능한 선택입니다. 두번째 양식은 아마도 자바스크립트의 동적 속성을 가장 잘 나타내고 있습니다. 하지만 코드 작성과 읽고 이해하는 부분에 어려움이 있습니다. </p> + +<div class="note"> +<p>Firefox 3.0 이전 버전의 경우, getter and setter 메서드들은 DOM 요소들에는 지원되지 않습니다. 이전 버전의 Firefox에서는 아무런 에러 없이 작동하지 않을 것입니다. 이것에 대한 예외가 필요하다면, HTMLElement의 prototype<code>(HTMLElement.prototype.__define[SG]etter__)</code>을 변경하고 예외를 던지는 것이 하나의 방법입니다.</p> + +<p>Firefox 3.0 버전에서는 이미 정의된 속서에 대해 getter or setter를 정의 할 경우 예외가 발생됩니다. 이전 버전의 Firefox에서는 아니지만 해당 속성을 반드시 사전에 제거해야만 합니다. </p> +</div> + +<h4 id="Defining_getters_and_setters_See_also" name="Defining_getters_and_setters_See_also">추가로 볼 것들 </h4> + +<ul> + <li><code><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineProperty" title="en-US/docs/JavaScript/Reference/Global_Objects/Object/defineSetter">Object.defineProperty</a></code></li> + <li><code><a href="/en-US/docs/JavaScript/Reference/Operators/get" title="en-US/docs/JavaScript/Reference/Operators/Special Operators/get Operator">get</a></code></li> + <li><code><a href="/en-US/docs/JavaScript/Reference/Operators/set" title="en-US/docs/JavaScript/Reference/Operators/Special Operators/set Operator">set</a></code></li> +</ul> + +<h2 id="프로퍼티의_삭제">프로퍼티의 삭제</h2> + +<p>상속 받지 않은 속성은 <code>delete</code> 연산자를 이용하여 제거 할 수 있다. 다음 코드는 어떻게 속성을 제거하는지 보여준다.</p> + +<pre class="brush: js">// 새 객체 myobj를 두 개의 속성 a, b 와 함께 생성 +var myobj = new Object; +myobj.a = 5; +myobj.b = 12; + +// 속성을 삭제. myobj 에는 속성 b 만 남게 됨. +delete myobj.a; +console.log ("a" in myobj) // "false"를 출력 +</pre> + +<p><code>var</code> 키워드로 선언하지 않은 전역 변수도 <code>delete</code>를 이용하여 삭제를 할 수 있다:</p> + +<pre class="brush: js">g = 17; +delete g; +</pre> + +<p>더 자세한 정보는 <code><a href="/ko/docs/Web/JavaScript/Reference/Operators/delete">delete</a></code>를 보면 된다.</p> + +<h2 id="객체_간의_비교">객체 간의 비교</h2> + +<p>JavaScript 에서는 객체들은 레퍼런스 타입이다. 두 개의 별개 객체들은, 설령 그 속성 값들이 모두 다 동일하다고 하더라도, 절대로 동일하다고 비교(equal)될 수 없다. In JavaScript objects are a reference type. Two distinct objects are never equal, even if they have the same properties. Only comparing the same object reference with itself yields true.</p> + +<pre class="brush: js">// 속성은 같지만 서로 별개인 두 변수와 두 객체 +var fruit = {name: "apple"}; +var fruitbear = {name: "apple"}; + +fruit == fruitbear // false 리턴 +fruit === fruitbear // false 리턴</pre> + +<pre class="brush: js">// 두 개의 변수이지만 하나의 객체 +var fruit = {name: "apple"}; +var fruitbear = fruit; // fruit 객체 레퍼런스를 fruitbear 에 할당 + +// here fruit and fruitbear are pointing to same object +fruit == fruitbear // true 리턴 +fruit === fruitbear // true 리턴 +</pre> + +<p>비교 연산자에 대한 상세한 정보는 <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">Comparison operators</a>를 참고하기 바란다.</p> + +<h2 id="추가_검토">추가 검토</h2> + +<ul> + <li><a class="external" href="http://es5.github.com/#x4.2" title="http://es5.github.com/#x4.2">ECMAScript 5.1 spec: Language Overview</a></li> + <li><a class="external" href="http://dmitrysoshnikov.com/ecmascript/javascript-the-core" title="http://dmitrysoshnikov.com/ecmascript/javascript-the-core">JavaScript. The core. (Dmitry A. Soshnikov ECMA-262 article series)</a></li> +</ul> + +<div>{{PreviousNext("Web/JavaScript/Guide/Regular_Expressions", "Web/JavaScript/Guide/Details_of_the_Object_Model")}}</div> diff --git a/files/ko/web/javascript/guide/객체_모델의_세부사항/index.html b/files/ko/web/javascript/guide/객체_모델의_세부사항/index.html new file mode 100644 index 0000000000..230d5cb9e1 --- /dev/null +++ b/files/ko/web/javascript/guide/객체_모델의_세부사항/index.html @@ -0,0 +1,714 @@ +--- +title: 객체 모델의 세부 사항 +slug: Web/JavaScript/Guide/객체_모델의_세부사항 +translation_of: Web/JavaScript/Guide/Details_of_the_Object_Model +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Working_with_Objects", "Web/JavaScript/Guide/Iterators_and_Generators")}}</div> + +<p class="summary">자바스크립트는 클래스 기반이 아닌 prototype에 기초한 객체 기반 언어 입니다. 이런 차이점으로 인해, 객체들의 계층 구조의 생성과 속성 및 속성 값의 상속을 어떻게 구현해야 하는지에 대한 부분이 덜 분명할 수 있습니다. 이번 장에서는 이런 상황을 명확하게 하고자 합니다. </p> + +<p>이번 장에선 이미 자바스크립트를 어느 정도 알고 있고, 간단한 객체를 생성하는 함수들을 사용해보았다는 가정하에 진행합니다.</p> + +<h2 id="클래스_기반_언어_대_프로토타입_기반_언어">클래스 기반 언어 대 프로토타입 기반 언어</h2> + +<p>Java와 C++같은 클래스 기반의 언어들은 두개의 구별되는 개념에 기반을 두고 있습니다: 그건 바로 클래스와 인스턴스입니다.</p> + +<ul> + <li>클래스는 특정 객체군을 특징 짓는 모든 속성들(Java에서는 메서드들과 필드들을 , C++에서는 멤버들을 속성으로 간주합니다. )을 정의합니다.클래스는 해당 객체군을 표현할 수 있는 특정 멤버를 지칭하는 것이 아닌 그보다 더 추상적인 것입니다. 예를 들어, <code>직원</code>클래스는 직원들을 대표할 수 있습니다.</li> + <li>반면 인스턴스는 클래스를 기반으로 실체화된 것입니다. 예를 들어, <code>빅토리아</code>는 특정 직원 개인을 나타내는 <code>직원</code>클래스의 인스턴스가 될 수 있습니다. 인스턴스는 부모 클래스의 속성과 동일한 속성들을 가집니다.</li> +</ul> + +<p>자바스크립트같은 프로토타입기반의 언어들은 위와 같은 클래스와 인스턴스의 차이를 두지 않습니다. 간단하게 객체들을 가질 뿐입니다. prototype기반의 언어는 원형(프로토타입)의 객체 개념을 가지고 있습니다. 하나의 객체는 새로운 객체를 생성했을 때 초기 속성을 가질 수 있도록 하는 형판(template)으로 사용됩니다. 객체는 생성될 때 혹은 실행 시에 자기 자신의 속성을 명시할 수 있습니다. 추가적으로, 객체들은 또 다른 객체를 생성하기 위한 프로토타입으로 연관지어 질 수 있으며 프로토타입으로부터 생성된 두번째 객체가 프로토타입인 첫번째 객체의 속성을 공유(혹은 접근)하는 것을 허용합니다. </p> + +<h3 id="클래스_정의">클래스 정의</h3> + +<p>클래스 기반의 언어들에서, 별도의 클래스를 생성하고 그 안에서 해당 클래스를 정의 할 수 있습니다. 해당 정의에서 클래스의 인스턴스를 생성할 수 있는 생성자라고하는 특별한 메서드를 명시할 수 있습니다. 생성자는 해당 인스턴스의 초기 속성 값을 지정할 수 있고, 생성 시점에, 다른 적절한 처리를 수행 할 수 있습니다. 클래스의 인스턴스를 생성하기 위해서 new 연산자와 함께 생성자를 호출해야 합니다. </p> + +<p>자바스크립트는 위와 비슷한 방법을 취합니다. 하지만 생성자이외에 따로 클래스 정의를 가지고 있지는 않습니다. 대신, 특정 속성및 속성값들을 가지고 객체를 생성하는 생성자 함수를 정의할 수 있습니다. 특정 자바스크립트 함수는 생성자로 사용 될 수 있습니다. 새로운 객체를 생성할려면 new연산자와 함께 생성자 함수를 사용해야 합니다.</p> + +<div class="blockIndicator note"> +<p>ECMAScript 2015에 <a href="/en-US/docs/Web/JavaScript/Reference/Classes">클래스 선언</a>이 새롭게 소개되었습니다.</p> + +<blockquote> +<p>ECMAScript 2015에서 소개된 자바스크립트 클래스는 주로 문법적 설탕으로 기존 자바스크립트 프로토타입 기반 상속에 읽기 좋은 형식으로 바뀌었습니다. 이 클래스 문법이 자바스크립트에 새로운 객체 중심 상속 모델을 소개한 것은 아닙니다.</p> +</blockquote> +</div> + +<h3 id="하위_클래스와_상속">하위 클래스와 상속</h3> + +<p>클래스 기반 언어에서는 클래스 정의를 통해 클래스 계층구조를 생성합니다. 클래스를 정의할 때 이미 존재하는 클래스의 하위 클래스를 새로운 클래스로 지정할 수 있습니다. 이 하위 클래스는 부모 클래스의 모든 속성을 상속받으며 추가로 새로운 속성을 추가하거나 상속받은 속성을 수정할 수 있습니다. 예를 들어 이름(<code>name</code>)과 부서(<font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">dept</span></font>)을 가진 직원(<code>Employee</code>) 클래스와 그 하위 클래스에 보고(<font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">reports</span></font>) 속성을 추가한 관리자(<font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">Manager</span></font>) 클래스가 있다고 해봅시다. 이 경우 관리자(<font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">Manager</span></font>)의 인스턴스는 다음과 같이 세가지 속성을 모두 가질 수 있습니다 - 이름(<code>name</code>), 부서(<font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">dept</span></font>), 보고(<font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">reports</span></font>).</p> + +<p>자바스크립트는 생성자 함수와 프로토타입 객체를 연결해 상속을 구현합니다. 이런 식으로 직원(<code>Employee</code>) — 관리자(<font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">Manager</span></font>) 예제를 똑같이 구현할 수 있지만 조금 다른 * 사용합니다. 먼저, 이름(<code>name</code>), 부서(<font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">dept</span></font>) 속성을 명시하여 직원(<code>Employee</code>) 생성자 함수를 정의합니다. 그런 다음, 직원(<code>Employee</code>)의 생성자를 호출한 후 보고(<font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">reports</span></font>) 속성을 명시해 관리자(<font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">Manager</span></font>) 생성자 함수를 정의합니다. 마지막으로 <code>Employee.prototype</code> 에서 파생된 새로운 객체를 관리자(<font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">Manager</span></font>) 생성자 함수의 프로토타입으로 지정합니다. 그런 다음 새로운 관리자(<font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">Manager</span></font>)를 만들면 관리자(<font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">Manager</span></font>) 객체를 직원(<code>Employee</code>) 객체로부터 이름(<code>name</code>), 부서(<font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">dept</span></font>) 속성을 상속받습니다. </p> + +<h3 id="속성의_추가_삭제">속성의 추가 삭제</h3> + +<p>클래스 기반의 언어들에서는, 일반적으로 컴파일 시점에 클래스를 생성한 후에 컴파일 시점 혹은 실행 시에 해당 클래스의 인스턴스를 생성합니다. 클래스가 한번 정의된 후에 클래스를 다시 컴파일 하지 않는다면, 속성의 갯수나 형식을 변경할 수 없습니다. 하지만 자바스크립트에서느 실행 시에 객체의 속성을 추가 혹은 삭제 할 수 있습니다. 만약 객체군의 프로토타입으로 사용되는 객체에 속성을 추가하면, 프로토타입이 되는 객체들에도 새로운 속성이 추가가 됩니다.</p> + +<h3 id="차이점들에_대한_정리">차이점들에 대한 정리</h3> + +<p>다음 표는 이런 차이점들에 대한 간략한 요약을 포함하고 있습니다. 이번 장의 다음 내용들은 객체의 계층 구조를 생성하기 위한 자바스크립트 생성자와 프로토타입들의 사용에 대한 세부 사항에 대해 기술합니다. 그리고 동일한 작업을 자바에서 어떻게 처리해야 하는지도 비교해서 살펴보겠습니다.</p> + +<table class="standard-table"> + <caption>클래스 기반(자바)과 프로토타입(prototype)기반(자바스크립트) 객체 시스템의 비교</caption> + <thead> + <tr> + <th scope="col">클래스 기반(자바)</th> + <th scope="col">원형 기반(자바스크립트)</th> + </tr> + </thead> + <tbody> + <tr> + <td>클래스와 인스턴스는 별개입니다.</td> + <td>모든 객체는 다른 객체로부터 상속을 받습니다.</td> + </tr> + <tr> + <td>클래스 정의를 가지고 클래스를 생성하고 생성자 메서드로 인스턴스를 생성합니다.</td> + <td>생성자 함수를 가지고 객체군을 정의 및 생성합니다.</td> + </tr> + <tr> + <td>new 연산자로 하나의 객체(인스턴스)를 생성합니다.</td> + <td>동일합니다.</td> + </tr> + <tr> + <td>이미 존재하는 클래스에 대한 하위 클래스를 정의함으로써 객체의 계층구조를 생성합니다.</td> + <td>하나의 객체를 생성자 함수와 결합된 프로토타입에 할당함으로써 객체의 계층구조를 생성 합니다.</td> + </tr> + <tr> + <td>클래스의 상속 구조에 따라 속성을 상속 받습니다.</td> + <td>프로토타입 체인에 따라 속성을 상속 받습니다.</td> + </tr> + <tr> + <td>클래스 정의는 모든 인스턴스의 모든 속성을 명시합니다. 실행시에 동적으로 속성을 추가할 수 없습니다.</td> + <td>생성자 함수 혹은 프로토타입은 초기 속성들을 명시합니다. 개별 객체 혹은 전체 객체군에 동적으로 속성을 추가 삭제할 수 있습니다.</td> + </tr> + </tbody> +</table> + +<h2 id="직원_예제">직원 예제</h2> + +<p>이장의 나머지 부분에서는 다음과 같은 직원 객체의 계층구조를 사용합니다. </p> + +<div class="twocolumns"> +<p>직원 객체의 계층 구조.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/3060/figure8.1.png"></p> + +<ul> + <li>직원(<code>Employee</code>) 객체는 빈 문자열을 기본값으로 가지는 이름(<code>name</code>) 그리고 "일반(general)"을 기본 값으로 가지는 부서(<code>dept</code>)를 속성으로 가집니다.</li> + <li><font face="Consolas, Liberation Mono, Courier, monospace">관리자(</font><code>Manager</code>)객체는 직원(<code>Employee</code>) 객체를 근간으로 하며, 직원 객체들을 포함하기 위한 빈 배열을 기본 값으로 하는 보고(<code>reports</code>)속성을 가지고 있습니다.</li> + <li>근로자(<code>WorkerBee</code>)객체 또한 직원(<code>Employee</code>) 객체를 근간으로 하며, 문자열들을 포함하기 위한 빈 배열을 기본 값으로 하는 프로젝트(<code>projects</code>)속성을 가집니다.</li> + <li>영업사원(<code>SalesPerson</code>)객체는 또한 근로자(<code>WorkerBee</code>) 객체를 근간으로 하며, 100을 기본값으로 하는 할당량(<code>quota</code>)를 속성으로 가집니다. 또한 같은 부서내의 모든 영업사원을 지칭하기 위한 부서 속성을 "판매부서"로 재정의 합니다. </li> + <li>엔지니어(<code>Engineer</code>)객체도 근로자(<code>WorkerBee</code>) 객체를 근간으로 하며, 빈 문자열을 기본값으로 가지는 장비(<code>machine</code>) 속성을 가집니다.그리고 엔지니어링(engineering)이라는 값으로 부서 속성을 재정의 합니다.</li> +</ul> +</div> + +<h2 id="계층_구조_생성">계층 구조 생성</h2> + +<p>직원 계층 구조를 구현하기 위한 적절한 생성자 함수를 정의하는 방법에는 여러가지가 있습니다. 개발하려고 하는 어플리케이션에 따라 생성자 함수를 정의 하는 방법은 달라질 수 있습니다. </p> + +<p>이번 절에서는 상속을 구현하기 위한 간단한 (비교적 유연하지는 않은) 정의 방법을 보여 줄 것입니다. 이런 정의 방법을 사용하게되면, 객체를 생성할 때 어떤 속성 값도 지정을 할 수 없습니다. 새로이 생성된 객체들은 기본값들을 가지고 있으며, 나중에 해당 속성 값들을 변경할 수 있습니다.</p> + +<p>실제 어플리케이션에서는, 객체를 생성할때, 해당 객체가 가져야할 속성을 인자로 받는 생성자를 정의 할수 있습니다.(보다 자세한 사항은 다음을 참조하세요. <a href="#More_flexible_constructors">More flexible constructors</a>). 지금 당장은, 상속이 어떻게 작동하는지를 보여주기 위한 간단한 예제를 사용합니다. </p> + +<p>다음의 자바와 자바스크립트로 작성된 직원 정의는 비슷합니다. 차이점은 자바언어에서는 개별 속성에 대한 타입(type)을 일일이 지정을 해야 하지만 자바스크립트에서는 일일이 개별 속성에 대한 타입(type)을 지정할 필요가 없다는 것입니다.(이런 이유로 자바스크립트가 약하게 형식화된 언어로 불리는 반면 자바는 <a href="http://en.wikipedia.org/wiki/Strong_and_weak_typing">강력하게 형식화된 언어</a>로 불립니다.)</p> + +<table> + <tbody> + <tr> + <td> + <h4 id="자바스크립트">자바스크립트</h4> + + <pre class="brush: js"> +function Employee() { + this.name = ""; + this.dept = "general"; +}</pre> + </td> + <td> + <h4 id="자바">자바</h4> + + <pre class="brush: java"> +public class Employee { + public String name = ""; + public String dept = "general"; +} +</pre> + </td> + </tr> + </tbody> +</table> + +<p>관리자와 근로자 정의는 계층 구조상에서 상위에 위치하는 객체를 어떻게 표시하는지에 대한 차이점을 보여 줍니다. 자바스크립트에서는 생성자 함수 정의 이후에 언제든 생성자 함수의 프로토타입(<code>prototype)</code> 속성의 값으로 프로토타입 인스턴스를 추가할 수 있습니다. 자바에서는 클래스 정의에 상위 클래스를 명시해야 합니다. 클래스 정의 이후에는 상위 클래스를 변경할 수 없습니다.</p> + +<div class="twocolumns"> +<h4 id="자바스크립트_2">자바스크립트</h4> + +<pre class="brush: js">function Manager() { + Employee.call(this); + this.reports = []; +} +Manager.prototype = Object.create(Employee.prototype); + +function WorkerBee() { + Employee.call(this); + this.projects = []; +} +WorkerBee.prototype = Object.create(Employee.prototype); +</pre> + +<h4 id="자바_2">자바</h4> + +<pre class="brush: java">public class Manager extends Employee { + public Employee[] reports = new Employee[0]; +} + + + +public class WorkerBee extends Employee { + public String[] projects = new String[0]; +} + + +</pre> +</div> + +<p>엔지니어와 영업사원 정의들은 객체들을 생성합니다. 생성된 객체는 근로자 객체의 하위 객체이고 따라서 직원 객체의 하위 객체가 됩니다. 상속 관계에 따라 엔지니어와 영업사원 객체들은 근로자와 직원객체의 속성을 가지게 됩니다. 게다가, 상속받은 부서 속성은 엔지니어와 영업사원에서 재정되어 새로운 값을 가지게 됩니다. </p> + +<div class="twocolumns"> +<h4 id="자바스크립트_3">자바스크립트</h4> + +<pre class="brush: js">function SalesPerson() { + WorkerBee.call(this); + this.dept = "sales"; + this.quota = 100; +} +SalesPerson.prototype = Object.create(WorkerBee.prototype); + +function Engineer() { + WorkerBee.call(this); + this.dept = "engineering"; + this.machine = ""; +} +Engineer.prototype = Object.create(WorkerBee.prototype); +</pre> + +<h4 id="Java">Java</h4> + +<pre class="brush: java">public class SalesPerson extends WorkerBee { + public double quota; + public dept = "sales"; + public quota = 100.0; +} + + +public class Engineer extends WorkerBee { + public String machine; + public dept = "engineering"; + public machine = ""; +} +</pre> +</div> + +<p>이런 정의 방법을 통해, 기본값을 가지는 각각의 속성을 포함하는 객체의 인스턴스를 생성할 수 있습니다. 다음 그림은 새로운 객체를 생성하고 새로운 객체에 대한 속성값들을 보여 표시하기 위한 자바스크립트의 정의들을 보여 줍니다.</p> + +<div class="note"> +<p><strong>유의사항: </strong>클래스 기반 언어들에서 인스턴스라는 용어는 특정한 기술적 의미를 가지고 있습니다. 이러한 언어들에서, 하나의 인스턴스란 하나의 클래스의 개별적인 실체이며 클래스와는 근본적으로 다릅니다. 자바스크립트에서는 클래스와 인스턴스 간의 차이가 없기 때문에, "인스턴스"가 이런 기술적 의미를 갖지 않습니다. 하지만, 자바스크립트에 대해서 얘기하자면, 비공식적으로 "인스턴스"는 특정한 생성자 함수를 이용하여 생성된 오브젝트를 의미합니다. 그래서 이번 예제에서는 <code><code>jane</code></code>이 <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: #eeeeee; font-size: 16px;"> Engineer </span></font>의 인스턴스라고 할 수 있습니다. 이와 유사하게, 부모, 자식, 상위, 하위의 용어들은 자바스크립트에서 공식적인 의미를 갖지 않습니다; 다만 프로토타입 체인 상의 상위 또는 하위 객체를 지칭하기 위해서 비공식적으로 사용할 수 있습니다.</p> +</div> + +<h3 id="간단한_정의로_객체_생성">간단한 정의로 객체 생성</h3> + +<div class="twocolumns"> +<h4 id="객체의_계층구조">객체의 계층구조</h4> + +<p>오른쪽에 보이는 코드로 생성된 객체의 계층 구조는 아래와 같습니다.</p> + +<p><img src="https://mdn.mozillademos.org/files/10412/=figure8.3.png"></p> + +<h4 id="개별_객체들">개별 객체들</h4> + +<pre class="brush: js">var jim = new Employee; +// jim.name is '' +// jim.dept is 'general' + +var sally = new Manager; +// sally.name is '' +// sally.dept is 'general' +// sally.reports is [] + +var mark = new WorkerBee; +// mark.name is '' +// mark.dept is 'general' +// mark.projects is [] + +var fred = new SalesPerson; +// fred.name is '' +// fred.dept is 'sales' +// fred.projects is [] +// fred.quota is 100 + +var jane = new Engineer; +// jane.name is '' +// jane.dept is 'engineering' +// jane.projects is [] +// jane.machine is '' +</pre> +</div> + +<h2 id="객체_속성들">객체 속성들</h2> + +<p>이번 장에서는 객체가 프로토타입체인 상의 다른 객체로부터 특성을 상속받는 방법과 런타임 상에서 프로퍼티를 추가하면 무슨 일이 일어나는 지 살펴봅니다.</p> + +<h3 id="속성_상속">속성 상속</h3> + +<p>아래 구문처럼 <code>WorkerBee</code> 생성자로 <code>mark</code> 객체를 생성했다고 가정합니다.</p> + +<pre class="brush: js">var mark = new WorkerBee; +</pre> + +<p>new 연산자를 만나면, 자바스크립트는 새로운 일반 객체를 생성하고 암묵적으로 내부의 [[Prototype]](<code>__proto__</code>) 속성의 값을 <code>WorkerBee.prototype</code> 의 값으로 할당하며, 해당 객체를 <code>this</code> 키워드의 값으로써 생성자 함수 <code>WorkerBee</code>에 전달합니다. 내부의 [[Prototype]] 속성은 속성값을 반환하기 위해 사용할 프로토타입 체인을 결정합니다. 이런 속성들이 할당되면, 자바스크립트는 새 객체를 반환하고, 할당 구문에 의해 변수 <code>mark</code>를 객체에 할당합니다.</p> + +<p>이러한 절차는 <code>mark</code>가 프로토타입 체인으로부터 상속받는 속성의 값을 <code>mark</code> 객체 내부에(local values) 명시적으로 부여하진 않습니다. 당신이 속성의 값을 요청하면, 자바스크립트는 먼저 해당 객체에 값이 존재하는지 확인합니다. 존재한다면, 해당 값이 반환됩니다. 만약 해당 객체에 값이 없다면, 프로토타입 체인을 (내장 [[Prototype]] 속성;<code>__proto__</code>을 이용하여)확인합니다. 체인 상의 어떤 객체가 해당 속성의 값을 가지고 있다면 그 값이 반환됩니다. 그런 속성이 발견되지 않는다면, 자바스크립트는 객체가 속성을 가지고있지 않다고 할 것입니다. 이런 식으로, <code>mark</code> 객체는 다음의 속성과 값을 가집니다.</p> + +<pre class="brush: js">mark.name = ""; +mark.dept = "general"; +mark.projects = [];</pre> + +<p><code>mark</code> 객체는 <code>mark.__proto__</code>로 연결되어 있는 원형의 객체로부터 이름(<code>name</code>)과 부서(<code>dept</code>)에 대한 값을 상속 받습니다. 근로자(<code>WorkerBee</code>) 생성자로부터 <code>projects</code>속성에 대한 값을 할당을 받습니다.이것들이 자바스크립트내에서 속성과 속성 값의 상속입니다. 이런 과정의 몇몇 세부 사항들은 <a href="#Property_inheritance_revisited">Property inheritance revisited</a>에서 다룹니다. </p> + +<p>이런 생성자들은 당신이 직접 인스턴스에만 해당 하는 값을 설정하도록 하지 않기때문에, 객체에 대한 이런 정보들은 일반적으로 적용됩니다. 근로자(<code>WorkerBee</code>)로부터 생성된 모든 새로운 객체들은 기본값이 적용된 속성 값들을 가지게 됩니다. 물론, 속성 값들을 변경할 수 있습니다. 아래처럼 특정 인스턴스에만 해당하는 값을 설정할 수 있습니다. </p> + +<pre class="brush: js">mark.name = "Doe, Mark"; +mark.dept = "admin"; +mark.projects = ["navigator"];</pre> + +<h3 id="속성_추가">속성 추가</h3> + +<p>자바스크립트에선, 실행 시점에 특정 객체에 속성들을 추가 할 수 있습니다.생성자 함수가 제공하는 속성외에 다른 속성을 추가할 수 있습니다. 특정 단일 객체에 속성을 추가하기 위해선, 다음과 같이 해당 객체에 값을 할당 하면 됩니다:</p> + +<pre class="brush: js">mark.bonus = 3000; +</pre> + +<p>이렇게 하면 <code>mark</code>객체는 보너스(<code>bonus</code>)속성을 가지게 됩니다. 하지만 mark객체를 제외한 나머지 근로자<code>(WorkerBee)</code>객체들은 보너스 속성을 가지지 않습니다. </p> + +<p>만약 생성자 함수의 원형으로 사용되는 객체에 새로운 속성을 추가한다면, 해당 프로토타입 객체(prototype)의 속성을 상속받는 모든 객체에 해당 속성이 추가됩니다. 예를 들면, 전문분야(<code>specialty</code>)속성을 모든 직원 객체에 다음과 같은 구문으로 추가할 수 있습니다:</p> + +<pre class="brush: js">Employee.prototype.specialty = "none"; +</pre> + +<p>위의 구문을 실행한 직후, <code>mark</code>객체는 <code>"none"</code>이라는 값을 가지는 전문분야<code>(specialty)</code>속성을 가지게 됩니다.아래의 그림들은 해당 속성을 추가한 후 엔지니어<code>(Engineer)</code> 프로토타입에 대해 해당 속성을 재정의 했을 경우 각 객체에 미치는 영향을 보여줍니다.</p> + +<p><img alt="" class="internal" src="/@api/deki/files/4422/=figure8.4.png" style="height: 519px; width: 833px;"><br> + <span style="font-size: 12px; line-height: 17px;"><strong>속성의 추가</strong></span></p> + +<h2 id="좀_더_유연한_생성자들">좀 더 유연한 생성자들</h2> + +<p>지금까지 살펴 본 생성자 함수들은 인스턴스를 생성하면서 동시에 속성값을 지정할 수 없었습니다. 자바의 경우, 인스턴스를 생성 시 생성자에 인자들을 넘겨주어 인스턴스의 속성들을 초기화 할 수 있습니다. 다음의 예제 그림들은 자바처럼 인스턴스 생성 시 속성값을 설정하는 방법을 보여줍니다.</p> + +<p><img alt="" class="internal" id="figure8.5" src="/@api/deki/files/4423/=figure8.5.png" style="height: 481px; width: 1012px;"><br> + <small><strong>Specifying properties in a constructor, take 1</strong></small></p> + +<p>다음의 표는 자바와 자바스크립트 각각의 생성자와 객체에 대한 정의를 보여 줍니다. </p> + +<div class="twocolumns"> +<h4 id="자바스크립트_4">자바스크립트</h4> + +<h4 id="자바_3">자바</h4> +</div> + +<div class="twocolumns"> +<pre class="brush: js">function Employee (name, dept) { + this.name = name || ""; + this.dept = dept || "general"; +} +</pre> + +<pre class="brush: java">public class Employee { + public String name; + public String dept; + public Employee () { + this("", "general"); + } + public Employee (String name) { + this(name, "general"); + } + public Employee (String name, String dept) { + this.name = name; + this.dept = dept; + } +} +</pre> +</div> + +<div class="twocolumns"> +<pre class="brush: js">function WorkerBee (projs) { + + this.projects = projs || []; +} +WorkerBee.prototype = new Employee; +</pre> + +<pre class="brush: java">public class WorkerBee extends Employee { + public String[] projects; + public WorkerBee () { + this(new String[0]); + } + public WorkerBee (String[] projs) { + projects = projs; + } +} +</pre> +</div> + +<div class="twocolumns"> +<pre class="brush: js"> +function Engineer (mach) { + this.dept = "engineering"; + this.machine = mach || ""; +} +Engineer.prototype = new WorkerBee; +</pre> + +<pre class="brush: java">public class Engineer extends WorkerBee { + public String machine; + public Engineer () { + dept = "engineering"; + machine = ""; + } + public Engineer (String mach) { + dept = "engineering"; + machine = mach; + } +} +</pre> +</div> + +<p>자바스크립트의 속성값을 설정하는 방법은 기본값을 설정하기 위한 관용구를 사용합니다.</p> + +<pre class="brush: js">this.name = name || ""; +</pre> + +<p>자바스크립트의 OR 논리 연산자(<code>||</code>) 첫번째 인자를 평가합니다. 첫번째 인자가 참이면 첫번째 인자를 반환하고 그렇지 않은 경우는 두번째 인자를 반환합니다. 그러므로, 위의 코드는 <code>name</code>인자가 <code>name</code> 속성에 사용 가능한 값을 가지고 있는지 확인합니다. 확인 결과 <code>name</code>속성에 사용가능한 값을 가지고 있을 경우, 해당 값을 <code>this.name</code>에 설정하게 됩니다. 반대로 그렇지 않은 경우는 빈 문자열을 <code>this.name</code>에 설정합니다.얼핏 보면 헛갈리지만 보다 짧은 관용구를 사용하였습니다.</p> + +<div class="note"> +<p><strong>주의:</strong> 만약 인자로 false와 빈 문자열 값을 줄 경우 해당 구문은 예상한 대로 작동하지 않을 수 있습니다.</p> +</div> + +<p>이런 정의들을 가지고, 객체의 인스턴스를 생성할때, 객체 자신만의 속성에 대한 값을 지정할 수 있습니다. 새로운 <code>Engineer</code>를 생성하기 위해서 다음과 같은 구문을 사용할 수 있습니다:</p> + +<pre class="brush: js">var jane = new Engineer("belau"); +</pre> + +<p><code>Jane</code>의 속성들은 다음과 같습니다:</p> + +<pre class="brush: js">jane.name == ""; +jane.dept == "engineering"; +jane.projects == []; +jane.machine == "belau" +</pre> + +<p>위와 같은 코드 구문으로는 <code>name</code>과 같이 상속받은 속성에 대한 초기값을 지정할 수 없습니다.만약 상속 받은 속성의 초기값을 설정하고자 한다면, 생성자 함수의 코드를 변경해야 합니다.</p> + +<p>지금까지, 원형 객체를 생성한 후, 그 새로운 객체 자신의 속성과 속성 값을 지정하는 것을 살펴 보았습니다. 프로토타입 체인상에서 해당 생성자가 상위 객체에 대한 생성자를 직접 호출 함으로써 더 많은 속성을 추가하도록 할 수 있습니다. 다음의 그림은 새로운 정의 방법을 보여 줍니다.</p> + +<p><img alt="" class="internal" src="/@api/deki/files/4430/=figure8.6.png" style="height: 534px; width: 1063px;"><br> + <small><strong>생성자내에서 속성들 정의, 그림 2</strong></small></p> + +<p>그럼 좀 더 상세하게 생성자 내에서 속성들을 정의하는 것을 살펴 보겠습니다. 다음은 엔지니어(<code>Engineer)</code> 생성자의 새로운 정의입니다:</p> + +<pre class="brush: js">function Engineer (name, projs, mach) { + this.base = WorkerBee; + this.base(name, "engineering", projs); + this.machine = mach || ""; +} +</pre> + +<p>다음과 같이 새로운 엔지니어(<code>Engineer)</code>객체를 생성할 수 있습니다:</p> + +<pre class="brush: js">var jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau"); +</pre> + +<p>다음과 같은 순서에 따라 객체를 생성하고 속성을 정의하게 됩니다:</p> + +<ol> + <li><code>new</code> 연산자는 프로토타입 객체를 생성하고 생성된 객체의 <code>__proto__</code>속성을 <code>Engineer.prototype</code>으로 설정합니다.</li> + <li><code>new</code> 연산자는 새로이 생성된 객체를 엔지니어<code>(Engineer)</code>생성자에 this 키워드의 값으로 전달합니다.</li> + <li>생성자는 생성한 객체에 대한 <code>base</code>라는 새로운 속성을 생성하고 근로자<code>(WorkerBee)</code> 생성자의 값을 base 속성에 할당합니다. 이런 과정은 근로자<code>(WorkerBee)</code> 생성자를 엔지니어<code>(Engineer)</code>객체의 메서드로 만듭니다. <code>base</code> 속성의 이름은 그리 특별하지 않습니다. 다른 어떤 속성명을 사용해도 무방합니다. <code>base</code> 속성명은 단지 해당 속성의 목적을 환기시키기 위한 것입니다.</li> + <li> + <p>생성자는 <code>base</code> 메서드에 필요한 인자들 (<code>"Doe, Jane"</code> and <code>["navigator", "javascript"]</code>)을 주어 호출합니다.명시적으로 생성자에서 사용한 <code>"engineering"</code>은 모든 엔지니어<code>(Engineer)</code>객체들이 상속받은 부서 속성에 대한 동일한 값을 가지며, 직원<code>(Employee)</code>으로부터 상속받은 값을 재정의 하는 것을 나타냅니다.</p> + </li> + <li><code>base</code>가 엔지니어<code>(Engineer)</code>의 메서드이기때문에 <code>base</code>메서드 내에서 <code>this</code>키워드를 스텝1에서 생성한 객체를 지칭하도록 해줍니다. 따라서, 근로자<code>(WorkerBee)</code> 함수는 차례대로 <code>"Doe, Jane"</code>과 <code>"engineering"</code> 인자를 직원<code>(Employee)</code>생성자에 전달합니다. 직원<code>(Employee)</code>생성자로부터 반환 시, 근로자<code>(WorkerBee)</code>함수는 남은 인자들을 프로젝트<code>(projects)</code>속성을 설정하기 위해 사용합니다. </li> + <li><code>base</code>메서드로부터 반환 시, 엔지니어<code>(Engineer)</code> 생성자는 해당 객체의 장비<code>(machine)</code>속성을 "belau"로 초기화 합니다.</li> + <li>생성자로부터 반환 시, 새롭게 생성된 객체를 <code>jane</code>변수에 할당 합니다.</li> +</ol> + +<p>엔지니어(<code>Engineer</code>) 생성자내에서 근로자(<code>WorkerBee</code>)생성자를 호출하면, 엔지니어(<code>Engineer</code>)에 대한 상송을 적절하게 설정할 수 도 있을 것이라고 생각할 수 있을 것입니다.하지만 그렇지 않습니다. 근로자(<code>WorkerBee</code>)생성자를 호출하는 것은 엔지니어<code>(Engineer)</code>객체로 하여금 호출되는 모든 생성자 함수내에서 열거된 속성들을 가지고도록 보장합니다.그러나, 나중에 직원<code>(Employee)</code>혹은 근로자<code>(WorkerBee)</code> 원형에 속성을 추가한다면, 엔지니어<code>(Engineer)</code>객체에 의해 추가된 속성들은 상속이 되지 않습니다. 예를 들어, 아래와 같은 구문을 작성하였다고 가정합니다:</p> + +<pre class="brush: js">function Engineer (name, projs, mach) { + this.base = WorkerBee; + this.base(name, "engineering", projs); + this.machine = mach || ""; +} +var jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau"); +Employee.prototype.specialty = "none"; +</pre> + +<p><code>jane</code>객체는 전문분야<code>(specialty)</code>속성을 상속받지 않습니다.</p> + +<pre class="brush: js">function Engineer (name, projs, mach) { + this.base = WorkerBee; + this.base(name, "engineering", projs); + this.machine = mach || ""; +} +Engineer.prototype = new WorkerBee; +var jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau"); +Employee.prototype.specialty = "none"; +</pre> + +<p>이제 <code>jane</code>객체의 전문분야<code>(specialty)</code>속성은 "none"이 되었습니다.</p> + +<p><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call" title="en-US/docs/JavaScript/Reference/Global Objects/Function/call">call()</a></code> 혹은 <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply" title="en-US/docs/JavaScript/Reference/Global Objects/Function/apply">apply()</a></code> 메서드를 사용는 것은 상속을 구현하는 또 다른 방법입니다. 다음의 두 예제는 동일한 결과를 보여줍니다. </p> + +<div class="twocolumns"> +<pre class="brush: js">function Engineer (name, projs, mach) { + this.base = WorkerBee; + this.base(name, "engineering", projs); + this.machine = mach || ""; +} +</pre> + +<pre class="brush: js">function Engineer (name, projs, mach) { + WorkerBee.call(this, name, "engineering", projs); + this.machine = mach || ""; +} +</pre> +</div> + +<p><code>base</code>를 사용하지 않고 구현을 하기 때문에, <code>call()</code> 메서드를 사용하여 상속을 구현하는 것이 보다 깔끔합니다.</p> + +<h2 id="속성_상속의_재고">속성 상속의 재고</h2> + +<p>이전 절에서 자바스크립트의 생성자와 원형(prototype)이 어떤 방식으로 상속과 객체의 계층 구조를 제공하는지를 살펴 보았습니다. 이번장에서는 이전 절에서 반드시 명백하게 짚고 넘어가지 않은 일부 미묘한 점들에 대해 살펴보겠습니다.</p> + +<h3 id="객체_자신의_값과_상속받은_값">객체 자신의 값과 상속받은 값</h3> + +<p>이번 장에서 이미 설명된 것 처럼, 객체의 속성에 접근할 때, 자바스크립트는 아래와 같은 절차를 따릅니다.</p> + +<ol> + <li>해당 속성에 대한 객체 자신의 값이 있는지 확인하고 있으면 그 값을 반환한다.</li> + <li>객체 자신의 값이 없으면 <code>__proto__</code> 속성을 사용하여 프로토타입 체인을 확인한다.</li> + <li>프로토타입 체인상의 특정 객체가 해당 속성에 대한 값을 가지고 있다면 해당 객체의 값을 반환한다.</li> + <li>해당 속성을 가진 어떤 객체도 발견하지 못하면 해당 객체는 그 속성을 가지고 있지 않은 것으로 판단한다.</li> +</ol> + +<p>이런 단계들의 결과는 생성자 및 프로토타입 체인등의 것들을 어떻게 정의 하느냐에 따라 달라집니다. 아래와 같은 원래의 예제는 이런 정의들을 가지고 있습니다:</p> + +<pre class="brush: js">function Employee () { + this.name = ""; + this.dept = "general"; +} + +function WorkerBee () { + this.projects = []; +} +WorkerBee.prototype = new Employee; +</pre> + +<p>이런 정의들을 가지고, <code>amy</code>라는 근로자<code>(WorkerBee)</code>인스턴스를 아래와 같이 생성하였다고 가정합니다.</p> + +<pre class="brush: js">var amy = new WorkerBee; +</pre> + +<p><code>amy</code>객체는 프로젝트라는 자신만의 속성을 가집니다.이름과 부서 속성들은 <code>amy</code> 자신의 속성이 아닌 <code>amy</code>객체의 <code>__proto__</code>속성을 통해 가지고 온 속성들입니다. 따라서 <code>amy</code>는 이런 속성들의 값을 가지게 됩니다.</p> + +<pre class="brush: js">amy.name == ""; +amy.dept == "general"; +amy.projects == []; +</pre> + +<p>직원(<code>Employee)</code>과 연관되어 있는 프로토타입내의 이름 속성의 값을 아래와 같이 변경하였다고 가정합니다.</p> + +<pre class="brush: js">Employee.prototype.name = "Unknown" +</pre> + +<p>얼핏보기에, 새로운 값이 모든 직원 인스턴스에 적용이 될것으로 예상하겠지만 그렇지 않습니다. </p> + +<p>직원 객체의 인스턴스를 생성할때, 해당 인스턴스는 이름 속성에 대해 자신이 가지고 있는 값(빈 문자열)을 취하게 됩니다.이것이 의미하는 것은 새로운 직원 객체를 생성하여 근로자(<code>WorkerBee)</code>의 프로토타입에 설정을 할때, <code>WorkerBee.prototype</code>이 이름 속성에 대한 자신만의 값을 가지고 있다는 것입니다.그러므로, <code>amy</code>객체(근로자 인스턴스)의 이름 속성에 대해 검색할때, <code>WorkerBee.prototype</code>내에서 이름 속성에 대한 <code>amy</code> 객체 자신의 값을 찾게됩니다. 그렇기때문에 <code>Employee.prototype</code>까지의 프로토타입 체인을 검색하지 않게 됩니다.</p> + +<p>실행시에 객체의 속성 값을 변경하고 새로운 값이 모든 하위 객체들에게도 적용되도록 할려면, 객체의 생성자함수에서는 속성을 정의할 수 없습니다. 대신에, 생성자와 연결된 프로토타입에 추가할 수 있습니다. 예를 들어, 이전의 코드를 아래와 같이 변경하였다고 가정합니다:</p> + +<pre class="brush: js">function Employee () { + this.dept = "general"; +} +Employee.prototype.name = ""; + +function WorkerBee () { + this.projects = []; +} +WorkerBee.prototype = new Employee; + +var amy = new WorkerBee; + +Employee.prototype.name = "Unknown"; +</pre> + +<p>이 경우 <code>amy</code> 객체의 이름 속성의 값은 "Unknown"이 됩니다.</p> + +<p>위의 예제에서처럼, 객체 생성 시에 객체의 속성에 대한 기본 값을 설정하고 실행 시에 해당 속성의 값을 변경하기를 원한다면, 해당 속성들을 생성자 함수 자체안에가 아닌 생성자의 프로토타입에 설정 하여야 합니다.</p> + +<h3 id="인스턴스_관계_결정">인스턴스 관계 결정</h3> + +<p>자바스크립트에서의 속성 검색은 객체 자신의 속성들을 먼저 살펴보고 해당 속성명을 찾지 못할 경우, 객체의 특별한 속성인 <code>__proto__</code>내에서 찾게 됩니다. 이런 검색은 재귀적으로 진행되며, 이런 과정을 "프로토타입 체인에서의 검색"이라고 합니다.</p> + +<p>특별한 속성인 <code>__proto__</code>객체가 생성이 될때 설정이 됩니다.<code> __proto__</code>속성은 생성자의 프로토타입 속성의 값으로 설정이 됩니다. 따라서 <code>new Foo()</code> 표현식은 <code>__proto__ == <code class="moz-txt-verticalline">Foo.prototype</code></code><code class="moz-txt-verticalline">인 </code>객체를 생성합니다. 결과적으로 <code class="moz-txt-verticalline">Foo.prototype</code><code class="moz-txt-verticalline">의 속성들에 대한 변경은 </code><code>new Foo()</code> 표현식으로 생성한 모든 객체에 대한 속성 검색을 변경하게 됩니다.</p> + +<p>모든 객체는 <code>__proto__</code>라는 객체 속성을 가집니다.(예외: <code>Object</code>). 모든 함수들은 <code>prototype</code>이라는 객체 속성을 가집니다. 따라서 객체들은 '프로토타입 상속'에 의해 다른 객체들과의 관계를 가지게 됩니다.객체의 <code>__proto__</code>속성과 함수의 <code>prototype </code>객체를 비교하여 상속을 테스트 해볼 수 있습니다. 자바스크립트는 특정 객체가 함수 <code>prototype</code>으로부터 상속 받는 객체일 경우 참<code>(true)</code>를 반환하는 <code>instanceof</code>라는 연산자를 제공합니다. 예를 들면,</p> + +<pre class="brush: js">var f = new Foo(); +var isTrue = (f instanceof Foo);</pre> + +<p><a href="#Inheriting_properties">Inheriting properties</a>에 나오는 예제와 동일한 정의들을 작성해 놓았을 경우, 보다 상세한 예제는 아래와 같습니다.엔지니어(<code>Engineer)</code>객체를 아래와 같이 생성합니다:</p> + +<pre class="brush: js">var chris = new Engineer("Pigman, Chris", ["jsd"], "fiji"); +</pre> + +<p>생성된 객체를 가지고 아래와 같은 구문을 실행할 경우 각 구문에 대한 결과는 모두 참(true)입니다.</p> + +<pre class="brush: js">chris.__proto__ == Engineer.prototype; +chris.__proto__.__proto__ == WorkerBee.prototype; +chris.__proto__.__proto__.__proto__ == Employee.prototype; +chris.__proto__.__proto__.__proto__.__proto__ == Object.prototype; +chris.__proto__.__proto__.__proto__.__proto__.__proto__ == null; +</pre> + +<p>주어진 이런 상황에서, <code>instanceOf</code>를 다음과 같이 <font face="Consolas, Liberation Mono, Courier, monospace">직접 작성할 수 있을 것입니다:</font></p> + +<pre class="brush: js">function instanceOf(object, constructor) { + object = object.__proto__; + while (object != null) { + if (object == constructor.prototype) + return true; + if (typeof object == 'xml') { + return constructor.prototype == XML.prototype; + } + object = object.__proto__; + } + return false; +} +</pre> + +<div class="note"> +<p><strong>주의: </strong>위의 구현내용은 최신 버전의 자바스크립트에서 XML객체들이 표현되는 방법의 특질을 해결하기 위해 해당 객체의 타입이 "xml"인지 확인합니다. 핵심적인 세부 사항을 확인하려면 {{ bug(634150) }}를 참조하세요.</p> +</div> + +<p>위의 instanceOf함수를 사용하면 아래의 표현들은 모두 참(true)입니다:</p> + +<pre class="brush: js">instanceOf (chris, Engineer) +instanceOf (chris, WorkerBee) +instanceOf (chris, Employee) +instanceOf (chris, Object) +</pre> + +<p>하지만 아래의 표현식은 거짓(false)가 됩니다:</p> + +<pre class="brush: js">instanceOf (chris, SalesPerson) +</pre> + +<h3 id="생성자내에서의_전역_정보">생성자내에서의 전역 정보</h3> + +<p>생성자를 생성할때, 생성자내에서 전역 정보를 설정할 경우, 주의를 해야 합니다. 예를 들어, 각각의 새로운 직원에게 자동으로 고유한 ID값을 할당하기를 원한다고 했을 때, 다음과 같은 직원(<code>Employee</code>) 정의를 사용할 수 있을 것입니다:</p> + +<pre class="brush: js">var idCounter = 1; + +function Employee (name, dept) { + this.name = name || ""; + this.dept = dept || "general"; + this.id = idCounter++; +} +</pre> + +<p>이런 정의 내용을 가지고, 새로운 직원을 생성했을 때, 생성자는 다음의 고유한 ID값을 새로운 직원객체에 할당하고 전역 ID 카운터를 증가 시킵니다. 따라서 다음과 같은 구문으로 각각의 객체를 생성한다면, 결과는 <code>victoria.id</code>는 1 그리고 <code>harry.id</code>는 2가 됩니다:</p> + +<pre class="brush: js">var victoria = new Employee("Pigbert, Victoria", "pubs") +var harry = new Employee("Tschopik, Harry", "sales") +</pre> + +<p>얼핏보면 괜찮아 보입니다. 하지만 이유를 불문하고 직원 객체가 생성될때마다 <code>idCounter</code>는 증가분을 가지게 됩니다.이번장에서 나온 예제에서처럼 전체 직원<code>(Employee)</code> 객체의 계층 구조를 생성하였다면, 프로토타입을 설정할때마다 직원 생성자는 매번 호출 됩니다.다음과 같은 코드를 작성하였다고 가정합니다:</p> + +<pre class="brush: js">var idCounter = 1; + +function Employee (name, dept) { + this.name = name || ""; + this.dept = dept || "general"; + this.id = idCounter++; +} + +function Manager (name, dept, reports) {...} +Manager.prototype = new Employee; + +function WorkerBee (name, dept, projs) {...} +WorkerBee.prototype = new Employee; + +function Engineer (name, projs, mach) {...} +Engineer.prototype = new WorkerBee; + +function SalesPerson (name, projs, quota) {...} +SalesPerson.prototype = new WorkerBee; + +var mac = new Engineer("Wood, Mac"); +</pre> + +<p>여기서 생략된 정의가 <code>base</code>속성을 가지고 해당 생성자를 프로토타입 체인내의 상위 생성자들을 호출한닥고 좀 더 가정하면, 이런 경우, 생성된 <code>mac</code>객체의 <code>id</code>값은 5가 됩니다.</p> + +<p>어플리케이셔네 따라, 카운터가 이렇게 추가적으로 증가된 것은 문제가 될 수도 그렇지 않을 수 도 있습니다. 카운터에 정확한 값이 설정되기를 원한다면, 사용가능한 해결적은 아래와 같은 생성자를 대신 사용하는 것입니다:</p> + +<pre class="brush: js">function Employee (name, dept) { + this.name = name || ""; + this.dept = dept || "general"; + if (name) + this.id = idCounter++; +} +</pre> + +<p>prototype으로 사용할 직원 인스턴스를 생성할 때, 생성자에 인자들을 주어선 안됩니다. 이 생성자 정의를 사용하여, 인자들을 주지 않을 경우, 생성자는 id에 값을 할당하지 않으며 카운터를 갱신하지 않습니다. 따라서, id값을 가지는 직원 객체에 대해, 반드시 해당 직원의 이름을 명시해야 합니다. 이 예제의 경우 <code>mac</code>인스턴스의 <code>id</code>값은 1이 됩니다.</p> + +<h3 id="다중상속_금지">다중상속 금지</h3> + +<p>몇몇 객체 지향언어들은 다중 상속을 허용합니다. 그것은, 관련이 없는 부모 객체들로 부터 속성들과 값들을 상속 받을 수 있는 것을 말합니다. 자바스크립트는 다중 상속을 지원하지 않습니다.</p> + +<p>속성 값의 상속은 속성에 대한 값을 찾기 위한 프로토타입 체인을 검색에 의해 실행 시점에 이루어 집니다. 하나의 객체는 오로지 하나의 결합된 prototype만을 가지기 때문에, 자바스크립트는 동적으로 하나 이상의 프로토타입 체인으로 부터 상속을 할 수 없습니다. </p> + +<p>자바스크립트에서, 하나 이상의 다른 생성자 함수를 호출하는 생성자를 사용할 수 있습니다. 이것은 다중 상속처럼 보여질 수 있습니다. 예를 들어, 다음과 같은 구문들을 살펴보세요:</p> + +<pre class="brush: js">function Hobbyist (hobby) { + this.hobby = hobby || "scuba"; +} + +function Engineer (name, projs, mach, hobby) { + this.base1 = WorkerBee; + this.base1(name, "engineering", projs); + this.base2 = Hobbyist; + this.base2(hobby); + this.machine = mach || ""; +} +Engineer.prototype = new WorkerBee; + +var dennis = new Engineer("Doe, Dennis", ["collabra"], "hugo") +</pre> + +<p><code>WorkerBee</code>의 정의는 이번 장의 이전에 사용된 것과 동일하다고 가정합니다.이런 경우, <code>dennis</code>객체는 다음과 같은 속성들을 가지게 됩니다:</p> + +<pre class="brush: js">dennis.name == "Doe, Dennis" +dennis.dept == "engineering" +dennis.projects == ["collabra"] +dennis.machine == "hugo" +dennis.hobby == "scuba" +</pre> + +<p> 따라서 <code>dennis</code>객체는 <code>Hobbyist</code> 생성자로부터 <code>취미(hobby)</code>속성을 받아 오지 않습니다. 그런데 <code>Hobbyist</code>생성자의 프로토타입에 속성을 추가 했다고 가정하면 </p> + +<pre class="brush: js">Hobbyist.prototype.equipment = ["mask", "fins", "regulator", "bcd"] +</pre> + +<p><code>dennis</code>객체는 새로이 추가된 속성을 상속받지 않습니다.</p> + +<div>{{PreviousNext("Web/JavaScript/Guide/Working_with_Objects", "Web/JavaScript/Guide/Iterators_and_Generators")}}</div> diff --git a/files/ko/web/javascript/guide/메타_프로그래밍/index.html b/files/ko/web/javascript/guide/메타_프로그래밍/index.html new file mode 100644 index 0000000000..fe4fa13f83 --- /dev/null +++ b/files/ko/web/javascript/guide/메타_프로그래밍/index.html @@ -0,0 +1,258 @@ +--- +title: 메타 프로그래밍 +slug: Web/JavaScript/Guide/메타_프로그래밍 +translation_of: Web/JavaScript/Guide/Meta_programming +--- +<div>{{jsSidebar("JavaScript Guide")}} {{Previous("Web/JavaScript/Guide/Iterators_and_Generators")}}</div> + +<p class="summary">Starting with ECMAScript 2015, JavaScript gains support for the {{jsxref("Proxy")}} and {{jsxref("Reflect")}} objects allowing you to intercept and define custom behavior for fundamental language operations (e.g. property lookup, assignment, enumeration, function invocation, etc). With the help of these two objects you are able to program at the meta level of JavaScript.</p> + +<h2 id="Proxies">Proxies</h2> + +<p> ECMAScript 6에서 소개되었습니다, {{jsxref("Proxy")}} 객체는 특정 작업을 가로막는것과 사용자 정의 행위를 시행하는것을 허용합니다.예를 들면 객체가 속성을 가지는 것입니다:</p> + +<pre class="brush: js">var handler = { + get: function(target, name){ + return name in target ? target[name] : 42; + } +}; +var p = new Proxy({}, handler); +p.a = 1; +console.log(p.a, p.b); // 1, 42 +</pre> + +<p>The <code>Proxy</code> object defines a <em>target</em> (an empty object here) and a <em>handler</em> object in which a <code>get</code> <em>trap</em> is implemented. Here, an object that is proxied will not return <code>undefined</code> when getting undefined properties, but will instead return the number 42.</p> + +<p>Additional examples are available on the {{jsxref("Proxy")}} reference page.</p> + +<h3 id="Terminology">Terminology</h3> + +<p>The following terms are used when talking about the functionality of proxies.</p> + +<dl> + <dt>{{jsxref("Global_Objects/Proxy/handler","handler","","true")}}</dt> + <dd>Placeholder object which contains traps.</dd> + <dt>traps</dt> + <dd>The methods that provide property access. This is analogous to the concept of traps in operating systems.</dd> + <dt>target</dt> + <dd>Object which the proxy virtualizes. It is often used as storage backend for the proxy. Invariants (semantics that remain unchanged) regarding object non-extensibility or non-configurable properties are verified against the target.</dd> + <dt>invariants</dt> + <dd>Semantics that remain unchanged when implementing custom operations are called <em>invariants</em>. If you violate the invariants of a handler, a {{jsxref("TypeError")}} will be thrown.</dd> +</dl> + +<h2 id="Handlers_and_traps">Handlers and traps</h2> + +<p>The following table summarizes the available traps available to <code>Proxy</code> objects. See the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler">reference pages</a> for detailed explanations and examples.</p> + +<table> + <thead> + <tr> + <th>Handler / trap</th> + <th>Interceptions</th> + <th>Invariants</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{jsxref("Global_Objects/Proxy/handler/getPrototypeOf", "handler.getPrototypeOf()")}}</td> + <td>{{jsxref("Object.getPrototypeOf()")}}<br> + {{jsxref("Reflect.getPrototypeOf()")}}<br> + {{jsxref("Object/proto", "__proto__")}}<br> + {{jsxref("Object.prototype.isPrototypeOf()")}}<br> + {{jsxref("Operators/instanceof", "instanceof")}}</td> + <td> + <ul> + <li><code>getPrototypeOf</code> method must return an object or <code>null</code>.</li> + <li>If <code>target</code> is not extensible, <code>Object.getPrototypeOf(proxy)</code> method must return the same value as <code>Object.getPrototypeOf(target)</code>.</li> + </ul> + </td> + </tr> + <tr> + <td>{{jsxref("Global_Objects/Proxy/handler/setPrototypeOf", "handler.setPrototypeOf()")}}</td> + <td>{{jsxref("Object.setPrototypeOf()")}}<br> + {{jsxref("Reflect.setPrototypeOf()")}}</td> + <td>If <code>target</code> is not extensible, the <code>prototype</code> parameter must be the same value as <code>Object.getPrototypeOf(target)</code>.</td> + </tr> + <tr> + <td>{{jsxref("Global_Objects/Proxy/handler/isExtensible", "handler.isExtensible()")}}</td> + <td>{{jsxref("Object.isExtensible()")}}<br> + {{jsxref("Reflect.isExtensible()")}}</td> + <td><code>Object.isExtensible(proxy)</code> must return the same value as <code>Object.isExtensible(target)</code>.</td> + </tr> + <tr> + <td>{{jsxref("Global_Objects/Proxy/handler/preventExtensions", "handler.preventExtensions()")}}</td> + <td>{{jsxref("Object.preventExtensions()")}}<br> + {{jsxref("Reflect.preventExtensions()")}}</td> + <td><code>Object.preventExtensions(proxy)</code> only returns <code>true</code> if <code>Object.isExtensible(proxy)</code> is <code>false</code>.</td> + </tr> + <tr> + <td>{{jsxref("Global_Objects/Proxy/handler/getOwnPropertyDescriptor", "handler.getOwnPropertyDescriptor()")}}</td> + <td>{{jsxref("Object.getOwnPropertyDescriptor()")}}<br> + {{jsxref("Reflect.getOwnPropertyDescriptor()")}}</td> + <td> + <ul> + <li><code>getOwnPropertyDescriptor</code> must return an object or <code>undefined</code>.</li> + <li>A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object.</li> + <li>A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible.</li> + <li>A property cannot be reported as existent, if it does not exists as an own property of the target object and the target object is not extensible.</li> + <li>A property cannot be reported as non-configurable, if it does not exists as an own property of the target object or if it exists as a configurable own property of the target object.</li> + <li>The result of <code>Object.getOwnPropertyDescriptor(target)</code>can be applied to the target object using <code>Object.defineProperty</code> and will not throw an exception.</li> + </ul> + </td> + </tr> + <tr> + <td>{{jsxref("Global_Objects/Proxy/handler/defineProperty", "handler.defineProperty()")}}</td> + <td>{{jsxref("Object.defineProperty()")}}<br> + {{jsxref("Reflect.defineProperty()")}}</td> + <td> + <ul> + <li>A property cannot be added, if the target object is not extensible.</li> + <li>A property cannot be added as or modified to be non-configurable, if it does not exists as a non-configurable own property of the target object.</li> + <li>A property may not be non-configurable, if a corresponding configurable property of the target object exists.</li> + <li>If a property has a corresponding target object property then <code>Object.defineProperty(target, prop, descriptor)</code> will not throw an exception.</li> + <li>In strict mode, a <code>false</code> return value from the <code>defineProperty</code> handler will throw a {{jsxref("TypeError")}} exception.</li> + </ul> + </td> + </tr> + <tr> + <td>{{jsxref("Global_Objects/Proxy/handler/has", "handler.has()")}}</td> + <td>Property query: <code>foo in proxy</code><br> + Inherited property query: <code>foo in Object.create(proxy)</code><br> + {{jsxref("Reflect.has()")}}</td> + <td> + <ul> + <li>A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object.</li> + <li>A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible.</li> + </ul> + </td> + </tr> + <tr> + <td>{{jsxref("Global_Objects/Proxy/handler/get", "handler.get()")}}</td> + <td>Property access: <code>proxy[foo]</code>and <code>proxy.bar</code><br> + Inherited property access: <code>Object.create(proxy)[foo]</code><br> + {{jsxref("Reflect.get()")}}</td> + <td> + <ul> + <li>The value reported for a property must be the same as the value of the corresponding target object property if the target object property is a non-writable, non-configurable data property.</li> + <li>The value reported for a property must be undefined if the corresponding target object property is non-configurable accessor property that has undefined as its [[Get]] attribute.</li> + </ul> + </td> + </tr> + <tr> + <td>{{jsxref("Global_Objects/Proxy/handler/set", "handler.set()")}}</td> + <td>Property assignment: <code>proxy[foo] = bar</code>and <code>proxy.foo = bar</code><br> + Inherited property assignment: <code>Object.create(proxy)[foo] = bar</code><br> + {{jsxref("Reflect.set()")}}</td> + <td> + <ul> + <li>Cannot change the value of a property to be different from the value of the corresponding target object property if the corresponding target object property is a non-writable, non-configurable data property.</li> + <li>Cannot set the value of a property if the corresponding target object property is a non-configurable accessor property that has <code>undefined</code> as its [[Set]] attribute.</li> + <li>In strict mode, a <code>false</code> return value from the <code>set</code>handler will throw a {{jsxref("TypeError")}} exception.</li> + </ul> + </td> + </tr> + <tr> + <td>{{jsxref("Global_Objects/Proxy/handler/deleteProperty", "handler.deleteProperty()")}}</td> + <td>Property deletion: <code>delete proxy[foo]</code> and <code>delete proxy.foo</code><br> + {{jsxref("Reflect.deleteProperty()")}}</td> + <td>A property cannot be deleted, if it exists as a non-configurable own property of the target object.</td> + </tr> + <tr> + <td>{{jsxref("Global_Objects/Proxy/handler/enumerate", "handler.enumerate()")}}</td> + <td>Property enumeration / for...in: <code>for (var name in proxy) {...}</code><br> + {{jsxref("Reflect.enumerate()")}}</td> + <td>The <code>enumerate</code> method must return an object.</td> + </tr> + <tr> + <td>{{jsxref("Global_Objects/Proxy/handler/ownKeys", "handler.ownKeys()")}}</td> + <td>{{jsxref("Object.getOwnPropertyNames()")}}<br> + {{jsxref("Object.getOwnPropertySymbols()")}}<br> + {{jsxref("Object.keys()")}}<br> + {{jsxref("Reflect.ownKeys()")}}</td> + <td> + <ul> + <li>The result of <code>ownKeys</code> is a List.</li> + <li>The Type of each result List element is either {{jsxref("String")}} or {{jsxref("Symbol")}}.</li> + <li>The result List must contain the keys of all non-configurable own properties of the target object.</li> + <li>If the target object is not extensible, then the result List must contain all the keys of the own properties of the target object and no other values.</li> + </ul> + </td> + </tr> + <tr> + <td>{{jsxref("Global_Objects/Proxy/handler/apply", "handler.apply()")}}</td> + <td><code>proxy(..args)</code><br> + {{jsxref("Function.prototype.apply()")}} and {{jsxref("Function.prototype.call()")}}<br> + {{jsxref("Reflect.apply()")}}</td> + <td>There are no invariants for the <code>handler.apply</code>method.</td> + </tr> + <tr> + <td>{{jsxref("Global_Objects/Proxy/handler/construct", "handler.construct()")}}</td> + <td><code>new proxy(...args)</code><br> + {{jsxref("Reflect.construct()")}}</td> + <td>The result must be an <code>Object</code>.</td> + </tr> + </tbody> +</table> + +<h2 id="Revocable_Proxy">Revocable <code>Proxy</code></h2> + +<p>The {{jsxref("Proxy.revocable()")}} method is used to create a revocable <code>Proxy</code> object. This means that the proxy can be revoked via the function <code>revoke</code> and switches the proxy off. Afterwards, any operation on the proxy leads to a {{jsxref("TypeError")}}</p> + +<pre class="brush: js">var revocable = Proxy.revocable({}, { + get: function(target, name) { + return '[[' + name + ']]'; + } +}); +var proxy = revocable.proxy; +console.log(proxy.foo); // "[[foo]]" + +revocable.revoke(); + +console.log(proxy.foo); // TypeError is thrown +proxy.foo = 1; // TypeError again +delete proxy.foo; // still TypeError +typeof proxy; // "object", typeof doesn't trigger any trap</pre> + +<h2 id="Reflection">Reflection</h2> + +<p>{{jsxref("Reflect")}} is a built-in object that provides methods for interceptable JavaScript operations. The methods are the same as those of the {{jsxref("Global_Objects/Proxy/handler","proxy handlers","","true")}}. <code>Reflect</code> is not a function object.</p> + +<p><code>Reflect</code> helps with forwarding default operations from the handler to the target.</p> + +<p>With {{jsxref("Reflect.has()")}} for example, you get the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in"><code>in</code> operator</a> as a function:</p> + +<pre><code>Reflect.has(Object, 'assign'); // true</code></pre> + +<h3 id="A_better_apply_function">A better <code>apply</code> function</h3> + +<p>In ES5, you typically use the {{jsxref("Function.prototype.apply()")}} method to call a function with a given <code>this</code> value and <code>arguments</code> provided as an array (or an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#Working_with_array-like_objects">array-like object</a>).</p> + +<pre><code>Function.prototype.apply.call(Math.floor, undefined, [1.75]);</code></pre> + +<p>With {{jsxref("Reflect.apply")}} this becomes less verbose and easier to understand:</p> + +<pre><code>Reflect.apply(Math.floor, undefined, [1.75]); +// 1; + +Reflect.apply(String.fromCharCode, undefined, [104, 101, 108, 108, 111]); +// "hello" + +Reflect.apply(RegExp.prototype.exec, /ab/, ['confabulation']).index; +// 4 + +Reflect.apply(''.charAt, 'ponies', [3]); +// "i"</code></pre> + +<h3 id="Checking_if_property_definition_has_been_successful">Checking if property definition has been successful</h3> + +<p>With {{jsxref("Object.defineProperty")}}, which returns an object if successful, or throws a {{jsxref("TypeError")}} otherwise, you would use a {{jsxref("Statements/try...catch","try...catch")}} block to catch any error that occurred while defining a property. Because {{jsxref("Reflect.defineProperty")}} returns a Boolean success status, you can just use an {{jsxref("Statements/if...else","if...else")}} block here:</p> + +<pre><code>if (Reflect.defineProperty(target, property, attributes)) { + // success +} else { + // failure +}</code></pre> + +<p>{{Previous("Web/JavaScript/Guide/Iterators_and_Generators")}}</p> + +<p> </p> diff --git a/files/ko/web/javascript/guide/소개/index.html b/files/ko/web/javascript/guide/소개/index.html new file mode 100644 index 0000000000..cac0779ee0 --- /dev/null +++ b/files/ko/web/javascript/guide/소개/index.html @@ -0,0 +1,153 @@ +--- +title: Introduction +slug: Web/JavaScript/Guide/소개 +tags: + - JavaScript + - 가이드 + - 안내서 + - 자바스크립트 +translation_of: Web/JavaScript/Guide/Introduction +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}</div> + +<p class="summary">이 장은 JavaScript를 소개하고 그 일부 기초 개념을 다룹니다.</p> + +<h2 id="무엇을_미리_알고_있어야_하나요">무엇을 미리 알고 있어야 하나요?</h2> + +<p>이 안내서는 당신이 다음의 기본적인 배경지식이 있다고 가정합니다.</p> + +<ul> + <li>인터넷과 월드 와이드 웹({{Glossary("WWW")}})에 대한 전반적인 이해.</li> + <li>HyperText 마크업 언어({{Glossary("HTML")}})에 대한 괜찮은 실무 지식.</li> + <li>약간의 프로그래밍 경험. 만약 프로그래밍이 처음이라면, <a href="/ko/docs/Web/JavaScript">JavaScript</a> 메인 페이지에 링크된 tutorial 중 하나를 따라하세요.</li> +</ul> + +<h2 id="어디서_JavaScript_정보를_찾을_수_있을까">어디서 JavaScript 정보를 찾을 수 있을까</h2> + +<p>MDN에 있는 JavaScript 문서는 다음 세가지 파트로 되어있습니다.</p> + +<ul> + <li><a href="/ko/docs/Learn">Learning the Web</a>은 입문자를 위한 정보를 제공하며, 프로그래밍과 인터넷에 대한 기본 개념을 소개합니다.</li> + <li><a href="/ko/docs/Web/JavaScript/Guide">JavaScript Guide</a> (이 안내서)는 JavaScript 언어와 객체에 대한 개요를 제공합니다.</li> + <li><a href="/ko/docs/Web/JavaScript/Reference">JavaScript Reference</a> JavaScript에 관련된 자세한 참고 자료를 제공합니다.</li> +</ul> + +<p>JavaScript가 처음이라면, <a href="/ko/docs/Learn">learning area</a>와 <a href="/ko/docs/Web/JavaScript/Guide">JavaScript Guide</a>에 있는 문서를 먼저 보세요. 일단 기초를 확실히 파악한 후에는, 각 객체와 문(statement)에 대한 더 자세한 정보를 <a href="/ko/docs/Web/JavaScript/Reference">JavaScript Reference</a>에서 확인할 수 있습니다.</p> + +<h2 id="JavaScript는_무엇인가">JavaScript는 무엇인가?</h2> + +<p>JavaScript는 크로스-플랫폼, 객체지향 스크립트 언어입니다. 작고 가벼운 언어입니다. 호스트 환경(가령, 웹 브라우저) 내에서, JavaScript는 프로그램 제어를 제공하기 위해 그 환경의 객체에 연결될 수 있습니다. Node.Js와 같은 자바 스크립트의 고급 서버언어로 사용 할 수도 있습니다.이것을 사용하면 단순히 파일을 다운로드하는 것 (예 : 여러 컴퓨터 간의 실시간 공동 작업)보다 웹 사이트에 더 많은 기능을 추가 할 수 있습니다. 호스트 환경 (예 : 웹 브라우저) 내에서 JavaScript는 해당 환경의 객체에 연결되어 프로그래밍 방식으로 제어 할 수 있습니다.</p> + +<p>JavaScript는 <code>Array</code>, <code>Date</code>, <code>Math</code>와 같은 객체에 대한 표준 라이브러리와 연산자(operator), 제어 구조, 문과 같은 언어 요소의 코어 집합을 포함합니다. 코어 JavaScript는 거기에 추가 객체를 보충하여 다양한 목적으로 확장될 수 있습니다. 예를 들면:</p> + +<ul> + <li><em>클라이언트 측 JavaScript</em>는 브라우저와 문서 객체 모델(DOM) 을 제어하는 객체를 제공하여 코어 언어를 확장합니다. 예를 들어, 클라이언트 측 확장은 어플리케이션이 요소(element)를 HTML 폼에 두고, 마우스 클릭, 폼 입력 및 페이지 탐색 같은 사용자 이벤트에 응답하게 해줍니다.</li> + <li><em>서버 측 JavaScript</em>는 서버에서 JavaScript 실행에 관련된 객체를 제공하여 코어 언어를 확장합니다. 예를 들어, 서버 측 확장은 어플리케이션이 데이터베이스와 통신하고, 한 번의 호출 정보의 연속성을 어플리케이션의 다른 곳에 제공하거나, 서버에서 파일 조작을 수행할 수 있도록 해줍니다.</li> +</ul> + +<p>이것은 브라우저에서 JavaScript가 웹 페이지 (DOM)의 모양을 바꿀 수 있음을 의미합니다. 또한 서버의 Node.js JavaScript는 브라우저에 작성된 코드의 사용자 정의 요청에 응답 할 수 있습니다.</p> + +<h2 id="JavaScript_and_Java" name="JavaScript_and_Java">JavaScript 와 Java</h2> + +<p>JavaScript 와 Java는 여러 면에서 비슷하지만 어떤 면에서는 근본적으로 다릅니다. JavaScript 언어는 Java를 닮았지만 Java의 정적 형지정(static typing)과 강한 형 검사(strong type checking)가 없습니다. JavaScript는 대부분의 Java 식 구문, 명명 규칙 및 기본적인 흐름 제어 구조를 따릅니다. 그것이 LiveScript에서 JavaScript로 이름이 바뀐 이유였습니다.</p> + +<p>Java의 선언에 의해 생성되는 클래스의 컴파일-타임 시스템과는 달리, JavaScript는 숫자, 불리언, 그리고 문자열 값을 표현하는 적은 수의 자료 형을 기반으로 한 런타임 시스템을 지원합니다. JavaScript 는 더 일반적인 클래스 기반 객체 모델 대신에 프로토타입 기반 객체 모델을 갖습니다. 프로토타입 기반 모델은 동적 상속을 제공합니다. 즉, 상속된 대상은 각각의 객체에 따라 다양할 수 있습니다. JavaScript는 또한 어떤 특정한 선언을 요구하지 않는 함수도 지원합니다. 함수는 객체의 속성이나, 타입이 느슨하게 형지정된 채 실행되는 메소드가 될 수 있습니다.</p> + +<p>JavaScript는 Java에 비해 매우 자유로운 형태의 언어입니다. 여러분은 모든 변수, 클래스, 및 메소드를 선언하지 않아도 됩니다. 여러분은 메소드가 public, private, 또는 protected 인지 염려할 필요가 없고 인터페이스를 구현하지 않아도 됩니다. 변수, 매개변수(parameter), 및 함수의 반환 형은 명시적으로 지정되지 않습니다.</p> + +<p>Java는 빠른 실행과 형 안전성(type safety)을 위해 설계된 클래스 기반 프로그래밍 언어입니다. 형 안전성은, 예를 들어, 여러분이 Java 정수를 객체의 레퍼런스로 형변환(cast)하거나 Java 바이트코드를 변경하여 private 메모리에 접근할 수 없음을 의미합니다. Java의 클래스 기반 모델은 프로그램이 오로지 클래스와 그 메소드로만 구성된다는 것을 뜻합니다. Java의 클래스 상속과 강한 형지정은 보통 단단하게 결합된 객체 계층구조를 요구합니다. 이러한 요구는 Java 프로그래밍을 JavaScript 프로그래밍보다 더 복잡하게 만듭니다.</p> + +<p>반면에, JavaScript는 HyperTalk 과 dBASE 같은 더 작고 동적 형지정이 가능한 언어들의 정신을 계승했습니다. 이러한 스크립팅 언어는 더 쉬운 구문과 특별한 내장(built-in) 기능 및 객체 생성을 위한 최소 요구사항으로 인해 훨씬 더 많은 사람들에게 프로그래밍 도구를 제공합니다.</p> + +<table class="standard-table"> + <caption>Java와 비교한 JavaScript</caption> + <thead> + <tr> + <th scope="col">JavaScript</th> + <th scope="col">Java</th> + </tr> + </thead> + <tbody> + <tr> + <td>객체 지향. 객체의 형 간에 차이 없음. 프로토타입 메커니즘을 통한 상속, 그리고 속성과 메서드는 어떤 객체든 동적으로 추가될 수 있음.</td> + <td>클래스 기반. 객체는 클래스 계층구조를 통한 모든 상속과 함께 클래스와 인스턴스로 나뉨. 클래스와 인스턴스는 동적으로 추가된 속성이나 메소드를 가질 수 없음.</td> + </tr> + <tr> + <td>변수 자료형이 선언되지 않음(dynamic typing, loosely typed).</td> + <td>변수 자료형은 반드시 선언되어야 함(정적 형지정, static typing).</td> + </tr> + <tr> + <td>하드 디스크에 자동으로 작성 불가.</td> + <td>하드 디스크에 자동으로 작성 가능.</td> + </tr> + </tbody> +</table> + +<p>JavaScript와 Java의 차이에 대한 더 많은 정보는, <a href="/ko/docs/Web/JavaScript/Guide/객체_모델의_세부사항">객체 모델의 세부사항</a> 장을 보세요.</p> + +<h2 id="JavaScript_and_the_ECMAScript_Specification" name="JavaScript_and_the_ECMAScript_Specification">JavaScript 와 ECMAScript 명세</h2> + +<p>JavaScript는 JavaScript에 기반한 표준화된 국제 프로그래밍 언어를 제공하기 위해<a class="external" href="http://www.ecma-international.org/">Ecma International</a> 에서 표준화 됩니다 — European association for standardizing information and communication systems (ECMA는 이전에 European Computer Manufacturers Association의 두문자어였습니다). ECMAScript라 불리는 이 JavaScript의 표준화 버전은 표준을 지원하는 모든 어플리케이션에서 같은 방식으로 동작합니다. 회사들은 그들의 JavaScript 구현을 개발하기 위해 공개 표준 언어를 사용할 수 있습니다. ECMAScript 표준은 ECMA-262 명세(specification)에서 문서화되었습니다. JavaScript와 ECMAScript 명세 판의 여러 버전에 대한 더 많은 것을 배우려면 <a href="/ko/docs/Web/JavaScript/New_in_JavaScript">New in JavaScript</a> 을 보세요.</p> + +<p>ECMA-262 표준은 또한 IOS-16262로서 <a class="external" href="http://www.iso.ch/">ISO</a> (국제 표준화 기구) 에 의해 승인되었습니다. <a class="external" href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">Ecma International website</a> 에서 그 명세를 찾을 수 있습니다. ECMAScript 명세는 <a class="external" href="http://www.w3.org/">World Wide Web Consortium (W3C)</a> 나 <a href="https://whatwg.org/">WHATWG (Web Hypertext Application Technology Working Group)</a>에 의해 표준화된 Document Object Model (DOM)을 설명하지 않습니다. DOM은 여러분의 스크립트에 HTML 문서 객체를 드러내는 방법을 정의합니다. JavaScript로 프로그래밍을 할 때 사용되는 여러 기술들에 대한 정보를 얻으 시려면, <a href="/ko/docs/Web/JavaScript/JavaScript_technologies_overview">JavaScript technologies overview</a> 를 참고하세요.</p> + +<h3 id="JavaScript_Documentation_versus_the_ECMAScript_Specification" name="JavaScript_Documentation_versus_the_ECMAScript_Specification">JavaScript 문서 vs ECMAScript 명세</h3> + +<p>ECMAScript 명세는 ECMAScript 구현을 위한 요구사항의 집합입니다; 여러분이 여러분의 ECMAScript 구현이나 엔진(가령 Firefox의 SpiderMonkey, 또는 Chrome의 v8)에서 표준을 따르는 언어의 기능을 구현하길 원할 때 유용합니다.</p> + +<p>ECMAScript 문서는 스크립트 프로그래머를 돕기 위함이 아닙니다; 스크립트 작성을 위한 정보는 JavaScript 문서를 사용하세요.</p> + +<p>ECMAScript 명세는 JavaScript 프로그래머에게 익숙하지 않을 수 있는 용어와 문법을 사용합니다. 언어의 기술이 ECMAScript 에서 다를 수 있지만, 언어 그 자체는 같습니다. JavaScript는 ECMAScript 명세에 서술된 모든 기능을 지원합니다.</p> + +<p>JavaScript 문서는 JavaScript 프로그래머에게 적합한 언어의 측면을 설명합니다.</p> + +<h2 id="JavaScript_시작하기">JavaScript 시작하기</h2> + +<p>JavaScript 시작은 쉽습니다: 최신 웹 브라우저만 있으면 됩니다. 이 안내서는 현재 Firefox의 최신 버전에서만 사용 가능한 약간의 JavaScript 기능을 포함하므로, 가장 최신 버전의 Firefox를 사용하기를 권합니다.</p> + +<p>JavaScript를 실험하기 유용한 두 도구가 Firefox에 내장되어 있습니다: Web Console과 Scratchpad.</p> + +<h3 id="웹_콘솔">웹 콘솔</h3> + +<p><a href="/ko/docs/Tools/Web_Console">웹 콘솔</a>은 현재 로드된 페이지에 대한 정보를 보이고, 또한 여러분이 현재 페이지에서 JavaScript 식을 실행해볼 수 있는<a href="/ko/docs/Tools/Web_Console#The_command_line_interpreter"> 명령어 입력줄(command line)</a>을 제공합니다.</p> + +<p>웹 콘솔을 열기 위해서는, Firefox의 "도구" 메뉴 하위에 있는 "개발자" 메뉴의 "웹 콘솔"을 선택(윈도우와 리눅스에서는 <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>I</kbd>, 맥에서는 <kbd>Cmd</kbd>-<kbd>Option</kbd>-<kbd>K</kbd>)합니다. 브라우저 창의 아래에 웹 콘솔이 나타납니다. 콘솔의 바닥을 따라 나온 것이 여러분이 JavaScript를 입력할 수 있는 명령어 입력줄이고, 실행 결과는 바로 위 공간에 표시됩니다:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/16569/2019-04-04_00-15-29.png" style="display: block; height: 1824px; margin-left: auto; margin-right: auto; width: 2784px;"></p> + +<p>이 콘솔은 eval과 완전히 동일하게 동작합니다:마지막 입력된 표현식이 반환되죠. 간단하게 생각해서, 콘솔에 뭔가 입력할 때마다 eval로 감싼 console.log로 둘러싸인 형태라고 보시면 됩니다.</p> + +<pre class="notranslate">function greetMe(yourName) { alert('Hello ' + yourName); } <code>console.log(eval('3 + 5'));</code></pre> + +<h3 id="Scratchpad">Scratchpad</h3> + +<p>Web Console은 한 줄 JavaScript를 실행하기에 훌륭합니다. 하지만 비록 여러 줄을 실행할 수 있지만, 아주 불편하고 Web Console을 사용해 여러분의 샘플 코드를 저장할 수도 없습니다. 그러므로 좀 더 복잡한 예제를 위해서는 <a href="ko/docs/도구들/Scratchpad">Scratchpad</a>가 더 나은 도구입니다.</p> + +<p>Scratchpad를 열기 위해, Firefox의 메뉴 "Tools" 의 하위에 있는 "Web Developer" 메뉴의 "Scratchpad" 를 선택합니다(단축키: <kbd>Shift</kbd>+<kbd>F4</kbd>). 이것은 분리된 창에서 열리고 브라우저에서 JavaScript를 작성하고 실행하기 위해 사용할 수 있는 에디터입니다. 여러분은 또한 디스크로부터 스크립트를 부르거나 저장할 수도 있습니다.</p> + +<p><img src="https://mdn.mozillademos.org/files/13468/scratchpad.png"></p> + +<h3 id="Hello_world">Hello world</h3> + +<p>JavaScript 작성을 시작하기 위해서, Scratchpad를 열고 첫 JavaScript 코드 "Hello World" 를 작성하세요.</p> + +<pre class="notranslate"><code>(function(){ + "use strict"; + /* Start of your code */ + function greetMe(yourName) { + alert('Hello ' + yourName); + } + + greetMe('World'); + /* End of your code */ +})();</code></pre> + +<p>패드에서 코드를 선택하고 Ctrl + R 키를 눌러 브라우저에서 펼쳐지는 것을 지켜보십시오! 다음 페이지에서 이 가이드는 JavaScript 구문 및 언어 기능을 소개하므로보다 복잡한 응용 프로그램을 작성할 수 있습니다. 그러나 당분간은 <code>(function () { "use strict"</code>를 코드 앞에 추가하고<code>}}) ();</code>를 코드마지막에 추가하세요. 아직은 이코드가 뭔지 잘 모르겠지만 나중에 이 코드가 의미하는 것을 배울 것입니다, 지금은 간단히 다음과 같다고 생각하세요.</p> + +<ol> + <li>성능을 크게 개선합니다.</li> + <li>초보자가 실수하게 만드는 Javascript의 일부 시맨틱을 막습니다.</li> + <li>콘솔에서 실행되는 코드 스니펫이 서로 상호 작용하지 못하도록합니다 (예 : 한 콘솔 실행에서 생성 된 내용을 다른 콘솔 실행에 사용하는 경우).</li> +</ol> + +<p>{{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}</p> diff --git a/files/ko/web/javascript/guide/정규식/assertions/index.html b/files/ko/web/javascript/guide/정규식/assertions/index.html new file mode 100644 index 0000000000..350c50f8f9 --- /dev/null +++ b/files/ko/web/javascript/guide/정규식/assertions/index.html @@ -0,0 +1,244 @@ +--- +title: Assertions +slug: Web/JavaScript/Guide/정규식/Assertions +translation_of: Web/JavaScript/Guide/Regular_Expressions/Assertions +--- +<p>{{jsSidebar("JavaScript Guide")}}</p> + +<p>Assertions에는 행이나 단어의 시작 · 끝을 나타내는 경계와 (앞, 뒤 읽고 조건식을 포함한) 어떤 식 으로든 매치가 가능한 것을 나타내는 다른 패턴이 포함됩니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/regexp-assertions.html", "taller")}}</div> + +<h2 id="Types">Types</h2> + +<h3 id="Boundary-type_assertions">Boundary-type assertions</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Characters</th> + <th scope="col">Meaning</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>^</code></td> + <td> + <p>Matches the beginning of input. If the multiline flag is set to true, also matches immediately after a line break character. For example, <code>/^A/</code> does not match the "A" in "an A", but does match the first "A" in "An A".</p> + + <div class="blockIndicator note"> + <p>This character has a different meaning when it appears at the start of a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges">group</a>.</p> + </div> + </td> + </tr> + <tr> + <td><code>$</code></td> + <td> + <p>Matches the end of input. If the multiline flag is set to true, also matches immediately before a line break character. For example, <code>/t$/</code> does not match the "t" in "eater", but does match it in "eat".</p> + </td> + </tr> + <tr> + <td><code>\b</code></td> + <td> + <p>Matches a word boundary. This is the position where a word character is not followed or preceded by another word-character, such as between a letter and a space. Note that a matched word boundary is not included in the match. In other words, the length of a matched word boundary is zero.</p> + + <p>Examples:</p> + + <ul> + <li><code>/\bm/</code> matches the "m" in "moon".</li> + <li><code>/oo\b/</code> does not match the "oo" in "moon", because "oo" is followed by "n" which is a word character.</li> + <li><code>/oon\b/</code> matches the "oon" in "moon", because "oon" is the end of the string, thus not followed by a word character.</li> + <li><code>/\w\b\w/</code> will never match anything, because a word character can never be followed by both a non-word and a word character.</li> + </ul> + + <p>To match a backspace character (<code>[\b]</code>), see <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes">Character Classes</a>.</p> + </td> + </tr> + <tr> + <td><code>\B</code></td> + <td> + <p>Matches a non-word boundary. This is a position where the previous and next character are of the same type: Either both must be words, or both must be non-words, for example between two letters or between two spaces. The beginning and end of a string are considered non-words. Same as the matched word boundary, the matched non-word boundary is also not included in the match. For example, <code>/\Bon/</code> matches "on" in "at noon", and <code>/ye\B/</code> matches "ye" in "possibly yesterday".</p> + </td> + </tr> + </tbody> +</table> + +<h3 id="Other_assertions">Other assertions</h3> + +<div class="blockIndicator note"> +<p><strong>Note</strong>: The <code>?</code> character may also be used as a quantifier.</p> +</div> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Characters</th> + <th scope="col">Meaning</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>x(?=y)</code></td> + <td> + <p><strong>Lookahead assertion: </strong>Matches "x" only if "x" is followed by "y". For example, /<code>Jack(?=Sprat)/</code> matches "Jack" only if it is followed by "Sprat".<br> + <code>/Jack(?=Sprat|Frost)/</code> matches "Jack" only if it is followed by "Sprat" or "Frost". However, neither "Sprat" nor "Frost" is part of the match results.</p> + </td> + </tr> + <tr> + <td><code>x(?!y)</code></td> + <td> + <p><strong>Negative lookahead assertion: </strong>Matches "x" only if "x"<span> is not followed by </span>"y"<span>.</span> For example, <code>/\d+(?!\.)/</code><span> matches a number only if it is not followed by a decimal point. </span><code>/\d+(?!\.)/.exec('3.141')</code> matches "141" but not "3.</p> + </td> + </tr> + <tr> + <td><code>(?<=y)x</code></td> + <td> + <p><strong>Lookbehind assertion: </strong>Matches "x" only if "x" is preceded by "y". For example, <code>/(?<=Jack)Sprat/</code><span> matches "Sprat" only if it is preceded by "Jack". </span><code>/(?<=Jack|Tom)Sprat/</code> matches "Sprat" only if it is preceded by "Jack" or "Tom". However, neither "Jack" nor "Tom" is part of the match results.</p> + </td> + </tr> + <tr> + <td><code>(?<!y)x</code></td> + <td> + <p><strong>Negative lookbehind assertion: </strong>Matches "x" only if "x" is not preceded by "y". For example, <code>/(?<!-)\d+/</code><span> matches a number only if it is not preceded by a minus sign. </span><code>/(?<!-)\d+/.exec('3')</code> matches "3". <code>/(?<!-)\d+/.exec('-3')</code> match is not found because the number is preceded by the minus sign.</p> + </td> + </tr> + </tbody> +</table> + +<h2 id="Examples">Examples</h2> + +<h3 id="General_boundary-type_overview_example">General boundary-type overview example</h3> + +<pre class="brush: js notranslate">// Using Regex boundaries to fix buggy string. +buggyMultiline = `tey, ihe light-greon apple +tangs on ihe greon traa`; + +// 1) Use ^ to fix the matching at the begining of the string, and right after newline. +buggyMultiline = buggyMultiline.replace(/^t/gim,'h'); +console.log(1, buggyMultiline); // fix 'tey', 'tangs' => 'hey', 'hangs'. Avoid 'traa'. + +// 2) Use $ to fix matching at the end of the text. +buggyMultiline = buggyMultiline.replace(/aa$/gim,'ee.'); +console.log(2, buggyMultiline); // fix 'traa' => 'tree'. + +// 3) Use \b to match characters right on border between a word and a space. +buggyMultiline = buggyMultiline.replace(/\bi/gim,'t'); +console.log(3, buggyMultiline); // fix 'ihe' but does not touch 'light'. + +// 4) Use \B to match characters inside borders of an entity. +fixedMultiline = buggyMultiline.replace(/\Bo/gim,'e'); +console.log(4, fixedMultiline); // fix 'greon' but does not touch 'on'. +</pre> + +<h3 id="Matching_the_beginning_of_an_input_using_a_control_character">Matching the beginning of an input using a ^ control character</h3> + +<p>입력 시작시 일치를 위해 <code>^</code>를 사용하십시오. 이 예에서는 <code>/^A/</code> regex로 'A'로 시작하는 결과를 얻습니다. 여기서 <code>^</code>는 한 가지 역할 만합니다. 적절한 결과를 보기위해 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">화살표</a> 함수가있는 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter">필터</a> 메소드를 사용합니다.</p> + +<pre class="brush: js notranslate">let fruits = ["Apple", "Watermelon", "Orange", "Avocado", "Strawberry"]; + +// Select fruits started with 'A' by /^A/ Regex. +// Here '^' control symbol used only in one role: Matching begining of an input. + +let fruitsStartsWithA = fruits.filter(fruit => /^A/.test(fruit)); +console.log(fruitsStartsWithA); // [ 'Apple', 'Avocado' ] +</pre> + +<p>두 번째 예제에서 <code>^</code>는 두 가지 모두에 사용됩니다 : 입력의 일치 시작점, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges">그룹</a>에서 사용될 때 부정 또는 보완 문자 세트.</p> + +<pre class="brush: js notranslate">let fruits = ["Apple", "Watermelon", "Orange", "Avocado", "Strawberry"]; + +// Selecting fruits that dose not start by 'A' by a /^[^A]/ regex. +// In this example, two meanings of '^' control symbol are represented: +// 1) Matching begining of the input +// 2) A negated or complemented character set: [^A] +// That is, it matches anything that is not enclosed in the brackets. + +let fruitsStartsWithNotA = fruits.filter(fruit => /^[^A]/.test(fruit)); + +console.log(fruitsStartsWithNotA); // [ 'Watermelon', 'Orange', 'Strawberry' ]</pre> + +<h3 id="Matching_a_word_boundary">Matching a word boundary</h3> + +<pre class="brush: js notranslate">let fruitsWithDescription = ["Red apple", "Orange orange", "Green Avocado"]; + +// Select descriptions that contains 'en' or 'ed' words endings: +let enEdSelection = fruitsWithDescription.filter(descr => /(en|ed)\b/.test(descr)); + +console.log(enEdSelection); // [ 'Red apple', 'Green Avocado' ]</pre> + +<h3 id="Lookahead_assertion">Lookahead assertion</h3> + +<pre class="brush: js notranslate">// JS Lookahead assertion x(?=y) + +let regex = /First(?= test)/g; + +console.log('First test'.match(regex)); // [ 'First' ] +console.log('First peach'.match(regex)); // null +console.log('This is a First test in a year.'.match(regex)); // [ 'First' ] +console.log('This is a First peach in a month.'.match(regex)); // null +</pre> + +<h3 id="Basic_negative_lookahead_assertion">Basic negative lookahead assertion</h3> + +<p>For example, <code>/\d+(?!\.)/</code><span> matches a number only if it is not followed by a decimal point. </span><code>/\d+(?!\.)/.exec('3.141')</code> matches "141" but not "3.</p> + +<pre class="brush: js notranslate">console.log(/\d+(?!\.)/g.exec('3.141')); // [ '141', index: 2, input: '3.141' ] +</pre> + +<h3 id="Different_meaning_of_!_combination_usage_in_Assertions_and_Ranges">Different meaning of '?!' combination usage in Assertions and Ranges </h3> + +<p>Different meaning of <code>?!</code> combination usage in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Assertions">Assertions</a> <code>/x(?!y)/ </code>and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges">Ranges</a> <code>[^?!]</code>.</p> + +<pre class="brush: js notranslate">let orangeNotLemon = "Do you want to have an orange? Yes, I do not want to have a lemon!"; + +// Different meaning of '?!' combination usage in Assertions /x(?!y)/ and Ranges /[^?!]/ +let selectNotLemonRegex = /[^?!]+have(?! a lemon)[^?!]+[?!]/gi +console.log(orangeNotLemon.match(selectNotLemonRegex)); // [ 'Do you want to have an orange?' ] + +let selectNotOrangeRegex = /[^?!]+have(?! an orange)[^?!]+[?!]/gi +console.log(orangeNotLemon.match(selectNotOrangeRegex)); // [ ' Yes, I do not want to have a lemon!' ] +</pre> + +<h3 id="Lookbehind_assertion">Lookbehind assertion</h3> + +<pre class="brush: js notranslate">let oranges = ['ripe orange A ', 'green orange B', 'ripe orange C',]; + +let ripe_oranges = oranges.filter( fruit => fruit.match(/(?<=ripe )orange/)); +console.log(ripe_oranges); // [ 'ripe orange A ', 'ripe orange C' ] +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-assertion', 'RegExp: Assertions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>For browser compatibility information, check out the <a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Browser_compatibility">main Regular Expressions compatibility table</a>.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions">Regular expressions guide</a> + + <ul> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes">Character classes</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Quantifiers">Quantifiers</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Unicode_Property_Escapes">Unicode property escapes</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges">Groups and ranges</a></li> + </ul> + </li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp">The <code>RegExp()</code> constructor</a></li> +</ul> diff --git a/files/ko/web/javascript/guide/정규식/groups_and_ranges/index.html b/files/ko/web/javascript/guide/정규식/groups_and_ranges/index.html new file mode 100644 index 0000000000..2e2109b4ed --- /dev/null +++ b/files/ko/web/javascript/guide/정규식/groups_and_ranges/index.html @@ -0,0 +1,91 @@ +--- +title: Groups and Ranges +slug: Web/JavaScript/Guide/정규식/Groups_and_Ranges +translation_of: Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges +--- +<p>{{jsSidebar("JavaScript Guide")}}{{draft}}</p> + +<p>그룹(Groups)과 범위(ranges)는 표현 문자의 그룹과 범위를 나타냅니다.</p> + +<h2 id="Types">Types</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Characters</th> + <th scope="col">Meaning</th> + </tr> + </thead> + <tbody> + <tr> + <td><code><em>x</em>|<em>y</em></code></td> + <td> + <p><code>x</code>또는 <code>y</code>와 매칭되는 경우. 예를들면 <code>/green|red/</code> 은 "green apple"의 "green"과 매치되고 "red apple"의 "red"와 매치됩니다.</p> + </td> + </tr> + <tr> + <td><code>[xyz]<br> + [a-c]</code></td> + <td> + <p>A character set. Matches any one of the enclosed characters. You can specify a range of characters by using a hyphen, but if the hyphen appears as the first or last character enclosed in the square brackets it is taken as a literal hyphen to be included in the character set as a normal character. It is also possible to include a character class in a character set.</p> + + <p>For example, <code>[abcd]</code> is the same as <code>[a-d]</code>. They match the "b" in "brisket" and the "c" in "chop".</p> + + <p>For example, [abcd-] and [-abcd] match the "b" in "brisket", the "c" in "chop" and the "-" (hyphen) in "non-profit".</p> + + <p>For example, [\w-] is the same as [A-Za-z0-9_-]. They match the "b" in "brisket", the "c" in "chop" and the "n" in "non-profit".</p> + </td> + </tr> + <tr> + <td> + <p><code>[^xyz]<br> + [^a-c]</code></p> + </td> + <td> + <p>A negated or complemented character set. That is, it matches anything that is not enclosed in the brackets. You can specify a range of characters by using a hyphen, but if the hyphen appears as the first or last character enclosed in the square brackets it is taken as a literal hyphen to be included in the character set as a normal character. For example, <code>[^abc]</code> is the same as <code>[^a-c]</code>. They initially match "o" in "bacon" and "h" in "chop".</p> + + <div class="blockIndicator note"> + <p>The ^ character may also indicate the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Boundaries">beginning of input</a>.</p> + </div> + </td> + </tr> + <tr> + <td><code>(<em>x</em>)</code></td> + <td> + <p><strong>Capturing group: </strong>Matches <code><em>x</em></code> and remembers the match. For example, <code>/(foo)/</code> matches and remembers "foo" in "foo bar". </p> + + <p>A regular expression may have multiple capturing groups. In results, matches to capturing groups typically in an array whose members are in the same order as the left parentheses in the capturing group. This is usually just the order of the capturing groups themselves. This becomes important when capturing groups are nested. Matches are accessed using the index of the the result's elements (<code>[1], ..., [n]</code>) or from the predefined <code>RegExp</code> object's properties (<code>$1, ..., $9</code>).</p> + + <p>Capturing groups have a performance penalty. If you don't need the matched substring to be recalled, prefer non-capturing parentheses (see below).</p> + + <p><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match">String.match()</a></code> won't return groups if the <code>/.../g</code> flag is set. However, you can still use <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll">String.matchAll()</a></code> to get all matches.</p> + </td> + </tr> + <tr> + <td><code>\<em>n</em></code></td> + <td> + <p>Where <code><em>n</em></code> is a positive integer. A back reference to the last substring matching the n parenthetical in the regular expression (counting left parentheses). For example, <code>/apple(,)\sorange\1/</code> matches "apple, orange," in "apple, orange, cherry, peach". A complete example follows this table.</p> + </td> + </tr> + <tr> + <td><code>(?<Name>x)</code></td> + <td> + <p><strong>Named capturing group: </strong>Matches <code>x</code> and stores it on the groups property of the returned matches under the name specified by <code><Name></code>. The angle brackets ('<code><</code>' and '<code>></code>') are required for group name.</p> + + <p>For example, to extract the United States area code from a phone number, I could use <code>/\((?<area>\d\d\d)\)/</code>. The resulting number would appear under <code>matches.groups.area</code>.</p> + </td> + </tr> + <tr> + <td><code>(?:<em>x</em>)</code></td> + <td><strong>Non-capturing group: </strong>Matches <code><em>x</em></code> but does not remember the match. The matched substring cannot be recalled from the resulting array's elements (<code>[1], ..., [n]</code>) or from the predefined <code>RegExp</code> object's properties (<code>$1, ..., $9</code>).</td> + </tr> + </tbody> +</table> + +<h2 id="Examples">Examples</h2> + +<h2 id="Browser_support">Browser support</h2> + +<p>Firefox currently doesn't support named groups. See <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1362154">corresponding issue</a>.</p> + +<h2 id="See_also">See also</h2> diff --git a/files/ko/web/javascript/guide/정규식/index.html b/files/ko/web/javascript/guide/정규식/index.html new file mode 100644 index 0000000000..5fbbcef0a0 --- /dev/null +++ b/files/ko/web/javascript/guide/정규식/index.html @@ -0,0 +1,666 @@ +--- +title: 정규 표현식 +slug: Web/JavaScript/Guide/정규식 +tags: + - 자바스크립트 + - 정규식 +translation_of: Web/JavaScript/Guide/Regular_Expressions +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Text_formatting", "Web/JavaScript/Guide/Indexed_collections")}}</div> + +<p class="summary">정규 표현식은 문자열에 나타는 특정 문자 조합과 대응시키기 위해 사용되는 패턴입니다. 자바스크립트에서, 정규 표현식 또한 객체입니다. 이 패턴들은 {{jsxref("RegExp")}}의 {{jsxref("RegExp.exec", "exec")}} 메소드와 {{jsxref("RegExp.test", "test")}} 메소드 ,그리고 {{jsxref("String")}}의 {{jsxref("String.match", "match")}}메소드 , {{jsxref("String.replace", "replace")}}메소드 , {{jsxref("String.search", "search")}}메소드 , {{jsxref("String.split", "split")}} 메소드와 함께 쓰입니다 . 이 장에서는 자바스크립트의 정규식에 대하여 설명합니다.</p> + +<h2 id="정규_표현식_만들기">정규 표현식 만들기</h2> + +<p>(역주: 정규 표현식을 줄여서 '정규식'이라고 하기도 합니다. 아래 부분부터 '정규식'이라는 용어를 사용하겠습니다.)</p> + +<p>정규식을 만드는 방법에는 두 가지가 있습니다.</p> + +<p>정규식 리터럴(슬래쉬"/"로 감싸는 패턴)을 사용하는 방법은 다음과 같습니다.</p> + +<pre class="brush: js">var re = /ab+c/; +</pre> + +<p>정규식 리터럴은 스크립트가 불러와질 때 컴파일됩니다. 만약 정규식이 상수라면, 이렇게 사용하는 것이 성능을 향상시킬 수 있습니다.</p> + +<p>다른 방법으로는, {{jsxref("RegExp")}} 객체의 생성자 함수를 호출하는 방법도 있습니다:</p> + +<pre class="brush: js">var re = new RegExp("ab+c"); +</pre> + +<p>생성자 함수를 사용하면 정규식이 실행 시점에 컴파일됩니다. 정규식의 패턴이 변경될 수 있는 경우, 혹은 사용자 입력과 같이 다른 출처로부터 패턴을 가져와야 하는 경우에는 생성자 함수를 사용하세요.</p> + +<h2 id="정규식_패턴_작성하기">정규식 패턴 작성하기</h2> + +<p>정규식 패턴은 <code>/abc/</code> 같이 단순 문자로 구성될 수도 있고, <code>/ab*c/</code> 또는 <code>/Chapter (\d+)\.\d*/</code>와 같이 단순 문자와 특수 문자의 조합으로 구성될 수도 있습니다. 마지막 예제는 기억장치처럼 쓰이는 괄호를 포함하고 있습니다. {{web.link("#.ED.8C.A8.ED.84.B4.ED.99.94.EB.90.9C_.EB.B6.80.EB.B6.84_.EB.AC.B8.EC.9E.90.EC.97.B4_.EC.9D.BC.EC.B9.98_.EC.82.AC.EC.9A.A9.ED.95.98.EA.B8.B0", "패턴화된 부분 문자열 일치 사용하기") }}에서 설명하는것 처럼 패턴에서 괄호를 포함한 부분은 나중에 사용하기 위하여 저장됩니다.</p> + +<h3 id="단순_패턴_사용하기">단순 패턴 사용하기</h3> + +<p>단순 패턴은 문자열을 있는 그대로 대응시키고자 할 때 사용됩니다. 예를 들어, <code>/abc/</code>라는 패턴은 문자열에서 정확히 'abc' 라는 문자들이 모두 함께 순서대로 나타나야 대응됩니다. 위의 패턴은 "Hi, do you know your abc's?" 와 "The latest airplane designs evolved from slabcraft." 두가지 예에서 부분 문자열 'abc'에 대응될 것입니다. 'Grab crab' 이라는 문자열에서 'ab c' 라는 부분 문자열을 포함하고 있지만, 'abc'를 정확하게 포함하고 있지 않기 때문에 대응되지 않습니다.</p> + +<h3 id="특수_문자_사용하기">특수 문자 사용하기</h3> + +<p>검색에서 하나 이상의 b들을 찾거나, 혹은 공백을 찾는 것과 같이 '있는 그대로의 대응' 이상의 대응을 필요로 할 경우, 패턴에 특수한 문자를 포함시킵니다. 예를 들어, <code>/ab*c/</code> 패턴은 'a' 문자 뒤에 0개 이상의 'b' 문자(<code>*</code> 문자는 바로 앞의 문자가 0개 이상이라는 것을 의미합니다)가 나타나고 바로 뒤에 'c' 문자가 나타나는 문자 조합에 대응됩니다. 문자열 "cbbabbbbcdebc," 에서 위의 패턴은 부분 문자열 'abbbbc' 와 대응됩니다.</p> + +<p>아래 표는 정규식에서 사용되는 모든 특수문자 목록 및 그에 대한 설명입니다.</p> + +<table class="standard-table"> + <caption>정규식에서의 특수문자</caption> + <thead> + <tr> + <th scope="col">Character</th> + <th scope="col">Meaning</th> + </tr> + </thead> + <tbody> + <tr> + <td><a href="#special-backslash" id="special-backslash" name="special-backslash"><code>\</code></a></td> + <td> + <p>다음의 규칙에 따라 일치합니다:<br> + <br> + 특수 문자가 아닌 문자(non-special character) 앞에서 사용된 백슬래시는 '해당 문자는 특별하고, 문자 그대로 해석되면 안된다'는 사실을 가리킵니다. 예를 들어, 앞에 \가 없는 '<code>b</code>'는 보통 소문자 b가 나오는 패턴과 대응됩니다. 그러나 '<code>\b</code>' 자체는 어떤 문자와도 대응되지 않습니다; 이 문자는 특별한 <a href="#special-word-boundary" title="#special-word-boundary">단어 경계 문자</a>를 형성합니다.<br> + <br> + 특수 문자 앞에 위치한 백슬래시는 '다음에 나오는 문자는 특별하지않고, 문자 그대로 해석되어야 한다'는 사실을 가리킵니다. 예를 들어, 패턴 <code>/a*/</code> 에서의 특수문자 '<code>*</code>'는 0개 이상의 'a' 문자가 등장함을 나타냅니다. 이와는 다르게, 패턴 <code>/a\*/</code> 는 '<code>*</code>'이 특별하지 않다는 것을 나타내며, 'a*'와 같은 문자열과 대응될 수 있습니다.<br> + <br> + RegExp("pattern") 표기를 쓰면서 \ 자체를 이스케이프 하는 것을 잊지 마세요. 왜냐하면 \ 는 문자열에서도 이스케이프 문자이기 때문입니다. (역주: <code>/a\*/</code> 와 같은 패턴을 생성자로 만들려면 <code>new RegExp('a\\*')</code>와 같이 백슬래시 자체를 이스케이프 시켜주어야 합니다.)</p> + </td> + </tr> + <tr> + <td><a href="#special-caret" id="special-caret" name="special-caret"><code>^</code></a></td> + <td>입력의 시작 부분에 대응됩니다. 만약 다중행 플래그가 참으로 설정되어 있다면, 줄 바꿈 문자 바로 다음 부분과도 대응됩니다.<br> + <br> + 예를 들어, <code>/^A/</code> 는 "an A" 의 'A'와는 대응되지 않습니다, 그러나 "An E" 의 'A'와는 대응됩니다.<br> + <br> + '<code>^</code>' 가 문자셋([abc]) 패턴의 첫 글자로 쓰인다면, 그 때는 전혀 다른 의미를 가집니다. 자세한 내용은 <a href="#special-negated-character-set" title="#special-negated-character-set">역 문자셋</a>을 참고하세요.</td> + </tr> + <tr> + <td><a href="#special-dollar" id="special-dollar" name="special-dollar"><code>$</code></a></td> + <td> + <p>입력의 끝 부분과 대응됩니다. 만약 다중행 플래그가 참으로 설정되어 있다면, 줄 바꿈 문자의 바로 앞 부분과도 대응됩니다.</p> + + <p>예를 들어, <code>/t$/</code> 는 "eater" 의 't'에는 대응되지 않습니다, 그러나 "eat" 과는 대응됩니다.</p> + </td> + </tr> + <tr> + <td><a href="#special-asterisk" id="special-asterisk" name="special-asterisk"><code>*</code></a></td> + <td> + <p>앞의 표현식이 0회 이상 연속으로 반복되는 부분과 대응됩니다. {0,} 와 같은 의미입니다.</p> + + <p>예를 들어, <code>/bo*/</code> 는 "A ghost booooed" 의 'boooo' 와 대응되고, "A bird warbled" 의 'b'에 대응되지만 "A goat grunted" 내의 어느 부분과도 대응되지 않습니다.</p> + </td> + </tr> + <tr> + <td><a href="#special-plus" id="special-plus" name="special-plus"><code>+</code></a></td> + <td> + <p>앞의 표현식이 1회 이상 연속으로 반복되는 부분과 대응됩니다. <code>{1,}</code> 와 같은 의미입니다.</p> + + <p>예를 들어, <code>/a+/</code> 는 "candy"의 'a'에 대응되고 "caaaaaaandy" 의 모든 'a'들에 대응되지만, "cndy" 내의 어느 부분과도 대응되지 않습니다.</p> + </td> + </tr> + <tr> + <td><a href="#special-questionmark" id="special-questionmark" name="special-questionmark"><code>?</code></a></td> + <td>앞의 표현식이 0 또는 1회 등장하는 부분과 대응됩니다. <code>{0,1}</code> 와 같은 의미입니다.<br> + <br> + 예를 들어, <code>/e?le?/</code> 는 "angel"의 'el' 에 대응되고, "angle"의 'le' 에 대응되고 또한 "oslo" 의 'l'에도 대응됩니다.<br> + <br> + 만약 수량자 *, +, ?, {} 바로 뒤에 사용하면, 기본적으로 탐욕스럽던(가능한 한 많이 대응시킴) 수량자를 탐욕스럽지 않게(가능한 가장 적은 문자들에 대응시킴) 만듭니다. 예를 들어, <code>/\d+/</code>를 "123abc"에 적용시키면 "123"과 대응됩니다. 그러나 <code>/\d+?/</code>를 같은 문자열에 적용시키면 오직 "1"과만 대응됩니다.<br> + <br> + 또한 이 문자는 <code>x(?=y)</code> 와 <code>x(?!y)</code> 항목에서 설명하는 바와 같이 사전 검증(lookahead assertion)을 위해서도 쓰입니다.<br> + </td> + </tr> + <tr> + <td><a href="#special-dot" id="special-dot" name="special-dot"><code>.</code></a></td> + <td> + <p>개행 문자를 제외한 모든 단일 문자와 대응됩니다.</p> + + <p>예를 들어, <code>/.n/</code>는 "nay, an apple is on the tree"에서 'an'과 'on'에 대응되지만, 'nay' 에는 대응되지 않습니다.</p> + </td> + </tr> + <tr> + <td><a href="#special-capturing-parentheses" id="special-capturing-parentheses" name="special-capturing-parentheses"><code>(x)</code></a></td> + <td> + <p>다음의 예제가 보여주는것 처럼 'x'에 대응되고, 그것을 기억합니다. 괄호는 <em>포획 괄호(capturing parentheses)라</em> 불립니다.<br> + <br> + 패턴 <code>/(foo) (bar) \1 \2/</code> 안의 '<code>(foo)</code>' 와 '<code>(bar)</code>'는 문자열"foo bar foo bar"에서 처음의 두 단어에 대응되고 이를 기억합니다. 패턴 내부의 <code>\1</code>와 <code>\2</code>는 문자열의 마지막 두 단어에 대응됩니다. (역주: \n 패턴은 앞의 n번째 포획괄호에 대응된 문자열과 똑같은 문자열에 대응됩니다.) <code>\1, \2, \n</code>과 같은 문법은 정규식의 패턴 부분에서 사용됩니다. 정규식의 치환 부분에서는 <code>$1, $2, $n</code>과 같은 문법이 사용되어야 합니다. 예를 들어, <code>'bar foo'.replace( /(...) (...)/, '$2 $1')</code>와 같이 사용되어야 합니다. <code>$&</code> 패턴은 앞에서 대응된 전체 문자열을 가리킵니다.</p> + </td> + </tr> + <tr> + <td><a href="#special-non-capturing-parentheses" id="special-non-capturing-parentheses" name="special-non-capturing-parentheses"><code>(?:x)</code></a></td> + <td>'x'에 대응되지만 대응된 것을 기억하지 않습니다. 괄호는 <em>비포획 괄호(non-capturing parentheses)</em>라고 불리우고, 정규식 연산자가 같이 동작할 수 있게 하위 표현을 정의할 수 있습니다. 정규식 예제 <code>/(?:foo){1,2}/</code>을 생각해보세요. 만약 정규식이 <code>/foo{1,2}/</code>라면, <code>{1,2}</code>는 'foo'의 마지막 'o' 에만 적용됩니다. 비포획 괄호과 같이 쓰인다면, <code>{1,2}</code>는 단어 'foo' 전체에 적용됩니다.</td> + </tr> + <tr> + <td><a href="#special-lookahead" id="special-lookahead" name="special-lookahead"><code>x(?=y)</code></a></td> + <td> + <p>오직 'y'가 뒤따라오는 'x'에만 대응됩니다. 이것은 lookahead 라고 불립니다.</p> + + <p>예를 들어, <code>/Jack(?=Sprat)/</code> 는 'Sprat'가 뒤따라오는 'Jack' 에만 대응됩니다. <code>/Jack(?=Sprat|Frost)/</code>는 'Sprat' 또는 'Frost'가 뒤따라오는 'Jack'에만 대응됩니다. 그러나, 'Sprat' 및 'Frost' 는 대응 결과의 일부가 아닙니다.</p> + </td> + </tr> + <tr> + <td><a href="#special-negated-look-ahead" id="special-negated-look-ahead" name="special-negated-look-ahead"><code>x(?!y)</code></a></td> + <td> + <p>'x'뒤에 'y'가 없는경우에만 'x'에 일치합니다. 이것은 negated lookahead 라고 불립니다.</p> + + <p>예를 들어, <code>/\d+(?!\.)/</code>는 소숫점이 뒤따라오지 않는 숫자에 일치합니다. 정규식 <code>/\d+(?!\.)/.exec("3.141")</code>는 '3.141' 이 아닌 '141'에 일치합니다.</p> + </td> + </tr> + <tr> + <td><a href="#special-or" id="special-or" name="special-or"><code>x|y</code></a></td> + <td> + <p>'x' 또는 'y'에 대응됩니다.</p> + + <p>예를 들어, <code>/green|red/</code>는 "green apple"의 'green'에 대응되고, "red apple."의 'red'에 대응됩니다.</p> + </td> + </tr> + <tr> + <td><a href="#special-quantifier" id="special-quantifier" name="special-quantifier"><code>{n}</code></a></td> + <td>앞 표현식이 n번 나타나는 부분에 대응됩니다. n은 반드시 양의 정수여야 합니다.<br> + <br> + 예를 들어, <code>/a{2}/</code>는 "candy,"의 'a'에는 대응되지 않지만, "caandy,"의 모든 a 와, "caaandy."의 첫 두 a 에는 대응됩니다.</td> + </tr> + <tr> + <td><a href="#special-quantifier-range" id="special-quantifier-range" name="special-quantifier-range"><code>{n,m}</code></a></td> + <td> + <p><code>n</code>과 <code>m</code>은 양의 정수이고, <code>n <= m</code>를 만족해야 합니다. 앞 문자가 최소 <code>n</code>개, 최대 <code>m</code>개가 나타나는 부분에 대응됩니다. <code>m</code>이 생략된다면, m은 ∞로 취급됩니다.</p> + + <p>예를 들어, <code>/a{1,3}/</code>는 "cndy"에서 아무것에도 대응되지 않지만, "caandy,"의 첫 두 a 와 "caaaaaaandy"의 첫 세 a 에 대응됩니다. "caaaaaaandy"에서 더 많은 a 들이 있지만, "aaa"에만 대응된다는 점에 주목하세요.</p> + </td> + </tr> + <tr> + <td><a href="#special-character-set" id="special-character-set" name="special-character-set"><code>[xyz]</code></a></td> + <td>문자셋(Character set) 입니다. 이 패턴 타입은 괄호 안의 어떤 문자(<a href="https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Values,_variables,_and_literals#Unicode_escape_sequences" title="https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Values,_variables,_and_literals#Unicode_escape_sequences">이스케이프 시퀀스</a>까지 포함)와도 대응됩니다. 점(<code>.</code>) 이나 별표 (<code>*</code>) 같은 특수 문자는 문자셋 내부에서는 특수 문자가 아닙니다. 따라서 이스케이프시킬 필요가 없습니다. 하이픈을 이용하여 문자의 범위를 지정해줄 수 있습니다.<br> + <br> + 예를 들어, 패턴 <code> [a-d]</code> 는 패턴 <code>[abcd]</code> 와 똑같이 동작하며, "brisket"의 'b' 에 일치하고, "city"의 'c' 에 일치합니다. 패턴 <code>/[a-z.]+/ </code> 와 <code>/[\w.]+/</code> 는 "test.i.ng" 전체 문자열이 일치합니다.</td> + </tr> + <tr> + <td><a href="#special-negated-character-set" id="special-negated-character-set" name="special-negated-character-set"><code>[^xyz]</code></a></td> + <td> + <p>부정 문자셋(negated character set) 또는 보충 문자셋(complemented character set)입니다. 괄호 내부에 등장하지 않는 어떤 문자와도 대응됩니다. 하이픈을 이용하여 문자의 범위를 지정할 수 있습니다. 일반적인 문자셋에서 작동하는 모든 것은 여기에서도 작동합니다.</p> + + <p>예를 들어, 패턴<code>[^abc]</code>는 패턴<code>[^a-c]</code>와 동일합니다. 두 패턴은 "brisket"의 'r', "chop."의 'h' 에 대응됩니다.</p> + </td> + </tr> + <tr> + <td><a href="#special-backspace" id="special-backspace" name="special-backspace"><code>[\b]</code></a></td> + <td>백스페이스(U+0008)에 대응됩니다. 이와 같이, 백스페이스 문자 리터럴에 대응시키려면, 대괄호("[]")를 이용해야만 합니다. (<code>\b</code>와 혼동하지 마세요.)</td> + </tr> + <tr> + <td><a href="#special-word-boundary" id="special-word-boundary" name="special-word-boundary"><code>\b</code></a></td> + <td> + <p>단어 경계에 대응됩니다. 단어 경계는 다른 '단어 문자'가 앞이나 뒤에 등장하지 않는 위치에 대응됩니다. 단어의 경계는 대응 결과에 포함되지 않는다는 사실에 주의하세요. 다른 말로는, 단어의 경계에 대응되는 문자열의 길이는 항상 0입니다. (패턴 <code>[\b]</code>와 혼동하지 마세요.)</p> + + <p>예제:<br> + <code>/\bm/</code>는 "moon"의 'm'에 대응됩니다;<br> + <code>/oo\b/</code> 는 "moon"의 'oo' 부분에 대응되지 않는데, 왜냐하면 'oo'를 뒤따라오는 'n'이 단어 문자이기 때문입니다;<br> + <code>/oon\b/</code>는 "moon"의 'oon'에 대응됩니다. 왜냐하면, 'oon'은 문자열의 끝이라서, 뒤따라오는 단어 문자가 없기 때문입니다 ;<br> + <code>/\w\b\w/</code>는 어떤 것에도 일치하지 않습니다. 왜냐하면, 단어 문자는 절대로 비 단어 문자와 단어 문자 두개가 뒤따라올수 없기 때문입니다.</p> + + <div class="note"> + <p><strong>숙지하세요:</strong> 자바스크립트의 정규식 엔진은 <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-15.10.2.6">특정 문자 집합</a>을 '단어 문자'로 정의합니다. 이 집단에 속하지 않는 모든 문자는 단어 분리(word break) 로 여겨집니다. 단어 문자로 간주되는 문자들은 얼마 없습니다: 오로지 로마자 소문자와 대문자, 10진수 숫자, 밑줄 문자로 구성되어 있습니다. "é" 또는 "ü" 같이, 강세 표시 문자들은 안타깝게도 단어 분리(word breaks) 로 취급됩니다.</p> + </div> + </td> + </tr> + <tr> + <td><a href="#special-non-word-boundary" id="special-non-word-boundary" name="special-non-word-boundary"><code>\B</code></a></td> + <td> + <p>단어 경계가 아닌 부분에 대응됩니다. 아래와 같은 경우들이 있습니다:</p> + + <ul> + <li>문자열의 첫 번째 문자가 단어 문자가 아닌 경우, 해당 문자의 앞 부분에 대응됩니다.</li> + <li>문자열의 마지막 문자가 단어 문자가 아닌 경우, 해당 문자의 뒷 부분에 대응됩니다.</li> + <li>두 단어 문자의 사이에 대응됩니다.</li> + <li>단어 문자가 아닌 두 문자 사이에 대응됩니다.</li> + <li>빈 문자열에 대응됩니다.</li> + </ul> + + <p>문자열의 시작 부분과 끝 부분은 단어가 아닌 것으로 간주됩니다.</p> + + <p>예를 들어, <code>/\B../</code> 는 "noonday"의 'oo'와 대응되며, <code>/y\B./</code> 는 "possibly yesterday."의 'ye'와 대응됩니다.</p> + </td> + </tr> + <tr> + <td><a href="#special-control" id="special-control" name="special-control"><code>\c<em>X</em></code></a></td> + <td> + <p>문자열 내부의 제어 문자에 대응됩니다. 여기서 <em>X</em>는 A에서 Z까지의 문자 중 하나입니다.</p> + + <p>예를 들어, <code>/\cM/</code>는 문자열에서 control-M (U+000D)에 대응됩니다.</p> + </td> + </tr> + <tr> + <td><a href="#special-digit" id="special-digit" name="special-digit"><code>\d</code></a></td> + <td> + <p>숫자 문자에 대응됩니다. <code>[0-9]</code>와 동일합니다.</p> + + <p>예를 들어, <code>/\d/</code> 또는 <code>/[0-9]/</code>는 "B2 is the suite number."에서 '2'에 대응됩니다.</p> + </td> + </tr> + <tr> + <td><a href="#special-non-digit" id="special-non-digit" name="special-non-digit"><code>\D</code></a></td> + <td> + <p>숫자 문자가 아닌 문자에 대응됩니다. <code>[^0-9]</code>와 동일합니다.</p> + + <p>예를 들어, <code>/\D/</code> 또는 <code>/[^0-9]/</code>는 "B2 is the suite number."의 'B'에 대응됩니다.</p> + </td> + </tr> + <tr> + <td><a href="#special-form-feed" id="special-form-feed" name="special-form-feed"><code>\f</code></a></td> + <td>폼피드 (U+000C) 문자에 대응됩니다.</td> + </tr> + <tr> + <td><a href="#special-line-feed" id="special-line-feed" name="special-line-feed"><code>\n</code></a></td> + <td>줄 바꿈 (U+000A) 문자에 대응됩니다.</td> + </tr> + <tr> + <td><a href="#special-carriage-return" id="special-carriage-return" name="special-carriage-return"><code>\r</code></a></td> + <td>캐리지 리턴(U+000D) 문자에 대응됩니다.</td> + </tr> + <tr> + <td><a href="#special-white-space" id="special-white-space" name="special-white-space"><code>\s</code></a></td> + <td> + <p>스페이스, 탭, 폼피드, 줄 바꿈 문자등을 포함한 하나의 공백 문자에 대응됩니다. <code>[ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]</code>.와 동일합니다.</p> + + <p>예를 들어, <code>/\s\w*/</code>는 "foo bar."의 ' bar'에 대응됩니다.</p> + </td> + </tr> + <tr> + <td><a href="#special-non-white-space" id="special-non-white-space" name="special-non-white-space"><code>\S</code></a></td> + <td> + <p>공백 문자가 아닌 하나의 문자에 대응됩니다. <code>[^ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]</code>. 와 동일합니다.</p> + + <p>예를 들어, <code>/\S\w*/</code>는 "foo bar."의 'foo' 에 대응됩니다.</p> + </td> + </tr> + <tr> + <td><a href="#special-tab" id="special-tab" name="special-tab"><code>\t</code></a></td> + <td>탭 (U+0009) 문자에 대응됩니다.</td> + </tr> + <tr> + <td><a href="#special-vertical-tab" id="special-vertical-tab" name="special-vertical-tab"><code>\v</code></a></td> + <td>수직 탭(U+000B) 문자에 대응됩니다.</td> + </tr> + <tr> + <td><a href="#special-word" id="special-word" name="special-word"><code>\w</code></a></td> + <td> + <p>밑줄 문자를 포함한 영숫자 문자에 대응됩니다. <code>[A-Za-z0-9_]</code> 와 동일합니다. (역주: 여기에 대응되는 문자를 단어 문자라고 합니다.)</p> + + <p>예를 들어, <code>/\w/</code>는 "apple,"의 'a' 에 대응되고, "$5.28,"의 '5'에 대응되고,"3D."의 '3'에 대응됩니다.</p> + </td> + </tr> + <tr> + <td><a href="#special-non-word" id="special-non-word" name="special-non-word"><code>\W</code></a></td> + <td> + <p>단어 문자가 아닌 문자에 대응됩니다. <code>[^A-Za-z0-9_]</code> 와 동일합니다.</p> + + <p>예를 들어, <code>/\W/</code> 또는 <code>/[^A-Za-z0-9_]/</code>는 "50%."의 '%' 에 대응됩니다.</p> + </td> + </tr> + <tr> + <td><a href="#special-backreference" id="special-backreference" name="special-backreference"><code>\<em>n</em></code></a></td> + <td> + <p>정규식 내부의 <em>n</em>번째 괄호에서 대응된 부분에 대한 역참조 입니다. 여기서, <em>n은 양의 정수입니다.</em></p> + + <p>예를 들어, <code>/apple(,)\sorange\1/</code>는 "apple, orange, cherry, peach."의 'apple, orange,' 에 일치합니다.</p> + </td> + </tr> + <tr> + <td><a href="#special-null" id="special-null" name="special-null"><code>\0</code></a></td> + <td>널 (U+0000)문자에 대응합니다. 이 때 다른 숫자를 뒤에 쓰지 마세요. 왜냐하면 <code>\0<digits></code>는 8진 <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Values,_variables,_and_literals#Unicode_escape_sequences" title="https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Values,_variables,_and_literals#Unicode_escape_sequences">이스케이프 시퀀스</a>이기 때문입니다.</td> + </tr> + <tr> + <td><a href="#special-hex-escape" id="special-hex-escape" name="special-hex-escape"><code>\xhh</code></a></td> + <td>코드가 hh(두 16진 숫자)인 문자에 일치합니다.</td> + </tr> + <tr> + <td><a href="#special-unicode-escape" id="special-unicode-escape" name="special-unicode-escape"><code>\uhhhh</code></a></td> + <td>코드가 hhhh(네개의 16진 숫자)인 문자에 일치합니다.</td> + </tr> + </tbody> +</table> + +<p>사용자 입력을 이스케이프해서 정규식 내부에서 문자 그대로 취급해야 하는 경우, 간단히 치환을 하면 됩니다:</p> + +<pre class="brush: js">function escapeRegExp(string){ + return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $&는 일치한 전체 문자열을 의미합니다. +}</pre> + +<h3 id="괄호를_사용하기">괄호를 사용하기</h3> + +<p>정규식 내부의 일부를 둘러싼 괄호는, 해당 부분에서 대응된 문자열을 기억하는 효과를 갖습니다. 기억된 문자열은 이후 {{ web.link("#.ED.8C.A8.ED.84.B4.ED.99.94.EB.90.9C_.EB.B6.80.EB.B6.84_.EB.AC.B8.EC.9E.90.EC.97.B4_.EC.9D.BC.EC.B9.98_.EC.82.AC.EC.9A.A9.ED.95.98.EA.B8.B0", "패턴화된 부분 문자열 일치 사용하기") }}에서 설명한 것처럼 다른 곳에서 사용하기 위하여 불러와질 수 있습니다.</p> + +<p>예를 들면, 패턴 <code>/Chapter (\d+)\.\d*/</code>는 패턴의 일부분이 기억될 거라는 사실을 나타냅니다. 이 패턴은 하나 이상의 숫자(<code>\d</code>는 숫자를 의미하고 <code>+</code>는 1개 이상을 의미합니다.) 이후에 하나의 소숫점(\가 앞에 붙은 소숫점은 문자 그대로의 문자 '.' 에 대응됨을 나타냅니다), 그뒤 0개 이상의 숫자(<code>\d</code> 는 숫자, <code>*</code> 는 0개 이상을 의미합니다.)가 뒤따라오는 'Chapter ' 문자열에 대응됩니다. 더해서, 괄호는 처음으로 일치하는 숫자 문자들을 기억하기 위하여 사용되었습니다.</p> + +<p>이 패턴은 "Open Chapter 4.3, paragraph 6"에 나타나며, '4'가 기억됩니다. 이 패턴은 "Chapter 3 and 4"에는 나타나지 않습니다. 왜냐하면 문자열이 '3'이후에 마침표를 가지고 있지 않기 때문입니다.</p> + +<p>부분 문자열을 대응시키면서도 해당 부분을 기억하지 않으려면, 괄호의 첫머리에 <code>?:</code>패턴을 사용하세요. 예를 들어, <code>(?:\d+)</code>는 1개 이상의 숫자에 대응되지만 해당 문자들을 기억하지 않습니다.</p> + +<h2 id="정규식_사용하기">정규식 사용하기</h2> + +<p>정규식은 <code>RegExp,</code> <code>test,</code> <code>exec,</code> <code>String,</code> <code>match</code>, <code>replace</code>, <code>search</code>, <code>split</code> 메소드와 함께 쓰입니다. 이 메소드는 <a href="/en-US/docs/Web/JavaScript/Reference" title="en-US/docs/JavaScript/Reference">JavaScript reference</a>에서 잘 설명되어 있습니다.</p> + +<table class="standard-table"> + <caption>정규식에서 쓰이는 메소드</caption> + <thead> + <tr> + <th scope="col">Method</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{jsxref("RegExp.exec", "exec")}}</td> + <td>대응되는 문자열을 찾는 <code style="font-style: normal;">RegExp</code><span style="background-color: rgba(212, 221, 228, 0.14902);"> 메소드입니다</span>. 정보를 가지고 있는 배열을 반환합니다. 대응되는 문자열을 찾지 못했다면 null을 반환합니다.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.test", "test")}}</td> + <td>대응되는 문자열이 있는지 검사하는 <code style="font-style: normal;">RegExp</code><strong style="background-color: rgba(212, 221, 228, 0.14902); font-family: courier new,andale mono,monospace; font-weight: bold;"> </strong>메소드 입니다. true 나 false를 반환합니다.</td> + </tr> + <tr> + <td>{{jsxref("String.match", "match")}}</td> + <td>대응되는 문자열을 찾는 <code style="font-style: normal;">RegExp</code><span style="background-color: rgba(212, 221, 228, 0.14902);"> 메소드입니다</span>. 정보를 가지고 있는 배열을 반환합니다. 대응되는 문자열을 찾지 못했다면 null을 반환합니다.</td> + </tr> + <tr> + <td>{{jsxref("String.search", "search")}}</td> + <td> + <p class="syntaxbox">대응되는 문자열이 있는지 검사하는 <code style="font-style: normal;">String</code><strong style="background-color: rgba(212, 221, 228, 0.14902); font-family: courier new,andale mono,monospace; font-weight: bold;"> </strong>메소드 입니다. 대응된 부분의 인덱스를 반환합니다. 대응되는 문자열을 찾지 못했다면 -1을 반환합니다.</p> + </td> + </tr> + <tr> + <td>{{jsxref("String.replace", "replace")}}</td> + <td>대응되는 문자열을 찾아 다른 문자열로 치환하는 <code>String</code> 메소드입니다.</td> + </tr> + <tr> + <td>{{jsxref("String.split", "split")}}</td> + <td>정규식 혹은 문자열로 대상 문자열을 나누어 배열로 반환하는 <code>String</code> 메소드입니다.</td> + </tr> + </tbody> +</table> + +<p>문자열 내부에 패턴과 대응되는 부분이 있는지 알고 싶다면, <code>test</code> 나 <code>search</code> 메소드를 사용하세요; 좀 더 많은 정보를 원하면 (대신 실행이 느림) <code>exec</code> 나 <code>match</code> 메소드를 사용하세요. 만약 <code>exec</code> 나 <code>match</code> 메소드를 사용했는데 대응되는 부분이 있다면, 이 메소드는 배열을 반환하고 정규식 객체의 속성을 업데이트 합니다. 만약 대응되는 부분이 없다면, <code>exec</code> 메소드는 <code>null</code> 을 반환합니다. (즉, <code>false</code>와 같은 의미로 사용될 수 있습니다.).</p> + +<p>아래의 예에서는, 문자열 내부에서 대응되는 부분을 찾기 위해 <code>exec</code> 메소드를 사용했습니다.</p> + +<pre class="brush: js">var myRe = /d(b+)d/g; +var myArray = myRe.exec("cdbbdbsbz"); +</pre> + +<p>만약 정규식 속성에 접근할 필요가 없다면, 아래와 같이 <code>myArray</code>를 만드는 다른 방법도 있습니다:</p> + +<pre class="brush: js">var myArray = /d(b+)d/g.exec("cdbbdbsbz"); +</pre> + +<p>문자열로부터 정규식을 만들고 싶다면, 이런 방법도 있습니다:</p> + +<pre class="brush: js">var myRe = new RegExp("d(b+)d", "g"); +var myArray = myRe.exec("cdbbdbsbz"); +</pre> + +<p>위의 스크립트에서는, 대응되는 부분이 발견되었고 아래의 표에서 설명하는 대로 배열을 반환하며 속성을 갱신합니다.</p> + +<table class="standard-table" style="height: 299px; width: 1168px;"> + <caption>정규식 실행결과</caption> + <thead> + <tr> + <th scope="col">Object</th> + <th scope="col">Property or index</th> + <th scope="col">Description</th> + <th scope="col">In this example</th> + </tr> + </thead> + <tbody> + <tr> + <td rowspan="4"><code>myArray</code></td> + <td></td> + <td>대응된 문자열 및 기억한 모든 부분 문자열</td> + <td><code>['dbbd', 'bb', index: 1, input: 'cdbbdbsbz']</code></td> + </tr> + <tr> + <td><code>index</code></td> + <td>입력된 문자열에서 대응된 부분에 해당하는 인덱스 (0부터 시작)</td> + <td><code>1</code></td> + </tr> + <tr> + <td><code>input</code></td> + <td>입력된 원본 문자열</td> + <td><code>"cdbbdbsbz"</code></td> + </tr> + <tr> + <td><code>[0]</code></td> + <td>마지막으로 대응된 문자열</td> + <td><code>"dbbd"</code></td> + </tr> + <tr> + <td rowspan="2"><code>myRe</code></td> + <td><code>lastIndex</code></td> + <td>다음 검색 시 검색을 시작할 인덱스 (이 속성은 g 옵션을 설정한 정규식에 대해서만 설정됩니다. 자세한 사항은 {{ web.link("#Advanced_searching_with_flags", "Advanced Searching With Flags") }} 부분을 참고하세요.)</td> + <td><code>5</code></td> + </tr> + <tr> + <td><code>source</code></td> + <td>패턴 문자열. 정규식이 생성될 때 갱신됩니다. 실행 시점에는 갱신되지 않습니다.</td> + <td><code>"d(b+)d"</code></td> + </tr> + </tbody> +</table> + +<p>위 예제에서의 두 번째 형태처럼, 정규식 객체를 변수에 대입하지 않고도 사용할 수 있습니다. 하지만, 이렇게 하면 정규식 객체가 매번 새로 생성됩니다. 이러한 이유로, 만약 변수에 대입하지 않는 형태를 사용하는 경우 나중에 그 정규식의 속성에 접근할 수 없게 됩니다. 예를 들어, 이러한 스크립트가 있을 수 있습니다:</p> + +<pre class="brush: js">var myRe = /d(b+)d/g; +var myArray = myRe.exec("cdbbdbsbz"); +console.log("The value of lastIndex is " + myRe.lastIndex); + +// "The value of lastIndex is 5" +</pre> + +<p>그러나, 만약 이러한 스크립트가 있으면:</p> + +<pre class="brush: js">var myArray = /d(b+)d/g.exec("cdbbdbsbz"); +console.log("The value of lastIndex is " + /d(b+)d/g.lastIndex); + +// "The value of lastIndex is 0" +</pre> + +<p>두 구문에서의 <code>/d(b+)d/g</code> 는 서로 다른 정규식 객체이고, 따라서 별개의 <code>lastIndex</code> 속성을 갖게 됩니다. 정규식 객체의 속성을 사용해야 하는 경우라면, 먼저 변수에 대입하세요.</p> + +<h3 id="괄호로_둘러싼_패턴_사용하기">괄호로 둘러싼 패턴 사용하기</h3> + +<p>정규식 패턴에 괄호를 사용하면, 그 부분을 별도로 대응시키면서 대응된 부분을 기억합니다. 예를 들면, <code>/a(b)c/</code> 는 'abc' 와 대응되면서 'b'를 기억합니다. 괄호로 감싸진 문자열을 불러오려면, 배열 요소 <code>[1]</code>, ..., <code>[n]</code> 를 사용하세요.</p> + +<p>괄호로 감쌀 수 있는 문자의 개수에는 제한이 없습니다. 반환된 배열은 찾아낸 모든 것들을 갖고 있습니다. 다음의 예는 괄호로 둘러싸진 부분이 어떻게 대응되는지 보여줍니다.</p> + +<p>다음의 예는 문자열 내부의 단어를 바꾸기 위해 {{jsxref("String.replace", "replace()")}} 메소드를 이용하고 있습니다. 치환 문자열로는 <code>$1</code> 과 <code>$2</code> 를 사용하고 있는데, 이는 각각 첫 번째와 두 번째 괄호가 쳐진 부분에 대응된 문자열을 가리킵니다.</p> + +<pre class="brush: js">var re = /(\w+)\s(\w+)/; +var str = "John Smith"; +var newstr = str.replace(re, "$2, $1"); +console.log(newstr); + +// "Smith, John" +</pre> + +<h3 id="플래그를_사용한_고급검색">플래그를 사용한 고급검색</h3> + +<p>정규식은 여섯 개의 플래그를 설정해줄 수 있으며, 이를 통해 전역 검색 또는 대소문자 구분 없는 검색을 수행할 수 있습니다. 이 플래그들은 각기 사용될 수도 있고 함께 사용될 수도 있고 순서에 구분이 없습니다.</p> + +<table class="standard-table"> + <caption>Regular expression flags</caption> + <thead> + <tr> + <th scope="col">Flag</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>g</code></td> + <td>전역 검색</td> + </tr> + <tr> + <td>i</td> + <td>대소문자 구분 없는 검색</td> + </tr> + <tr> + <td>m</td> + <td>다중행(multi-line) 검색</td> + </tr> + <tr> + <td>s</td> + <td><code>.</code>에 개행 문자도 매칭(ES2018)</td> + </tr> + <tr> + <td>u</td> + <td>유니코드; 패턴을 유니코드 코드 포인트의 나열로 취급합니다.</td> + </tr> + <tr> + <td>y</td> + <td>"sticky" 검색을 수행. 문자열의 현재 위치부터 검색을 수행합니다. {{jsxref("RegExp.sticky", "sticky")}} 문서를 확인하세요.</td> + </tr> + </tbody> +</table> + +<p>정규식에 플래그를 포함시키려면, 아래 문법을 사용하세요:</p> + +<pre class="brush: js">var re = /pattern/flags; +</pre> + +<p>혹은 아래와 같이 할 수도 있습니다:</p> + +<pre class="brush: js">var re = new RegExp("pattern", "flags"); +</pre> + +<p>이 플래그는 정규식에 합쳐지는 정보임을 기억하는게 좋습니다. 이것들은 나중에 추가되거나 제거될 수 없습니다.</p> + +<p>예를 들어, <code>re = /\w+\s/g</code> 는 한 개 이상의 문자열 뒤에 공백이 하나 있는 패턴을 찾는 정규식을 생성합니다. 그리고 문자열 전체에 걸쳐 이 조합을 검색합니다.</p> + +<pre class="brush: js">var re = /\w+\s/g; +var str = "fee fi fo fum"; +var myArray = str.match(re); +console.log(myArray); + +// ["fee ", "fi ", "fo "] +</pre> + +<p>아래 코드는:</p> + +<pre class="brush: js">var re = /\w+\s/g; +</pre> + +<p>이렇게 바꿔쓸 수 있습니다:</p> + +<pre class="brush: js">var re = new RegExp("\\w+\\s", "g"); +</pre> + +<p>그리고 똑같은 결과를 얻습니다.</p> + +<p> <code>.exec()</code> 메소드를 사용할 때에는 '<strong><code>g</code></strong>' 플래그에 대한 동작이 다릅니다. ("클래스"와 "인수"의 역할이 뒤바뀝니다: <code>.match()</code>를 사용할 때는, string 클래스가 메소드를 갖고 정규식은 인수였던 것에 반해, <code>.exec()</code>를 사용할 때는 정규식이 메소드를 갖고 문자열이 인수가 됩니다. <em><code>str.match(re)</code></em> 과 <em><code>re.exec(str)</code></em>를 비교해보세요.) '<code><strong>g</strong></code>' 플래그와 <strong><code>.exec()</code></strong> 메소드가 함께 사용되면 진행상황에 대한 정보가 반환됩니다.</p> + +<pre><code>var xArray; while(xArray = re.exec(str)) console.log(xArray); +// 다음과 같이 출력됩니다: +// ["fee ", index: 0, input: "fee fi fo fum"] +// ["fi ", index: 4, input: "fee fi fo fum"] +// ["fo ", index: 7, input: "fee fi fo fum"]</code></pre> + +<p><code>m</code> 플래그는 여러 줄의 입력 문자열이 실제로 여러 줄로서 다뤄져야 하는 경우에 쓰입니다. 만약 <code>m</code> 플래그가 사용되면, <code>^</code> 와 <code>$</code> 문자는 전체 문자열의 시작과 끝에 대응되는 것이 아니라 각 라인의 시작과 끝에 대응됩니다.</p> + +<h2 id="예시">예시</h2> + +<p>다음의 예는 정규 표현식의 몇 가지 사용법을 보여줍니다.</p> + +<h3 id="입력_문자열에서_순서를_변경하기">입력 문자열에서 순서를 변경하기</h3> + +<p>다음 예는 정규식의 , <code>string.split()과</code> <code>string.replace()</code>의 사용을 설명합니다. 그것은 공백, 탭과 정확히 하나의 세미콜론의 구분으로 이름(이름을 먼저)이 포함된 대략 형식의 입력 문자열을 정리합니다. 마지막으로, 순서(성을 먼저)를 뒤바꾸고 목록을 정렬합니다.</p> + +<pre class="brush: js">// The name string contains multiple spaces and tabs, +// and may have multiple spaces between first and last names. +var names = "Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ; Chris Hand "; + +var output = ["---------- Original String\n", names + "\n"]; + +// Prepare two regular expression patterns and array storage. +// Split the string into array elements. + +// pattern: possible white space then semicolon then possible white space +var pattern = /\s*;\s*/; + +// Break the string into pieces separated by the pattern above and +// store the pieces in an array called nameList +var nameList = names.split(pattern); + +// new pattern: one or more characters then spaces then characters. +// Use parentheses to "memorize" portions of the pattern. +// The memorized portions are referred to later. +pattern = /(\w+)\s+(\w+)/; + +// New array for holding names being processed. +var bySurnameList = []; + +// Display the name array and populate the new array +// with comma-separated names, last first. +// +// The replace method removes anything matching the pattern +// and replaces it with the memorized string—second memorized portion +// followed by comma space followed by first memorized portion. +// +// The variables $1 and $2 refer to the portions +// memorized while matching the pattern. + +output.push("---------- After Split by Regular Expression"); + +var i, len; +for (i = 0, len = nameList.length; i < len; i++){ + output.push(nameList[i]); + bySurnameList[i] = nameList[i].replace(pattern, "$2, $1"); +} + +// Display the new array. +output.push("---------- Names Reversed"); +for (i = 0, len = bySurnameList.length; i < len; i++){ + output.push(bySurnameList[i]); +} + +// Sort by last name, then display the sorted array. +bySurnameList.sort(); +output.push("---------- Sorted"); +for (i = 0, len = bySurnameList.length; i < len; i++){ + output.push(bySurnameList[i]); +} + +output.push("---------- End"); + +console.log(output.join("\n")); +</pre> + +<h3 id="입력을_확인하기_위해_특수_문자를_사용하기">입력을 확인하기 위해 특수 문자를 사용하기</h3> + +<p>다음 예에서, 사용자는 전화번호를 입력 할 것으로 예상됩니다. 사용자가 "Check" 버튼을 누를 때, 스크립트는 번호의 유효성을 검사합니다. 번호가 유효한 경우(정규식에 의해 지정된 문자 시퀀스와 일치합니다), 스크립트는 사용자에게 감사하는 메시지와 번호를 확인하는 메시지를 나타냅니다. 번호가 유효하지 않은 경우, 스크립트는 전화번호가 유효하지 않다는 것을 사용자에게 알립니다.</p> + +<p>비 캡처링 괄호 <code>(?:</code> , 정규식은 세 자리 숫자를 찾습니다 <code>\d{3}</code> OR <code>|</code> 왼쪽 괄호<code>\(</code> 세 자리 숫자 다음에 <code>\d{3}</code>, 닫는 괄호 다음에 <code>\)</code>, (비 캡처링 괄호를 종료<code>)</code>) 안에, 하나의 대시, 슬래시, 또는 소수점을 다음과 같이 발견했을 때, 세 자리 숫자 다음에 <code>d{3}</code>, 대시의 기억 매치, 슬래시, 또는 소수점 다음에 <code>\1</code>, 네 자리 숫자 다음에 <code>\d{4}</code> 문자를 기억합니다<strong><font face="Courier New">([-\/\.])</font></strong>.</p> + +<p>사용자가 <Enter> 키를 누를 때 활성화 <code>변경</code> 이벤트는 <code>RegExp.input</code>의 값을 설정합니다.</p> + +<pre class="brush: html"><!DOCTYPE html> +<html> + <head> + <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> + <meta http-equiv="Content-Script-Type" content="text/javascript"> + <script type="text/javascript"> + var re = /(?:\d{3}|\(\d{3}\))([-\/\.])\d{3}\1\d{4}/; + function testInfo(phoneInput){ + var OK = re.exec(phoneInput.value); + if (!OK) + window.alert(OK.input + " isn't a phone number with area code!"); + else + window.alert("Thanks, your phone number is " + OK[0]); + } + </script> + </head> + <body> + <p>Enter your phone number (with area code) and then click "Check". + <br>The expected format is like ###-###-####.</p> + <form action="#"> + <input id="phone"><button onclick="testInfo(document.getElementById('phone'));">Check</button> + </form> + </body> +</html> +</pre> + +<p>{{PreviousNext("Web/JavaScript/Guide/Text_formatting", "Web/JavaScript/Guide/Indexed_collections")}}</p> diff --git a/files/ko/web/javascript/guide/함수/index.html b/files/ko/web/javascript/guide/함수/index.html new file mode 100644 index 0000000000..cf9d928eb3 --- /dev/null +++ b/files/ko/web/javascript/guide/함수/index.html @@ -0,0 +1,658 @@ +--- +title: 함수 +slug: Web/JavaScript/Guide/함수 +translation_of: Web/JavaScript/Guide/Functions +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Loops_and_iteration", "Web/JavaScript/Guide/Expressions_and_Operators")}}</div> + +<p class="summary">함수는 JavaScript에서 기본적인 구성 블록 중의 하나입니다. 함수는 작업을 수행하거나 값을 계산하는 문장 집합 같은 자바스크립트 절차입니다. 함수를 사용하려면 함수를 호출하고자 하는 범위 내에서 함수를 정의해야만 합니다.</p> + +<p>세부 사항에 대해서는 <a href="/ko/docs/Web/JavaScript/Reference/Functions">exhaustive reference chapter about JavaScript functions</a>를 참조하세요.</p> + +<h2 id="함수_정의">함수 정의</h2> + +<h3 id="함수_선언">함수 선언</h3> + +<p>함수 정의(또는 함수 선언)는 다음과 같은 <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/function" title="function"><code>함수</code></a> 키워드로 구성되어 있습니다:</p> + +<ul> + <li>함수의 이름</li> + <li>괄호 안에서 쉼표로 분리된 함수의 매개변수 목록 </li> + <li>중괄호 <code>{ }</code> 안에서 함수를 정의하는 자바스크립트 표현</li> +</ul> + +<p>예를 들어, 다음의 코드는 <code>square</code>라는 간단한 함수를 정의하였습니다:</p> + +<pre class="brush: js"><code>function square(number) { + return number * number; +}</code></pre> + +<p>함수 <code>square</code>은 <code>number</code>라는 하나의 매개변수를 가집니다. 이 함수는 인수 (즉, <code>number</code>) 자체를 곱하여 반환하는 하나의 문장으로 구성되어 있습니다. <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/return" title="return">return</a></code> 문은 함수에 의해 반환된 값을 지정합니다.</p> + +<pre class="brush: js"><code>return number * number;</code></pre> + +<p>기본 자료형인 매개변수(number와 같은)는 <strong>값으로</strong> 함수에 전달됩니다; 즉, 값이 함수로 전달됩니다. 그러나 함수가 매개변수의 값을 바꾸더라도 이는 <strong>전역적으로 또는 함수를 호출하는 곳에는 반영되지 않습니다</strong>.</p> + +<p>만약 여러분이 매개변수로 (예: {{jsxref("Array")}}이나 사용자가 정의한 객체와 같이 기본 자료형이 아닌 경우)를 전달하거나 함수가 객체의 속성을 변하게 하는 경우, 다음의 예처럼 그 변화는 함수 외부에서 볼 수 있습니다:</p> + +<pre class="brush: js">function myFunc(theObject) { + theObject.make = "Toyota"; +} + +var mycar = {make: "Honda", model: "Accord", year: 1998}; +var x, y; + +x = mycar.make; // x 의 값은 "Honda" 입니다. + +myFunc(mycar); +y = mycar.make; // y 의 값은 "Toyota" 입니다. + // (make 속성은 myFunc에서 변경되었습니다.) +</pre> + +<h3 id="함수_표현식">함수 표현식</h3> + +<p>위에서 함수 선언은 구문적인 문(statement)이지만, <strong>함수 표현식(</strong> <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/function">function expression</a><strong>)</strong>에 의해서 함수가 만들어 질 수도 있습니다. 이 같은 함수를 <strong>익명</strong>이라고 합니다. 이 말은 모든 함수가 이름을 가질 필요는 없다는 것을 뜻합니다. 예를 들어, 함수 <code>square</code>은 다음과 같이 정의 될 수도 있습니다:</p> + +<pre class="brush: js">var square = function(number) { return number * number }; +var x = square(4) // x 의 값은 16 입니다.</pre> + +<p>하지만, 함수 표현식에서 함수의 이름을 지정 할 수 있으며, 함수내에서 자신을 참조하는데 사용되거나, 디버거 내 스택 추적에서 함수를 식별하는 데 사용될 수 있습니다.</p> + +<pre class="brush: js">var factorial = function fac(n) { return n<2 ? 1 : n*fac(n-1) }; + +console.log(factorial(3)); +</pre> + +<p>함수 표현식은 함수를 다른 함수의 매개변수로 전달할 때 편리합니다. 다음 예는 첫 번째 인자로로 함수를, 두 번째 인자로 배열을 받는 <code>map</code> 함수를 보여줍니다.</p> + +<pre class="brush: js">function map(f,a) { + var result = [], // Create a new Array + i; + for (i = 0; i != a.length; i++) + result[i] = f(a[i]); + return result; +} +</pre> + +<p>다음 코드에서, 함수 표현식으로 정의된 함수를 인자로 받아, 2번 째 인자인 배열의 모든 요소에 대해 그 함수를 실행합니다.</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">function</span> <span class="function token">map</span><span class="punctuation token">(</span>f<span class="punctuation token">,</span> a<span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">var</span> result <span class="operator token">=</span> <span class="punctuation token">[</span><span class="punctuation token">]</span><span class="punctuation token">;</span> <span class="comment token">// Create a new Array</span> + <span class="keyword token">var</span> i<span class="punctuation token">;</span> <span class="comment token">// Declare variable</span> + <span class="keyword token">for</span> <span class="punctuation token">(</span>i <span class="operator token">=</span> <span class="number token">0</span><span class="punctuation token">;</span> i <span class="operator token">!=</span> a<span class="punctuation token">.</span>length<span class="punctuation token">;</span> i<span class="operator token">++</span><span class="punctuation token">)</span> + result<span class="punctuation token">[</span>i<span class="punctuation token">]</span> <span class="operator token">=</span> <span class="function token">f</span><span class="punctuation token">(</span>a<span class="punctuation token">[</span>i<span class="punctuation token">]</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="keyword token">return</span> result<span class="punctuation token">;</span> +<span class="punctuation token">}</span> +<span class="keyword token">var</span> f <span class="operator token">=</span> <span class="keyword token">function</span><span class="punctuation token">(</span>x<span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">return</span> x <span class="operator token">*</span> x <span class="operator token">*</span> x<span class="punctuation token">;</span> +<span class="punctuation token">}</span> +<span class="keyword token">var</span> numbers <span class="operator token">=</span> <span class="punctuation token">[</span><span class="number token">0</span><span class="punctuation token">,</span> <span class="number token">1</span><span class="punctuation token">,</span> <span class="number token">2</span><span class="punctuation token">,</span> <span class="number token">5</span><span class="punctuation token">,</span> <span class="number token">10</span><span class="punctuation token">]</span><span class="punctuation token">;</span> +<span class="keyword token">var</span> cube <span class="operator token">=</span> <span class="function token">map</span><span class="punctuation token">(</span>f<span class="punctuation token">,</span>numbers<span class="punctuation token">)</span><span class="punctuation token">;</span> +console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span>cube<span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> + +<p>함수는 [0, 1, 8, 125, 1000] 을 반환합니다.</p> + +<p>JavaScript에서 함수는 조건에 의해 정의될 수 있습니다. 예를 들어, 다음 함수 정의는 오직 <code>num</code>이 0일 때 경우에 만 <code>myFunc</code>을 정의합니다.</p> + +<pre class="brush: js">var myFunc; +if (num == 0){ + myFunc = function(theObject) { + theObject.make = "Toyota" + } +}</pre> + +<p>여기에 기술된 바와 같이 함수를 정의하는것에 더하여 {{jsxref("eval", "eval()")}} 과 같이 런타임에 문자열에서 함수들을 만들기위해 {{jsxref("Function")}} 생성자를 사용할 수 있습니다.</p> + +<p>객체내의 한 속성이 함수인 경우 <strong>메서드</strong>라고 합니다. <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/Working_with_Objects" title="en-US/docs/JavaScript/Guide/Working with Objects">Working with objects</a>에서 객체와 방법에 대해 자세히 알아보세요.</p> + +<h2 id="함수_호출">함수 호출</h2> + +<p>함수를 정의하는 것은 함수를 실행하는 것이 아닙니다. 함수를 정의하는 것은 간단히 함수의 이름을 지어주고, 함수가 호출될 때 무엇을 할지 지정 해주는 것입니다. 사실 함수를 <strong>호출</strong>하는 것은 나타나있는 매개변수를 가지고 지정된 행위를 수행하는 것입니다. 예를 들어, 만약 여러분이 함수 <code>square</code>를 정의한다면, 함수를 다음과 같이 호출할 수 있습니다.</p> + +<pre class="brush: js">square(5); +</pre> + +<p>위의 문장은 5라는 인수를 가지고 함수를 호출합니다. 함수는 이 함수의 실행문을 실행하고 값 25를 반환합니다.</p> + +<p>함수는 호출될 때 범위 내에 있어야 합니다. 그러나 함수의 선언은 이 예에서와 같이, 호이스팅 될 수 있습니다. (코드에서 호출 아래에 선언문이 있습니다.):</p> + +<pre class="brush: js">console.log(square(5)); +/* ... */ +function square(n) { return n*n } +</pre> + +<p>함수의 범위는 함수가 선언된 곳이거나, 전체 프로그램 에서의 최상위 레벨(전역)에 선언된 곳입니다.</p> + +<div class="note"> +<p><strong>비고:</strong> 위에 구문을 사용하여 함수를 정의하는 경우에만 작동합니다 (즉, <code>function funcName(){}</code> ). 아래와 같은 코드는 작동되지 않습니다. 이것이 의미하는 바는, 함수 호이스팅은 오직 함수 선언과 함께 작동하고, 함수 표현식에서는 동작하지 않습니다.</p> +</div> + +<pre class="brush: js example-bad">console.log(square); // square는 초기값으로 undefined를 가지고 호이스트된다. +console.log(square(5)); // TypeError: square는 함수가 아니다. +square = function (n) { + return n * n; +} +</pre> + +<p>함수의 인수는 문자열과 숫자에 제한되지 않습니다. 여러분은 함수에 전체 객체를 전달할 수 있습니다. <code>show_props()</code> 함수(<a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Objects_and_Properties" title="https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects#Objects_and_Properties">Working with objects</a>에서 정의된)는 인수로 객체를 취하는 함수의 예입니다.</p> + +<p>함수는 자신을 호출할 수 있습니다. 예를 들어, 팩토리얼을 재귀적으로 계산하는 함수가 있습니다:</p> + +<pre class="brush: js">function factorial(n){ + if ((n == 0) || (n == 1)) + return 1; + else + return (n * factorial(n - 1)); +} +</pre> + +<p>여러분은 다음과 같이 1부터 5까지의 팩토리얼을 계산할 수 있습니다.</p> + +<pre class="brush: js">var a, b, c, d, e; +a = factorial(1); // a gets the value 1 +b = factorial(2); // b gets the value 2 +c = factorial(3); // c gets the value 6 +d = factorial(4); // d gets the value 24 +e = factorial(5); // e gets the value 120 +</pre> + +<p>함수를 호출하는 다른 방법들이 있습니다. 함수를 동적 호출해야 하거나, 함수의 인수의 수가 달라져야 하거나, 함수 호출의 맥락이 런타임에서 결정된 특정한 객체로 설정될 필요가 있는 경우가 자주 있습니다. 함수가 그 자체로 객체이고 이들 객체는 차례로 메서드를({{jsxref("Function")}} 객체를 참조) 가지고 있습니다. 이들 중 하나인 {{jsxref("Function.apply", "apply()")}} 메서드는 이러한 목표를 달성하기 위해 사용될 수 있습니다.</p> + +<h2 class="deki-transform" id="함수의_범위">함수의 범위</h2> + +<p>함수 내에서 정의된 변수는 변수가 함수의 범위에서만 정의되어 있기 때문에, 함수 외부의 어느 곳에서든 액세스할 수 없습니다. 그러나, 함수가 정의된 범위 내에서 정의된 모든 변수나 함수는 액세스할 수 있습니다. 즉, 전역함수는 모든 전역 변수를 액세스할 수 있습니다. 다른 함수 내에서 정의 된 함수는 부모 함수와 부모 함수가 액세스 할 수 있는 다른 변수에 정의된 모든 변수를 액세스할 수 있습니다.</p> + +<pre class="brush: js">// The following variables are defined in the global scope +var num1 = 20, + num2 = 3, + name = "Chamahk"; + +// This function is defined in the global scope +function multiply() { + return num1 * num2; +} + +multiply(); // Returns 60 + +// A nested function example +function getScore () { + var num1 = 2, + num2 = 3; + + function add() { + return name + " scored " + (num1 + num2); + } + + return add(); +} + +getScore(); // Returns "Chamahk scored 5" +</pre> + +<h2 id="Scope_and_the_function_stack" name="Scope_and_the_function_stack">범위와 함수 스택</h2> + +<h3 id="Recursion" name="Recursion">재귀</h3> + +<p>함수는 자신을 참조하고 호출할 수 있습니다. 함수가 자신을 참조하는 방법은 세 가지가 있습니다.</p> + +<ol> + <li>함수의 이름</li> + <li><code><a href="/ko/docs/Web/JavaScript/Reference/Functions/arguments/callee">arguments.callee</a></code></li> + <li>함수를 참조하는 범위 내 변수</li> +</ol> + +<p>예를 들어, 다음 함수의 정의를 고려해보세요.</p> + +<pre class="brush: js">var foo = function bar() { + // statements go here +}; +</pre> + +<p>함수 본문 내에서 다음은 모두 동일합니다.</p> + +<ol> + <li><code>bar()</code></li> + <li><code>arguments.callee()</code></li> + <li><code>foo()</code></li> +</ol> + +<p>자신을 호출하는 함수를 <em>재귀 함수</em>라고 합니다. 어떤 면에서, 재귀는 루프와 유사합니다. 둘 다 동일한 코드를 여러 번 실행하고, 조건(<span class="atn">무한 루프</span><span class="atn">를 방지</span><span class="atn">하거나, 이</span><span> 경우에는</span> <span class="hps">오히려</span> <span class="atn hps">무한 재귀</span><span class="atn">하는)</span>을 요구합니다. 예를 들어, 다음 루프는:</p> + +<pre class="brush: js">var x = 0; +while (x < 10) { // "x < 10" is the loop condition + // do stuff + x++; +} +</pre> + +<p>아래와 같이 재귀 함수와 그 함수에 대한 호출로 변환될 수 있습니다.</p> + +<pre class="brush: js">function loop(x) { + if (x >= 10) // "x >= 10" 는 탈출 조건 ("!(x < 10)"와 동등) + return; + // do stuff + loop(x + 1); // the recursive call +} +loop(0); +</pre> + +<p>그러나 일부 알고리즘은 단순 재귀 루프로 변환할 수 없습니다. 예를 들어, 트리 구조(가령, <a href="/en-US/docs/DOM">DOM</a>)의 모든 노드를 얻는 것은 재귀를 사용하여 보다 쉽게 할 수 있습니다:</p> + +<pre class="brush: js">function walkTree(node) { + if (node == null) // + return; + // do something with node + for (var i = 0; i < node.childNodes.length; i++) { + walkTree(node.childNodes[i]); + } +} +</pre> + +<p>함수 <code>loop</code> 와 비교하여, 각 재귀 호출 자체는 여기에 많은 재귀 호출을 만듭니다.</p> + +<p>재귀적 알고리즘은 비 재귀적인 알고리즘으로 변환 할 수 있습니다. 그러나 변환된 알고리즘이 훨씬 더 복잡하며 그렇게 함으로써 스택의 사용을 요구합니다. 사실, 재귀 자체가 함수 스택을 사용 합니다.</p> + +<p>스택형 동작은 다음의 예에서 볼 수 있습니다:</p> + +<pre class="brush: js">function foo(i) { + if (i < 0) + return; + console.log('begin:' + i); + foo(i - 1); + console.log('end:' + i); +} +foo(3); + +// Output: + +// begin:3 +// begin:2 +// begin:1 +// begin:0 +// end:0 +// end:1 +// end:2 +// end:3</pre> + +<h3 id="중첩된_함수와_클로저">중첩된 함수와 클로저</h3> + +<p>여러분은 함수 내에 함수를 끼워 넣을 수 있습니다. 중첩 된 (내부) 함수는 그것을 포함하는 (외부) 함수와 별개입니다. 그것은 또한 <em>클로저</em>를 형성합니다. 클로저는 그 변수(“폐쇄”라는 표현)를 결합하는 환경을 자유롭게 변수와 함께 가질 수 있는 표현(전형적인 함수)입니다.</p> + +<p>중첩 함수는 클로저이므로, 중첩된 함수는 그것을 포함하는 함수의 인수와 변수를 “상속”할 수 있는 것을 의미합니다. 즉, 내부 함수는 외부 함수의 범위를 포함합니다.</p> + +<p>요약하면:</p> + +<ul> + <li>내부 함수는 외부 함수의 명령문에서만 액세스할 수 있습니다.</li> +</ul> + +<ul> + <li>내부 함수는 클로저를 형성합니다: 외부 함수는 내부 함수의 인수와 변수를 사용할 수 없는 반면에, 내부 함수는 외부 함수의 인수와 변수를 사용할 수 있습니다.</li> +</ul> + +<p>다음 예는 중첩된 함수를 보여줍니다:</p> + +<pre class="brush: js">function addSquares(a,b) { + function square(x) { + return x * x; + } + return square(a) + square(b); +} +a = addSquares(2,3); // returns 13 +b = addSquares(3,4); // returns 25 +c = addSquares(4,5); // returns 41 +</pre> + +<p>내부 함수는 클로저를 형성하기 때문에, 여러분은 외부 함수를 호출하고, 외부 및 내부 함수 모두에 인수를 지정할 수 있습니다.</p> + +<pre class="brush: js">function outside(x) { + function inside(y) { + return x + y; + } + return inside; +} +fn_inside = outside(3); // Think of it like: give me a function that adds 3 to whatever you give it +result = fn_inside(5); // returns 8 + +result1 = outside(3)(5); // returns 8 +</pre> + +<h3 id="Efficiency_considerations" name="Efficiency_considerations">변수의 보존</h3> + +<p>중첩된 내부 함수가 반환될 때 외부 함수의 인수 <code>x</code>가 보존된다는 점을 알 수 있습니다. 클로저는 그것을 참조하는 모든 범위에서 인수와 변수를 보존해두어야 합니다. 매번 호출될 때마다 잠재적으로 다른 인수를 제공할 수 있기 때문에, 클로저는 외부 함수에 대하여 매번 새로 생성됩니다. 메모리는 그 무엇도 내부 함수에 접근하지 않을 때만 해제됩니다.</p> + +<p>변수의 보존은 일반 객체에서 참조를 저장해두는 것과 다르지 않지만, 사용자가 직접 참조를 설정하는 것이 아니고 자세히 들여다볼 수 없어서 종종 명확하지 않습니다.</p> + +<h3 id="Multiply-nested_functions" name="Multiply-nested_functions">다중 중첩 함수</h3> + +<p>함수는 다중 중첩될 수 있습니다. 즉, 함수 (C)를 포함하는 함수 (B)를 포함하는 함수 (A). 여기에서 두 함수 B와 C는 모두 클로저를 형성합니다. 그래서 B는 A를 엑세스할 수 있고, C는 B를 액세스 할 수 있습니다. 이와 같이, 클로저는 다중 범위를 포함 할 수 있습니다; 그들은 재귀적으로 그것을 포함하는 함수의 범위를 포함합니다. 이것을 <em>범위 체이닝</em>이라 합니다.(그것을 “체이닝”이라 하는 이유는 추후에 설명할 것입니다.)</p> + +<p>다음 예를 살펴 보겠습니다:</p> + +<pre class="brush: js">function A(x) { + function B(y) { + function C(z) { + console.log(x + y + z); + } + C(3); + } + B(2); +} +A(1); // logs 6 (1 + 2 + 3) +</pre> + +<p>이 예에서, C는 B의 y와 A의 x를 엑세스 합니다. 이 때문에 수행할 수 있습니다:</p> + +<ol> + <li>B는 A를 포함하는 클로저를 형성합니다. 즉, B는 A의 인수와 변수를 엑세스할 수 있습니다.</li> + <li>C는 B를 포함하는 클로저를 형성합니다.</li> + <li>B의 클로저는 A를 포함하고, C의 클로저는 A를 포함하기 때문에, C는 B와 A의 인수와 변수를 엑세스할 수 있습니다. 즉, 순서대로 C는 A와 B의 범위를 체이닝합니다.</li> +</ol> + +<p>그러나 역은 사실이 아닙니다. A는 C에 접근 할 수 없습니다. 왜냐하면 A는 B의 인수와 변수(C는 B변수)에 접근할수 없기 때문입니다. 그래서 C는 B에게만 사적으로 남게됩니다.</p> + +<h3 id="Name_conflicts" name="Name_conflicts">이름 충돌</h3> + +<p>클로저의 범위에서 두 개의 인수 또는 변수의 이름이 같은 경우, <em>이름 충돌</em>이 있습니다. 더 안쪽 범위가 우선순위를 갖습니다. 그래서 가장 바깥 범위는 우선순위가 가장 낮은 반면에, 가장 안쪽 범위는 가장 높은 우선순위를 갖습니다. 이것이 범위 체인(scope chaini)입니다. <span class="atn">체인에서</span> 첫번째는 <span class="hps">가장 안쪽</span> <span class="atn hps">범위</span><span>이고,</span> <span class="atn hps">마지막</span><span>은</span> <span class="atn hps">가장 바깥 쪽</span><span class="atn">의 범위입니다</span><span>.</span> <span class="hps">다음 사항을 고려하세요:</span></p> + +<pre class="brush: js">function outside() { + var x = 10; + function inside(x) { + return x; + } + return inside; +} +result = outside()(20); // returns 20 instead of 10 +</pre> + +<p>이름 충돌이 x를 반환하는 문과 내부의 매개 변수 x와 외부 변수 x 사이에서 발생합니다. 여기에서 범위 체이닝은 {내부, 외부, 전역 객체}입니다. 따라서 내부의 x는 외부의 x보다 높은 우선순위를 갖게 되고, 20(내부의 x)이 10(외부의 x) 대신에 반환됩니다.</p> + +<h2 id="클로저">클로저</h2> + +<p>클로저는 자바스크립트의 강력한 기능 중 하나입니다. 자바스크립트는 함수의 중첩(함수 안에 함수를 정의하는것)을 허용하고, 내부함수가 외부 함수 안에서 정의된 모든 변수와 함수들을 완전하게 접근 할 수 있도록 승인해줍니다.(그리고 외부함수가 접근할수 있는 모든 다른 변수와 함수들까지) 그러나 외부 함수는 내부 함수 안에서 정의된 변수와 함수들에 접근 할 수 없습니다. 이는 내부 함수의 변수에 대한 일종의 캡슐화를 제공합니다. 또한, 내부함수는 외부함수의 범위에 접근할 수 있기 때문에, 내부 함수가 외부 함수의 수명을 초과하여 생존하는 경우, 외부함수에서 선언된 변수나 함수는 외부함수의 실행 기간보다 오래갑니다. 클로저는 내부 함수가 어떻게든 외부 함수 범위 밖의 모든 범위에서 사용 가능해지면 생성됩니다.</p> + +<pre class="brush: js">var pet = function(name) { // 외부 함수는 'name'이라 불리는 변수를 정의합니다. + var getName = function() { + return name; // 내부 함수는 외부 함수의 'name' 변수에 접근합니다. + } + return getName; // 내부 함수를 리턴함으로써, 외부 범위에 노출됩니다. +}, +myPet = pet("Vivie"); + +myPet(); // "Vivie"로 리턴합니다. +</pre> + +<p>클로저는 위 코드보다 더 복잡해 질 수도 있습니다. 외부 함수의 내부 변수를 다루는 메서드를 포함한 객체도 반환될 수도 있습니다.</p> + +<pre class="brush: js">var createPet = function(name) { + var sex; + + return { + setName: function(newName) { + name = newName; + }, + + getName: function() { + return name; + }, + + getSex: function() { + return sex; + }, + + setSex: function(newSex) { + if(typeof newSex == "string" && (newSex.toLowerCase() == "male" || newSex.toLowerCase() == "female")) { + sex = newSex; + } + } + } +} + +var pet = createPet("Vivie"); +pet.getName(); // Vivie + +pet.setName("Oliver"); +pet.setSex("male"); +pet.getSex(); // male +pet.getName(); // Oliver +</pre> + +<p>위 코드에서, 외부 함수의 'name' 이란 변수는 내부 함수에서 접근이 가능합니다. 그리고 그 내장 함수를 통하는 방법 말고는 내부 변수로 접근할 수 없습니다. 내부 함수의 내부 변수는 외부 인수와 변수를 안전하게 저장합니다. 내부 변수는 내부 함수가 작동하기 위해 '지속적'이고 '갭슐화된' 데이터를 보유합니다. 함수는 변수로 할당되거나, 이름을 가질 필요가 없습니다.</p> + +<pre class="brush: js">var getCode = (function(){ + var secureCode = "0]Eal(eh&2"; // A code we do not want outsiders to be able to modify... + + return function () { + return secureCode; + }; +})(); + +getCode(); // Returns the secureCode +</pre> + +<p>그러나 클로저를 쓰면서 조심해야 할 위험이 많이 있습니다. 만약 내부 함수가 외부 함수의 범위에 있는 이름과 같은 변수를 정의하였을 경우, 다시는 외부 함수 범위의 변수를 참조(접근)할 방법이 없습니다.</p> + +<pre class="brush: js">var createPet = function(name) { // 외부 함수가 "name" 이라는 변수를 정의하였다 + return { + setName: function(name) { // 내부 함수 또한 "name" 이라는 변수를 정의하였다 + name = name; // ??? 어떻게 우리는 외부 함수에 정의된 "name"에 접근할까??? + } + } +} +</pre> + +<h2 id="인수(arguments)_객체_사용하기">인수(arguments) 객체 사용하기</h2> + +<p>함수의 인수는 배열과 비슷한 객체로 처리가 됩니다. 함수 내에서는, 전달 된 인수를 다음과 같이 다룰 수 있습니다. :</p> + +<pre class="brush: js">arguments[i] +</pre> + +<p>i 는 0 으로 시작하는 순서 번호입니다. 따라서 함수에 전달된 첫 번째 인수는 <code>arguments[0]</code> 입니다. 총 인수의 개수는 <code>arguments.length</code> 에서 얻을 수 있습니다.</p> + +<p>인수(<code>arguments</code>) 객체를 이용하면, 보통 함수에 정의된 개수보다 많은 인수를 넘겨주면서 함수를 호출할 수 있습니다. 이것은 얼마나 많은 인수가 함수로 넘겨질지 모르는 상황에서 유용합니다. <code>arguments.length</code>를 함수에 실제로 넘겨받은 인수의 수를 알아낼 때 사용할 수 있고 , 각각의 인수에 인수(<code>arguments</code>) 객체를 이용하여 접근 할 수 있습니다.</p> + +<p>예를 들어, 몇 개의 문자열을 연결하는 함수를 생각해 봅시다. 이 함수의 유일한 형식 인수는 각 문자열을 구분해주는 문자를 나타내는 문자열입니다 . 이 함수는 다음과 같이 정의됩니다:</p> + +<pre class="brush: js">function myConcat(separator) { + var result = ""; // 리스트를 초기화한다 + var i; + // arguments를 이용하여 반복한다 + for (i = 1; i < arguments.length; i++) { + result += arguments[i] + separator; + } + return result; +} +</pre> + +<p>어떤 개수의 인수도 이 함수로 넘겨줄 수 있고, 이 함수는 각각의 인수를 하나의 문자열 "리스트" 로 연결합니다. :</p> + +<pre class="brush: js">// returns "red, orange, blue, " +myConcat(", ", "red", "orange", "blue"); + +// returns "elephant; giraffe; lion; cheetah; " +myConcat("; ", "elephant", "giraffe", "lion", "cheetah"); + +// returns "sage. basil. oregano. pepper. parsley. " +myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley"); +</pre> + +<div class="note"> +<p><strong>Note:</strong> 인수(arguments) 객체는 배열과 닮은 것이지 배열이 아닙니다. 인수(arguments) 객체는 번호 붙여진 인덱스와 길이 속성을 가지고 있다는 점에서 배열과 닮은 것입니다. 인수(arguments) 객체는 배열을 다루는 모든 메서드를 가지고 있지 않습니다.</p> +</div> + +<p>더 자세한 정보를 얻고 싶으면 자바스크립트 참조문의 {{jsxref("Function")}}객체에 대하여 보세요.</p> + +<h2 id="함수의_매개변수">함수의 매개변수</h2> + +<p> ECMAScript 2015와 함께 시작된,두 종류의 매개변수가 있습니다 : 디폴트 매개변수 , 나머지 매개변수.</p> + +<h3 id="디폴트_매개변수">디폴트 매개변수</h3> + +<p>자바스크립트에서, 함수의 매개변수는 <code>undefined</code> 가 기본으로 설정됩니다. 그러나, 어떤 상황에서는 다른 값을 기본값으로 가진 것이 유용할 때가 있습니다. 이때가 디폴트 매개변수가 도움을 줄 수 있는 상황입니다.</p> + +<p>옛날엔, 기본값을 설정하는 보편적인 전략은 함수의 본문에서 매개변수 값을 테스트하여 그 값이 <code>undefined</code> 인 경우에 값을 할당하는 것이었습니다. 다음과 같은 예제에서, 함수호출 시 <code>b</code> 매개변수에 아무 값을 주지 않으면, <code>a*b</code> 계산 시 <code>b</code> 매개변수의 값은 <code>undefined</code> 일 것이므로 <code>multiply</code> 함수 호출은 <code>NaN</code>을 리턴할 것입니다. 그러나 이런 것은 이 예제의 2번째 줄에서 걸립니다:</p> + +<pre class="brush: js">function multiply(a, b) { + b = typeof b !== 'undefined' ? b : 1; + + return a*b; +} + +multiply(5); // 5 +</pre> + +<p>디폴트 매개변수와 함께라면, 함수 본문에서 검사하는 부분은 필요가 없습니다. 이제 , 함수 머리에서 <code>b</code> 의 기본값에 간단히 1을 넣어주면 됩니다:</p> + +<pre class="brush: js">function multiply(a, b = 1) { + return a*b; +} + +multiply(5); // 5</pre> + +<p>더 자세한 내용을 보고 싶으시면, <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters">default parameters</a> 문서를 참조하세요.</p> + +<h3 id="나머지_매개변수">나머지 매개변수</h3> + +<p> <a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">나머지 매개변수</a> 구문을 사용하면 배열로 불확실한 개수의 인수를 나타낼 수 있습니다. 이 예제에서, 우리는 나머지 매개변수를 2번째 인수부터 마지막 인수까지 얻기 위하여 사용하였습니다. 그리고 우리는 첫번째 값으로 나머지 매개변수에 곱하였습니다. 이 예제는 다음 섹션에서 소개할 화살표(arrow) 함수 입니다.</p> + +<pre class="brush: js">function multiply(multiplier, ...theArgs) { + return theArgs.map(x => multiplier * x); +} + +var arr = multiply(2, 1, 2, 3); +console.log(arr); // [2, 4, 6]</pre> + +<h2 id="화살표_함수">화살표 함수</h2> + +<p> <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">화살표 함수 표현</a> (<strong>뚱뚱한 화살표(fat arrow) 함수라고 알려진</strong>)은 함수 표현과 비교하였을때 짧은 문법을 가지고 있고 사전적으로 this 값을 묶습니다. 화살표 함수는 언제나 익명입니다. hacks.mozilla.org 블로그 포스트 "<a href="https://hacks.mozilla.org/2015/06/es6-in-depth-arrow-functions/">ES6 In Depth: Arrow functions</a>" 를 참조하세요.</p> + +<p>화살표 함수 소개에 영향을 주는 두 요소: 더 짧은 함수와 바인딩 되지않은 <code>this</code>.</p> + +<h3 id="더_짧은_함수">더 짧은 함수</h3> + +<p>어떤 함수적 패턴에서는, 더 짧은 함수가 환영받습니다. 다음을 비교해 보세요:</p> + +<pre class="brush: js">var a = [ + "Hydrogen", + "Helium", + "Lithium", + "Beryllium" +]; + +var a2 = a.map(function(s){ return s.length }); + +console.log(a2); // logs [8, 6, 7, 9] + +var a3 = a.map( s => s.length ); + +console.log(a3); // logs [8, 6, 7, 9]</pre> + +<h3 id="사전적_this">사전적 <code>this</code></h3> + +<p>화살표 함수에서, 모든 new함수들은 그들의 <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">this</a> 값을 정의합니다 (생성자로서의 새로운 객체, 정의되지 않은 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>의 함수 호출, 함수가 "object method"로 호출했을때의 context object ,등등.). 이런 것은 객체지향 프로그래밍 스타일에서 짜증을 불러 일으킵니다.</p> + +<pre class="brush: js">function Person() { + // The Person() constructor defines `<code>this`</code> as itself. + this.age = 0; + + setInterval(function growUp() { + // In nonstrict mode, the growUp() function defines `this` + // as the global object, which is different from the `this` + // defined by the Person() constructor. + this.age++; + }, 1000); +} + +var p = new Person();</pre> + +<p>IECMAScript 3/5 에서는, 이 문제는 <code>this</code> 안의 값을 뒤덮을 수 있는변수에 할당하면서 고쳐졌습니다.</p> + +<pre class="brush: js">function Person() { + var self = this; // Some choose `that` instead of `self`. + // Choose one and be consistent. + self.age = 0; + + setInterval(function growUp() { + // The callback refers to the `self` variable of which + // the value is the expected object. + self.age++; + }, 1000); +}</pre> + +<p>또는, 적절한 <code>this</code> 값이 <code>growUp()</code> 함수에 전달되도록, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">바인딩된 함수</a>가 생성될 수 있습니다.</p> + + + +<p>화살표 함수에는 <code>this;</code>가 없습니다. 화살표 함수를 포함하는 객체 값이 사용됩니다. 따라서 다음 코드에서 setInterval에 전달 된 함수 내의 this 값은 화살표 함수를 둘러싼 함수의 this와 같은 값을 갖습니다.</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">function</span> <span class="function token">Person</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">this</span><span class="punctuation token">.</span>age <span class="operator token">=</span> <span class="number token">0</span><span class="punctuation token">;</span> + + <span class="function token">setInterval</span><span class="punctuation token">(</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="operator token">=</span><span class="operator token">></span> <span class="punctuation token">{</span> + <span class="keyword token">this</span><span class="punctuation token">.</span>age<span class="operator token">++</span><span class="punctuation token">;</span> <span class="comment token">// |this| properly refers to the person object</span> + <span class="punctuation token">}</span><span class="punctuation token">,</span> <span class="number token">1000</span><span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="punctuation token">}</span> + +<span class="keyword token">var</span> p <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Person</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> + +<h2 id="미리_정의된_함수들">미리 정의된 함수들</h2> + +<p>자바스크립트에는 최고 등급의 몇가지 내장함수가 있습니다:</p> + +<dl> + <dt>{{jsxref("Global_Objects/eval", "eval()")}}</dt> + <dd> + <p><code><strong>eval()</strong></code> 메소드는 문자열로 표현된 자바스크립트 코드를 수행합니다.</p> + </dd> + <dt>{{jsxref("Global_Objects/uneval", "uneval()")}} {{non-standard_inline}}</dt> + <dd> + <p><code><strong>uneval()</strong></code> 메소드는 {{jsxref("Object")}}의 소스코드를 표현하는 문자열을 만듭니다.</p> + </dd> + <dt>{{jsxref("Global_Objects/isFinite", "isFinite()")}}</dt> + <dd> + <p>전역 <code><strong>isFinite()</strong></code> 함수는 전달받은 값이 유한한지 결정합니다. 만약 필요하다면, 매개변수는 첫번째로 숫자로 변환됩니다.</p> + </dd> + <dt>{{jsxref("Global_Objects/isNaN", "isNaN()")}}</dt> + <dd> + <p><code><strong>isNaN()</strong></code> 함수는 {{jsxref("Global_Objects/NaN", "NaN")}}인지 아닌지 결정합니다. Note: <code>isNaN</code> 함수 안의 강제 변환은 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN#Description">흥미로운</a> 규칙을 가지고 있습니다; {{jsxref("Number.isNaN()")}}을 대신 사용하고 싶을것입니다, ECMAScript 6 에서 정의된,또는 값이 숫자값이 아닐때, <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/typeof">typeof</a></code> 를 사용할 수도 있습니다 .</p> + </dd> + <dt>{{jsxref("Global_Objects/parseFloat", "parseFloat()")}}</dt> + <dd> + <p><code><strong>parseFloat()</strong></code> 함수는 문자열 인수 값을 해석하여 부동소숫점 수를 반환합니다.</p> + </dd> + <dt>{{jsxref("Global_Objects/parseInt", "parseInt()")}}</dt> + <dd> + <p><code><strong>parseInt()</strong></code> 함수는 문자열 인수 값을 해석하여 특정한 진법의 정수를 반환합니다 (수학적 수 체계를 기반으로 해서).</p> + </dd> + <dt>{{jsxref("Global_Objects/decodeURI", "decodeURI()")}}</dt> + <dd> + <p><code><strong>decodeURI()</strong></code> 함수는 사전에 {{jsxref("Global_Objects/encodeURI", "encodeURI")}}을 통해 만들어지거나 비슷한 과정을 통해 만들어진 URI(Uniform Resource Identifier) 를 해독합니다.</p> + </dd> + <dt>{{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}</dt> + <dd> + <p><code><strong>decodeURIComponent()</strong></code> 메소드는 사전에{{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent")}}를 통하여 만들어 지거나 또는 비슷한 과정을 통해 만들어진 URI (Uniform Resource Identifier) 컴포넌트를 해독합니다.</p> + </dd> + <dt>{{jsxref("Global_Objects/encodeURI", "encodeURI()")}}</dt> + <dd> + <p><code><strong>encodeURI()</strong></code> 메소드는 URI(Uniform Resource Identifier)를 각 인스턴스의 특정한 문자를 한개, 두개,세개, 또는 네개의 UTF-8인코딩으로 나타내어지는 연속된 확장문자들과 바꾸는 방법으로 부호화 합니다 .(두"surrogate"문자로 구성된 문자들은 오직 네개의 연속된 확장문자 입니다. ).</p> + </dd> + <dt>{{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}</dt> + <dd> + <p><code><strong>encodeURIComponent()</strong></code> 메소드는 URI(Uniform Resource Identifier) 컴포넌트를 각 인스턴스의 특정한 문자를 한개, 두개,세개, 또는 네개의 UTF-8인코딩으로 나타내어지는 연속된 확장문자들과 바꾸는 방법으로 부호화 합니다 .(두"surrogate"문자로 구성된 문자들은 오직 네개의 연속된 확장문자 입니다. ).).</p> + </dd> + <dt>{{jsxref("Global_Objects/escape", "escape()")}} {{deprecated_inline}}</dt> + <dd> + <p>곧 사라질 <code><strong>escape()</strong></code> 메소드는 한 문자열에서 특정 문자들이 16진 확장 비트열로 바뀌어진 문자열로 계산합니다. {{jsxref("Global_Objects/encodeURI", "encodeURI")}} 또는 {{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent")}} 를 사용하세요.</p> + </dd> + <dt>{{jsxref("Global_Objects/unescape", "unescape()")}} {{deprecated_inline}}</dt> + <dd> + <p>곧 사라질 <code><strong>unescape()</strong></code> 메소드는 문자열에서 확장 비트열이 확장 비트열이 나타내는 문자로 바뀌어진 문자열로 계산합니다. {{jsxref("Global_Objects/escape", "escape")}}에서 확장 비트열이 소개될 것입니다. <code>unescape()</code> 메소드가 곧 사라지기 때문에, {{jsxref("Global_Objects/decodeURI", "decodeURI()")}} or {{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent")}} 를 대신 사용하세요.</p> + </dd> +</dl> + +<p>{{PreviousNext("Web/JavaScript/Guide/Loops_and_iteration", "Web/JavaScript/Guide/Expressions_and_Operators")}}</p> + +<div class="itanywhere-activator" style="left: 154px; top: 13819.2px; display: none;" title="Google Translator Anywhere"></div> + +<div class="itanywhere-activator" style="display: none;" title="Google Translator Anywhere"></div> diff --git a/files/ko/web/javascript/index.html b/files/ko/web/javascript/index.html new file mode 100644 index 0000000000..923d422500 --- /dev/null +++ b/files/ko/web/javascript/index.html @@ -0,0 +1,118 @@ +--- +title: JavaScript +slug: Web/JavaScript +tags: + - JavaScript + - Landing + - Learn + - 'l10n:priority' + - 자바스크립트 +translation_of: Web/JavaScript +--- +<div>{{JsSidebar}}</div> + +<p class="summary"><span class="seoSummary"><strong>JavaScript</strong>(JS)는 가벼운 인터프리터 또는 <a href="https://ko.wikipedia.org/wiki/JIT_%EC%BB%B4%ED%8C%8C%EC%9D%BC">JIT 컴파일</a> 프로그래밍 언어로, {{Glossary("First-class Function", "일급 함수")}}를 지원합니다. 웹 페이지의 스크립트 언어로서 제일 유명하지만 {{Glossary("Node.js")}}, <a href="https://couchdb.apache.org/">Apache CouchDB</a>, <a href="http://www.adobe.com/devnet/acrobat/javascript.html">Adobe Acrobat</a>처럼 <a class="external" href="https://en.wikipedia.org/wiki/JavaScript#Uses_outside_Web_pages">많은 비 브라우저 환경</a>에서도 사용하고 있습니다.</span> JavaScript는 {{Glossary("Prototype-based programming", "프로토타입 기반")}}의 동적 다중 패러다임 스크립트 언어로, 객체지향형, 명령형, 선언형(함수형 프로그래밍 등) 스타일을 지원합니다. 자세한 내용은 <a href="/ko/docs/Web/JavaScript/About">JavaScript에 대하여</a>를 참고하세요.</p> + +<p>이 문서는 JavaScript 언어 자체만 다루며 웹 페이지를 비롯한 다른 사용 환경에 대해서는 다루지 않습니다. 웹 페이지의 특정 {{Glossary("API")}}에 대하여 알고 싶다면 <a href="/ko/docs/Web/API">웹 API</a>와 <a href="/ko/docs/Glossary/DOM">DOM</a>을 참고하시기 바랍니다.</p> + +<p>JavaScript의 표준은 <a href="/ko/docs/Web/JavaScript/언어_리소스">ECMAScript</a>입니다. 2012년 기준 <a href="http://kangax.github.io/compat-table/es5/">최신 브라우저</a>는 모두 ECMAScript 5.1을 온전히 지원합니다. 이전 브라우저의 경우는 최소한 ECMAScript 3까지는 지원합니다. 2015년 6월 17일 <a href="http://www.ecma-international.org">ECMA International</a>에서는 공식명 ECMAScript 2015 로 불리는 ECMAScript의 6번째 주 버전을 발표했습니다(보통 ECMAScript 6 혹은 ES6으로 불립니다). 그 이후 ECMAScript 표준의 출시 주기는 1년입니다. 이 문서는 최신 초안(현재 <a class="external" href="https://tc39.github.io/ecma262/">ECMAScript 2020</a>)에 기반을 둡니다.</p> + +<p>JavaScript를 <a href="https://ko.wikipedia.org/wiki/%EC%9E%90%EB%B0%94_(%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%B0%8D_%EC%96%B8%EC%96%B4)">Java 프로그래밍 언어</a>와 혼동해서는 안 됩니다. "Java"와 "JavaScript" 두 가지 모두 Oracle이 미국 및 기타 국가에 등록한 상표입니다. 하지만, 두 언어는 문법 체계와 사용 방법이 전혀 다릅니다.</p> + +<div class="column-container"> +<div class="column-half"> +<h2 id="자습서">자습서</h2> + +<p>안내서 및 자습서와 함께 JavaScript 프로그램을 짜는 법을 알아보세요.</p> + +<h3 id="입문">입문</h3> + +<p>JavaScript를 배우고 싶지만 JavaScript 또는 프로그래밍에 대한 이전 경험이 없는 경우 <a href="/ko/docs/Learn/JavaScript">Web 개발 학습하기의 JavaScript 주제</a>를 방문하세요. 사용할 수 있는 전체 모듈은 다음과 같습니다.</p> + +<dl> + <dt><a href="/ko/docs/Learn/JavaScript/First_steps">JavaScript 첫 걸음</a></dt> + <dd>"JavaScript는 무엇인가요?", "어떤 모습인가요?", "뭘 할 수 있나요?"와 같은 기본적인 질문에 대답하면서 변수, 문자열, 숫자, 배열과 같은 JavaScript의 주요 기능에 대해서도 알아봅니다.</dd> + <dt><a href="/ko/docs/Learn/JavaScript/Building_blocks">JavaScript 구성 요소</a></dt> + <dd>JavaScript의 핵심 기본 기능에 대한 이해를 넓히기 위해 조건문, 반복문, 함수, 이벤트와 같이 흔히 찾을 수 코드 블록의 형태에 대해서 알아봅니다.</dd> + <dt><a href="/ko/docs/Learn/JavaScript/Objects">JavaScript 객체 소개</a></dt> + <dd>JavaScript에 대한 지식을 쌓고, 보다 효율적인 코드를 작성하기 위해서는 JavaScript의 객체지향적인 모습을 이해해야 합니다.</dd> + <dt><a href="/ko/docs/Learn/JavaScript/Asynchronous">비동기 JavaScript</a></dt> + <dd>비동기 JavaScript가 중요한 이유와, 비동기적 코드를 사용해 서버에서 리소스 가져오기 등 블록킹 연산을 효율적으로 처리하는 방법을 알아봅니다.</dd> + <dt><a href="/ko/docs/Learn/JavaScript/Client-side_web_APIs">클라이언트측 웹 API</a></dt> + <dd>API란 무엇인지 탐색해보고, 제일 흔히 사용해서 개발 중 자주 마주치게 될 일부 API의 사용법을 배웁니다.</dd> + <dt> + <h3 id="JavaScript_안내서">JavaScript 안내서</h3> + </dt> + <dt><a href="/ko/docs/Web/JavaScript/Guide">JavaScript 안내서</a></dt> + <dd> + <p>JavaScript 또는 다른 언어의 경험을 가진 독자를 대상으로 한 JavaScript 상세 안내서입니다.</p> + </dd> +</dl> + +<h3 id="중급">중급</h3> + +<dl> + <dt><a href="/ko/docs/A_re-introduction_to_JavaScript" title="A re-introduction to JavaScript">JavaScript 재입문</a></dt> + <dd>JavaScript에 대해 안다고 <em>생각하는</em> 이들을 위한 개요.</dd> + <dt><a href="/ko/docs/Web/JavaScript/Data_structures" title="JavaScript data structures">JavaScript 데이터 구조</a></dt> + <dd>JavaScript에서 이용 가능한 데이터 구조 개요.</dd> + <dt><a href="/ko/docs/Web/JavaScript/Equality_comparisons_and_sameness" title="Equality comparisons and sameness">같음 비교 및 동일성</a></dt> + <dd>JavaScript는 세 가지 다른 값 비교 연산을 제공합니다: <code>===</code>를 사용한 엄격한(strict) 같음, <code>==</code>를 사용한 느슨한(loose) 같음 및 {{jsxref("Global_Objects/Object/is", "Object.is()")}} 메서드.</dd> + <dt><a href="/ko/docs/Web/JavaScript/Guide/Closures">클로저</a></dt> + <dd>클로저는 함수와 그 함수가 선언 된 어휘 환경의 조합입니다.</dd> +</dl> + +<h3 id="고급">고급</h3> + +<dl> + <dt><a href="/ko/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain" title="Inheritance and the prototype chain">상속 및 프로토타입 체인</a></dt> + <dd>널리 오해 받고 과소 평가된 프로토타입(원형) 기반 상속의 설명.</dd> + <dt><a href="/ko/docs/Web/JavaScript/Reference/Strict_mode" title="Strict mode">엄격 모드</a></dt> + <dd>엄격 모드는 초기화 전에 어떤 변수도 사용할 수 없음을 정의합니다. 이는 빠른 성능 및 쉬운 디버깅을 위한 ECMAScript 5의 제한된 변형(variant)입니다.</dd> + <dt><a href="/ko/docs/Web/JavaScript/Typed_arrays" title="JavaScript typed arrays">JavaScript 형식화된 배열</a></dt> + <dd>JavaScript 형식화된 배열은 원시(raw) 이진 데이터에 접근하기 위한 메커니즘을 제공합니다.</dd> + <dt><a href="/ko/docs/Web/JavaScript/Memory_Management">메모리 관리</a></dt> + <dd>JavaScript에서 메모리 라이프 사이클 및 가비지 컬렉션.</dd> + <dt><a href="/ko/docs/Web/JavaScript/EventLoop" title="Concurrency model and Event Loop">동시성 모델 및 이벤트 루프</a></dt> + <dd>JavaScript "이벤트 루프"에 기반을 둔 동시성 모델이 있습니다.</dd> +</dl> +</div> + +<div class="column-half"> +<h2 id="참고서">참고서</h2> + +<p>전체 <a href="/ko/docs/Web/JavaScript/Reference" title="JavaScript reference">JavaScript 참고서</a>를 훑어보세요.</p> + +<dl> + <dt><a href="/ko/docs/Web/JavaScript/Reference/Global_Objects" title="Standard objects">표준 객체</a></dt> + <dd>{{jsxref("Array")}}, {{jsxref("Boolean")}}, {{jsxref("Date")}}, {{jsxref("Error")}}, {{jsxref("Function")}}, {{jsxref("JSON")}}, {{jsxref("Math")}}, {{jsxref("Number")}}, {{jsxref("Object")}}, {{jsxref("RegExp")}}, {{jsxref("String")}}, {{jsxref("Map")}}, {{jsxref("Set")}}, {{jsxref("WeakMap")}}, {{jsxref("WeakSet")}} 등 표준 내장 객체 알아가기.</dd> + <dt><a href="/ko/docs/Web/JavaScript/Reference/Operators" title="Expressions and operators">표현식 및 연산자</a></dt> + <dd>JavaScript 연산자 {{jsxref("Operators/instanceof", "instanceof")}}, {{jsxref("Operators/typeof", "typeof")}}, {{jsxref("Operators/new", "new")}}, {{jsxref("Operators/this", "this")}}의 행동, <a href="/ko/docs/Web/JavaScript/Reference/Operators/연산자_우선순위" title="operator precedence">연산자 우선순위</a> 등에 대해 더 알아보기.</dd> + <dt><a href="/ko/docs/Web/JavaScript/Reference/Statements" title="Statements and declarations">명령문 및 선언문</a></dt> + <dd>{{jsxref("Statements/do...while", "do-while")}}, {{jsxref("Statements/for...in", "for-in")}}, {{jsxref("Statements/for...of", "for-of")}}, {{jsxref("Statements/try...catch", "try-catch")}}, {{jsxref("Statements/let", "let")}}, {{jsxref("Statements/var", "var")}}, {{jsxref("Statements/const", "const")}}, {{jsxref("Statements/if...else", "if-else")}}, {{jsxref("Statements/switch", "switch")}} 등의 JavaScript 명령문 및 키워드 작동 법 배우기.</dd> + <dt><a href="/ko/docs/Web/JavaScript/Reference/Functions" title="Functions">함수</a></dt> + <dd>어플리케이션 개발에 JavaScript 함수로 작업하는 법 배우기.</dd> +</dl> + +<h2 id="도구_자원">도구 & 자원</h2> + +<p><strong>JavaScript</strong> 코드 작성과 디버깅을 돕는 유용한 도구 모음입니다.</p> + +<dl> + <dt><a href="/ko/docs/도구들" title="Firefox Developer Tools">Firefox 개발자 도구</a></dt> + <dd><a href="/ko/docs/도구들/Web_Console">Web Console</a>, <a href="/ko/docs/도구들/Performance">JavaScript Profiler</a>, <a href="/ko/docs/도구들/Debugger">Debugger</a> 등.</dd> + <dt><a href="/ko/docs/Web/JavaScript/Shells">JavaScript 쉘</a></dt> + <dd>빠르게 JavaScript 코드 조각(snippet)을 테스트할 수 있는 JavaScript 쉘.</dd> + <dt><a href="https://togetherjs.com/">TogetherJS</a></dt> + <dd>간편한 협업.</dd> + <dt><a href="http://stackoverflow.com/questions/tagged/javascript">Stack Overflow</a></dt> + <dd>"JavaScript" 태그가 달린 Stack Overflow 질문.</dd> + <dt><a href="/ko/docs/Web/JavaScript/New_in_JavaScript" title="JavaScript versions and release notes">JavaScript 버전 및 출시 노트</a></dt> + <dd>JavaScript 기능 역사 및 구현 상태 훑어보기.</dd> + <dt><a href="https://jsfiddle.net/">JSFiddle</a></dt> + <dd>JavaScript, CSS, HTML 편집 및 실시간 결과 얻기. 외부 자원(resource)을 사용하며 온라인으로 팀과 협업하기.</dd> + <dt><a href="https://plnkr.co/">Plunker</a></dt> + <dd>Plunker는 온라인에서 여러분의 웹 개발 아이디어를 실제로 만들거나 다른사람과 공유 협업하는 커뮤니티 입니다. 실시간으로 JavaScrip, CSS, HTML을 만들고 편집 할 수 있습니다.</dd> +</dl> +</div> +</div> diff --git a/files/ko/web/javascript/introduction_to_object-oriented_javascript/index.html b/files/ko/web/javascript/introduction_to_object-oriented_javascript/index.html new file mode 100644 index 0000000000..67b15b963d --- /dev/null +++ b/files/ko/web/javascript/introduction_to_object-oriented_javascript/index.html @@ -0,0 +1,289 @@ +--- +title: 객체지향 자바스크립트 개요 +slug: Web/JavaScript/Introduction_to_Object-Oriented_JavaScript +translation_of: Learn/JavaScript/Objects +--- +<p>비록 다른 객체지향적인 언어들과의 차이점에 대한 논쟁들이 있긴 하지만, JavaScript는 강력한 객체지향 프로그래밍 능력들을 지니고 있다.</p> + +<p>이 글에서는 객체지향 프로그래밍에 대해 소개하는 것으로 시작해서 자바스크립트의 객체 모델, 그리고 자바스크립트에서의 객체지향 프로그래밍 개념에 대해 간단한 예제로 살펴볼 것이다.</p> + +<h2 id="JavaScript_Review" name="JavaScript_Review">자바스크립트 리뷰(JavaScript review)</h2> + +<p>만약 변수, 형, 함수, 스코프 등 자바스크립트의 개념에 대해 명확히 이해하고 있지 못하다면, <a href="/en/JavaScript/A_re-introduction_to_JavaScript" title="en/JavaScript/A_re-introduction_to_JavaScript">A re-introduction to JavaScript</a>를 참고해 보자. <a href="/en/JavaScript/Guide" title="en/JavaScript/Guide">Core JavaScript 1.5 Guide</a>라는 글도 도움이 될 것이다.</p> + +<h2 id="Object-oriented_programming" name="Object-oriented_programming">객체지향 프로그래밍(Object-oriented programming)</h2> + +<p>객체지향 프로그래밍은 실제 세계에 기반한 모델을 만들기 위해 추상화를 사용하는 프로그래밍 패러다임이다. 객체지향 프로그래밍은 modularity, polymorphism, encapsulation을 포함하여 이전에 정립된 패러다임들부터 여러가지 테크닉들을 사용한다. 오늘날 많은 유명한 프로그래밍 언어(자바, 자바스크립트, C#, C++, 파이썬, PHP, 루비, 오브젝트C)는 객체지향 프로그래밍을 지원한다.</p> + +<p>객체지향 프로그래밍은 함수들의 집합 혹은 단순한 컴퓨터의 명령어들의 목록 이라는 기존의 프로그래밍에 대한 전통적인 관점에 반하여, 관계성있는 객체들의 집합이라는 관점으로 접근하는 소프트웨어 디자인으로 볼 수 있다. 객체지향 프로그래밍에서, 각 객체는 메시지를 받을 수도 있고, 데이터를 처리할 수도 있으며, 또다른 객체에게 메시지를 전달할 수도 있다. 각 객체는 별도의 역할이나 책임을 갖는 작은 독립적인 기계로 볼 수 있는 것이다.</p> + +<p>객체지향 프로그래밍은 보다 유연하고 유지보수성이 높은 프로그래밍을 하도록 의도되었고, 대규모 소프트웨어 공학에서 널리 알려져 있다. 객체지향 프로그래밍이 갖는 modularity에 기반한 강력한 힘에 의해, 객체지향적인 코드는 개발을 보다 단순하게 했고, 시간이 흐른 뒤에도 보다 쉽게 이해할 수 있도록 했으며, 복잡한 상황이나 절차들을 덜 모듈화된 프로그래밍 방법들보다 더 직접적으로 분석하고, 코딩하고, 이해할 수 있도록 만들었다.<sup><a href="#Reference">2</a></sup></p> + +<h2 id="Terminology" name="Terminology">용어(Terminology)</h2> + +<dl> + <dt>Class</dt> + <dd>객체의 특성을 정의</dd> + <dt>Object</dt> + <dd>Class의 인스턴스</dd> + <dt>Property</dt> + <dd>객체의 특성(예: 색깔)</dd> + <dt>Method</dt> + <dd>객체의 능력(예: 걷기)</dd> + <dt>Constructor</dt> + <dd>인스턴스화 되는 시점에서 호출되는 메서드</dd> + <dt>Inheritance</dt> + <dd>클래스는 다른 클래스로부터 특성들을 상속받을 수 있다.</dd> + <dt>Encapsulation</dt> + <dd>클래스는 해당 객체의 특성들만을 정의할 수 있고, 메서드는 그 메서드가 어떻게 실행되는지만 정의할 수 있다. (외부 접근 불가)</dd> + <dt>Abstraction</dt> + <dd>복잡한 상속, 메서드, 객체의 속성의 결합은 반드시 현실 세계를 시뮬레이션할 수 있어야 한다.</dd> + <dt>Polymorphism</dt> + <dd>다른 클래스들이 같은 메서드나 속성으로 정의될 수 있다.</dd> +</dl> + +<p>객체지향 프로그래밍에 대한 보다 확장된 설명은 <a class="external" href="http://en.wikipedia.org/wiki/Object_oriented_programming">Object-oriented programming</a>를 참고하면 된다.</p> + +<h2 id="프로토타입기반_프로그래밍(Prototype-based_programming)">프로토타입기반 프로그래밍(Prototype-based programming)</h2> + +<p>프로토타입 기반 프로그래밍은 클래스가 존재하지 않는 객체지향 프로그래밍의 한가지 스타일로, 동작 재사용(behavior reuse, 클래스기반 언어에서는 상속이라고함)은 프로토타입으로서 존재하는 객체를 데코레이팅하는 과정을 통해 수행된다.</p> + +<p>프로토타입 기반 언어의 원형적인 예는 David Ungar과 Randall Smith가 개발한 'Self'라는 프로그래밍 언어이다. 그러나 클래스가 없는 프로그래밍 스타일이 최근 인기를 얻으며 성장하였고, 자바스크립트, Cecil, NewtonScript, Io, MOO, REBOL, Kevo, Squeak 등의 언어에서 채택되어 왔다.<sup><a href="#Reference">2</a></sup></p> + +<h2 id="JavaScript_Object_Oriented_Programming" name="JavaScript_Object_Oriented_Programming">자바스크립트 객체지향 프로그래밍(JavaScript Object Oriented Programming)</h2> + +<h3 id="Core_Objects" name="Core_Objects">Core Objects</h3> + +<p>자바스크립트는 코어(core)에 몇 개의 객체를 갖고 있다. 예를들면, Math, Object, Array, String과 같은 객체가 있다. 아래의 예제는 Math 객체를 사용해서 무작위 숫자를 만들어내는 것을 보여준다.</p> + +<pre class="brush: js">alert(Math.random()); +</pre> + +<div class="note"><strong>Note:</strong> <span style="color: #333333; line-height: inherit;">여기와 다른 예제들 모두 alert 이라는 함수가 전역에 선언되어 있다고 가정하고 있다. alert 함수는 실제로 자바스크립트 그 자체에 포함되진 않았지만, 대부분의 브라우저에서 지원하고 있다.</span></div> + +<p>자바스크립트의 core object들의 리스트는 <a href="/En/Core_JavaScript_1.5_Reference/Global_Objects" title="En/Core_JavaScript_1.5_Reference/Global_Objects">Core JavaScript 1.5 Reference:Global Objects</a>라는 글을 참고하면 자세히 알 수 있다.</p> + +<p>자바스크립트의 모든 객체는 Object 객체의 인스턴스이므로 Object의 모든 속성과 메서드를 상속받는다.</p> + +<h3 id="Custom_Objects" name="Custom_Objects">Custom Objects</h3> + +<h4 id="The_Class" name="The_Class">The Class</h4> + +<p>class문을 흔하게 볼 수 있는 C++이나 자바와는 달리 자바스크립트는 class문이 포함되지 않은 프로토타입 기반 언어이다. 이로인해 때때로 class 기반 언어에 익숙한 프로그래머들은 혼란을 일으킨다. 자바스크립트에서는 function을 class로서 사용한다. 클래스를 정의하는 것은 function을 정의하는 것만큼 쉽다. 아래 예제에서는 Person이라는 이름의 클래스를 새로 정의하고 있다.</p> + +<pre class="brush: js">function Person() { } +</pre> + +<h4 id="The_Object_.28Class_Instance.29" name="The_Object_.28Class_Instance.29">The Object (Class Instance)</h4> + +<p>obj라는 이름의 객체의 새로운 인스턴스를 만들 때에는 new obj라는 statement를 사용하고, 차후에 접근할 수 있도록 변수에 결과를 받는다.</p> + +<p>아래의 예제에서 Person이라는 이름의 클래스를 정의한 후에, 두 개의 인스턴스를 생성하고 있다.</p> + +<pre class="brush: js">function Person() { } +var person1 = new Person(); +var person2 = new Person(); +</pre> + +<div class="note"><a href="/en/JavaScript/Reference/Global_Objects/Object/create" title="Object.create">Object.create</a> 메서드 역시 새로운 인스턴스를 만들 때 사용할 수 있다.</div> + +<h4 id="The_Constructor" name="The_Constructor">The Constructor</h4> + +<p>생성자는 인스턴스화되는 순간(객체 인스턴스가 생성되는 순간) 호출된다. 생성자는 해당 클래스의 메서드이다. 자바스크립트에서는 함수 자체가 그 객체의 생성자 역할을 하기 때문에 특별히 생성자 메서드를 정의할 필요가 없다. 클래스 안에 선언된 모든 내역은 인스턴스화되는 그 시간에 실행된다. 생성자는 주로 객체의 속성을 설정하거나 사용하기 위해 객체를 준비시키는 메서드를 호출할 때 주로 사용된다. 클래스 메서드를 추가하고 정의하는 것은 나중에 설명한다.</p> + +<div>아래의 예제에서, Person 클래스의 생성자는 Person 이 인스턴스화되었을 때 alert 을 보여주게 된다.</div> + +<pre class="brush: js">function Person() { + alert('Person instantiated'); +} + +var person1 = new Person(); +var person2 = new Person(); +</pre> + +<h4 id="The_Property_.28object_attribute.29" name="The_Property_.28object_attribute.29">The Property (object attribute)</h4> + +<div>속성은 클래스 안에 있는 변수들을 말한다. 객체의 모든 인스턴스는 그 인스턴스의 속성을 갖는다. 속성들의 상속이 바르게 이루어지려면 해당 클래스(function)의 프로토타입에 선언되어 있어야 한다.</div> + +<div> </div> + +<div>클래스 내에서 속성 작업은 현재 객체를 가리키는 this 키워드에 의해 이루어진다. 클래스의 외부에서 속성에 접근(읽기 혹은 쓰기)하는 것은 "인스턴스명.속성명" 의 형식으로 이루어진다. 이러한 문법은 C++, 자바나 다른 수많은 언어에서와 동일한 방식이다. (클래스 내부에서 "this.속성명" 은 해당 속성의 값을 읽거나 쓸 때 주로 사용된다)</div> + +<div> </div> + +<div>아래의 예제에서 Person 클래스에 gender라는 속성을 정의하고 인스턴스화할 때 그 값을 설정한다.</div> + +<pre class="brush: js">function Person(gender) { + this.gender = gender; + alert('Person instantiated'); +} + +var person1 = new Person('Male'); +var person2 = new Person('Female'); + +//display the person1 gender +alert('person1 is a ' + person1.gender); // person1 is a Male +</pre> + +<h4 id="The_methods" name="The_methods">메서드(The methods)</h4> + +<p>메서드는 앞서 살펴본 속성과 같은 방식을 따른다. 차이점이 있다면 메서드는 function이기 때문에 function 형태로 정의된다는 것입니다. 메서드를 호출하는 것은 속성에 접근하는 것과 매우 유사한데 단지 끝에 ()를 추가하면 된다. argument가 있다면 괄호 안에 입력해준다. 메서드를 정의하기 위해서는 클래스의 prototype에 명명된 속성에 함수를 할당하면 된다. 이때 할당된 이름은 해당 객체의 메서드를 호출할 때 사용되는 이름이다.</p> + +<p>아래의 예에서는 Person 클래스에 sayHello()라는 메서드를 정의하고 사용하고 있다.</p> + +<pre class="brush: js">function Person(gender) { + this.gender = gender; + alert('Person instantiated'); +} + +Person.prototype.sayHello = function() +{ + alert ('hello'); +}; + +var person1 = new Person('Male'); +var person2 = new Person('Female'); + +// call the Person sayHello method. +person1.sayHello(); // hello +</pre> + +<p>자바스크립트에서 메서드는 "컨텍스트에 관계 없이" 호출될 수 있는 속성으로서 클래스/객체에 연결되어 있다. 다음 예제의 코드를 살펴보자.</p> + +<pre class="brush: js">function Person(gender) { + this.gender = gender; +} + +Person.prototype.sayGender = function() +{ + alert(this.gender); +}; + +var person1 = new Person('Male'); +var genderTeller = person1.sayGender; + +person1.sayGender(); // alerts 'Male' +genderTeller(); // alerts undefined +alert(genderTeller === person1.sayGender); // alerts true +alert(genderTeller === Person.prototype.sayGender); // alerts true +</pre> + +<p>위의 예제는 많은 개념들을 한꺼번에 보여주고 있다. </p> + +<div>먼저 이 예제는 자바스크립트에 "per-object methods" 가 존재하지 않는다는 것을 보여준다. JavaScript는 메서드에 대한 레퍼런스가 모두 똑같은 (프로토타입에 처음 정의한) 함수를 참조하고 있기 때문이다.</div> + +<div> </div> + +<div>자바스크립트는 어떤 객체의 메서드로서 함수가 호출될 때 현재 "객체의 컨텍스트"를 특별한 "this" 변수에 "연결한다". 이는 아래와 같이 function 객체의 call 메서드를 호출하는 것과 동일하다.</div> + +<div> </div> + +<div>(역자주: 참고로, genderTeller() 만 호출했을 때 undefined 가 나타난 것은 해당 메서드가 호출될 때 컨텍스트가 window 로 잡혔기 때문에 window.gender 는 존재하지 않으므로 undefined 가 나타난 것이다.)</div> + +<div> </div> + +<pre class="brush: js">genderTeller.call(person1); //alerts 'Male' +</pre> + +<div class="note">더 자세한 것은 <a href="/en/JavaScript/Reference/Global_Objects/Function/call" title="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call">Function.call</a> 과 <a href="/en/JavaScript/Reference/Global_Objects/Function/apply" title="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply">Function.apply</a> 를 참고하자.</div> + +<h4 id="Inheritance" name="Inheritance">상속(Inheritance)</h4> + +<p>상속은 하나 이상의 클래스를 특별한 버전의 클래스로 생성하는 하나의 방법이다. (다만 자바스크립트는 오직 하나의 클래스를 상속받는 것만 지원한다.) 이 특별한 클래스는 흔히 자식 클래스(child)라고 불리우고 원본 클래스는 흔히 부모 클래스(parent)라고 불리운다. 자바스크립트에서는 부모 클래스의 인스턴스를 자식 클래스에 할당함으로써 상속이 이루어진다. 최신 브라우저에서는 <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Object/create#Classical_inheritance_with_Object.create" title="/en-US/docs/JavaScript/Reference/Global_Objects/Object/create#Classical_inheritance_with_Object.create">Object.create</a> 메서드를 사용해서 상속을 수행할 수도 있다.</p> + +<div class="note"> +<p><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Object/prototype">Core JavaScript 1.5 Reference:Global Objects:Object:prototype</a> 에 나와있는 설명과 같이 자바스크립트는 자식 클래스의 prototype.constructor 를 검색하지 않으므로 직접 명시해주어야 한다.</p> +</div> + +<p>아래의 예제에서는, Student라는 클래스를 Person 클래스의 자식 클래스로 정의한다. 그 후에 우리는 sayHello() 메서드를 재정의하고 sayGoodBye() 메서드를 추가한다.</p> + +<pre class="brush: js">// define the Person Class +function Person() {} + +Person.prototype.walk = function(){ + alert ('I am walking!'); +}; +Person.prototype.sayHello = function(){ + alert ('hello'); +}; + +// define the Student class +function Student() { + // Call the parent constructor + Person.call(this); +} + +// inherit Person +Student.prototype = new Person(); + +// correct the constructor pointer because it points to Person +Student.prototype.constructor = Student; + +// replace the sayHello method +Student.prototype.sayHello = function(){ + alert('hi, I am a student'); +} + +// add sayGoodBye method +Student.prototype.sayGoodBye = function(){ + alert('goodBye'); +} + +var student1 = new Student(); +student1.sayHello(); +student1.walk(); +student1.sayGoodBye(); + +// check inheritance +alert(student1 instanceof Person); // true +alert(student1 instanceof Student); // true +</pre> + +<p>Object.create 를 사용하면 상속을 아래와 같이 수행할 수 있다.</p> + +<pre class="brush: js">Student<code class="js plain">.prototype = Object.create(</code>Person<code class="js plain">.prototype);</code></pre> + +<h4 id="Encapsulation" name="Encapsulation">캡슐화(Encapsulation)</h4> + +<p>이전의 예제에서, Student 클래스는 Person 클래스의 walk() 메서드가 어떻게 실행되는지에 대해 알 필요가 없고, walk() 메서드를 사용하는데에도 전혀 문제가 없다. 또 Student 클래스에서는 walk() 메서드의 내용을 바꾸려는게 아니라면 walk() 메서드를 특별히 정의할 필요도 없다. 자식 클래스는 부모 클래스의 모든 메서드를 상속받고, 상속받은 메서드중 일부를 수정하고 싶은 경우에만 해당 메서드를 정의하는 것을 우리는 캡슐화(encapsulation)이라고 부른다.</p> + +<h4 id="Abstraction" name="Abstraction">추상화(Abstraction)</h4> + +<p>추상화는 작업 문제의 현재 부분을 모델링할 수 있도록 하는 매커니즘이다. 추상화는 상속(specialization, 추상의 수준을 낮추는 것)과 합성으로 구현할 수 있다. 자바스크립트는 상속에 의해 특별화(specialization)를, 클래스들의 인스턴스를 다른 객체의 속성값이 되게 함으로써 합성을 구현한다.</p> + +<p>자바스크립트 Function 클래스는 Object 클래스를 상속받고(이는 모델의 특별화를 보여준다), Function.prototype 속성은 Object의 인스턴스이다(이는 합성을 보여준다).</p> + +<pre class="brush: js">var foo = function(){}; +alert( 'foo is a Function: ' + (foo instanceof Function) ); +alert( 'foo.prototype is an Object: ' + (foo.prototype instanceof Object) ); +</pre> + +<h4 id="Polymorphism" name="Polymorphism">다형성(Polymorphism)</h4> + +<p>모든 메서드와 속성들은 prototype 속성에 선언되어 있고, 클래스가 다르다면 같은 이름의 메서드도 선언할 수 있다. 메서드들은 메서드가 선언된 클래스로 그 실행 영역이 한정된다. 물론 이건 두 개의 클래스들이 서로 부모-자식 관계가 아닐때에만 성립한다. 즉 다시 말해 부모-자식 관계의 상속 관계로 하나가 다른 하나에게서 상속받지 않았을 때에만 성립한다.</p> + +<h2 id="Notes" name="Notes">Notes</h2> + +<p>객체지향 프로그래밍을 구현하는데 있어서 자바스크립트는 매우 유연하기 때문에, 이 글에서 선보인 테크닉들은 자바스크립트에서 객체지향을 구현하는 유일한 방법들 중 일부일 뿐이다.</p> + +<p>또, 여기에서 선보인 테크닉들은 어떤 hack도 사용하지 않았고 또한 다른 언어의 객체 이론 구현물들을 모방하지도 않았다.</p> + +<p>자바스크립트의 객체지향 프로그래밍에 있어서 다른 보다 깊이있는 테크닉들이 많이 있지만, 소개하는 글이라는 이 글의 특성상 다루지 않기로 한다.</p> + +<h2 id="References" name="References">References</h2> + +<ol> + <li>Mozilla. "Core JavaScript 1.5 Guide", http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide</li> + <li>Wikipedia. "Object-oriented programming", <a class="external" href="http://en.wikipedia.org/wiki/Object-oriented_programming" rel="freelink">http://en.wikipedia.org/wiki/Object-...ed_programming</a></li> +</ol> + +<div class="originaldocinfo"> +<h2 id="Original_Document_Information">Original Document Information</h2> + +<ul> + <li>Author(s): Fernando Trasviña <f_trasvina at hotmail dot com></li> + <li>Copyright Information: © 1998-2005 by individual mozilla.org contributors; content available under a <a class="external" href="http://www.mozilla.org/foundation/licensing/website-content.html">Creative Commons license</a></li> +</ul> +</div> + +<p> </p> diff --git a/files/ko/web/javascript/javascript_technologies_overview/index.html b/files/ko/web/javascript/javascript_technologies_overview/index.html new file mode 100644 index 0000000000..185a417001 --- /dev/null +++ b/files/ko/web/javascript/javascript_technologies_overview/index.html @@ -0,0 +1,83 @@ +--- +title: JavaScript 기술 개요 +slug: Web/JavaScript/JavaScript_technologies_overview +tags: + - Beginner + - DOM + - JavaScript +translation_of: Web/JavaScript/JavaScript_technologies_overview +--- +<div>{{JsSidebar("Introductory")}}</div> + +<h2 id="개요">개요</h2> + +<p><a href="/ko/docs/Web/HTML">HTML</a>이 웹 페이지의 구조와 내용을, <a href="/ko/docs/Web/CSS">CSS</a>가 서식과 외관을 결정한다면, <a href="/ko/docs/Web/JavaScript">JavaScript</a>는 상호작용성을 추가하여 풍부한 웹 어플리케이션을 만듭니다.</p> + +<p>그러나, 웹 브라우저 맥락에서 포괄적으로 쓰이는 용어로써의 "JavaScript"는 사실 매우 다른 요소 여럿을 포함하는 것입니다. 그 중 하나는 핵심 언어(ECMAScript)고, 다른 하나는 DOM(Document Object Model)을 포함한 <a href="/ko/docs/Web/API">Web API</a>입니다.</p> + +<h2 id="핵심_언어_JavaScript(ECMAScript)">핵심 언어, JavaScript(ECMAScript)</h2> + +<p>JavaScript의 핵심 언어는 ECMA TC39 위원회가 <a href="/ko/docs/Web/JavaScript/Language_Resources">ECMAScript</a>라는 이름으로 표준화했습니다.</p> + +<p>핵심 언어는 <a href="https://nodejs.org">Node.js</a> 등 비브라우저 환경에서도 사용됩니다.</p> + +<h3 id="ECMAScript에_속하는_것">ECMAScript에 속하는 것</h3> + +<p>ECMAScript는 다음 항목을 포함하고 있습니다.</p> + +<ul> + <li>언어 구문 (구문 분석 규칙, 키워드, 흐름 제어, 객체 리터럴 초기화 등)</li> + <li>오류 처리 방법 ({{jsxref("Statements/throw", "throw")}}, {{jsxref("Statements/try...catch", "try...catch")}}, 사용자 정의 {{jsxref("Error")}} 유형 등)</li> + <li>자료형 (불리언, 숫자, 문자열, 함수, 객체, ...)</li> + <li>전역 객체. 브라우저에서 전역 객체는 {{domxref("Window", "window")}} 객체지만, ECMAScript는 브라우저에 국한되지 않는 API({{jsxref("parseInt")}}, {{jsxref("parseFloat")}}, {{jsxref("decodeURI")}}, {{jsxref("encodeURI")}} 등)만 정의합니다.</li> + <li>프로토타입 기반 상속 구조</li> + <li>내장 객체 및 함수 ({{jsxref("JSON")}}, {{jsxref("Math")}}, {{jsxref("Array.prototype", "Array.prototype", "메서드")}} 메서드, {{jsxref("Object")}} 내성검사 메서드 등)</li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Strict_mode">엄격 모드</a></li> +</ul> + +<h3 id="브라우저_지원">브라우저 지원</h3> + +<p>2016년 10월 기준 주요 브라우저의 현버전은 ECMAScript 5.1과 ECMAScript 2015를 구현하지만, (여전히 사용 중인) 오래된 브라우저는 ECMAScript 5만 구현합니다.</p> + +<h3 id="미래">미래</h3> + +<p>2015년 7월 17일, ECMAScript 6판이 ECMA General Assembly에 의해 공식으로 채택되고 표준으로 출판됐습니다. 이후 ECMAScript는 매년 새로운 판을 출판하고 있습니다.</p> + +<h3 id="국제화_API">국제화 API</h3> + +<p><a href="http://ecma-international.org/ecma-402/1.0/">ECMAScript 국제화 API 명세</a>는 ECMAScript 언어 명세의 부속이며, 마찬가지로 ECMA TC39가 표준화했습니다. 국제화 API는 JavaScript 어플리케이션에 콜레이션(문자열 비교), 숫자 서식, 날짜 및 시간 서식 기능을 제공하므로, 어플리케이션이 언어를 선택하고 필요에 맞춰 기능을 적용할 수 있는 방법입니다. 초기 표준안은 2012년 12월에 통과했으며 브라우저 구현 상태는 {{jsxref("Intl")}} 객체 문서에서 추적 중입니다. 최근에는 국제화 명세도 매년 비준하고 있으며 브라우저 구현도 계속하여 향상 중입니다.</p> + +<h2 id="DOM_API">DOM API</h2> + +<h3 id="WebIDL">WebIDL</h3> + +<p><a class="external" href="https://heycam.github.io/webidl/" title="http://dev.w3.org/2006/webapi/WebIDL/">WebIDL 명세</a>는 DOM 기술과 ECMAScript 사이를 연결하는 역할을 합니다.</p> + +<h3 id="DOM의_핵심">DOM의 핵심</h3> + +<p>DOM(Document Object Model)은 HTML, XHTML, XML 문서의 객체를 나타내고 상호작용하기 위한, <strong>언어에 제약되지 않는</strong> 크로스 플랫폼 협약입니다. DOM 트리의 객체는 해당 객체의 메서드를 사용해 조작할 수 있습니다. {{glossary("W3C")}}는 HTML와 XML 문서를 객체로 추상화하는 Core Document Object Model을 표준화하고, 추상화를 조작하기 위한 방법도 정의합니다. DOM에 정의된 내용 중 일부는 다음과 같습니다.</p> + +<ul> + <li>문서 구조, 트리 모델, <a class="external" href="https://dom.spec.whatwg.org/" title="http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html">DOM core</a>의 DOM Event Architecture: {{domxref("Node")}}, {{domxref("Element")}}, {{domxref("DocumentFragment")}}, {{domxref("Document")}}, {{domxref("DOMImplementation")}}, {{domxref("Event")}}, {{domxref("EventTarget")}}, …</li> + <li>덜 엄격한 DOM Event Architecture 정의, <a class="external" href="https://w3c.github.io/uievents/" title="http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html">DOM events</a>에 속하는 특정 이벤트.</li> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Traversal-Range/traversal.html">DOM Traversal</a>, <a class="external" href="https://dom.spec.whatwg.org/#ranges" title="http://html5.org/specs/dom-range.html">DOM Range</a> 등</li> +</ul> + +<p>ECMAScript의 관점에서, DOM 명세에 정의된 객체는 "호스트 객체"라고 부릅니다.</p> + +<h3 id="HTML_DOM">HTML DOM</h3> + +<p>웹 마크업 언어인 <a class="external" href="http://www.whatwg.org/html" title="http://www.whatwg.org/html">HTML</a>은 DOM 코어에 정의된 추상화 개념에 엘리먼트의 <em>의미</em>를 더한 레이어라고 할 수 있겠다. HTML DOM은 HTML 엘리먼트의 <code>className</code> 같은 속성과 {{ domxref("document.body") }} 같은 API도 포함한다.</p> + +<p>HTML 명세는 문서의 제약도 정의한다. 예를들어 순서가 없는 리스트를 나타내는 <code>ul</code> 의 모든 자식들은 리스트 요소를 나타내는 <code>li</code> 엘리먼트여야 한다. 또한 표준에 정의되지 않은 엘리먼트와 속성을 사용하는것도 금지된다.</p> + +<h2 id="알아둘만한_다른_API">알아둘만한 다른 API</h2> + +<ul> + <li>setTimeout 과 setInterval 함수는 HTML 표준의 <a class="external" href="http://www.whatwg.org/html/#window" title="http://www.whatwg.org/html/#window">Window</a> 인터페이스에 처음으로 정의되었다.</li> + <li><a class="external" href="http://dev.w3.org/2006/webapi/XMLHttpRequest-2/" title="http://dev.w3.org/2006/webapi/XMLHttpRequest-2/">XMLHttpRequest</a>는 비동기적 HTTP 요청을 보낼 수 있게 해주는 API이다.</li> + <li><a class="external" href="http://dev.w3.org/csswg/cssom/">CSS Object Model</a>는 CSS 규칙을 오브젝트처럼 다룰 수 있도록 추상화 해준다.</li> + <li><a class="external" href="http://www.whatwg.org/specs/web-workers/current-work/">WebWorkers</a>는 병렬 처리를 가능하게 하는 API이다.</li> + <li><a class="external" href="http://www.whatwg.org/C/#network">WebSockets</a>는 양방향 저수준 통신을 가능하게 하는 API이다.</li> + <li><a class="external" href="http://www.whatwg.org/html/#2dcontext" title="http://www.whatwg.org/html/#2dcontext">Canvas 2D Context</a>는 canvas 엘리먼트에 그릴 수 있게 해주는 API이다.</li> +</ul> diff --git a/files/ko/web/javascript/memory_management/index.html b/files/ko/web/javascript/memory_management/index.html new file mode 100644 index 0000000000..22cccc5e76 --- /dev/null +++ b/files/ko/web/javascript/memory_management/index.html @@ -0,0 +1,183 @@ +--- +title: 자바스크립트의 메모리관리 +slug: Web/JavaScript/Memory_Management +translation_of: Web/JavaScript/Memory_Management +--- +<p>{{JsSidebar("Advanced")}}<br> + C 언어같은 저수준 언어에서는 메모리 관리를 위해 <code>malloc()</code> 과 <code>free()</code>를 사용한다. 반면, 자바스크립트는 객체가 생성되었을 때 자동으로 메모리를 할당하고 쓸모 없어졌을 때 자동으로 해제한다(가비지 컬렉션). 이러한 자동 메모리 관리는 잠재적 혼란의 원인이기도 한데, 개발자가 메모리 관리에 대해 고민할 필요가 없다는 잘못된 인상을 줄 수 있기 때문이다.</p> + +<h2 id="메모리_생존주기">메모리 생존주기</h2> + +<p>메모리 생존주기는 프로그래밍 언어와 관계없이 비슷하다.</p> + +<ol> + <li>필요할때 할당한다.</li> + <li>사용한다. (읽기, 쓰기)</li> + <li>필요없어지면 해제한다. </li> +</ol> + +<p>두 번째 부분은 모든 언어에서 명시적으로 사용된다. 그러나 첫 번째 부분과 마지막 부분은 저수준 언어에서는 명시적이며, 자바스크립트와 같은 대부분의 고수준 언어에서는 암묵적으로 작동한다. </p> + +<h3 id="자바스크립트에서_메모리_할당">자바스크립트에서 메모리 할당</h3> + +<h4 id="값_초기화">값 초기화</h4> + +<p>프로그래머를 할당 문제로 괴롭히지 않기 위해서, 자바스크립트는 값을 선언할 때 자동으로 메모리를 할당한다.</p> + +<div style="overflow: hidden;"> +<pre class="brush: js">var n = 123; // 정수를 담기 위한 메모리 할당 +var s = 'azerty'; // 문자열을 담기 위한 메모리 할당 + +var o = { + a: 1, + b: null +}; // 오브젝트와 그 오브젝트에 포함된 값들을 담기 위한 메모리 할당 + +// (오브젝트처럼) 배열과 배열에 담긴 값들을 위한 메모리 할당 +var a = [1, null, 'abra']; + +function f(a){ + return a + 2; +} // 함수를 위한 할당(함수는 호출 가능한 오브젝트이다) + +// 함수식 또한 오브젝트를 담기위한 메모리를 할당한다. +someElement.addEventListener('click', function(){ + someElement.style.backgroundColor = 'blue'; +}, false); +</pre> +</div> + +<h4 id="함수_호출을_통한_할당">함수 호출을 통한 할당</h4> + +<p>함수 호출의 결과 메모리 할당이 일어나기도 한다. </p> + +<pre class="brush: js">var d = new Date(); // Date 개체를 위해 메모리를 할당 + +var e = document.createElement('div'); // DOM 엘리먼트를 위해 메모리를 할당한다. +</pre> + +<p>메소드가 새로운 값이나 오브젝트를 할당하기도 한다.</p> + +<pre class="brush: js">var s = 'azerty'; +var s2 = s.substr(0, 3); // s2는 새로운 문자열 +// 자바스크립트에서 문자열은 immutable 값이기 때문에, +// 메모리를 새로 할당하지 않고 단순히 [0, 3] 이라는 범위만 저장한다. + +var a = ['ouais ouais', 'nan nan']; +var a2 = ['generation', 'nan nan']; +var a3 = a.concat(a2); +// a 와 a2 를 이어붙여, 4개의 원소를 가진 새로운 배열 +</pre> + +<h3 id="값_사용">값 사용</h3> + +<p>값 사용이란 기본적으로는 할당된 메모리를 읽고 쓰는 것을 의미한다. 변수나 오브젝트 속성 값을 읽고 쓸때 값 사용이 일어난다. 또 함수 호출시 함수에 인수를 넘길때도 일어난다. </p> + +<h3 id="할당된_메모리가_더_이상_필요없을_때_해제하기">할당된 메모리가 더 이상 필요없을 때 해제하기</h3> + +<p>이 단계에서 대부분의 문제가 발생한다. "할당된 메모리가 더 이상 필요없을 때"를 알아내기가 어렵기 때문이다.</p> + +<p>저수준 언어에서는 메모리가 필요없어질 때를 개발자가 직접 결정하고 해제하는 방식을 사용한다. </p> + +<p>자바스크립트와 같은 고수준 언어들은 "<a href="https://en.wikipedia.org/wiki/Garbage_collection_(computer_science)">가비지 콜렉션</a>(GC)"이라는 자동 메모리 관리 방법을 사용한다. 가비지 콜렉터의 목적은 메모리 할당을 추적하고 할당된 메모리 블록이 더 이상 필요하지 않게게 되었는지를 판단하여 회수하는 것이다. 이러한 자동 메모리 관리 프로세스는 궁극의 방법은 아니다. 왜냐하면 어떤 메모리가 여전히 필요한지 아닌지를 판단하는 것은 <a class="external" href="http://en.wikipedia.org/wiki/Decidability_%28logic%29">비결정적</a> 문제이기 때문이다.</p> + +<h2 id="가비지_콜렉션">가비지 콜렉션</h2> + +<p>위에서 언급한 것처럼 "더 이상 필요하지 않은" 모든 메모리를 찾는건 비결정적 문제다. 따라서 가비지 컬렉터들은 이 문제에 대한 제한적인 해결책을 구현한다. 이 섹션에서는 주요한 가비지 컬렉션 알고리즘들과 그 한계를 이해하는데 필요한 개념을 설명한다.</p> + +<h3 id="참조">참조</h3> + +<p>가비지 콜렉션 알고리즘의 핵심 개념은 <em>참조</em>이다. A라는 메모리를 통해 (명시적이든 암시적이든) B라는 메모리에 접근할 수 있다면 "B는 A에 참조된다" 라고 한다. 예를 들어 모든 자바스크립트 오브젝트는 <a href="/en/JavaScript/Guide/Inheritance_and_the_prototype_chain" title="en/JavaScript/Guide/Inheritance_and_the_prototype_chain">prototype</a> 을 암시적으로 참조하고 그 오브젝트의 속성을 명시적으로 참조한다.</p> + +<p>앞으로 "오브젝트"라는 어휘의 의미를 넓혀서 기존의 자바스크립트 오브젝트뿐만 아니라 함수 스코프도 포괄하자.</p> + +<h3 id="참조-세기Reference-counting_가비지_콜렉션">참조-세기(Reference-counting) 가비지 콜렉션</h3> + +<p>참조-세기 알고리즘은 가장 소박한 알고리즘이다. 이 알고리즘은 "더 이상 필요없는 오브젝트"를 "어떤 다른 오브젝트도 참조하지 않는 오브젝트"라고 정의한다. 이 오브젝트를 "가비지"라 부르며, 이를 참조하는 다른 오브젝트가 하나도 없는 경우, 수집이 가능하다.</p> + +<h4 id="예제">예제</h4> + +<pre class="brush: js">var x = { + a: { + b:2 + } +}; +// 2개의 오브젝트가 생성되었다. 하나의 오브젝트는 다른 오브젝트의 속성으로 참조된다. +// 나머지 하나는 'x' 변수에 할당되었다. +// 명백하게 가비지 콜렉션 수행될 메모리는 하나도 없다. + + +var y = x; // 'y' 변수는 위의 오브젝트를 참조하는 두 번째 변수이다. +x = 1; // 이제 'y' 변수가 위의 오브젝트를 참조하는 유일한 변수가 되었다. + +var z = y.a; // 위의 오브젝트의 'a' 속성을 참조했다. + // 이제 'y.a'는 두 개의 참조를 가진다. + // 'y'가 속성으로 참조하고 'z'라는 변수가 참조한다. + +y = "yo"; // 이제 맨 처음 'y' 변수가 참조했던 오브젝트를 참조하는 오브젝트는 없다. + // (역자: 참조하는 유일한 변수였던 y에 다른 값을 대입했다) + // 이제 오브젝트에 가비지 콜렉션이 수행될 수 있을까? + // 아니다. 오브젝트의 'a' 속성이 여전히 'z' 변수에 의해 참조되므로 + // 메모리를 해제할 수 없다. + +z = null; // 'z' 변수에 다른 값을 할당했다. + // 이제 맨 처음 'x' 변수가 참조했던 오브젝트를 참조하는 + // 다른 변수는 없으므로 가비지 콜렉션이 수행된다. +</pre> + +<h4 id="한계_순환_참조">한계: 순환 참조</h4> + +<p>순환 참조를 다루는 일에는 한계가 있다. 다음 예제에서는 두 객체가 서로 참조하는 속성으로 생성되어 순환 구조를 생성한다. 함수 호출이 완료되면 이 두 객체는 스코프를 벗어나게 될 것이며, 그 시점에서 두 객체는 불필요해지므로 할당된 메모리는 회수되어야 한다. 그러나 두 객체가 서로를 참조하고 있으므로, 참조-세기 알고리즘은 둘 다 가비지 컬렉션의 대상으로 표시하지 않는다. 이러한 순환 참조는 메모리 누수의 흔한 원인이다.</p> + +<pre class="brush: js">function f(){ + var o = {}; + var o2 = {}; + o.a = o2; // o는 o2를 참조한다. + o2.a = o; // o2는 o를 참조한다. + + return "azerty"; +} + +f(); +</pre> + +<h4 id="실제_예제">실제 예제</h4> + +<p>인터넷 익스플로러 6, 7 은 DOM 오브젝트에 대해 참조-세기 알고리즘으로 가비지 콜렉션을 수행한다. 흔히, 이 두 브라우저에서는 다음과 같은 패턴의 메모리 누수가 발생한다. </p> + +<pre class="brush: js">var div = document.createElement("div"); +div.onclick = function(){ + doSomething(); +}; // div 오브젝트는 이벤트 핸들러를 'onclick' 속성을 통해 참조한다. +// 이벤트 핸들러의 스코프에도 div 오브젝트가 있으므로 div 오브젝트에 접근할 수 있다. 따라서 이벤트 핸들러도 div 오브젝트를 참조한다. +// 순환이 발생했고 메모리 누수가 일어난다. +</pre> + +<h3 id="표시하고-쓸기Mark-and-sweep_알고리즘">표시하고-쓸기(Mark-and-sweep) 알고리즘</h3> + +<p>이 알고리즘은 "더 이상 필요없는 오브젝트"를 "닿을 수 없는 오브젝트"로 정의한다.</p> + +<p>이 알고리즘은 <em>roots</em> 라는 오브젝트의 집합을 가지고 있다(자바스크립트에서는 전역 변수들을 의미한다). 주기적으로 가비지 콜렉터는 roots로 부터 시작하여 roots가 참조하는 오브젝트들, roots가 참조하는 오브젝트가 참조하는 오브젝트들... 을 <em>닿을 수 있는 오브젝트</em>라고 표시한다. 그리고 닿을 수 있는 오브젝트가 아닌 닿을 수 없는 오브젝트에 대해 가비지 콜렉션을 수행한다.</p> + +<p>이 알고리즘은 위에서 설명한 참조-세기 알고리즘보다 효율적이다. 왜냐하면 "참조되지 않는 오브젝트"는 모두 "닿을 수 없는 오브젝트" 이지만 역은 성립하지 않기 때문이다. 위에서 반례인 순환 참조하는 오브젝트들을 설명했다.</p> + +<p>2012년 기준으로 모든 최신 브라우저들은 가비지 콜렉션에서 표시하고-쓸기 알고리즘을 사용한다. 지난 몇 년간 연구된 자바스크립트 가비지 콜렉션 알고리즘의 개선들은 모두 이 알고리즘에 대한 것이다. 개선된 알고리즘도 여전히 "더 이상 필요없는 오브젝트"를 "닿을 수 없는 오브젝트"로 정의하고 있다.</p> + +<h4 id="순환_참조는_이제_문제가_되지_않는다.">순환 참조는 이제 문제가 되지 않는다.</h4> + +<p>첫 번째 예제에서 함수가 리턴되고 나서 두 오브젝트는 닿을 수 없다. 따라서 가비지 콜렉션이 일어난다.</p> + +<p>두 번째 예제에서도 마찬가지다. div 변수와 이벤트 핸들러가 roots로 부터 닿을 수 없어지면 순환 참조가 일어났음에도 불구하고 가비지 콜렉션이 일어난다. (역자2: div 선언을 블럭안에다 넣어야 된다.(테스트는 못 해봤다.))</p> + +<h4 id="한계_수동_메모리_해제.">한계: 수동 메모리 해제.</h4> + +<p>어떤 메모리를 언제 해제할지에 대해 수동으로 결정하는 것이 편리할 때가 있습니다. 그리고 수동으로 객체의 메모리를 해제하려면, 객체 메모리에 도달할 수 없도록 명시하는 기능이 있어야 합니다.<br> + <br> + 2019년 현재의 JavaScript에서는 명시적으로 또는 프로그래밍 방식으로 가비지 컬렉션을 작동할 수 없습니다.</p> + +<p>더 보기</p> + +<ul> + <li><a class="external" href="http://www.ibm.com/developerworks/web/library/wa-memleak/">IBM article on "Memory leak patterns in JavaScript" (2007)</a></li> + <li><a class="external" href="http://msdn.microsoft.com/en-us/magazine/ff728624.aspx">Kangax article on how to register event handler and avoid memory leaks (2010)</a></li> +</ul> diff --git a/files/ko/web/javascript/new_in_javascript/1.5/index.html b/files/ko/web/javascript/new_in_javascript/1.5/index.html new file mode 100644 index 0000000000..a34931d815 --- /dev/null +++ b/files/ko/web/javascript/new_in_javascript/1.5/index.html @@ -0,0 +1,37 @@ +--- +title: New in JavaScript 1.5 +slug: Web/JavaScript/New_in_JavaScript/1.5 +translation_of: Archive/Web/JavaScript/New_in_JavaScript/1.5 +--- +<div>{{jsSidebar("New_in_JS")}}</div> + +<p>다음은 JavaScript 1.5의 변경 내역입니다. 이 버전은 2000년 11월 14일에 출시된 Netscape Navigator 6.0과 그 이 후 버전 그리고 Firefox 1.0에 포함되어 있습니다. You can compare JavaScript 1.5 to JScript version 5.5 and Internet Explorer 5.5, which was released in July 2000. 해당하는 ECMA 표준은 ECMA-262 Edition 3(1999년 12월 이후) 입니디.</p> + +<h2 id="New_features_in_JavaScript_1.5">New features in JavaScript 1.5</h2> + +<ul> + <li>{{jsxref("Number.prototype.toExponential()")}}</li> + <li>{{jsxref("Number.prototype.toFixed()")}}</li> + <li>{{jsxref("Number.prototype.toPrecision()")}}</li> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/const">const</a></code> is now a <code><a href="/en-US/docs/Web/JavaScript/Reference/Reserved_Words">reserved word</a></code>.</li> + <li>Multiple catch clauses in a <a href="/en-US/docs/Web/JavaScript/Reference/Statements/try...catch"><code>try...catch</code></a> statement are supported.</li> + <li>JavaScript authors can now add getters and setters to their objects.</li> +</ul> + +<h2 id="Changed_functionality_in_JavaScript_1.5">Changed functionality in JavaScript 1.5</h2> + +<ul> + <li>Runtime errors are now reported as exceptions.</li> + <li>Regular Expression changes: + <ul> + <li>Quantifiers — +, *, ? and {} — can now be followed by a ? to force them to be non-greedy.</li> + <li>Non-capturing parentheses, (?:x) can be used instead of capturing parentheses, (x). When non-capturing parentheses are used, matched subexpressions are not available as back-references.</li> + <li>Positive and negative lookahead assertions are supported. Both assert a match depending on what follows the string being matched.</li> + <li>The m flag has been added to specify that the regular expression should match over multiple lines.</li> + </ul> + </li> + <li>Functions can now be declared inside an if clause.</li> + <li> + <p>Functions can now be declared inside an expression.</p> + </li> +</ul> diff --git a/files/ko/web/javascript/new_in_javascript/1.6/index.html b/files/ko/web/javascript/new_in_javascript/1.6/index.html new file mode 100644 index 0000000000..db92810578 --- /dev/null +++ b/files/ko/web/javascript/new_in_javascript/1.6/index.html @@ -0,0 +1,85 @@ +--- +title: New in JavaScript 1.6 +slug: Web/JavaScript/New_in_JavaScript/1.6 +tags: + - E4X + - JavaScript + - JavaScript_version_overviews +translation_of: Archive/Web/JavaScript/New_in_JavaScript/1.6 +--- +<div>{{jsSidebar("New_in_JS")}}</div> + +<p>JavaScript 1.6 여러 새 기능(E4X, 여러 새 <code>Array</code> 메소드, Array과 String generic)을 소개합니다.</p> + +<p>JavaScript 1.6은 <a href="ko/Firefox_1.5">Firefox 1.5</a>와 이후 버전에서 지원합니다.</p> + +<h3 id="E4X" name="E4X">E4X</h3> + +<p>ECMAScript for XML (<a>E4X</a>)는 <a href="ko/JavaScript">JavaScript</a> 안의 <a href="ko/XML">XML</a> 컨텐트를 만들고 처리하는 강력한 기술입니다. 우리는 기존 <a href="ko/DOM">DOM</a>과의 transparent한 통합 추가를 포함하는 E4X 지원 향상을 계속할 예정이지만 XML 기반 웹 응용프로그램을 만드는(build) 개발자는 Firefox 1.5의 E4X 지원에서 이득을 얻을 수 있습니다.</p> + +<p>아직은 E4X를 쓸 때 표준 MIME 형을 쓸 수 있습니다.</p> + +<pre><script type="text/javascript"> +</pre> + +<p>그러나, E4X 구문이 옛날 브라우저에서 그것을 숨기기 위해 HTML 주석 (<code><span class="nowiki"><!--...--></span></code>)에 스크립트를 넣는 흔한 관례(practice)와 충돌할지도 모릅니다. E4X 또한 스크립트에 기호 "<"와 ">"를 허용하는 XML CDATA 절 (<code><![CDATA{{ mediawiki.external('...') }}]></code>) 에 스크립트를 놓는 더 현대식 관례와 충돌할지도 모릅니다(이는 HTML에는 적용되지 않음을 주의하세요). 만약 설명할 수 없는 구문 에러를 보면, MIME 형에 "; e4x=1"를 보태세요.</p> + +<pre><script type="text/javascript; e4x=1"> +</pre> + +<p>확장기능의 스크립트는 항상 HTML 주석을 E4X 상수(literal)로 다룸을 주의하세요. 즉, "e4x=1"을 묵시(implicit)로 적용합니다.</p> + +<p>E4X는 <a href="ko/Core_JavaScript_1.5_Guide/Processing_XML_with_E4X">Processing XML with E4X</a>에서 설명합니다.</p> + +<h3 id="Array_.EC.B6.94.EA.B0.80.EB.B6.84" name="Array_.EC.B6.94.EA.B0.80.EB.B6.84">Array 추가분</h3> + +<p>두 갈래(item location 메소드와 iterative 메소드)로 구분할 수 있는 7가지 새 <code><a href="ko/Core_JavaScript_1.5_Reference/Objects/Array">Array</a></code> 메소드가 있습니다. item location 메소드는</p> + +<ul> + <li><code><a href="ko/Core_JavaScript_1.5_Reference/Objects/Array/indexOf">indexOf()</a></code> - 주어진 item의 맨 처음 출현(occurrence) 인덱스를 반환합니다.</li> + <li><code><a href="ko/Core_JavaScript_1.5_Reference/Objects/Array/lastIndexOf">lastIndexOf()</a></code> - 주어진 item의 맨 마지막 출현 인덱스를 반환합니다.</li> +</ul> + +<p>iterative 메소드는</p> + +<ul> + <li><code><a href="ko/Core_JavaScript_1.5_Reference/Objects/Array/every">every()</a></code> - 함수가 참을 반환하는 동안 배열의 항목들에 함수를 돌립니다. 만약 함수가 방문할 수 있는 모든 항목에 대해 참을 반환하면 참을 반환합니다.</li> + <li><code><a href="ko/Core_JavaScript_1.5_Reference/Objects/Array/filter">filter()</a></code> - 배열의 각 항목에 함수를 돌리고 함수가 참을 반환하는 모든 항목의 배열을 반환합니다.</li> + <li><code><a href="ko/Core_JavaScript_1.5_Reference/Objects/Array/forEach">forEach()</a></code> - 배열의 모든 항목에 함수를 돌립니다.</li> + <li><code><a href="ko/Core_JavaScript_1.5_Reference/Objects/Array/map">map()</a></code> - 배열의 모든 항목에 함수를 돌리고 배열에 결과를 반환합니다.</li> + <li><code><a href="ko/Core_JavaScript_1.5_Reference/Objects/Array/some">some()</a></code> - 함수가 거짓을 반환하는 동안 배열의 항목들에 함수를 돌립니다. 만약 함수가 방문할 수 있는 어떤 항목에 참을 반환하면 참을 반환합니다.</li> +</ul> + +<p>더 자세한 정보는 <a href="ko/Core_JavaScript_1.5_Guide/Working_with_Arrays#Introduced_in_JavaScript_1.6">Working with Arrays</a>나 Nicholas C. Zakas의 기사 <a class="external" href="http://www.webreference.com/programming/javascript/ncz/column4/index.html">Mozilla's New Array Methods</a>를 보세요.</p> + +<h3 id="Array.EC.99.80_String_generic" name="Array.EC.99.80_String_generic">Array와 String generic</h3> + +<p>간혹 배열 메소드를 문자열에 쓰고 싶습니다. 이리하여, 문자열을 문자 배열로 다룹니다. 예를 들어, 변수 <var>str</var>의 모든 문자(character)가 문자(letter)인지 검사하기 위해, 당신은 작성합니다.</p> + +<pre>function isLetter(character) { + return (character >= "a" && character <= "z"); +} + +if (Array.prototype.every.call(str, isLetter)) + alert("The string '" + str + "' contains only letters!"); +</pre> + +<p>이 표기(notation)는 약간 낭비라서 JavaScript 1.6은 generic 속기(shorthand)를 도입합니다.</p> + +<pre>if (Array.every(str, isLetter)) + alert("The string '" + str + "' contains only letters!"); +</pre> + +<p>비슷하게 문자열 메소드를 어느 개체든지 쉽게 적용할 수 있습니다.</p> + +<pre>var num = 15; +alert(String.replace(num, /5/, '2')); +</pre> + +<h3 id=".EA.B0.99.EC.9D.B4_.EB.B3.B4.EA.B8.B0" name=".EA.B0.99.EC.9D.B4_.EB.B3.B4.EA.B8.B0">같이 보기</h3> + +<p><a href="ko/Core_JavaScript_1.5_Guide/Working_with_Arrays#Working_with_Array-like_objects">Working with Array-like objects</a>.</p> + +<div class="noinclude"> </div> + +<p>{{ languages( { "en": "en/New_in_JavaScript_1.6", "es": "es/Novedades_en_JavaScript_1.6", "fr": "fr/Nouveaut\u00e9s_dans_JavaScript_1.6", "ja": "ja/New_in_JavaScript_1.6", "pl": "pl/Nowo\u015bci_w_JavaScript_1.6", "ru": "ru/\u041d\u043e\u0432\u043e\u0435_\u0432_JavaScript_1.6", "zh-cn": "cn/New_in_JavaScript_1.6" } ) }}</p> diff --git a/files/ko/web/javascript/new_in_javascript/1.8.1/index.html b/files/ko/web/javascript/new_in_javascript/1.8.1/index.html new file mode 100644 index 0000000000..2a50e35cf7 --- /dev/null +++ b/files/ko/web/javascript/new_in_javascript/1.8.1/index.html @@ -0,0 +1,26 @@ +--- +title: New in JavaScript 1.8.1 +slug: Web/JavaScript/New_in_JavaScript/1.8.1 +translation_of: Archive/Web/JavaScript/New_in_JavaScript/1.8.1 +--- +<div>{{jsSidebar("New_in_JS")}}</div> + +<p>다음은 JavaScript 1.8.1의 변경사항입니다. <a href="/en-US/Firefox/Releases/3.5">Firefox 3.5</a> 버전에 포함되었습니다.</p> + +<p>JavaScript 1.8.1는 약간의 문법적인 업데이트가 있습니다. 이번 릴리즈의 주요 변경사항은 <a href="/en-US/docs/SpiderMonkey/Internals/Tracing_JIT" title="SpiderMonkey/Internals/Tracing JIT">Tracemonkey just-in-time compiler</a>(성능적인 향상이 포함된 릴리즈입니다)의 추가되어있습니다</p> + +<h2 id="JavaScript_1.8.1의_새로운_특징">JavaScript 1.8.1의 새로운 특징</h2> + +<ul> + <li>{{jsxref("Object.getPrototypeOf()")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Using_native_JSON">Support for native JSON</a></li> + <li>{{jsxref("String.prototype.trim()")}}</li> + <li>{{jsxref("String.prototype.trimLeft()")}}</li> + <li>{{jsxref("String.prototype.trimRight()")}}</li> +</ul> + +<h2 id="JavaScript_1.8.1에서_변경된_기능">JavaScript 1.8.1에서 변경된 기능</h2> + +<ul> + <li>객체 및 배열 initializer에서 속성의 암시적 설정(implicit setting)은 더 이상 JavaScript에서 setter를 실행하지 않습니다. 덕분에 속성 값을 좀더 예측 가능하게 설정하는 동작이 만들어집니다.</li> +</ul> diff --git a/files/ko/web/javascript/new_in_javascript/1.8.5/index.html b/files/ko/web/javascript/new_in_javascript/1.8.5/index.html new file mode 100644 index 0000000000..27853f0531 --- /dev/null +++ b/files/ko/web/javascript/new_in_javascript/1.8.5/index.html @@ -0,0 +1,126 @@ +--- +title: New in JavaScript 1.8.5 +slug: Web/JavaScript/New_in_JavaScript/1.8.5 +tags: + - ECMAScript5 + - JavaScript + - JavaScript 1.8.5 +translation_of: Archive/Web/JavaScript/New_in_JavaScript/1.8.5 +--- +<div>{{jsSidebar("New_in_JS")}}</div> + +<p>다음은 JavaScript 1.8.5에 대한 변경기록입니다. 이 버전은 <a href="/ko/Firefox/Releases/4">Firefox 4</a>에서 포함되었습니다.</p> + +<h2 id="JavaScript_1.8.5의_새로운_기능">JavaScript 1.8.5의 새로운 기능</h2> + +<h3 id="새로운_함수">새로운 함수</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">함수</th> + <th scope="col">설명</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{jsxref("Object.create()")}}</td> + <td>지정된 프로토타입 객체 및 속성을 갖는 새로운 객체 생성. {{bug("492840")}}</td> + </tr> + <tr> + <td>{{jsxref("Object.defineProperty()")}}</td> + <td>객체에 주어진 설명자로 기술된 유명(named) 속성을 추가.</td> + </tr> + <tr> + <td>{{jsxref("Object.defineProperties()")}}</td> + <td>객체에 주어진 설명자로 기술된 유명 속성을 추가.</td> + </tr> + <tr> + <td>{{jsxref("Object.getOwnPropertyDescriptor()")}}</td> + <td>객체의 유명 속성에 대한 속성 설명자를 반환. {{bug("505587")}}</td> + </tr> + <tr> + <td>{{jsxref("Object.keys()")}}</td> + <td>객체의 모든 열거가능 속성 배열을 반환. {{bug("307791")}}</td> + </tr> + <tr> + <td>{{jsxref("Object.getOwnPropertyNames()")}}</td> + <td>객체의 모든 열거가능 및 열거불가 속성 배열을 반환. {{bug("518663")}}</td> + </tr> + <tr> + <td>{{jsxref("Object.preventExtensions()")}}</td> + <td>객체 확장을 막음. {{bug("492849")}}</td> + </tr> + <tr> + <td>{{jsxref("Object.isExtensible()")}}</td> + <td>객체 확장이 허용되는지 판단. {{bug("492849")}}</td> + </tr> + <tr> + <td>{{jsxref("Object.seal()")}}</td> + <td>다른 코드가 객체의 속성을 삭제하는 것으로부터 막음. {{bug("492845")}}</td> + </tr> + <tr> + <td>{{jsxref("Object.isSealed()")}}</td> + <td>객체가 봉인되었는지 판단. {{bug("492845")}}</td> + </tr> + <tr> + <td>{{jsxref("Object.freeze()")}}</td> + <td>객체 동결: 다른 코드가 어떤 속성도 삭제 또는 변경할 수 없음. {{bug("492844")}}</td> + </tr> + <tr> + <td>{{jsxref("Object.isFrozen()")}}</td> + <td>객체가 동결됐는지 판단. {{bug("492844")}}</td> + </tr> + <tr> + <td>{{jsxref("Array.isArray()")}}</td> + <td>변수가 배열인지 확인. {{bug("510537")}}</td> + </tr> + <tr> + <td>{{jsxref("Date.prototype.toJSON()")}}</td> + <td><code>Date</code> 객체의 JSON 형식 문자열 반환.</td> + </tr> + <tr> + <td>{{jsxref("Function.prototype.bind()")}}</td> + <td>호출될 때 그 자체가 (주어진 인수열과 함께) 주어진 문맥에서 이 함수를 호출하는 새로운 함수 생성 {{bug("429507")}}</td> + </tr> + </tbody> +</table> + +<h3 id="ECMAScript5_새로운_기능">ECMAScript5 새로운 기능</h3> + +<ul> + <li><code><a href="/ko/docs/Web/JavaScript/Reference/Operators/get">get</a></code> 및 <code><a href="/ko/docs/Web/JavaScript/Reference/Operators/set">set</a></code> 연산자는 이제 식별자가 숫자 또는 문자열이 될 수 있습니다. {{bug("520696")}}</li> + <li>{{jsxref("Function.apply()")}}는 인수 목록으로 모든 배열같은 객체를 받아들일 수 있습니다, 실제 배열만이 아니라.</li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode">엄격 모드 지원</a></li> + <li>{{jsxref("Array.toString()")}}은 이제 가능한 경우 그 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/join"><code>join()</code></a> 메서드 호출 결과를 반환 또는 그 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Object/toString"><code>toString()</code></a> 메서드를 호출하여 심지어 비배열에서도 동작합니다.</li> +</ul> + +<h3 id="다른_표준화_작업">다른 표준화 작업</h3> + +<p>getter 및 setter를 정의하는 다양한 비표준 구문이 제거되었습니다; ECMAScript 5에서 정의된 구문은 변경되지 않았습니다. 이들은 모두 꽤 난해하고 거의 쓰이지 않았습니다; 영향을 미치는 경우, 자세한 사항은 <a class="external" href="http://whereswalden.com/2010/04/16/more-spidermonkey-changes-ancient-esoteric-very-rarely-used-syntax-for-creating-getters-and-setters-is-being-removed/">이 블로그 게시글</a> 참조.</p> + +<h3 id="새로운_객체">새로운 객체</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">객체</th> + <th scope="col">설명</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{jsxref("Proxy")}}</td> + <td>JavaScript에서 메타프로그래밍을 가능케 하는 <code>Object</code> 및 <code>Function</code> 프록시 생성 지원을 제공.</td> + </tr> + </tbody> +</table> + +<h2 id="JavaScript_1.8.5에서_바뀐_기능">JavaScript 1.8.5에서 바뀐 기능</h2> + +<ul> + <li><code>Date</code> 객체 ISO 8601 지원: {{jsxref("Date")}} 객체의 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Date/parse">parse()</a> 메서드가 이제 단순한 ISO 8601 형식 date 문자열을 지원합니다.</li> + <li>Global 객체가 읽기 전용이 됨: <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/NaN"><code>NaN</code></a>, <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Infinity"><code>Infinity</code></a> 및 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/undefined"><code>undefined</code></a> global 객체는 읽기 전용이 되었습니다, ECMAScript 5 스펙에 따라.</li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Object/Parent"><code>obj.__parent__</code></a> 및 <code>obj.__count__</code>는 폐기(obsolete)되었습니다. 이유에 대한 일부 정보: <a class="external" href="http://whereswalden.com/2010/05/07/spidermonkey-change-du-jour-the-special-__parent__-property-has-been-removed/">SpiderMonkey change du jour: the special __parent__ property has been removed</a> {{bug("551529")}} & {{bug("552560")}}.</li> + <li>후행(trailing) 쉼표는 {{jsxref("JSON.parse()")}}에서 더 이상 허용되지 않습니다.</li> +</ul> diff --git a/files/ko/web/javascript/new_in_javascript/1.8/index.html b/files/ko/web/javascript/new_in_javascript/1.8/index.html new file mode 100644 index 0000000000..3372eeac27 --- /dev/null +++ b/files/ko/web/javascript/new_in_javascript/1.8/index.html @@ -0,0 +1,138 @@ +--- +title: New in JavaScript 1.8 +slug: Web/JavaScript/New_in_JavaScript/1.8 +tags: + - JavaScript + - JavaScript_version_overviews +translation_of: Archive/Web/JavaScript/New_in_JavaScript/1.8 +--- +<p>{{jsSidebar("New_in_JS")}} 자바스크립트 1.8은 (<a href="ko/Firefox_3">Firefox 3</a>에 포함될 예정인) Gecko 1.9의 일부분으로 계획되어 있습니다. 자바스크립트 1.8은 <a href="ko/New_in_JavaScript_1.7">자바스크립트 1.7</a>보다는 변경된 부분이 적습니다. 그러나, ECMAScript 4/JavaScript 2로 진행되는 과정의 몇몇 변경점이 있습니다. 이번 자바스크립트 1.8 릴리즈에는 <a href="ko/New_in_JavaScript_1.6">자바스크립트 1.6</a>과 <a href="ko/New_in_JavaScript_1.7">자바스크립트 1.7</a>에 있는 모든 부분이 포함될 것입니다.</p> + +<p>자바스크립트 1.8가 개발되어지고 있는 상황은 {{ Bug(380236) }}을 참조하십시오.</p> + +<h3 id=".EC.9E.90.EB.B0.94.EC.8A.A4.ED.81.AC.EB.A6.BD.ED.8A.B8_1.8.EC.9D.98_.EC.82.AC.EC.9A.A9" name=".EC.9E.90.EB.B0.94.EC.8A.A4.ED.81.AC.EB.A6.BD.ED.8A.B8_1.8.EC.9D.98_.EC.82.AC.EC.9A.A9">자바스크립트 1.8의 사용</h3> + +<p>HTML에서 자바스크립트 1.8의 새로운 기능 몇 가지를 사용하려면 다음과 같이 사용하십시오.</p> + +<pre class="eval"> <script type="application/javascript;version=1.8"> ... your code ... </script> +</pre> + +<p><a href="ko/Introduction_to_the_JavaScript_shell">자바스크립트 쉘</a>, 자바스크립트 XPCOM 컴포넌트, 혹은 XUL의 <code><script></code> 엘리먼트를 사용할 때에는 자동적으로 가장 마지막의 자바스크립트 버전(모질라 1.9에서는 자바스크립트 1.8)이 사용되어 집니다({{ Bug(381031) }}, {{ Bug(385159) }}).</p> + +<p>새로운 예약어 "yield"와 "let"를 사용하려면 버전을 1.8이나 그 이상으로 지정하여야 합니다. 왜냐하면 기존 코드에 변수나 함수의 이름으로 이런 키워드를 사용하고 있을 수 있기 때문입니다. (generator expressions처럼) 새로운 예약어로 소개되지 않는 것들은 자바스크립트 버전을 명시하지 않아도 사용할 수 있습니다.</p> + +<h3 id="closures_.ED.91.9C.ED.98.84" name="closures_.ED.91.9C.ED.98.84">closures 표현</h3> + +<p>추가된 closures 표현은 간단한 함수 작성을 쉽게 할 수 있는 것 뿐입니다. 문자 그대로인 <a class="external" href="http://en.wikipedia.org/wiki/Lambda_calculus#Lambda_calculus_and_programming_languages">Lambda notation</a>과 유사한 어떤 것을 자바스크립트도 가능하도록 합니다.</p> + +<p><a href="ko/New_in_JavaScript_1.7">자바스크립트 1.7</a>과 그 이전 버전:</p> + +<pre class="eval"> function(x) { return x * x; } +</pre> + +<p>자바스크립트 1.8:</p> + +<pre class="eval"> function(x) x * x +</pre> + +<p>이런 문법은 괄호를 없애고 'return' 문을 쓰지 않아도 되도록 해줍니다. - 즉, 내용을 함축적으로 만들어 줍니다. 문법이 더 짧아진다는 것 외에 코드에 이 문법을 사용하여 얻을 수 있는 추가적인 이점은 없습니다.</p> + +<p><b>예제:</b></p> + +<p>이벤트 리스너 연결:</p> + +<pre class="eval"> document.addEventListener("click", function() false, true); +</pre> + +<p><a href="ko/New_in_JavaScript_1.6">자바스크립트 1.6</a>의 배열 함수의 some을 사용하면:</p> + +<pre class="eval"> elems.some(function(elem) elem.type == "text"); +</pre> + +<h3 id="Generator_expression" name="Generator_expression">Generator expression</h3> + +<p>Generator expression은 (<a href="ko/New_in_JavaScript_1.7">자바스크립트 1.7</a>에서 소개된) generator를 간단하게 만들 수 있게 해줍니다. 문자 그대로 함수 내부에 yield를 포함한 사용자 함수를 생성할 수 있습니다. 그러나 동일한 generator 문법과 같은 것을 포함하고 있는 배열 역시 사용할 수 있습니다.</p> + +<p>This addition allows you to simply create generators (which were introduced in <a href="ko/New_in_JavaScript_1.7">JavaScript 1.7</a>). Typically you would have to create a custom function which would have a yield in it, but this addition allows you to use array comprehension-like syntax to create an identical generator statement.</p> + +<p><a href="ko/New_in_JavaScript_1.7">자바스크립트 1.7</a>에서 오브젝트로부터 사용자 generator를 만드려면 다음과 같은 코드를 작성해야 했습니다:</p> + +<pre class="eval"> function add3(obj) { + for ( let i in obj ) + yield i + 3; + } + + let it = add3(someObj); + try { + while (true) { + document.write(it.next() + "<br>\n"); + } + } catch (err if err instanceof StopIteration) { + document.write("End of record.<br>\n"); + } +</pre> + +<p>위의 코드 대신에 자바스크립트 1.8에서는 generator expression을 사용하여 순환문 안에 사용자 generator 함수를 생성하는 부분을 포함할 수 있습니다:</p> + +<pre class="eval"> let it = (i + 3 for (i in someObj)); + try { + while (true) { + document.write(it.next() + "<br>\n"); + } + } catch (err if err instanceof StopIteration) { + document.write("End of record.<br>\n"); + } +</pre> + +<p>generator 표현은 또한 값처럼 함수에 전달할 수 있습니다. generator 표현은 generator가 실행되지 않을 때부터 반드시 필요할 때까지 (배열이 맨 처음 생성되어지는 전형적인 상황과는 다르게) 특히 주목할만 합니다. 다른 예는 아래에서 볼 수 있습니다:</p> + +<p>Generator expressions can also be passed in, as values, to a function. This is particularly noteworthy since generators aren't run until they are absolutely needed (unlike for typical array comprehension situations, where the arrays are constructed ahead of time). An example of the difference can be seen here:</p> + +<p>자바스크립트 1.7 Array Comprehension 사용</p> + +<pre class="eval"> handleResults([ i for ( i in obj ) if ( i > 3 ) ]); + + function handleResults( results ) { + for ( let i in results ) + // ... + } +</pre> + +<p>자바스크립트 1.8 Generator Expressions 사용</p> + +<pre class="eval"> handleResults( i for ( i in obj ) if ( i > 3 ) ); + + function handleResults( results ) { + for ( let i in results ) + // ... + } +</pre> + +<p>두 예제에서 generator expression을 사용함으로써 중요한 다른 점은 'obj' 하나에 대해서만 반복될 것이란 것과 전체에 대해서 반복될 것이라는 점입니다. 배열에 포함되었을 때 하나에 대해서만 반복될 것에 비해 generator expression은 전체에 대해 계속 반복됩니다.</p> + +<p>The significant difference between the two examples being that by using the generator expressions, you would only have to loop over the 'obj' structure once, total, as opposed to once when comprehending the array, and again when iterating through it.</p> + +<h3 id=".EB.B0.B0.EC.97.B4.EC.97.90_.EC.B6.94.EA.B0.80.EB.90.9C_.EA.B2.83.EB.93.A4" name=".EB.B0.B0.EC.97.B4.EC.97.90_.EC.B6.94.EA.B0.80.EB.90.9C_.EA.B2.83.EB.93.A4">배열에 추가된 것들</h3> + +<p>자바스크립트 1.8에는 <code><a href="ko/Core_JavaScript_1.5_Reference/Objects/Array">Array</a></code> 객체에 배열 항목마다 반복 적용되는 두 가지 새로운 메소드가 포함되었습니다:</p> + +<ul> + <li><code><a href="ko/Core_JavaScript_1.5_Reference/Objects/Array/reduce">reduce()</a></code> - 배열의 모든 항목에 대해 함수를 실행하고, 이전 호출에서 결과값을 수집합니다.</li> + <li><code><a href="ko/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight">reduceRight()</a></code> - 배열의 모든 항목에 대해 함수를 실행하고, 이전 호출에서 결과값을 수집합니다. 결과값은 순서가 반대로 수집됩니다.</li> + <li><code><a href="ko/Core_JavaScript_1.5_Reference/Objects/Array/reduce">reduce()</a></code> - runs a function on every item in the array and collects the results from previous calls.</li> + <li><code><a href="ko/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight">reduceRight()</a></code> - runs a function on every item in the array and collects the results from previous calls, but in reverse.</li> +</ul> + +<h3 id="Changes_in_destructuring_for..in" name="Changes_in_destructuring_for..in">Changes in destructuring for..in</h3> + +<p>TBD: mention <a href="ko/New_in_JavaScript_1.7#Looping_across_objects">New_in_JavaScript_1.7#Looping_across_objects</a> ({{ Bug(366941) }}).</p> + +<h3 id=".EA.B3.A7_.EB.B3.80.EA.B2.BD.EB.90.A0_.EC.82.AC.ED.95.AD.EB.93.A4" name=".EA.B3.A7_.EB.B3.80.EA.B2.BD.EB.90.A0_.EC.82.AC.ED.95.AD.EB.93.A4">곧 변경될 사항들</h3> + +<p>자바스크립트 1.8에 포함될 수 있을 것이라 기대되는 것들:</p> + +<ul> + <li>JSON 인코딩, 디코딩.</li> + <li>Slice syntax.</li> + <li>Generalized destructuring <code>for...in</code> (does this mean something other than <a href="#Changes_in_destructuring_for..in">#Changes in destructuring for..in</a>? --<a>Nickolay</a> 10:52, 9 September 2007 (PDT))</li> +</ul> diff --git a/files/ko/web/javascript/new_in_javascript/ecmascript_5_support_in_mozilla/index.html b/files/ko/web/javascript/new_in_javascript/ecmascript_5_support_in_mozilla/index.html new file mode 100644 index 0000000000..6662aee95b --- /dev/null +++ b/files/ko/web/javascript/new_in_javascript/ecmascript_5_support_in_mozilla/index.html @@ -0,0 +1,45 @@ +--- +title: ECMAScript 5 support in Mozilla +slug: Web/JavaScript/New_in_JavaScript/ECMAScript_5_support_in_Mozilla +tags: + - ECMAScript 5 + - JavaScript + - Versions +translation_of: Archive/Web/JavaScript/New_in_JavaScript/ECMAScript_5_support_in_Mozilla +--- +<div>{{jsSidebar("New_in_JS")}}</div> + +<p>ECMAScript 5.1, 자바스크립트에 기반한, 더 오래된 표준이 2011년 6월에 허가되었습니다.</p> + +<p>파이어폭스와 썬더버드를 포함하는 모질라 프로젝트들은 ECMAScript 5.1 의 기능들을 모두 지원합니다. 이 글은 모질라의 다양한 자바스크립트 런타임 버젼에 따라, 어떤 기능들이 지원되는지를 다룹니다.</p> + +<h2 id="지원_기능"><strong><font face="x-locale-heading-primary, zillaslab, Palatino, Palatino Linotype, x-locale-heading-secondary, serif"><span style="font-size: 37.33327865600586px;">지원 기능</span></font></strong></h2> + +<h3 id="자바스크립트_1.8.5에_추가(Gecko_2_Firefox_4_and_later)">자바스크립트 1.8.5에 추가(Gecko 2, Firefox 4 and later)</h3> + +<p>파이어폭스 4는 <code>Object.*</code> 와 Strict 모드를 포함한 ECMAScript 5의 모든 기능을 지원합니다. <a href="/ko/docs/Web/JavaScript/New_in_JavaScript/1.8.5">자바스크립트 1.8.5의 새기능</a> 보기.</p> + +<h3 id="자바스크립트_1.8.1에_추가_(Gecko_1.9.1_Firefox_3.5)">자바스크립트 1.8.1에 추가 (Gecko 1.9.1, Firefox 3.5)</h3> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/JSON">네이티브 JSON </a>지원</li> + <li><a class="internal" href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf" title="En/Core JavaScript 1.5 Reference/Global Objects/Object/GetPrototypeOf"><code>Object.getPrototypeOf()</code></a> 함수.</li> + <li><a class="internal" href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim" title="En/Core JavaScript 1.5 Reference/Global Objects/String/Trim"><code>String.trim()</code></a> 문자열 양 끝의 공백을 자르는 함수.</li> + <li>Gecko 1.9.1.4 는 ECMAScript 5와 호환하기 위해 <a href="/en-US/docs/Web/JavaScript/Guide/Using_native_JSON#Converting_objects_into_JSON" title="En/Using native JSON#Converting objects into JSON"><code>JSON.stringify()</code></a> 의 구현을 업데이트 하였습니다.</li> +</ul> + +<p>ECMAScript 5 는 특정한 상황에서 XTHML을 자바스크립트 코드로 판단하는 경우를 방지하는 파싱 알고리즘을 만들어냈습니다.</p> + +<h3 id="자바스크립트_1.6에_추가_(Gecko_1.8_Firefox_1.5)">자바스크립트 1.6에 추가 (Gecko 1.8, Firefox 1.5)</h3> + +<p>새로운 <code><a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Array">배열</a></code> 함수들은, 배열을 가공하기 위해 향상된 방법들을 제공합니다. -- <a href="/ko/docs/Web/JavaScript/New_in_JavaScript/1.6">자바스크립트 1.6</a>부터 자바스크립트의 일부였던 이 것은 이제 ECMAScript 5의 표준 기능으로 자리잡았습니다.</p> + +<h2 id="같이_보기"><font face="x-locale-heading-primary, zillaslab, Palatino, Palatino Linotype, x-locale-heading-secondary, serif"><span style="font-size: 37.33327865600586px;"><strong>같이 보기</strong></span></font></h2> + +<ul> + <li><a class="external" href="http://www.ecmascript.org/" title="http://www.ecmascript.org/">ECMAScript web site</a></li> + <li><a class="external" href="http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf" title="http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf">ECMAScript 5.1 specification</a></li> + <li>John Resig's post on <a class="external" href="http://ejohn.org/blog/objectgetprototypeof/" title="http://ejohn.org/blog/objectgetprototypeof/">Object.getPrototypeOf</a></li> + <li>Michael J. Ryan's implementation of <a class="external" href="http://frugalcoder.us/post/2010/01/07/EcmaScript-5s-Date-Extensions.aspx" title="http://frugalcoder.us/post/2010/01/07/EcmaScript-5s-Date-Extensions.aspx">ECMAScript5 Dates in JavaScript</a></li> + <li><a href="http://kangax.github.io/es5-compat-table/" title="http://kangax.github.io/es5-compat-table/">ECMAScript 5 support across browsers</a></li> +</ul> diff --git a/files/ko/web/javascript/new_in_javascript/ecmascript_6_support_in_mozilla/index.html b/files/ko/web/javascript/new_in_javascript/ecmascript_6_support_in_mozilla/index.html new file mode 100644 index 0000000000..bafb603919 --- /dev/null +++ b/files/ko/web/javascript/new_in_javascript/ecmascript_6_support_in_mozilla/index.html @@ -0,0 +1,285 @@ +--- +title: ECMAScript 2015 support in Mozilla +slug: Web/JavaScript/New_in_JavaScript/ECMAScript_6_support_in_Mozilla +tags: + - ECMAScript6 + - JavaScript +translation_of: Archive/Web/JavaScript/New_in_JavaScript/ECMAScript_2015_support_in_Mozilla +--- +<div>{{jsSidebar("New_in_JS")}}</div> + +<div> +<p>ECMAScript 2015는 ECMAScript 언어의 6번째 표준 스펙(Spec)입니다. 파이어폭스와 모질라 애플리케이션에서 사용되는 <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey">SpiderMonkey</a> 엔진의 표준 자바스크립트를 정의하고 있습니다.</p> + +<p>"ES.next", "Harmony", or "ECMAScript 6" 등의 코드네임으로 불린 이 표준은 2011년 7월 12일에 "ES.next"라는 명칭으로 초안이 발표되었습니다. 2014년 8월 드디어 ECMAScript 2015 초안의 기능들이 확정되고 안정화와 버그 수정 작업에 들어갔습니다. 그리고 2015년 6월 17일, 드디어 ECMA-262 Edition 6은 ECMA 총회(General Assembly)의 공식 승인을 받아 배포되었습니다. 이 표준은 국제 산업 규격 ISO/IEC 16262:2016이기도 합니다.</p> + +<p><a href="http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf">PDF</a>와 <a href="http://www.ecma-international.org/ecma-262/6.0/index.html">HTML</a> 버전의 표준을 <a href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">ecma-international.org 에서 무료로 다운로드 할 수 있습니다</a>.</p> +</div> + +<p>ECMAScript 표준에 대한 피드백 채널은 <a href="https://mail.mozilla.org/listinfo/es-discuss">es-discuss</a>을 이용하시면 됩니다.</p> + +<h2 id="표준_라이브러리">표준 라이브러리</h2> + +<h3 id="Array_객체_추가사항"><code>Array</code> 객체 추가사항</h3> + +<ul> + <li>{{jsxref("Array")}} iteration with {{jsxref("Statements/for...of", "for...of")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/13" style='background-color: rgb(255, 255, 255); font-family: "Open Sans", arial, x-locale-body, sans-serif;'>Firefox 13</a><span style='background-color: #ffffff; color: #333333; font-family: "Open Sans",arial,x-locale-body,sans-serif;'>)</span></li> + <li>{{jsxref("Array.from()")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/32">Firefox 32</a>)</li> + <li>{{jsxref("Array.of()")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/25">Firefox 25</a>)</li> + <li>{{jsxref("Array.prototype.fill()")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/31">Firefox 31</a>)</li> + <li>{{jsxref("Array.prototype.find()")}}, {{jsxref("Array.prototype.findIndex()")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/25">Firefox 25</a>)</li> + <li>{{jsxref("Array.prototype.entries()")}},<br> + {{jsxref("Array.prototype.keys()")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/28">Firefox 28</a>),<br> + {{jsxref("Array.prototype.values()")}}</li> + <li>{{jsxref("Array.prototype.copyWithin()")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/32">Firefox 32</a>)</li> + <li>{{jsxref("Array.@@species", "get Array[@@species]")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/48">Firefox 48</a>)</li> +</ul> + +<h3 id="새로운_Map과_Set_객체_그리고_WeakMap과_WeakSet_객체">새로운 <code>Map</code>과 <code>Set</code> 객체 그리고 <code>WeakMap과</code> <code>WeakSet 객체</code></h3> + +<ul> + <li>{{jsxref("Map")}} (<a href="/en-US/Firefox/Releases/13">Firefox 13</a>) + + <ul> + <li>{{jsxref("Statements/for...of", "for...of")}}에서의 {{jsxref("Map")}} 반복 (<a href="/en-US/Firefox/Releases/17">Firefox 17</a>)</li> + <li>{{jsxref("Map.prototype.forEach()")}} (<a href="/en-US/Firefox/Releases/25">Firefox 25</a>)</li> + <li>{{jsxref("Map.prototype.entries()")}} (<a href="/en-US/Firefox/Releases/20">Firefox 20</a>)</li> + <li>{{jsxref("Map.prototype.keys()")}} (<a href="/en-US/Firefox/Releases/20">Firefox 20</a>)</li> + <li>{{jsxref("Map.prototype.values()")}}</li> + <li>생성자 인수: <code>new {{jsxref("Map")}}(null)</code> (<a href="/en-US/Firefox/Releases/37">Firefox 37</a>)</li> + <li>몽키 패치 된 생성자 내의 <code>set()</code> (<a href="/en-US/Firefox/Releases/37">Firefox 37</a>)</li> + <li>{{jsxref("Map.@@species", "get Map[@@species]")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/41">Firefox 41</a>)</li> + </ul> + </li> + <li>{{jsxref("Set")}} (<a href="/en-US/Firefox/Releases/13">Firefox 13</a>) + <ul> + <li>{{jsxref("Statements/for...of", "for...of")}}에서의 {{jsxref("Set")}} 반복 (<a href="/en-US/Firefox/Releases/17">Firefox 17</a>)</li> + <li>{{jsxref("Set.prototype.forEach()")}} (<a href="/en-US/Firefox/Releases/25">Firefox 25</a>)</li> + <li>{{jsxref("Set.prototype.entries()")}},<br> + {{jsxref("Set.prototype.keys()")}},<br> + {{jsxref("Set.prototype.values()")}} (<a href="/en-US/Firefox/Releases/24">Firefox 24</a>)</li> + <li>생성자 인수: <code>new {{jsxref("Set")}}(null)</code> (<a href="/en-US/Firefox/Releases/37">Firefox 37</a>)</li> + <li>몽키 패치 된 생성자 내의 <code>add()</code> (<a href="/en-US/Firefox/Releases/37">Firefox 37</a>)</li> + </ul> + </li> + <li>{{jsxref("WeakMap")}} (<a href="/en-US/Firefox/Releases/6">Firefox 6</a>) + <ul> + <li>{{jsxref("WeakMap.clear()")}} (<a href="/en-US/Firefox/Releases/20">Firefox 20</a>)</li> + <li>반복 가능한 {{jsxref("WeakMap")}} 생성자 내의 선택적 인수 (<a href="/en-US/Firefox/Releases/36">Firefox 36</a>)</li> + <li>생성자 인수: <code>new {{jsxref("WeakMap")}}(null)</code> (<a href="/en-US/Firefox/Releases/37">Firefox 37</a>)</li> + <li>몽키 패치 된 생성자 내의 <code>set()</code> (<a href="/en-US/Firefox/Releases/37">Firefox 37</a>)</li> + </ul> + </li> + <li>{{jsxref("WeakSet")}} (<a href="/en-US/Firefox/Releases/34">Firefox 34</a>) + <ul> + <li>생성자 인수: <code>new {{jsxref("WeakSet")}}(null)</code> (<a href="/en-US/Firefox/Releases/37">Firefox 37</a>)</li> + <li>몽키 패치 된 생성자 내의 <code>add()</code> (<a href="/en-US/Firefox/Releases/37">Firefox 37</a>)</li> + </ul> + </li> +</ul> + +<h3 id="새로운_Math_함수">새로운 <code>Math</code> 함수</h3> + +<ul> + <li>{{jsxref("Math.imul()")}} (<a href="/en-US/Firefox/Releases/20">Firefox 20</a>)</li> + <li>{{jsxref("Math.clz32()")}} (<a href="/en-US/Firefox/Releases/31">Firefox 31</a>)</li> + <li>{{jsxref("Math.fround()")}} (<a href="/en-US/Firefox/Releases/26">Firefox 26</a>)</li> + <li>{{jsxref("Math.log10()")}}, {{jsxref("Math.log2()")}}, {{jsxref("Math.log1p()")}}, {{jsxref("Math.expm1()")}}, {{jsxref("Math.cosh()")}}, {{jsxref("Math.sinh()")}}, {{jsxref("Math.tanh()")}}, {{jsxref("Math.acosh()")}}, {{jsxref("Math.asinh()")}}, {{jsxref("Math.atanh()")}}, {{jsxref("Math.hypot()")}}, {{jsxref("Math.trunc()")}}, {{jsxref("Math.sign()")}}, {{jsxref("Math.cbrt()")}} (<a href="/en-US/Firefox/Releases/25">Firefox 25</a>)</li> +</ul> + +<h3 id="Number_객체_추가사항"><code>Number</code> 객체 추가사항</h3> + +<ul> + <li>{{jsxref("Number.isNaN()")}} (<a href="/en-US/Firefox/Releases/16">Firefox 16</a>)</li> + <li>{{jsxref("Number.isFinite()")}} (<a href="/en-US/Firefox/Releases/16">Firefox 16</a>)</li> + <li>{{jsxref("Number.isInteger()")}} (<a href="/en-US/Firefox/Releases/16">Firefox 16</a>)</li> + <li>{{jsxref("Number.parseInt()")}} (<a href="/en-US/Firefox/Releases/25">Firefox 25</a>)</li> + <li>{{jsxref("Number.parseFloat()")}} (<a href="/en-US/Firefox/Releases/25">Firefox 25</a>)</li> + <li>{{jsxref("Number.EPSILON")}} (<a href="/en-US/Firefox/Releases/25">Firefox 25</a>)</li> + <li>{{jsxref("Number.MAX_SAFE_INTEGER")}}, {{jsxref("Number.MIN_SAFE_INTEGER")}} (<a href="/en-US/Firefox/Releases/31">Firefox 31</a>)</li> + <li>{{jsxref("Number.isSafeInteger()")}} (<a href="/en-US/Firefox/Releases/32">Firefox 32</a>)</li> +</ul> + +<h3 id="Object_객체_추가사항"><code>Object</code> 객체 추가사항</h3> + +<ul> + <li>{{jsxref("Object.prototype.__proto__")}}가 표준이 되었습니다.</li> + <li>{{jsxref("Object.is()")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/22">Firefox 22</a>)</li> + <li>{{jsxref("Object.setPrototypeOf()")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/31">Firefox 31</a>)</li> + <li>{{jsxref("Object.assign()")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/34">Firefox 34</a>)</li> + <li>{{jsxref("Object.getOwnPropertySymbols()")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/33">Firefox 33</a>)</li> +</ul> + + + +<h3 id="Date_객체_추가사항"><code>Date</code> 객체 추가사항</h3> + +<ul> + <li>{{jsxref("Date.prototype")}} is an ordinary object (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/41">Firefox 41</a>)</li> + <li>generic {{jsxref("Date.prototype.toString")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/41">Firefox 41</a>)</li> + <li>{{jsxref("Date.prototype.@@toPrimitive", "Date.prototype[@@toPrimitive]")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/44">Firefox 44</a>)</li> +</ul> + + + +<h3 id="새로운_Promise_객체">새로운 <code>Promise</code> 객체</h3> + +<ul> + <li>{{jsxref("Promise")}} (<a href="/en-US/Firefox/Releases/24">Firefox 24</a>(<a href="/en-US/Firefox/Releases/29">Firefox 29</a>에서 기본값으로 활성화 되어 있음))</li> +</ul> + + + +<h3 id="새로운_Proxy_객체">새로운 <code>Proxy</code> 객체</h3> + +<ul> + <li>{{jsxref("Proxy")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/18">Firefox 18</a>)</li> + <li>{{jsxref("Global_Objects/Proxy/handler/preventExtensions", "preventExtensions()")}} trap (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/22">Firefox 22</a>)</li> + <li>{{jsxref("Global_Objects/Proxy/handler/isExtensible", "isExtensible()")}} trap (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/31">Firefox 31</a>)</li> + <li>{{jsxref("Global_Objects/Proxy/handler/getPrototypeOf", "getPrototypeOf()")}} and {{jsxref("Global_Objects/Proxy/handler/setPrototypeOf", "setPrototypeOf()")}} traps (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/49">Firefox 49</a>)</li> +</ul> + + + +<h3 id="새로운_Reflect_객체">새로운 <code>Reflect</code> 객체</h3> + +<ul> + <li>{{jsxref("Reflect")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/42">Firefox 42</a>)</li> +</ul> + + + + + +<h3 id="RegExp_객체_추가사항"><code>RegExp</code> 객체 추가사항</h3> + +<ul> + <li>{{jsxref("RegExp")}} sticky (y) flag (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/38">Firefox 38</a>)</li> + <li>{{jsxref("RegExp")}} unicode (u) flag (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/46">Firefox 46</a>)</li> + <li>generic {{jsxref("RegExp.prototype.toString")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/39">Firefox 39</a>)</li> + <li>{{jsxref("RegExp.prototype.@@match()", "RegExp.prototype[@@match]()")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/49">Firefox 49</a>)</li> + <li>{{jsxref("RegExp.prototype.@@replace()", "RegExp.prototype[@@replace]()")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/49">Firefox 49</a>)</li> + <li>{{jsxref("RegExp.prototype.@@search()", "RegExp.prototype[@@search]()")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/49">Firefox 49</a>)</li> + <li>{{jsxref("RegExp.prototype.@@split()", "RegExp.prototype[@@split]()")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/49">Firefox 49</a>)</li> + <li>{{jsxref("RegExp.@@species", "get RegExp[@@species]")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/49">Firefox 49</a>)</li> +</ul> + +<h3 id="String_객체_추가사항"><code>String</code> 객체 추가사항</h3> + +<ul> + <li>{{jsxref("String.fromCodePoint()")}} (<a href="/en-US/Firefox/Releases/29">Firefox 29</a>)</li> + <li>{{jsxref("String.prototype.codePointAt()")}} (<a href="/en-US/Firefox/Releases/29">Firefox 29</a>)</li> + <li>{{jsxref("String.prototype.startsWith()")}}, {{jsxref("String.prototype.endsWith()")}} (<a href="/en-US/Firefox/Releases/17">Firefox 17</a>)</li> + <li>{{jsxref("String.prototype.includes()")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/40">Firefox 40</a>) (formerly <code>String.prototype.contains()</code> (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/17">Firefox 17</a>))</li> + <li>{{jsxref("String.prototype.repeat()")}} (<a href="/en-US/Firefox/Releases/24">Firefox 24</a>)</li> + <li>{{jsxref("String.prototype.normalize()")}} (<a href="/en-US/Firefox/Releases/31">Firefox 31</a>)</li> + <li>{{jsxref("String.raw()")}} (<a href="/en-US/Firefox/Releases/34">Firefox 34</a>)</li> + <li>{{jsxref("Global_Objects/String", "u{XXXXXX} 유니코드 코드 포인트", "", 1)}} (<a href="/en-US/Firefox/Releases/40">Firefox 40</a>)</li> +</ul> + +<h3 id="새로운_Symbol_객체">새로운 <code>Symbol</code> 객체</h3> + +<ul> + <li>{{jsxref("Symbol")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/36">Firefox 36</a>)</li> + <li>{{jsxref("Symbol.iterator")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/36">Firefox 36</a>)</li> + <li>{{jsxref("Symbol.for()")}} - global Symbol registry (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/36">Firefox 36</a>)</li> + <li>{{jsxref("Symbol.match")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/40">Firefox 40</a>)</li> + <li>{{jsxref("Symbol.species")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/41">Firefox 41</a>)</li> + <li>{{jsxref("Symbol.toPrimitive")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/44">Firefox 44</a>)</li> + <li>{{jsxref("Symbol.prototype.@@toPrimitive", "Symbol.prototype[@@toPrimitive]")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/44">Firefox 44</a>)</li> + <li>{{jsxref("Symbol.replace")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/49">Firefox 49</a>)</li> + <li>{{jsxref("Symbol.search")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/49">Firefox 49</a>)</li> + <li>{{jsxref("Symbol.split")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/49">Firefox 49</a>)</li> + <li>{{jsxref("Symbol.hasInstance")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/50">Firefox 50</a>)</li> +</ul> + +<h3 id="형식화된_배열">형식화된 배열</h3> + +<p>형식화된 배열은 ECMAScript 2015의 일부로 지정되었고, 더 이상 <a href="https://www.khronos.org/registry/typedarray/specs/latest/">자신의 기존 명세서</a>를 따르지 않습니다.</p> + +<ul> + <li>{{jsxref("ArrayBuffer")}}</li> + <li>{{jsxref("ArrayBuffer.@@species", "get ArrayBuffer[@@species]")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/48">Firefox 48</a>)</li> + <li>{{jsxref("DataView")}}</li> + <li>{{jsxref("Int8Array")}}</li> + <li>{{jsxref("Uint8Array")}}</li> + <li>{{jsxref("Uint8ClampedArray")}}</li> + <li>{{jsxref("Int16Array")}}</li> + <li>{{jsxref("Uint16Array")}}</li> + <li>{{jsxref("Int32Array")}}</li> + <li>{{jsxref("Uint32Array")}}</li> + <li>{{jsxref("Float32Array")}}</li> + <li>{{jsxref("Float64Array")}}</li> + <li>{{jsxref("TypedArray.@@species", "get %TypedArray%[@@species]")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/48">Firefox 48</a>)</li> +</ul> + +<h2 id="표현식과_연산자">표현식과 연산자</h2> + +<ul> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new.target">new.target</a> (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/41">Firefox 41</a>)</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator">배열을 위한 Spread 연산자</a> (<a href="/en-US/Firefox/Releases/16">Firefox 16</a>) + <ul> + <li><code>Symbol.iterator</code> 속성 사용 (<a href="/en-US/Firefox/Releases/36">Firefox 36</a>)</li> + </ul> + </li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator">함수 호출을 위한 Spread 연산자</a> (<a href="/en-US/Firefox/Releases/27">Firefox 27</a>) + <ul> + <li><code>Symbol.iterator</code> 속성 사용 (<a href="/en-US/Firefox/Releases/36">Firefox 36</a>)</li> + </ul> + </li> + <li>{{jsxref("Statements/const", "const")}} (<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/1.5">JS 1.5</a>, Firefox 1.0) (ES2015 compliance {{bug("950547")}} implemented in Firefox 51)</li> + <li>{{jsxref("Statements/let", "let")}} (<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/1.7">JS 1.7</a>, <a href="https://developer.mozilla.org/en-US/Firefox/Releases/2">Firefox 2</a>) (ES2015 compliance {{bug("950547")}} implemented in Firefox 51)</li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">Destructuring assignment</a> (<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/1.7">JS 1.7</a>, <a href="https://developer.mozilla.org/en-US/Firefox/Releases/2">Firefox 2</a>) (ES2015 compliance {{bug("1055984")}})</li> +</ul> + +<h2 id="문문장">문(문장)</h2> + +<ul> + <li>{{jsxref("Statements/for...of", "for...of")}}(<a href="/en-US/Firefox/Releases/13">Firefox 13</a>) + + <ul> + <li><code>.iterator()</code>와 <code>.next()</code>에 관한 동작 (<a href="/en-US/Firefox/Releases/17">Firefox 17</a>)</li> + <li><code>"@@iterator"</code> 속성 사용 (<a href="/en-US/Firefox/Releases/27">Firefox 27</a>)</li> + <li><code>Symbol.iterator</code> 속성 사용 (<a href="/en-US/Firefox/Releases/36">Firefox 36</a>)</li> + </ul> + </li> +</ul> + +<h2 id="함수">함수</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/rest_parameters">Rest 매개 변수</a> (<a href="/en-US/Firefox/Releases/15">Firefox 15</a>)</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/default_parameters">Default 매개 변수</a> (<a href="/en-US/Firefox/Releases/15">Firefox 15</a>) + <ul> + <li>Parameters without defaults after default parameters (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/26">Firefox 26</a>)</li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters#Destructured_parameter_with_default_value_assignment" title="Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.">Destructured parameters with default value assignment</a> (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/41">Firefox 41</a>)</li> + </ul> + </li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/arrow_functions">Arrow 함수</a> (<a href="/en-US/Firefox/Releases/22">Firefox 22</a>)</li> + <li>{{jsxref("Statements/function*", "Generator 함수")}} (<a href="/en-US/Firefox/Releases/26">Firefox 26</a>) + <ul> + <li>{{jsxref("Operators/yield", "yield")}} (<a href="/en-US/Firefox/Releases/26">Firefox 26</a>)</li> + <li>{{jsxref("Operators/yield*", "yield*")}} (<a href="/en-US/Firefox/Releases/27">Firefox 27</a>)</li> + </ul> + </li> + <li>{{jsxref("Functions/arguments/@@iterator", "arguments[@@iterator]")}} (<a href="https://developer.mozilla.org/en-US/Firefox/Releases/46">Firefox 46</a>)</li> +</ul> + +<h2 id="그_밖의_기능">그 밖의 기능</h2> + +<ul> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Numeric_literals">2진과 8진 숫자 리터럴</a> (<a href="/en-US/Firefox/Releases/25">Firefox 25</a>)</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/template_strings">템플릿 문자열</a> (<a href="/en-US/Firefox/Releases/34">Firefox 34</a>)</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Property_definitions">객체 이니셜라이져: 줄임 속성 이름</a> (<a href="/en-US/Firefox/Releases/33">Firefox 33</a>)</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names">객체 이니셜라이저: 계산된 속성 이름</a> (<a href="/en-US/Firefox/Releases/34">Firefox 34</a>)</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Method_definitions">객체 이니셜라이저: 줄임 메소드 이름</a> (<a href="/en-US/Firefox/Releases/34">Firefox 34</a>)</li> +</ul> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="http://www.ecmascript.org/">ECMAScript 웹 사이트</a></li> + <li><a href="http://wiki.ecmascript.org/doku.php?id=harmony:specification_drafts">ECMAScript 2015 명세서 초안</a></li> + <li><a href="https://bugzilla.mozilla.org/show_bug.cgi?id=694100">Mozilla ES2015 버그 추적</a></li> + <li><a href="http://kangax.github.io/es5-compat-table/es6" title="http://kangax.github.io/es5-compat-table">브라우저에서의 ECMAScript 2015 지원</a></li> +</ul> diff --git a/files/ko/web/javascript/new_in_javascript/index.html b/files/ko/web/javascript/new_in_javascript/index.html new file mode 100644 index 0000000000..0972eba4d0 --- /dev/null +++ b/files/ko/web/javascript/new_in_javascript/index.html @@ -0,0 +1,71 @@ +--- +title: New in JavaScript +slug: Web/JavaScript/New_in_JavaScript +tags: + - JavaScript + - Versions +translation_of: Archive/Web/JavaScript/New_in_JavaScript +--- +<div>{{jsSidebar("New_in_JS")}}</div> + +<p>이 장은 JavaScript 버전 이력에 관한 정보 및 Mozilla/SpiderMonkey 기반 JavaScript 애플리케이션, 가령 Firefox의 구현 상태를 포함합니다.</p> + +<h2 id="ECMAScript_버전">ECMAScript 버전</h2> + +<dl> + <dt><a href="/ko/docs/Web/JavaScript/언어_리소스">언어 리소스</a></dt> + <dd>JavaScript 언어의 기반이 된 ECMAScript 표준에 대해 자세히 알아보세요.</dd> + <dt><a href="/ko/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_5_support_in_Mozilla">ECMAScript 5 지원</a></dt> + <dd>Mozilla 기반 엔진 및 제품에서 현재 표준 ECMA-262 Edition 5.1의 구현 상태.</dd> + <dt><a href="/ko/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_6_support_in_Mozilla">ECMAScript 6 지원</a></dt> + <dd>Mozilla 기반 엔진 및 제품에서 초안 ECMA-262 Edition 6 (ES2015/ES6)의 구현 상태.</dd> + <dt><a href="/ko/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_7_support_in_Mozilla">ECMAScript Next 지원</a></dt> + <dd>Mozilla 기반 엔진 및 제품에서 연간 (ES2016/ES2017/ES2018/...) 출시 계획에 따라 예정된 ECMA-262 기능의 구현 상태.</dd> +</dl> + +<h2 id="JavaScript_출시_기록">JavaScript 출시 기록</h2> + +<dl> + <dt><a href="/ko/docs/Web/JavaScript/New_in_JavaScript/Firefox_JavaScript_changelog">Firefox JavaScript changelog</a></dt> + <dd>Firefox 5 이상에서 구현된 JavaScript 기능은 이 changelog 참조.</dd> +</dl> + +<h2 id="JavaScript_버전">JavaScript 버전</h2> + +<p><strong>사라짐</strong> ({{deprecated_inline}}). 명백한 버전 관리 및 언어 기능의 채택은 Mozilla 전용이었고 <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=867609">제거되는 과정에 있습니다</a>. Firefox 4는 JavaScript 버전 (1.8.5)에 참조되었던 마지막 버전이었습니다. 새로운 ECMA 표준이 있다면, JavaScript 언어 기능은 이제 종종 ECMA-262 Edition 가령 Edition 6 (ES2015/ES6) 내 그들의 초기 정의에 언급됩니다.</p> + +<p>JavaScript는 Netscape Navigator 2.0 및 Internet Explorer 2.0에서 March 1996에 버전 1.0으로 출시되었습니다.</p> + +<dl> + <dt><a href="/ko/docs/Web/JavaScript/New_in_JavaScript/1.1">JavaScript 1.1</a></dt> + <dd>Netscape Navigator 3.0에 실린 버전. August 19, 1996에 출시됨.</dd> + <dt><a href="/ko/docs/Web/JavaScript/New_in_JavaScript/1.2">JavaScript 1.2</a></dt> + <dd>Netscape Navigator 4.0-4.05에 실린 버전. June 11, 1997에 출시됨.</dd> + <dt><a href="/ko/docs/Web/JavaScript/New_in_JavaScript/1.3">JavaScript 1.3</a></dt> + <dd>Netscape Navigator 4.06-4.7x에 실린 버전. October 19, 1998에 출시됨.<br> + ECMA-262 1st 및 2nd Edition을 따르는 표준화 작업.</dd> + <dt><a href="/ko/docs/Web/JavaScript/New_in_JavaScript/1.4">JavaScript 1.4</a></dt> + <dd>Netscape의 서버측 JavaScript에 실린 버전. 1999에 출시됨.</dd> + <dt><a href="/ko/docs/Web/JavaScript/New_in_JavaScript/1.5">JavaScript 1.5</a></dt> + <dd>Netscape Navigator 6.0 및 Firefox 1.0에 실린 버전. November 14, 2000에 출시됨.<br> + ECMA-262 3rd Edition을 따르는 표준화 작업.</dd> + <dt><a href="/ko/docs/Web/JavaScript/New_in_JavaScript/1.6">JavaScript 1.6</a></dt> + <dd>Firefox 1.5에 실린 버전. November 2005에 출시됨.<br> + ECMAScript for XML (E4X), 새로운 <code>Array</code> 메서드 더하기 <code>String</code> 및 <code>Array</code> generics 포함.</dd> + <dt><a href="/ko/docs/Web/JavaScript/New_in_JavaScript/1.7">JavaScript 1.7</a></dt> + <dd>Firefox 2에 실린 버전. October 2006에 출시됨.<br> + 생성기, 반복기, 배열 내포(comprehension), <code>let</code> 식 및 해체 할당 포함.</dd> + <dt><a href="/ko/docs/Web/JavaScript/New_in_JavaScript/1.8">JavaScript 1.8</a></dt> + <dd>Firefox 3에 실린 버전. June 2008에 출시됨.<br> + 식 클로저, 생성기 식 및 <code>Array.reduce()</code> 포함</dd> + <dt><a href="/ko/docs/Web/JavaScript/New_in_JavaScript/1.8.1">JavaScript 1.8.1</a></dt> + <dd>Firefox 3.5에 실린 버전. June 30, 2009에 출시됨.<br> + TraceMonkey JIT 포함 및 native JSON 지원.</dd> + <dt>JavaScript 1.8.2</dt> + <dd>Firefox 3.6에 실린 버전. June 22, 2009에 출시됨.<br> + minor changes만 포함.</dd> + <dt><a href="/ko/docs/Web/JavaScript/New_in_JavaScript/1.8.5">JavaScript 1.8.5</a></dt> + <dd>Firefox 4에 실린 버전. July 27, 2010에 출시됨.<br> + ECMA-262 Edition 5를 따르는 많은 새 기능 포함.<br> + 이게 마지막 JavaScript 버전입니다.</dd> +</dl> diff --git a/files/ko/web/javascript/reference/about/index.html b/files/ko/web/javascript/reference/about/index.html new file mode 100644 index 0000000000..f558451826 --- /dev/null +++ b/files/ko/web/javascript/reference/about/index.html @@ -0,0 +1,51 @@ +--- +title: 소개 +slug: Web/JavaScript/Reference/About +translation_of: Web/JavaScript/Reference/About +--- +<p>{{JsSidebar}}<br> + The JavaScript reference serves as a repository of facts about the JavaScript language. The entire language is described here in detail. As you write JavaScript code, you'll refer to these pages often (thus the title "JavaScript reference"). If you're learning JavaScript, or need help understanding some of its capabilities or features, check out the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide">JavaScript guide</a>.</p> + +<p>The JavaScript language is intended to be used within some larger environment, be it a browser, server-side scripts, or similar. For the most part, this reference attempts to be environment-agnostic and does not target a web browser environment.</p> + +<h2 id="Where_to_find_JavaScript_information">Where to find JavaScript information</h2> + +<p>JavaScript documentation of core language features (pure <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Language_Resources">ECMAScript</a>, for the most part) includes the following:</p> + +<ul> + <li>The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide">JavaScript guide</a></li> + <li>The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference">JavaScript reference</a></li> +</ul> + +<p>If you are new to JavaScript, start with the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide">guide</a>. Once you have a firm grasp of the fundamentals, you can use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference">reference</a> to get more details on individual objects and language constructs.</p> + +<h2 id="Structure_of_the_reference">Structure of the reference</h2> + +<p>In the JavaScript reference you can find the following chapters:</p> + +<dl> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects">Standard built-in objects</a></dt> + <dd>This chapter documents all the JavaScript standard built-in objects, along with their methods and properties.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements">Statements and declarations</a></dt> + <dd>JavaScript applications consist of statements with an appropriate syntax. A single statement may span multiple lines. Multiple statements may occur on a single line if each statement is separated by a semicolon. This isn't a keyword, but a group of keywords.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators">Expressions and operators</a></dt> + <dd>This chapter documents all the JavaScript language operators, expressions and keywords.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions">Functions</a></dt> + <dd>Chapter about JavaScript functions.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes">Classes</a></dt> + <dd>Chapter about JavaScript classes introduced in ECMAScript 2015.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors">Errors</a></dt> + <dd>Chapter about specific errors, exceptions and warnings thrown by JavaScript.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript">New in JavaScript</a></dt> + <dd>Chapter about JavaScript version history.</dd> +</dl> + +<h3 id="More_reference_pages">More reference pages</h3> + +<ul> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features">Deprecated and obsolete features</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar">Lexical grammar</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures">Data types and data structures</a></li> +</ul> + +<p> </p> diff --git a/files/ko/web/javascript/reference/classes/class_fields/index.html b/files/ko/web/javascript/reference/classes/class_fields/index.html new file mode 100644 index 0000000000..959c65fada --- /dev/null +++ b/files/ko/web/javascript/reference/classes/class_fields/index.html @@ -0,0 +1,396 @@ +--- +title: Class fields +slug: Web/JavaScript/Reference/Classes/Class_fields +translation_of: Web/JavaScript/Reference/Classes/Public_class_fields +--- +<div>{{JsSidebar("Classes")}}</div> + +<div class="note"> +<p><strong>This page describes experimental features.</strong></p> + +<p>Both Public and private field declarations are an <a href="https://github.com/tc39/proposal-class-fields">experimental feature (stage 3)</a> proposed at <a href="https://tc39.github.io/beta/">TC39</a>, the JavaScript standards committee.</p> + +<p>Support in browsers is limited, but the feature can be used through a build step with systems like <a href="https://babeljs.io/">Babel</a>. See the <a href="#Browser_compatibility">compat information</a> below.</p> +</div> + +<h2 id="Public_fields">Public fields</h2> + +<p>static fields와 instance의 public fields 는 둘 다 writable, enumerable, configurable 한 프로퍼티들이다. 예를들면, 정 반대인 private 과는 다르게, unlike their private counterparts, static fields는 프로토타입 상속에 관여한다.</p> + +<h3 id="Public_static_fields">Public static fields</h3> + +<p>Public static fields 는 클래스에서 생성하는 모든 인스턴스에 대한 필드가 아닌, 클래스마다 단 한개의 필드가 존재하기를 원할 때 유용하게 사용할 수 있다. Public fields는 캐시, 고정된 설정값, 또는 인스턴스 간 복제할 필요가 없는 어떤 데이터 등에 유용하게 쓰일 수 있다.</p> + +<p>Public static fields are declared using the <code>static</code> keyword. They are added to the class constructor at the time of class evaluation using {{jsxref("Global_Objects/Object/defineProperty", "Object.defineProperty()")}}. They are accessed again from the class constructor.</p> + +<pre class="brush: js">class ClassWithStaticField { + static staticField = 'static field' +} + +console.log(ClassWithStaticField.staticField) +// expected output: "static field" +</pre> + +<p>Fields without initializers are initialized to <code>undefined</code>.</p> + +<pre class="brush: js">class ClassWithStaticField { + static staticField +} + +console.assert(ClassWithStaticField.hasOwnProperty('staticField')) +console.log(ClassWithStaticField.staticField) +// expected output: "undefined"</pre> + +<p>Public static fields are not reinitialized on subclasses, but can be accessed via the prototype chain.</p> + +<pre class="brush: js">class ClassWithStaticField { + static baseStaticField = 'base field' +} + +class SubClassWithStaticField extends ClassWithStaticField { + static subStaticField = 'sub class field' +} + +console.log(SubClassWithStaticField.subStaticField) +// expected output: "sub class field" + +console.log(SubClassWithStaticField.baseStaticField) +// expected output: "base field"</pre> + +<p>When initializing fields, <code>this</code> refers to the class constructor. You can also reference it by name, and use <code>super</code> to get the superclass constructor (if one exists).</p> + +<pre class="brush: js">class ClassWithStaticField { + static baseStaticField = 'base static field' + static anotherBaseStaticField = this.baseStaticField + + static baseStaticMethod() { return 'base static method output' } +} + +class SubClassWithStaticField extends ClassWithStaticField { + static subStaticField = super.baseStaticMethod() +} + +console.log(ClassWithStaticField.anotherBaseStaticField) +// expected output: "base static field" + +console.log(SubClassWithStaticField.subStaticField) +// expected output: "base static method output" +</pre> + +<h3 id="Public_instance_fields">Public instance fields</h3> + +<p>Public instance fields exist on every created instance of a class. By declaring a public field, you can ensure the field is always present, and the class definition is more self-documenting.</p> + +<p>Public instance fields are added with {{jsxref("Global_Objects/Object/defineProperty", "Object.defineProperty()")}} either at construction time in the base class (before the constructor body runs), or just after <code>super()</code> returns in a subclass.</p> + +<pre class="brush: js">class ClassWithInstanceField { + instanceField = 'instance field' +} + +const instance = new ClassWithInstanceField() +console.log(instance.instanceField) +// expected output: "instance field"</pre> + +<p>Fields without initializers are initialized to <code>undefined</code>.</p> + +<pre class="brush: js">class ClassWithInstanceField { + instanceField +} + +const instance = new ClassWithInstanceField() +console.assert(instance.hasOwnProperty('instanceField')) +console.log(instance.instanceField) +// expected output: "undefined"</pre> + +<p>Like properties, field names may be computed.</p> + +<pre class="brush: js">const PREFIX = 'prefix' + +class ClassWithComputedFieldName { + [`${PREFIX}Field`] = 'prefixed field' +} + +const instance = new ClassWithComputedFieldName() +console.log(instance.prefixField) +// expected output: "prefixed field"</pre> + +<p>When initializing fields <code>this</code> refers to the class instance under construction. Just as in public instance methods, if you're in a subclass you can access the superclass prototype using <code>super</code>.</p> + +<pre class="brush: js">class ClassWithInstanceField { + baseInstanceField = 'base field' + anotherBaseInstanceField = this.baseInstanceField + baseInstanceMethod() { return 'base method output' } +} + +class SubClassWithInstanceField extends ClassWithInstanceField { + subInstanceField = super.baseInstanceMethod() +} + +const base = new ClassWithInstanceField() +const sub = new SubClassWithInstanceField() + +console.log(base.anotherBaseInstanceField) +// expected output: "base field" + +console.log(sub.subInstanceField) +// expected output: "base method output"</pre> + +<h2 id="Public_methods">Public methods</h2> + +<h3 id="Public_static_methods">Public static methods</h3> + +<p>The <code><strong>static</strong></code> keyword defines a static method for a class. Static methods aren't called on instances of the class. Instead, they're called on the class itself. These are often utility functions, such as functions to create or clone objects.</p> + +<p>{{EmbedInteractiveExample("pages/js/classes-static.html")}}</p> + +<div class="hidden"> +<p>The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p> +</div> + +<p>The static methods are added to the class constructor with {{jsxref("Global_Objects/Object/defineProperty", "Object.defineProperty()")}} at class evaluation time. These methods are writable, non-enumerable, and configurable.</p> + +<h3 id="Public_instance_methods">Public instance methods</h3> + +<p>As the name implies, public instance methods are methods available on class instances.</p> + +<pre class="brush: js">class ClassWithPublicInstanceMethod { + publicMethod() { + return 'hello world' + } +} + +const instance = new ClassWithPublicInstanceMethod() +console.log(instance.publicMethod()) +// expected output: "hello world"</pre> + +<p>Public instance methods are added to the class prototype at the time of class evaluation using {{jsxref("Global_Objects/Object/defineProperty", "Object.defineProperty()")}}. They are writable, non-enumerable, and configurable.</p> + +<p>You may make use of generator, async, and async generator functions.</p> + +<pre class="brush: js">class ClassWithFancyMethods { + *generatorMethod() { } + async asyncMethod() { } + async *asyncGeneratorMethod() { } +}</pre> + +<p>Inside instance methods, <code>this</code> refers to the instance itself. In subclasses, <code>super</code> lets you access the superclass prototype, allowing you to call methods from the superclass.</p> + +<pre class="brush: js">class BaseClass { + msg = 'hello world' + basePublicMethod() { + return this.msg + } +} + +class SubClass extends BaseClass { + subPublicMethod() { + return super.basePublicMethod() + } +} + +const instance = new SubClass() +console.log(instance.subPublicMethod()) +// expected output: "hello world" +</pre> + +<p>Getters and setters are special methods that bind to a class property and are called when that property is accessed or set. Use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get">get</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set">set</a> syntax to declare a public instance getter or setter.</p> + +<pre class="brush: js">class ClassWithGetSet { + #msg = 'hello world' + get msg() { + return this.#msg + } + set msg(x) { + this.#msg = `hello ${x}` + } +} + +const instance = new ClassWithGetSet() +console.log(instance.msg) +// expected output: "hello world" + +instance.msg = 'cake' +console.log(instance.msg) +// expected output: "hello cake" +</pre> + +<h2 id="Private_fields">Private fields</h2> + +<h3 id="Private_static_fields">Private static fields </h3> + +<p>Private fields are accessible on the class constructor from inside the class declaration itself.</p> + +<p>The limitation of static variables being called by only static methods still holds. </p> + +<pre class="brush: js">class ClassWithPrivateStaticField { + static #PRIVATE_STATIC_FIELD + + static publicStaticMethod() { + ClassWithPrivateStaticField.#PRIVATE_STATIC_FIELD = 42 + return ClassWithPrivateStaticField.#PRIVATE_STATIC_FIELD + } +} + +assert(ClassWithPrivateStaticField.publicStaticMethod() === 42)</pre> + +<p>Private static fields are added to the class constructor at class evaluation time.</p> + +<p>There is a provenance restriction on private static fields. Only the class which defines the private static field can access the field.</p> + +<p>This can lead to unexpected behaviour when using <strong><code>this</code></strong>.</p> + +<pre class="brush: js">class BaseClassWithPrivateStaticField { + static #PRIVATE_STATIC_FIELD + + static basePublicStaticMethod() { + this.#PRIVATE_STATIC_FIELD = 42 + return this.#PRIVATE_STATIC_FIELD + } +} + +class SubClass extends BaseClassWithPrivateStaticField { } + +assertThrows(() => SubClass.basePublicStaticMethod(), TypeError) +</pre> + +<h3 id="Private_instance_fields">Private instance fields</h3> + +<p>Private instance fields are declared with <strong># names </strong>(pronounced "<em>hash names</em>"), which are identifiers prefixed with <code>#</code>. The <code>#</code> is a part of the name itself. It is used for declaration and accessing as well.</p> + +<p>The encapsulation is enforced by the language. It is a syntax error to refer to <code>#</code> names from out of scope.</p> + +<pre class="brush: js">class ClassWithPrivateField { + #privateField + + constructor() { + this.#privateField = 42 + this.#randomField = 666 // Syntax error + } +} + +const instance = new ClassWithPrivateField() +instance.#privateField === 42 // Syntax error +</pre> + +<h2 id="Private_Methods">Private Methods</h2> + +<h3 id="Private_static_methods">Private static methods</h3> + +<p>Like their public equivalent, private static methods are called on the class itself, not instances of the class. Like private static fields, they are only accessible from inside the class declaration.</p> + +<p>Private static methods may be generator, async, and async generator functions.</p> + +<pre class="brush: js">class ClassWithPrivateStaticMethod { + static #privateStaticMethod() { + return 42 + } + + static publicStaticMethod1() { + return ClassWithPrivateStaticMethod.#privateStaticMethod(); + } + + static publicStaticMethod2() { + return this.#privateStaticMethod(); + } +} + +assert(ClassWithPrivateStaticField.publicStaticMethod1() === 42); +assert(ClassWithPrivateStaticField.publicStaticMethod2() === 42); +</pre> + +<p>This can lead to unexpected behaviour when using <strong><code>this</code></strong>(because <code>this</code> binding rule applies).</p> + +<pre class="brush: js">class Base { + static #privateStaticMethod() { + return 42; + } + static publicStaticMethod1() { + return Base.#privateStaticMethod(); + } + static publicStaticMethod2() { + return this.#privateStaticMethod(); + } +} + +class Derived extends Base {} + +console.log(Derived.publicStaticMethod1()); // 42 +console.log(Derived.publicStaticMethod2()); // TypeError +</pre> + +<h3 id="Private_instance_methods">Private instance methods</h3> + +<p>Private instance methods are methods available on class instances whose access is restricted in the same manner as private instance fields.</p> + +<pre class="brush: js">class ClassWithPrivateMethod { + #privateMethod() { + return 'hello world' + } + + getPrivateMessage() { + return this.#privateMethod() + } +} + +const instance = new ClassWithPrivateMethod() +console.log(instance.getPrivateMessage()) +// expected output: "hello world"</pre> + +<p>Private instance methods may be generator, async, or async generator functions. Private getters and setters are also possible:</p> + +<pre class="brush: js">class ClassWithPrivateAccessor { + #message + + get #decoratedMessage() { + return `✨${this.#message}✨` + } + set #decoratedMessage(msg) { + this.#message = msg + } + + constructor() { + this.#decoratedMessage = 'hello world' + console.log(this.#decoratedMessage) + } +} + +new ClassWithPrivateAccessor(); +// expected output: "✨hello world✨" +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td><a href="https://tc39.es/proposal-class-fields/#prod-FieldDefinition">FieldDefinition production</a></td> + <td>Stage 3</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<h3 id="Public_class_fields">Public class fields</h3> + + + +<p>{{Compat("javascript.classes.public_class_fields")}}</p> + +<h3 id="Private_class_fields">Private class fields</h3> + +<div class="hidden">The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</div> + +<p>{{Compat("javascript.classes.private_class_fields")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="https://rfrn.org/~shu/2018/05/02/the-semantics-of-all-js-class-elements.html">The Semantics of All JS Class Elements</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/classes/constructor/index.html b/files/ko/web/javascript/reference/classes/constructor/index.html new file mode 100644 index 0000000000..f07dbd43b9 --- /dev/null +++ b/files/ko/web/javascript/reference/classes/constructor/index.html @@ -0,0 +1,128 @@ +--- +title: constructor +slug: Web/JavaScript/Reference/Classes/constructor +tags: + - Classes + - ECMAScript 2015 + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Classes/constructor +--- +<div>{{jsSidebar("Classes")}}</div> + +<p><strong><code>constructor</code></strong> 메서드는 {{jsxref("Statements/class", "class")}} 내에서 객체를 생성하고 초기화하기 위한 특별한 메서드입니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/classes-constructor.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">constructor([<em>arguments</em>]) { ... } +</pre> + +<h2 id="설명">설명</h2> + +<p>클래스는 <code>constructor</code>라는 이름을 가진 특별한 메서드를 하나씩만 가질 수 있습니다. 두 개 이상의 <code>constructor</code> 메서드는 {{jsxref("SyntaxError")}}를 유발합니다.</p> + +<p>생성자 메서드는 {{jsxref("Operators/super", "super")}} 키워드를 사용하여 상위 클래스의 생성자 메서드를 호출할 수 있습니다.</p> + +<p>생성자 메서드를 지정하지 않은 경우엔 기본 생성자 메서드를 사용합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="constructor_메서드_사용하기"><code>constructor</code> 메서드 사용하기</h3> + +<pre class="brush: js">class Square extends Polygon { + constructor(length) { + // length로 다각형의 넓이와 높이를 정의하기 위해 부모클래스의 생성자를 호출합니다. + super(length, length); + // Note: 파생 클래스에서, 'this'를 사용하기 전에는 반드시 super()를 + // 호출하여야 합니다. 그렇지 않을 경우 참조에러가 발생합니다. + this.name = 'Square'; + } + + get area() { + return this.height * this.width; + } + + set area(value) { + this.area = value; + } +}</pre> + +<h3 id="다른예제">다른예제</h3> + +<pre class="brush: js">class Polygon { + constructor() { + this.name = "Polygon"; + } +} + +class Square extends Polygon { + constructor() { + super(); + } +} + +class Rectangle {} + +Object.setPrototypeOf(Square.prototype, Rectangle.prototype); + +console.log(Object.getPrototypeOf(Square.prototype) === Polygon.prototype); //false +console.log(Object.getPrototypeOf(Square.prototype) === Rectangle.prototype); //true + +let newInstance = new Square(); +console.log(newInstance.name); //Polygon</pre> + +<p>여기서 <strong>Square</strong> 클래스의 프로토 타입이 변경되었지만 사각형의 새 인스턴스가 만들어 질 때 이전 기본 클래스 인 <strong>Polygon</strong>의 생성자가 호출됩니다.</p> + +<h3 id="기본_생성자">기본 생성자</h3> + +<p>만약 생성자를 지정하지 않을 경우 기본 생성자 메서드를 사용합니다. 기본 클래스(즉, 아무것도 상속하지 않는 클래스)의 기본 생성자 메서드는 다음과 같습니다.</p> + +<pre class="brush: js">constructor() {} +</pre> + +<p>파생 클래스의 경우, 기본 생성자는 다음과 같습니다.</p> + +<pre class="brush: js">constructor(...args) { + super(...args); +}</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-static-semantics-constructormethod', 'Constructor Method')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-static-semantics-constructormethod', 'Constructor Method')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.classes.constructor")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Operators/super", "super")}}</li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Operators/class"><code>class</code> 표현식</a></li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Statements/class"><code>class</code> 선언문</a></li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Classes">클래스</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/classes/extends/index.html b/files/ko/web/javascript/reference/classes/extends/index.html new file mode 100644 index 0000000000..e1ae2eac31 --- /dev/null +++ b/files/ko/web/javascript/reference/classes/extends/index.html @@ -0,0 +1,112 @@ +--- +title: extends +slug: Web/JavaScript/Reference/Classes/extends +tags: + - Classes + - ECMAScript6 + - JavaScript +translation_of: Web/JavaScript/Reference/Classes/extends +--- +<div>{{jsSidebar("Classes")}}</div> + +<p><strong><code>extends</code></strong> 키워드는 클래스를 다른 클래스의 자식으로 만들기 위해 <a href="/ko/docs/Web/JavaScript/Reference/Statements/class" title="class declarations">class 선언</a> 또는 <a href="/ko/docs/Web/JavaScript/Reference/Operators/class" title="class expressions">class 식</a>에 사용됩니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/classes-extends.html", "taller")}}</p> + +<div class="hidden"> +<p>The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p> +</div> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">class ChildClass extends ParentClass { ... }</pre> + +<h2 id="설명">설명</h2> + +<p><code>extends</code> 키워드는 내장 객체뿐만 아니라 사용자 정의 클래스를 하위 클래스로 만들기 위해 사용될 수 있습니다.</p> + +<p>확장( 클래스)의 <code>.prototype</code>은 {{jsxref("Object")}} 또는 {{jsxref("null")}}이어야 합니다.</p> + +<h2 id="예">예</h2> + +<h3 id="extends_사용하기"><code>extends</code> 사용하기</h3> + +<p>첫 번째 예는 <code>Polygon</code> 클래스로부터 <code>Square</code> 클래스를 만듭니다. 이 예는 <a href="https://googlechrome.github.io/samples/classes-es6/index.html">live demo</a> <a href="https://github.com/GoogleChrome/samples/blob/gh-pages/classes-es6/index.html">(source)</a>에서 발췌했습니다.</p> + +<pre class="brush: js">class Square extends Polygon { + constructor(length) { + // 여기서, length와 함께 부모 클래스의 생성자를 호출 + // Polygon의 너비 및 높이가 제공됨 + super(length, length); + // 주의: 파생 클래스에서, super()가 먼저 호출되어야 'this'를 + // 사용할 수 있습니다. 이를 빼먹으면 참조 오류가 발생합니다. + this.name = 'Square'; + } + + get area() { + return this.height * this.width; + } + + set area(value) { + this.area = value; + } +}</pre> + +<h3 id="내장_객체에_extends_사용하기">내장 객체에 <code>extends</code> 사용하기</h3> + +<p>이 예제는 내장 객체 {{jsxref("Date")}}를 확장합니다. 이 예제는 <a href="https://googlechrome.github.io/samples/classes-es6/index.html">live demo</a> <a href="https://github.com/GoogleChrome/samples/blob/gh-pages/classes-es6/index.html">(source)</a>에서 발췌했습니다.</p> + +<pre class="brush: js">class myDate extends Date { + constructor() { + super(); + } + + getFormattedDate() { + var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']; + return this.getDate() + "-" + months[this.getMonth()] + "-" + this.getFullYear(); + } +}</pre> + +<h3 id="null_확장"><code>null</code> 확장</h3> + +<p>{{jsxref("null")}}에서 확장은 prototype 객체가 {{jsxref("Object.prototype")}}으로부터 상속받지 않은 것을 제외하면 보통 클래스처럼 동작합니다.</p> + +<pre class="brush: js">class nullExtends extends null { + constructor() {} +} + +Object.getPrototypeOf(nullExtends); // Function.prototype +Object.getPrototypeOf(nullExtends.prototype) // null</pre> + +<h2 id="스펙">스펙</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-class-definitions', 'extends')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-class-definitions', 'extends')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.classes.extends")}}</p> + +<h2 id="참조">참조</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Reference/Classes">Classes</a></li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Operators/super">super</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/classes/index.html b/files/ko/web/javascript/reference/classes/index.html new file mode 100644 index 0000000000..59f72f7652 --- /dev/null +++ b/files/ko/web/javascript/reference/classes/index.html @@ -0,0 +1,402 @@ +--- +title: Classes +slug: Web/JavaScript/Reference/Classes +translation_of: Web/JavaScript/Reference/Classes +--- +<div>{{JsSidebar("Classes")}}</div> + +<p>Class는 객체를 생성하기 위한 템플릿입니다. 클래스는 데이터와 이를 조작하는 코드를 하나로 추상화합니다. 자바스크립트에서 클래스는 프로토타입을 이용해서 만들어졌지만 ES5의 클래스 의미와는 다른 문법과 의미를 가집니다.</p> + +<h2 id="Class_정의">Class 정의</h2> + +<p>Class는 사실 "특별한 {{jsxref("Functions", "함수", "", "true")}}"입니다. 함수를 {{jsxref("Operators/function", "함수 표현식", "", "true")}}과 {{jsxref("Statements/function", "함수 선언", "", "true")}}으로 정의할 수 있듯이 class 문법도 {{jsxref("Operators/class", "class 표현식", "", "true")}} and {{jsxref("Statements/class", "class 선언", "", "true")}} 두 가지 방법을 제공합니다.</p> + +<h3 id="Class_선언">Class 선언</h3> + +<p>Class를 정의하는 한 가지 방법은 <strong>class 선언</strong>을 이용하는 것입니다. class를 선언하기 위해서는 클래스의 이름(여기서 "Rectangle")과 함께 <code>class</code> 키워드를 사용해야 합니다.</p> + +<pre class="brush: js notranslate">class Rectangle { + constructor(height, width) { + this.height = height; + this.width = width; + } +}</pre> + +<h4 id="Hoisting">Hoisting</h4> + +<p><strong>함수 선언</strong>과 <strong>클래스 선언</strong>의 중요한 차이점은 함수 선언의 경우 {{Glossary("Hoisting", "호이스팅")}}이 일어나지만, 클래스 선언은 그렇지 않다는 것입니다. 클래스를 사용하기 위해서는 클래스를 먼저 선언 해야 합니다. 그렇지 않으면, 다음 코드는 {{jsxref("ReferenceError")}}를 던질 것입니다. :</p> + +<pre class="brush: js example-bad notranslate">const p = new Rectangle(); // ReferenceError + +class Rectangle {} +</pre> + +<h3 id="Class_표현식">Class 표현식</h3> + +<p><strong>Class 표현식</strong>은 class를 정의하는 또 다른 방법입니다. Class 표현식은 이름을 가질 수도 있고, 갖지 않을 수도 있습니다. 이름을 가진 class 표현식의 이름은 클래스 body의 local scope에 한해 유효합니다. (하지만, 클래스의 (인스턴스 이름이 아닌) {{jsxref("Function.name", "name")}} 속성을 통해 찾을 수 있습니다).</p> + +<pre class="brush: js notranslate">// unnamed +let Rectangle = class { + constructor(height, width) { + this.height = height; + this.width = width; + } +}; +console.log(Rectangle.name); +// 출력: "Rectangle" + +// named +let Rectangle = class Rectangle2 { + constructor(height, width) { + this.height = height; + this.width = width; + } +}; +console.log(Rectangle.name); +// 출력: "Rectangle2" +</pre> + +<div class="note"> +<p><strong>참고:</strong> 클래스 <strong>표현식</strong>에는 {{anch ( "Class 선언")}} 섹션에 설명된 것과 동일한 호이스팅 제한이 적용됩니다.</p> +</div> + +<h2 id="Class_body_와_메서드_정의">Class body 와 메서드 정의</h2> + +<p>Class body는 중괄호 <code>{}</code> 로 묶여 있는 안쪽 부분입니다. 이곳은 여러분이 메서드나 constructor와 같은 class 멤버를 정의할 곳입니다.</p> + +<h3 id="Strict_mode">Strict mode</h3> + +<p>클래스의 본문(body)은 {{jsxref("Strict_mode", "strict mode", "", "true")}}에서 실행됩니다. 즉, 여기에 적힌 코드는 성능 향상을 위해 더 엄격한 문법이 적용됩니다. 그렇지 않으면, 조용히 오류가 발생할 수 있습니다. 특정 키워드는 미래의 ECMAScript 버전용으로 예약됩니다.</p> + +<h3 id="Constructor_생성자">Constructor (생성자)</h3> + +<p>{{jsxref("Classes/constructor", "constructor", "", "true")}} 메서드는 <code>class</code> 로 생성된 객체를 생성하고 초기화하기 위한 특수한 메서드입니다. "constructor" 라는 이름을 가진 특수한 메서드는 클래스 안에 한 개만 존재할 수 있습니다. 만약 클래스에 여러 개의 <code>constructor</code> 메서드가 존재하면 {{jsxref("SyntaxError")}} 가 발생할 것입니다.</p> + +<p>constructor는 부모 클래스의 constructor를 호출하기 위해 <code>super</code> 키워드를 사용할 수 있습니다.</p> + +<h3 id="프로토타입_메서드">프로토타입 메서드</h3> + +<p>{{jsxref("Functions/Method_definitions", "메서드 정의", "", "true")}}도 참조해보세요.</p> + +<pre class="brush: js notranslate">class Rectangle { + constructor(height, width) { + this.height = height; + this.width = width; + } + // Getter + get area() { + return this.calcArea(); + } + // 메서드 + calcArea() { + return this.height * this.width; + } +} + +const square = new Rectangle(10, 10); + +console.log(square.area); // 100</pre> + +<h3 id="정적_메서드와_속성">정적 메서드와 속성</h3> + +<p>{{jsxref("Classes/static", "static", "", "true")}} 키워드는 클래스를 위한 정적(static) 메서드를 정의합니다. 정적 메서드는 클래스의 인스턴스화(<a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#The_object_(class_instance)" title='An example of class instance is "var john = new Person();"'>instantiating</a>) 없이 호출되며, 클래스의 인스턴스에서는 호출할 수 없습니다. 정적 메서드는 어플리케이션(application)을 위한 유틸리티(utility) 함수를 생성하는 데 주로 사용됩니다. 반면, 정적 속성은 캐시, 고정 환경설정 또는 인스턴스 간에 복제할 필요가 없는 기타 데이터에 유용합니다.</p> + +<pre class="brush: js notranslate">class Point { + constructor(x, y) { + this.x = x; + this.y = y; + } + + static displayName = "Point"; + static distance(a, b) { + const dx = a.x - b.x; + const dy = a.y - b.y; + + return Math.hypot(dx, dy); + } +} + +const p1 = new Point(5, 5); +const p2 = new Point(10, 10); +p1.displayName; // undefined +p1.distance; // undefined +p2.displayName; // undefined +p2.distance; // undefined + +console.log(Point.displayName); // "Point" +console.log(Point.distance(p1, p2)); // 7.0710678118654755</pre> + +<h3 id="프로토타입_및_정적_메서드를_사용한_this_바인딩">프로토타입 및 정적 메서드를 사용한 <code>this</code> 바인딩</h3> + +<p>메서드를 변수에 할당 한 다음 호출하는 것과 같이, 정적 메서드나 프로토타입 메서드가 {{jsxref("Operators/this", "this")}} 값 없이 호출될 때, <code>this</code> 값은 메서드 안에서 <code>undefined</code>가 됩니다. 이 동작은 {{jsxref("Strict_mode", "\"use strict\"")}} 명령어 없이도 같은 방식으로 동작하는데, <code>class</code> 문법 안에 있는 코드는 항상 strict mode 로 실행되기 때문입니다.</p> + +<pre class="brush: js notranslate">class Animal { + speak() { + return this; + } + static eat() { + return this; + } +} + +let obj = new Animal(); +obj.speak(); // the Animal object +let speak = obj.speak; +speak(); // undefined + +Animal.eat() // class Animal +let eat = Animal.eat; +eat(); // undefined</pre> + +<p>위에 작성된 코드를 전통적 방식의 함수기반의 non–strict mode 구문으로 재작성하면, <code>this</code> 메서드 호출은 기본적으로 {{Glossary("Global_object", "전역 객체")}}인 초기 <code>this</code> 값에 자동으로 바인딩 됩니다. Strict mode에서는 자동 바인딩이 발생하지 않습니다; <code>this</code> 값은 전달된 대로 유지됩니다.</p> + +<pre class="brush: js notranslate">function Animal() { } + +Animal.prototype.speak = function() { + return this; +} + +Animal.eat = function() { + return this; +} + +let obj = new Animal(); +let speak = obj.speak; +speak(); // global object (in non–strict mode) + +let eat = Animal.eat; +eat(); // global object (in non-strict mode)</pre> + +<h3 id="인스턴스_속성">인스턴스 속성</h3> + +<p>인스턴스 속성은 반드시 클래스 메서드 내에 정의되어야 합니다:</p> + +<pre class="brush: js notranslate">class Rectangle { + constructor(height, width) { + this.height = height; + this.width = width; + } +}</pre> + +<p>정적 (클래스사이드) 속성과 프로토타입 데이터 속성은 반드시 클래스 선언부 바깥쪽에서 정의되어야 합니다. </p> + +<pre class="brush: js notranslate">Rectangle.staticWidth = 20; +Rectangle.prototype.prototypeWidth = 25; +</pre> + +<h3 id="Field_선언">Field 선언</h3> + +<div class="blockIndicator warning"> +<p>public과 private 필드 선언은 자바스크립트 표준화 위원회에 <a href="https://github.com/tc39/proposal-class-fields">실험적 기능 (stage 3)</a> <a href="https://tc39.es/">TC39</a> 로 제안되어있습니다. 현재 이를 지원하는 브라우져는 제한적인 상태입니다만, <a href="https://babeljs.io/">Babel</a> 과 같은 build 시스템을 사용한다면 이 기능을 사용해볼 수 있습니다.</p> +</div> + +<h4 id="Public_필드_선언">Public 필드 선언</h4> + +<p>자바스크립트의 필드 선언 문법을 사용해서 위의 예제는 아래와 같이 다시 쓰여질 수 있습니다.</p> + +<pre class="brush: js notranslate">class Rectangle { + height = 0; + width; + constructor(height, width) { + this.height = height; + this.width = width; + } +}</pre> + +<p>필드를 먼저 선언함으로서 클래스 정의는 self-documenting에 가까워졌고 필드는 언제나 존재하는 상태가 됩니다.</p> + +<p>위의 예에서 봤듯이 필드 선언은 기본 값과 같이 선언될 수도 있습니다.</p> + +<p>자세한 내용은 {{jsxref("Classes/Public_class_fields", "public class fields", "", "true")}}를 참조하세요.</p> + +<h4 id="Private_필드_선언">Private 필드 선언</h4> + +<p>private 필드를 사용하면 아래와 같이 예제를 개선할 수 있습니다.</p> + +<pre class="brush: js notranslate">class Rectangle { + #height = 0; + #width; + constructor(height, width) { + this.#height = height; + this.#width = width; + } +}</pre> + +<p>클래스의 바깥에서 private 필드를 접근하려고 하면 에러가 발생합니다. private필드는 클래스 내부에서만 읽고 쓰기가 가능합니다. 클래스 외부에서 보이지 않도록 정의하였으므로 클래스가 버젼업 되면서 내부 구현이 바뀌더라도 클래스 사용자 입장에서는 이에 아무런 영항을 받지 않도록 할 수 있습니다.</p> + +<div class="blockIndicator note"> +<p>Private 필드는 사용전에 선언되어야 합니다.</p> +</div> + +<p>일반적인 프로퍼티와는 다르게 private 필드는 값을 할당하면서 만들어질 수 없습니다.</p> + +<p>자세한 내용은 {{jsxref("Classes/Private_class_fields", "private class fields", "", "true")}}를 참조하세요.</p> + +<h2 id="extends를_통한_클래스_상속sub_classing"><code>extends</code>를 통한 클래스 상속(sub classing)</h2> + +<p>{{jsxref("Classes/extends", "extends")}} 키워드는 <em>클래스 선언</em>이나 <em>클래스 표현식</em>에서 다른 클래스의 자식 클래스를 생성하기 위해 사용됩니다.</p> + +<pre class="brush: js notranslate">class Animal { + constructor(name) { + this.name = name; + } + + speak() { + console.log(`${this.name} makes a noise.`); + } +} + +class Dog extends Animal { + constructor(name) { + super(name); // super class 생성자를 호출하여 name 매개변수 전달 + } + + speak() { + console.log(`${this.name} barks.`); + } +} + +let d = new Dog('Mitzie'); +d.speak(); // Mitzie barks.</pre> + +<p>subclass에 constructor가 있다면, "this"를 사용하기 전에 가장 먼저 super()를 호출해야 합니다.</p> + +<p>또한 es5에서 사용되던 전통적인 함수 기반의 클래스를 통하여 확장할 수도 있습니다.</p> + +<pre class="brush: js notranslate">function Animal (name) { + this.name = name; +} + +Animal.prototype.speak = function () { + console.log(`${this.name} makes a noise.`); +} + +class Dog extends Animal { + speak() { + console.log(`${this.name} barks.`); + } +} + +let d = new Dog('Mitzie'); +d.speak(); // Mitzie barks. + +// 유사한 메서드의 경우, 자식의 메서드가 부모의 메서드보다 우선합니다</pre> + +<p>클래스는 생성자가 없는 객체(non-constructible)을 확장할 수 없습니다. 만약 기존의 생성자가 없는 객체을 확장하고 싶다면, 이 메서드를 사용하세요. {{jsxref("Object.setPrototypeOf()")}}:</p> + +<pre class="brush: js notranslate">const Animal = { + speak() { + console.log(`${this.name} makes a noise.`); + } +}; + +class Dog { + constructor(name) { + this.name = name; + } +} + +// 이 작업을 수행하지 않으면 speak를 호출할 때 TypeError가 발생합니다 +Object.setPrototypeOf(Dog.prototype, Animal); + +let d = new Dog('Mitzie'); +d.speak(); // Mitzie makes a noise.</pre> + +<h2 id="Species">Species</h2> + +<p>배열을 상속 받은 MyArray 클래스에서 {{jsxref("Array")}} Object를 반환하고 싶을 수도 있을 것입니다. 그럴때 Species 패턴은 기본 생성자를 덮어쓰도록 해줍니다.</p> + +<p>예를 들어, {{jsxref("Array.map", "map()")}}과 같은 기본 생성자를 반환하는 메서드를 사용할 때 이 메서드가 MyArray 객체 대신 <code>Array</code> 객체가 반환하도록 하고 싶을 것입니다. {{jsxref("Symbol.species")}} 심볼은 이러한 것을 가능하게 해줍니다:</p> + +<pre class="brush: js notranslate">class MyArray extends Array { + // 부모 Array 생성자로 species 덮어쓰기 + static get [Symbol.species]() { return Array; } +} +var a = new MyArray(1,2,3); +var mapped = a.map(x => x * x); + +console.log(mapped instanceof MyArray); // false +console.log(mapped instanceof Array); // true</pre> + +<h2 id="super_를_통한_상위_클래스_호출"><code>super</code> 를 통한 상위 클래스 호출</h2> + +<p>{{jsxref("Operators/super", "super")}} 키워드는 객체의 부모가 가지고 있는 메서드를 호출하기 위해 사용됩니다. 이는 프로토타입 기반 상속보다 좋은 점 중 하나입니다.</p> + +<pre class="brush: js notranslate">class Cat { + constructor(name) { + this.name = name; + } + + speak() { + console.log(`${this.name} makes a noise.`); + } +} + +class Lion extends Cat { + speak() { + super.speak(); + console.log(`${this.name} roars.`); + } +} + +let l = new Lion('Fuzzy'); +l.speak(); +// Fuzzy makes a noise. +// Fuzzy roars.</pre> + +<h2 id="Mix-ins">Mix-ins</h2> + +<p>추상 서브 클래스 또는 믹스-인은 클래스를 위한 템플릿입니다. ECMAScript 클래스는 하나의 단일 슈퍼클래스만을 가질 수 있으며, 예를 들어 툴링 클래스로부터의 다중 상속은 불가능합니다. 기능은 반드시 슈퍼클래스에서 제공되어야 합니다.</p> + +<p>슈퍼클래스를 인자로 받고 이 슈퍼클래스를 확장하는 서브클래스를 생성하여 반환하는 함수를 사용하여 ECMAScript에서 믹스-인을 구현할 수 있습니다:</p> + +<pre class="brush: js notranslate">var calculatorMixin = Base => class extends Base { + calc() { } +}; + +var randomizerMixin = Base => class extends Base { + randomize() { } +};</pre> + +<p>위 믹스-인을 사용하는 클래스는 다음과 같이 작성할 수 있습니다:</p> + +<pre class="brush: js notranslate">class Foo { } +class Bar extends calculatorMixin(randomizerMixin(Foo)) { }</pre> + +<h2 id="클래스_재정의">클래스 재정의</h2> + +<p>클래스는 재정의될 수 없습니다. 재정의를 시도하면 <code>SyntaxError</code> 가 발생합니다.</p> + +<p>이를 실험해보고 싶으면 FireFox Web Console (<strong>Tools </strong>><strong> Web Developer </strong>><strong> Web Console</strong>) 에서 같은 이름으로 클래스를 두번 정의하려고 해보세요. 다음과 같은 오류를 보게 될 겁니다. <code>SyntaxError: redeclaration of let <em>ClassName</em>;</code>. (See further discussion of this issue in {{Bug(1428672)}}.) Doing something similar in Chrome Developer Tools gives you a message like <code>Uncaught SyntaxError: Identifier '<em>ClassName</em>' has already been declared at <anonymous>:1:1</code>.</p> + +<h2 id="명세서">명세서</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세서</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.classes")}}</p> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("Functions", "함수", "", "true")}}</li> + <li>{{jsxref("Statements/class", "class 선언", "", "true")}}</li> + <li>{{jsxref("Operators/class", "class 식", "", "true")}}</li> + <li>{{jsxref("Classes/Public_class_fields", "Public class fields", "", "true")}}</li> + <li>{{jsxref("Classes/Private_class_fields", "Private class fields", "", "true")}}</li> + <li>{{jsxref("Operators/super", "super")}}</li> + <li><a href="https://hacks.mozilla.org/2015/07/es6-in-depth-classes/">블로그 게시물: "ES6 In Depth: Classes"</a></li> + <li><a href="https://github.com/tc39/proposal-class-fields">Fields and public/private class properties proposal (stage 3)</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/classes/private_class_fields/index.html b/files/ko/web/javascript/reference/classes/private_class_fields/index.html new file mode 100644 index 0000000000..ea5508ab27 --- /dev/null +++ b/files/ko/web/javascript/reference/classes/private_class_fields/index.html @@ -0,0 +1,201 @@ +--- +title: Private class fields +slug: Web/JavaScript/Reference/Classes/Private_class_fields +tags: + - Class + - JavaScript + - Private Field +translation_of: Web/JavaScript/Reference/Classes/Private_class_fields +--- +<div>{{JsSidebar("Classes")}}</div> + +<p>class 의 속성(property)들은 기본적으로 public 하며 class 외부에서 읽히고 수정될 수 있다. 하지만, ES2019 에서는 해쉬 <code>#</code> prefix 를 추가해 private class 필드를 선언할 수 있게 되었다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="notranslate">class ClassWithPrivateField { + #privateField +} + +class ClassWithPrivateMethod { + #privateMethod() { + return 'hello world' + } +} + +class ClassWithPrivateStaticField { + static #PRIVATE_STATIC_FIELD +}</pre> + +<h2 id="Examples">Examples</h2> + +<h3 id="Private_static_fields">Private static fields</h3> + +<p>private 필드는 class 선언문 내부의 class 생성자(class constructor)에서 접근이 가능하다.</p> + +<p>static 메소드에서만 static 변수들을 호출할 수 있다는 제약은 그대로 유지된다.</p> + +<pre class="notranslate">class ClassWithPrivateStaticField { + static #PRIVATE_STATIC_FIELD + + static publicStaticMethod() { + ClassWithPrivateStaticField.#PRIVATE_STATIC_FIELD = 42 + return ClassWithPrivateStaticField.#PRIVATE_STATIC_FIELD + } +} + +console.assert(ClassWithPrivateStaticField.publicStaticMethod() === 42)</pre> + +<p>Private static 필드는 class evaluation 시 class 생성자(class constructor)에 추가된다.</p> + +<p>Private static 필드는 해당 필드를 선언한 class 에서만 접근할 수 있다.</p> + +<p>이는 <code>this</code> 를 사용함에 있어 예상치 못한 동작을 야기할 수 있다.</p> + +<pre class="notranslate">class BaseClassWithPrivateStaticField { + static #PRIVATE_STATIC_FIELD + + static basePublicStaticMethod() { + this.#PRIVATE_STATIC_FIELD = 42 + return this.#PRIVATE_STATIC_FIELD + } +} + +class SubClass extends BaseClassWithPrivateStaticField { } + +let error = null + +try { + SubClass.basePublicStaticMethod() +} catch(e) { error = e} + +console.assert(error instanceof TypeError)</pre> + +<h3 id="Private_instance_fields">Private instance fields</h3> + +<p>private 인스턴스 필드는 <strong># 이름 ('해쉬 이름' 으로 발음)</strong>,<strong> </strong>즉 <code>#</code> prefix 를 가진 식별자로 선언된다. <code>#</code> 은 그 이름 자체의 일부이며 선언과 접근 시에 모두 사용된다.</p> + +<p>캡슐화(encapsulation) 는 언어로부터 강제된다(enforced by the language). 즉, scope 밖에서 <code>#</code> 이름에 접근하는 것은 syntax error 이다.</p> + +<pre class="notranslate">class ClassWithPrivateField { + #privateField + + constructor() { + this.#privateField = 42 + this.#randomField = 444 // Syntax error + } +} + +const instance = new ClassWithPrivateField() +instance.#privateField === 42 // Syntax error</pre> + +<h3 id="Private_Methods">Private Methods</h3> + +<h4 id="Private_static_methods">Private static methods</h4> + +<p><strong>private static 메소드</strong>는 public static 메소드처럼 인스턴스가 아닌 class 로부터 호출된다. 그리고 private static 필드처럼 class 선언문 내부에서만 접근 가능하다. </p> + +<p>private static 메소드는 generator, async 그리고 async generator 함수가 될 수 있다.</p> + +<pre class="notranslate">class ClassWithPrivateStaticMethod { + static #privateStaticMethod() { + return 42 + } + + static publicStaticMethod1() { + return ClassWithPrivateStaticMethod.#privateStaticMethod(); + } + + static publicStaticMethod2() { + return this.#privateStaticMethod(); + } +} + +console.assert(ClassWithPrivateStaticMethod.publicStaticMethod1() === 42); +console.assert(ClassWithPrivateStaticMethod.publicStaticMethod2() === 42);</pre> + +<p>이는 <code>this</code> 를 사용할 때 예상치 못한 동작을 발생시킬 수 있다. (이는 <code>this</code> binding rule 이 적용되기 때문이다.) 다음 예시에서 <code>Derived.publicStaticMethod2()</code> 를 호출할 때, <code>this</code> 는 class <code>Derived</code> (<code>Base</code> 가 아니라) 를 가리킨다. </p> + +<pre class="notranslate">class Base { + static #privateStaticMethod() { + return 42; + } + static publicStaticMethod1() { + return Base.#privateStaticMethod(); + } + static publicStaticMethod2() { + return this.#privateStaticMethod(); + } +} + +class Derived extends Base {} + +console.log(Derived.publicStaticMethod1()); // 42 +console.log(Derived.publicStaticMethod2()); // TypeError</pre> + +<h4 id="Private_instance_methods">Private instance methods</h4> + +<p>private 인스턴스 메소드는 private 인스턴스 필드와는 다르게 class 인스턴스로부터 접근 가능하다.</p> + +<pre class="notranslate">class ClassWithPrivateMethod { + #privateMethod() { + return 'hello world' + } + + getPrivateMessage() { + return this.#privateMethod() + } +} + +const instance = new ClassWithPrivateMethod() +console.log(instance.getPrivateMessage()) +// expected output: "hello world"</pre> + +<p>private 인스턴스 메소드는 generator, async 그리고 async generator 함수가 될 수 있다. private getter 와 setter 또한 가능하다:</p> + +<pre class="notranslate">class ClassWithPrivateAccessor { + #message + + get #decoratedMessage() { + return `✨${this.#message}✨` + } + set #decoratedMessage(msg) { + this.#message = msg + } + + constructor() { + this.#decoratedMessage = 'hello world' + console.log(this.#decoratedMessage) + } +} + +new ClassWithPrivateAccessor(); +// expected output: "✨hello world✨"</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('Public and private instance fields', '#prod-FieldDefinition', 'FieldDefinition')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.classes.private_class_fields")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields">Public class fields</a></li> + <li><a href="https://rfrn.org/~shu/2018/05/02/the-semantics-of-all-js-class-elements.html">The Semantics of All JS Class Elements</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/classes/static/index.html b/files/ko/web/javascript/reference/classes/static/index.html new file mode 100644 index 0000000000..02701e550d --- /dev/null +++ b/files/ko/web/javascript/reference/classes/static/index.html @@ -0,0 +1,136 @@ +--- +title: static +slug: Web/JavaScript/Reference/Classes/static +tags: + - Classes + - ECMAScript 2015 + - JavaScript + - 자바스크립트 + - 클래스 +translation_of: Web/JavaScript/Reference/Classes/static +--- +<div>{{jsSidebar("Classes")}}</div> + +<p><strong>static</strong> 키워드는 클래스의 정적 메서드를 정의합니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/classes-static.html")}}</p> + +<div class="hidden"> +<p>The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p> +</div> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox">static methodName() { ... }</pre> + +<h2 id="설명">설명</h2> + +<p>정적 메서드는 클래스의 인스턴스 없이 호출이 가능하며 클래스가 인스턴스화되면 호출할 수 없다. 정적 메서드는 종종 어플리케이션의 유틸리티 함수를 만드는데 사용된다.</p> + +<h2 id="정적_메서드의_호출">정적 메서드의 호출</h2> + +<h4 id="다른_정적_메서드에서의_호출">다른 정적 메서드에서의 호출</h4> + +<p>동일한 클래스 내의 다른 정적 메서드 내에서 정적 메서드를 호출하는 경우 키워드 <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this">this</a></code>를 사용할 수 있다.</p> + +<pre class="brush: js">class StaticMethodCall { + static staticMethod() { + return 'Static method has been called'; + } + static anotherStaticMethod() { + return this.staticMethod() + ' from another static method'; + } +} +StaticMethodCall.staticMethod(); +// 'Static method has been called' + +StaticMethodCall.anotherStaticMethod(); +// 'Static method has been called from another static method' +</pre> + +<h3 id="클래스_생성자_및_다른_메서드에서의_호출">클래스 생성자 및 다른 메서드에서의 호출</h3> + +<p>정적 메서드가 비정적 메서드에서 키워드<code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this">this</a></code> 를 써서는 직접적인 접근을 할 수 없다. 바른 호출 방법은 클래스 명칭을 쓰거나, 즉 <code>CLASSNAME.STATIC_METHOD_NAME()</code> 을 이용하거나 혹은 그 메서드를 생성자의 한 속성으로 부르는 것으로, 즉 <code>constructor</code> : <code>this.constructor.STATIC_METHOD_NAME()</code>를 이용한다.</p> + +<pre class="brush: js">class StaticMethodCall { + constructor() { + console.log(StaticMethodCall.staticMethod()); + // 'static method has been called.' + + console.log(this.constructor.staticMethod()); + // 'static method has been called.' + } + + static staticMethod() { + return 'static method has been called.'; + } +} +</pre> + +<h2 id="예제">예제</h2> + +<p>아래 예제는 여러가지 내용을 설명합니다.</p> + +<ol> + <li>어떻게 정적 메서드가 클래스에서 구현되는지</li> + <li>클래스의 정적 맴버가 서브클래스화 되는 것을 보여줍니다.</li> + <li>정적 메서드가 어떤 경우에 호출 될 수 있는지와 없는지를 설명합니다.</li> +</ol> + +<pre class="brush: js">class Triple { + static triple(n) { + n = n || 1; //비트연산이 아니어야 합니다. + return n * 3; + } +} + +class BiggerTriple extends Triple { + static triple(n) { + return super.triple(n) * super.triple(n); + } +} + +console.log(Triple.triple()); // 3 +console.log(Triple.triple(6)); // 18 +console.log(BiggerTriple.triple(3)); // 81 +var tp = new Triple(); +console.log(BiggerTriple.triple(3)); // 81 (부모의 인스턴스에 영향을 받지 않습니다.) +console.log(tp.triple()); // 'tp.triple은 함수가 아닙니다.'. +console.log(tp.constructor.triple(4)); // 12 +</pre> + +<p> </p> + +<h2 id="명세서">명세서</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.classes.static")}}</p> + +<h2 id="참고">참고</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/class"><code>class</code> expression</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/class"><code>class</code> declaration</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Classes">Classes</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/deprecated_and_obsolete_features/index.html b/files/ko/web/javascript/reference/deprecated_and_obsolete_features/index.html new file mode 100644 index 0000000000..deffbf4caa --- /dev/null +++ b/files/ko/web/javascript/reference/deprecated_and_obsolete_features/index.html @@ -0,0 +1,290 @@ +--- +title: Deprecated and obsolete features +slug: Web/JavaScript/Reference/Deprecated_and_obsolete_features +tags: + - Deprecated + - JavaScript + - Obsolete +translation_of: Web/JavaScript/Reference/Deprecated_and_obsolete_features +--- +<div>{{JsSidebar("More")}}</div> + +<p>본 페이지는 자바스크립트의 제외 예정인(즉, 아직 사용할 수 있지만 제거 계획이 있는) 기능과 제외된(즉, 더 이상 사용할 수 없는) 기능을 나열합니다.</p> + +<h2 id="제외_예정_기능">제외 예정 기능</h2> + +<p>아래 기능은 아직 사용할 수 있지만, 언젠가 제거될 예정이므로 주의를 기울여야 합니다. 작성한 코드가 항목 중 하나를 포함하고 있다면 제거해야 합니다.</p> + +<h3 id="RegExp_속성">RegExp 속성</h3> + +<p>아래 속성은 제외 예정입니다. 이는 {{jsxref("String.replace")}} 사용에 영향을 주지 않습니다.</p> + +<table class="standard-table"> + <tbody> + <tr> + <th>Property</th> + <th>Description</th> + </tr> + <tr> + <td>{{jsxref("RegExp.n", "$1-$9")}}</td> + <td> + <p>Parenthesized substring matches, if any.<br> + <strong>Warning:</strong> Using these properties can result in problems, since browser extensions can modify them. Avoid them!</p> + </td> + </tr> + <tr> + <td>{{jsxref("RegExp.input", "$_")}}</td> + <td>See <code>input</code>.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.multiline", "$*")}}</td> + <td>See <code>multiline</code>.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.lastMatch", "$&")}}</td> + <td>See <code>lastMatch</code>.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.lastParen", "$+")}}</td> + <td>See <code>lastParen</code>.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.leftContext", "$`")}}</td> + <td>See <code>leftContext</code>.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.rightContext", "$'")}}</td> + <td>See <code>rightContext</code>.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.input", "input")}}</td> + <td>The string against which a regular expression is matched.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.lastMatch", "lastMatch")}}</td> + <td>The last matched characters.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.lastParen", "lastParen")}}</td> + <td>The last parenthesized substring match, if any.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.leftContext", "leftContext")}}</td> + <td>The substring preceding the most recent match.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.rightContext", "rightContext")}}</td> + <td>The substring following the most recent match.</td> + </tr> + </tbody> +</table> + +<p>The following are now properties of <code>RegExp</code> instances, no longer of the <code>RegExp</code> object:</p> + +<table class="standard-table"> + <tbody> + <tr> + <th>Property</th> + <th>Description</th> + </tr> + <tr> + <td>{{jsxref("RegExp.global", "global")}}</td> + <td>Whether or not to test the regular expression against all possible matches in a string, or only against the first.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.ignoreCase", "ignoreCase")}}</td> + <td>Whether or not to ignore case while attempting a match in a string.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.lastIndex", "lastIndex")}}</td> + <td>The index at which to start the next match.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.multiline", "multiline")}}</td> + <td>Whether or not to search in strings across multiple lines.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.source", "source")}}</td> + <td>패턴의 텍스트.</td> + </tr> + </tbody> +</table> + +<h3 id="RegExp_메서드">RegExp 메서드</h3> + +<ul> + <li>{{jsxref("RegExp.compile", "compile()")}} 메서드는 제외될 예정입니다.</li> + <li><code>valueOf</code> 메서드는 더 이상 <code>RegExp</code> 전용이 아닙니다. {{jsxref("Object.valueOf()")}}를 사용하세요.</li> +</ul> + +<h3 id="Function_속성">Function 속성</h3> + +<ul> + <li>The {{jsxref("Global_Objects/Function/caller", "caller")}} and {{jsxref("Global_Objects/Function/arguments", "arguments")}} properties are deprecated, because they leak the function caller. Instead of the arguments property, you should use the {{jsxref("Functions/arguments", "arguments")}} object inside function closures.</li> +</ul> + +<h3 id="Legacy_generator">Legacy generator</h3> + +<ul> + <li>{{jsxref("Statements/Legacy_generator_function", "Legacy generator function statement")}} and {{jsxref("Operators/Legacy_generator_function", "Legacy generator function expression")}} are deprecated. Use {{jsxref("Statements/function*", "function* statement")}} and {{jsxref("Operators/function*", "function* expression")}} instead.</li> + <li>{{jsxref("Operators/Array_comprehensions", "JS1.7/JS1.8 Array comprehension", "#Differences_to_the_older_JS1.7.2FJS1.8_comprehensions")}} and {{jsxref("Operators/Generator_comprehensions", "JS1.7/JS1.8 Generator comprehension", "#Differences_to_the_older_JS1.7.2FJS1.8_comprehensions")}} are deprecated.</li> +</ul> + +<h3 id="Iterator">Iterator</h3> + +<ul> + <li>{{jsxref("Global_Objects/StopIteration", "StopIteration")}} is deprecated.</li> + <li>{{jsxref("Global_Objects/Iterator", "Iterator")}} is deprecated.</li> +</ul> + +<h3 id="Object_methods">Object methods</h3> + +<ul> + <li>{{jsxref("Object.watch", "watch")}} and {{jsxref("Object.unwatch", "unwatch")}} are deprecated. Use {{jsxref("Proxy")}} instead.</li> + <li><code>__iterator__</code> is deprecated.</li> + <li>{{jsxref("Object.noSuchMethod", "__noSuchMethod__")}} is deprecated. Use {{jsxref("Proxy")}} instead.</li> +</ul> + +<h3 id="Date_methods">Date methods</h3> + +<ul> + <li>{{jsxref("Global_Objects/Date/getYear", "getYear")}} and {{jsxref("Global_Objects/Date/setYear", "setYear")}} are affected by the Year-2000-Problem and have been subsumed by {{jsxref("Global_Objects/Date/getFullYear", "getFullYear")}} and {{jsxref("Global_Objects/Date/setFullYear", "setFullYear")}}.</li> + <li>You should use {{jsxref("Global_Objects/Date/toISOString", "toISOString")}} instead of the deprecated {{jsxref("Global_Objects/Date/toGMTString", "toGMTString")}} method in new code.</li> + <li>{{jsxref("Global_Objects/Date/toLocaleFormat", "toLocaleFormat")}} is deprecated.</li> +</ul> + +<h3 id="Functions">Functions</h3> + +<ul> + <li>{{jsxref("Operators/Expression_closures", "Expression closures", "", 1)}} are deprecated. Use regular {{jsxref("Operators/function", "functions")}} or {{jsxref("Functions/Arrow_functions", "arrow functions", "", 1)}} instead.</li> +</ul> + +<h3 id="Proxy">Proxy</h3> + +<ul> + <li><a href="/en-US/docs/Archive/Web/Old_Proxy_API">Proxy.create</a> and <a href="/en-US/docs/Archive/Web/Old_Proxy_API">Proxy.createFunction</a> are deprecated. Use {{jsxref("Proxy")}} instead.</li> + <li>The following traps are obsolete: + <ul> + <li><code>hasOwn</code> ({{bug(980565)}}, Firefox 33).</li> + <li><code>getEnumerablePropertyKeys</code> ({{bug(783829)}}, Firefox 37)</li> + <li><code>getOwnPropertyNames</code> ({{bug(1007334)}}, Firefox 33)</li> + <li><code>keys</code> ({{bug(1007334)}}, Firefox 33)</li> + </ul> + </li> +</ul> + +<h3 id="Escape_sequences">Escape sequences</h3> + +<ul> + <li>Octal escape sequences (\ followed by one, two, or three octal digits) are deprecated in string and regular expression literals.</li> + <li>The {{jsxref("Global_Objects/escape", "escape")}} and {{jsxref("Global_Objects/unescape", "unescape")}} functions are deprecated. Use {{jsxref("Global_Objects/encodeURI", "encodeURI")}}, {{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent")}}, {{jsxref("Global_Objects/decodeURI", "decodeURI")}} or {{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent")}} to encode and decode escape sequences for special characters.</li> +</ul> + +<h3 id="String_methods">String methods</h3> + +<ul> + <li><a href="https://developer.mozilla.org/en-US/docs/tag/HTML%20wrapper%20methods">HTML wrapper methods</a> like {{jsxref("String.prototype.fontsize")}} and {{jsxref("String.prototype.big")}}.</li> + <li>{{jsxref("String.prototype.quote")}} is removed from Firefox 37.</li> + <li>non standard <code>flags</code> parameter in {{jsxref("String.prototype.search")}}, {{jsxref("String.prototype.match")}}, and {{jsxref("String.prototype.replace")}} are deprecated.</li> +</ul> + +<h2 id="Obsolete_features">Obsolete features</h2> + +<p>These obsolete features have been entirely removed from JavaScript and can no longer be used as of the indicated version of JavaScript.</p> + +<h3 id="Object">Object</h3> + +<table class="standard-table"> + <tbody> + <tr> + <th>Property</th> + <th>Description</th> + </tr> + <tr> + <td>{{jsxref("Global_Objects/Object/count", "__count__")}}</td> + <td>Returns the number of enumerable properties directly on a user-defined object.</td> + </tr> + <tr> + <td>{{jsxref("Global_Objects/Object/Parent", "__parent__")}}</td> + <td>Points to an object's context.</td> + </tr> + <tr> + <td>{{jsxref("Global_Objects/Object/eval", "Object.prototype.eval()")}}</td> + <td>Evaluates a string of JavaScript code in the context of the specified object.</td> + </tr> + <tr> + <td>{{jsxref("Object.observe()")}}</td> + <td>Asynchronously observing the changes to an object.</td> + </tr> + <tr> + <td>{{jsxref("Object.unobserve()")}}</td> + <td>Remove observers.</td> + </tr> + <tr> + <td>{{jsxref("Object.getNotifier()")}}</td> + <td>Creates an object that allows to synthetically trigger a change.</td> + </tr> + </tbody> +</table> + +<h3 id="Function">Function</h3> + +<table class="standard-table"> + <tbody> + <tr> + <th>Property</th> + <th>Description</th> + </tr> + <tr> + <td>{{jsxref("Global_Objects/Function/arity", "arity")}}</td> + <td>Number of formal arguments.</td> + </tr> + </tbody> +</table> + +<h3 id="Array">Array</h3> + +<table class="standard-table"> + <tbody> + <tr> + <td>Property</td> + <td>Description</td> + </tr> + <tr> + <td>{{jsxref("Array.observe()")}}</td> + <td>Asynchronously observing changes to Arrays.</td> + </tr> + <tr> + <td>{{jsxref("Array.unobserve()")}}</td> + <td>Remove observers.</td> + </tr> + </tbody> +</table> + +<h3 id="Number">Number</h3> + +<ul> + <li>{{jsxref("Number.toInteger()")}}</li> +</ul> + +<h3 id="ParallelArray">ParallelArray</h3> + +<ul> + <li>{{jsxref("ParallelArray")}}</li> +</ul> + +<h3 id="Statements">Statements</h3> + +<ul> + <li>{{jsxref("Statements/for_each...in", "for each...in")}} is deprecated. Use {{jsxref("Statements/for...of", "for...of")}} instead.</li> + <li>Destructuring {{jsxref("Statements/for...in", "for...in")}} is deprecated. Use {{jsxref("Statements/for...of", "for...of")}} instead.</li> + <li>let blocks and let expressions are obsolete.</li> +</ul> + +<h3 id="E4X">E4X</h3> + +<p>See <a href="/en-US/docs/Archive/Web/E4X">E4X</a> for more information.</p> + +<h3 id="Sharp_variables">Sharp variables</h3> + +<p>See <a href="/en-US/docs/Archive/Web/Sharp_variables_in_JavaScript">Sharp variables in JavaScript</a> for more information.</p> diff --git a/files/ko/web/javascript/reference/errors/bad_octal/index.html b/files/ko/web/javascript/reference/errors/bad_octal/index.html new file mode 100644 index 0000000000..8a4590e668 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/bad_octal/index.html @@ -0,0 +1,45 @@ +--- +title: 'SyntaxError: "x" is not a legal ECMA-262 octal constant' +slug: Web/JavaScript/Reference/Errors/Bad_octal +translation_of: Web/JavaScript/Reference/Errors/Bad_octal +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메시지">메시지</h2> + +<pre class="syntaxbox">Warning: SyntaxError: 08 is not a legal ECMA-262 octal constant. +Warning: SyntaxError: 09 is not a legal ECMA-262 octal constant. +</pre> + +<h2 id="에러_형식">에러 형식</h2> + +<p>{{jsxref("SyntaxError")}}<code>. </code>엄격 모드(<a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>)에서만 경고 됨.</p> + +<h2 id="무엇이_잘못되었을까">무엇이 잘못되었을까?</h2> + +<p>10진법의 리터럴은 <code>0</code>을 가장 앞 자리에 표시하고 뒤따라 다른 10진 숫자가 오게 할 수 있지만, <code>0</code>으로 시작하여 그 뒤를 따르는 모든 숫자들이 8보다 작다면, 그 수는 8진수로 해석됩니다. 이런 경우에는 <code>08<font face="Open Sans, Arial, sans-serif">과</font> 09<font face="Open Sans, Arial, sans-serif">는 허용되지 않기 때문에</font><font face="Open Sans, Arial, sans-serif"> </font></code>JavaScript는 경고를 띄웁니다. </p> + +<p>8진 리터럴과 8진 escape sequence는 사라지고 추가적인 경고가 나타날 것임을 알아 두세요. ECMAScript 6와 그 이후 버전의 구문은, 맨 앞자리에 위치하는 <code>0</code>의 뒤에 소문자 또는 대문자의 라틴 문자 "O" 를 위치시키도록 합니다 (<code>0o</code> or <code>0O)</code>. 더 자세한 설명은 <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Octal">lexical grammar</a> 페이지를 보세요.</p> + +<h2 id="예">예</h2> + +<h3 id="유효하지_않은_8진수">유효하지 않은 8진수</h3> + +<pre class="brush: js example-bad">08; +09; +// SyntaxError: 08 is not a legal ECMA-262 octal constant +// SyntaxError: octal literals and octal escape sequences are deprecated</pre> + +<h3 id="유효한_8진수">유효한 8진수</h3> + +<p>선두로 사용된 <code>0</code>의 뒤에는 문자 "o"가 오도록 한다. </p> + +<pre class="brush: js example-good">0O755; +0o644; +</pre> + +<h2 id="참고">참고</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Octal">Lexical grammar</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/bad_radix/index.html b/files/ko/web/javascript/reference/errors/bad_radix/index.html new file mode 100644 index 0000000000..3ea98bf1eb --- /dev/null +++ b/files/ko/web/javascript/reference/errors/bad_radix/index.html @@ -0,0 +1,57 @@ +--- +title: 'RangeError: radix must be an integer' +slug: Web/JavaScript/Reference/Errors/Bad_radix +translation_of: Web/JavaScript/Reference/Errors/Bad_radix +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메시지">메시지</h2> + +<pre class="syntaxbox">RangeError: radix must be an integer at least 2 and no greater than 36 (Firefox) +RangeError: toString() radix argument must be between 2 and 36 (Chrome) +</pre> + +<h2 id="에러_형식">에러 형식</h2> + +<p>{{jsxref("RangeError")}}</p> + +<h2 id="무엇이_잘못되었을까">무엇이 잘못되었을까?</h2> + +<p>{{jsxref("Number.prototype.toString()")}} 메소드는 선택적 파라메터인 <code>radix</code>(기수:진수를 지정하는 값)와 함께 사용되어 왔습니다. 이 파라메터는 반드시 수의 값을 나타내는 진법의 2와 36 사이로 지정된 정수(숫자)여야 합니다. </p> + +<p>왜 36으로 제한이 되었을까요? <code>radix</code>는 digit(밑기수) 알파벳 글자로 사용되는 10보다는 큽니다. 그렇기 때문에, <code>radix</code>는 라틴 알파벳 26글자를 가졌을 때, 36보다 클 수 없습니다. </p> + +<p>보통 아래의 <code>radix</code> 중 하나를 사용하게 될 것입니다.</p> + +<ul> + <li>2 for <a href="https://en.wikipedia.org/wiki/Binary_number">binary numbers</a> (2진수),</li> + <li>8 for <a href="https://en.wikipedia.org/wiki/Octal">octal numbers</a> (8진수),</li> + <li>10 for <a href="https://en.wikipedia.org/wiki/Decimal">decimal numbers</a> (10진수),</li> + <li>16 for <a href="https://en.wikipedia.org/wiki/Hexadecimal">hexadecimal numbers</a> (16진수).</li> +</ul> + +<h2 id="예">예</h2> + +<h3 id="허용되지_않는_경우">허용되지 않는 경우</h3> + +<pre class="brush: js example-bad">(42).toString(0); +(42).toString(1); +(42).toString(37); +(42).toString(150); +//포맷팅하기 위해 string을 이런 식으로 사용할 수는 없습니다. : +(12071989).toString("MM-dd-yyyy"); +</pre> + +<h3 id="허용된_경우">허용된 경우</h3> + +<pre class="brush: js example-good">(42).toString(2); // "101010" (2진수) +(13).toString(8); // "15" (8진수) +(0x42).toString(10); // "66" (10진수) +(100000).toString(16) // "186a0" (16진수) +</pre> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("Number.prototype.toString()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/bad_regexp_flag/index.html b/files/ko/web/javascript/reference/errors/bad_regexp_flag/index.html new file mode 100644 index 0000000000..2c8d12289d --- /dev/null +++ b/files/ko/web/javascript/reference/errors/bad_regexp_flag/index.html @@ -0,0 +1,107 @@ +--- +title: 'SyntaxError: invalid regular expression flag "x"' +slug: Web/JavaScript/Reference/Errors/Bad_regexp_flag +tags: + - 구문 에러 + - 자바스크립트 + - 정규식 + - 플래그 +translation_of: Web/JavaScript/Reference/Errors/Bad_regexp_flag +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메세지">메세지</h2> + +<pre class="syntaxbox">SyntaxError: Syntax error in regular expression (Edge) +SyntaxError: invalid regular expression flag "x" (Firefox) +SyntaxError: Invalid regular expression flags (Chrome) +</pre> + +<h2 id="에러_타입">에러 타입</h2> + +<p>{{jsxref("SyntaxError")}}</p> + +<h2 id="무엇이_잘못되었을까">무엇이 잘못되었을까?</h2> + +<p>코드에 잘못된 정규 표현식 플래그가 있습니다. 슬래시로 묶인 패턴으로 구성되어 있는 정규 표현식 문자에서 플래그는 두 번째 플래그 뒤에 정의됩니다. 플래그는 또한 {{jsxref("RegExp")}} 객체의 생성자 함수에서도 정의될 수 있습니다(두 번째 매개변수). 정규 표현식 플래그는 따로 또는 순서에 상관 없이 같이 사용될 수 있지만 ECMAScript에는 오직 5개만 있습니다.</p> + +<p>정규 표현식에 플래그를 포함시키려면 아래의 문법을 사용하세요:</p> + +<pre class="brush: js">var re = /pattern/flags; +</pre> + +<p>또는</p> + +<pre class="brush: js">var re = new RegExp('pattern', 'flags');</pre> + +<table class="standard-table"> + <caption>정규 표현식 플래그</caption> + <thead> + <tr> + <th scope="col">플래그</th> + <th scope="col">설명</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>g</code></td> + <td>전역 검색.</td> + </tr> + <tr> + <td>i</td> + <td>대소문자 구별 없이 검색.</td> + </tr> + <tr> + <td>m</td> + <td>여러 줄(Multi-line) 검색.</td> + </tr> + <tr> + <td>u</td> + <td>유니코드; 패턴을 유니코드 코드 포인트의 나열로 취급.</td> + </tr> + <tr> + <td>y</td> + <td>현재 위치에서 검색. ("sticky" 검색). {{jsxref("RegExp.sticky", "sticky")}} 참조.</td> + </tr> + </tbody> +</table> + +<h2 id="예제">예제</h2> + +<p>5개의 플래그만이 유효합니다.</p> + +<pre class="brush: js example-bad">/foo/bar; + +// SyntaxError: invalid regular expression flag "b" +</pre> + +<p>정규 표현식을 만들려고 했나요? 두 개의 슬래시가 포함된 표현식은 정규 표현식 문자로 해석됩니다.</p> + +<pre class="brush: js example-bad">let obj = { + url: /docs/Web +}; + +// SyntaxError: invalid regular expression flag "W" +</pre> + +<p>아니면 문자열로 만들려고 했나요? 작은 따옴표 또는 큰 따옴표를 추가하여 문자열을 만듭니다.</p> + +<pre class="brush: js example-good">let obj = { + url: '/docs/Web' +};</pre> + +<h3 id="유효한_정규_표현식_플래그">유효한 정규 표현식 플래그</h3> + +<p>자바스크립트에서 허용하는 5개의 유효한 정규 표현식 플래그를 위의 표에서 확인하세요.</p> + +<pre class="brush: js example-good">/foo/g; +/foo/gim; +/foo/uy; +</pre> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/%EC%A0%95%EA%B7%9C%EC%8B%9D">정규 표현식</a></li> + <li><a href="http://xregexp.com/flags/">XRegEx flags</a> – 새로운 4개의 플래그(<code>n</code>, <code>s</code>, <code>x</code>, <code>A</code>)를 제공하는 정규 표현식 라이브러리</li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/bad_return_or_yield/index.html b/files/ko/web/javascript/reference/errors/bad_return_or_yield/index.html new file mode 100644 index 0000000000..1239fa27f4 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/bad_return_or_yield/index.html @@ -0,0 +1,51 @@ +--- +title: 'SyntaxError: return not in function' +slug: Web/JavaScript/Reference/Errors/Bad_return_or_yield +translation_of: Web/JavaScript/Reference/Errors/Bad_return_or_yield +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메시지">메시지</h2> + +<pre class="syntaxbox">SyntaxError: return not in function +SyntaxError: yield not in function +</pre> + +<h2 id="에러_타입">에러 타입</h2> + +<p>{{jsxref("SyntaxError")}}.</p> + +<h2 id="뭐가_잘못된_걸까요">뭐가 잘못된 걸까요?</h2> + +<p><code><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/return">return</a></code> 또는 <code><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/yield">yield</a></code> 문장이 <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/%ED%95%A8%EC%88%98">function</a> 밖에서 호출되었기 때문입니다. 혹시 어딘가에 중괄호를 빠트리신 건 아닌가요? <code>return</code> 과 <code>yield</code> function 내에 있어야 합니다, 왜냐하면 이것들은 function의 실행 종료 (또는 일시정지 및 재개)를 의미하고 function 호출자에게 특정 값을 반환하기 위해 사용되기 때문입니다.</p> + +<h2 id="예제">예제</h2> + +<pre class="brush: js example-bad">var cheer = function(score) { + if (score === 147) + return 'Maximum!'; + }; + if (score > 100) { + return 'Century!'; + } +} + +// SyntaxError: return not in function</pre> + +<p>처음 볼 때는 중괄호가 제대로 있는 것처럼 보인다, 하지만 이 코드 조각에는 if 문장 다음에 중괄호가 하나 빠져 있다. 다음처럼 고쳐야 한다:</p> + +<pre class="brush: js example-good">var cheer = function(score) { + if (score === 147) { + return 'Maximum!'; + } + if (score > 100) { + return 'Century!'; + } +};</pre> + +<h2 id="또_다른_내용">또 다른 내용</h2> + +<ul> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/return">return</a></code></li> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/yield">yield</a></code></li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/cant_access_lexical_declaration_before_init/index.html b/files/ko/web/javascript/reference/errors/cant_access_lexical_declaration_before_init/index.html new file mode 100644 index 0000000000..593e8cca13 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/cant_access_lexical_declaration_before_init/index.html @@ -0,0 +1,56 @@ +--- +title: 'ReferenceError: can''t access lexical declaration`X'' before initialization' +slug: Web/JavaScript/Reference/Errors/Cant_access_lexical_declaration_before_init +translation_of: Web/JavaScript/Reference/Errors/Cant_access_lexical_declaration_before_init +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="Message">Message</h2> + +<pre class="syntaxbox">ReferenceError: can't access lexical declaration `X' before initialization (Firefox) +ReferenceError: 'x' is not defined (Chrome) +</pre> + +<h2 id="Error_type">Error type</h2> + +<p>{{jsxref("ReferenceError")}}</p> + +<h2 id="무엇이_잘못_되었을까요">무엇이 잘못 되었을까요?</h2> + +<p>변수가 초기화 되기 전에 엑세스가 되어버립니다. 이 문제는 let 또는 const 선언이 정의 되기 전에 엑세스되는 모든 block 문에서 발생합니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="잘못된_경우">잘못된 경우</h3> + +<p>이 경우에 변수 "foo"는 <code>let</code> 을 사용하여 block 문에서 다시 선언됩니다.</p> + +<pre class="brush: js example-bad">function test() { + let foo = 33; + if (true) { + let foo = (foo + 55); + // ReferenceError: can't access lexical + // declaration `foo' before initialization + } +} +test(); +</pre> + +<h3 id="올바른_경우">올바른 경우</h3> + +<p>if 문에서 "foo"를 변경하려면 재 선언을 발생시키는 <code>let</code> 을 제거해야합니다.</p> + +<pre class="brush: js example-good">function test(){ + let foo = 33; + if (true) { + foo = (foo + 55); + } +} +test(); +</pre> + +<h2 id="그밖에_볼_것">그밖에 볼 것</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/let#Temporal_Dead_Zone_and_errors_with_let">Temporal Dead Zone and errors with let</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/delete_in_strict_mode/index.html b/files/ko/web/javascript/reference/errors/delete_in_strict_mode/index.html new file mode 100644 index 0000000000..138384bcac --- /dev/null +++ b/files/ko/web/javascript/reference/errors/delete_in_strict_mode/index.html @@ -0,0 +1,71 @@ +--- +title: >- + SyntaxError: applying the 'delete' operator to an unqualified name is + deprecated +slug: Web/JavaScript/Reference/Errors/Delete_in_strict_mode +tags: + - 가비지 컬렉터 + - 구문 에러 + - 변수 삭제 + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Errors/Delete_in_strict_mode +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메세지">메세지</h2> + +<pre class="syntaxbox">SyntaxError: Calling delete on expression not allowed in strict mode (Edge) +SyntaxError: applying the 'delete' operator to an unqualified name is deprecated (Firefox) +SyntaxError: Delete of an unqualified identifier in strict mode. (Chrome) +</pre> + +<h2 id="에러_타입">에러 타입</h2> + +<p>엄격(Strict) 모드에서의 {{jsxref("SyntaxError")}}</p> + +<h2 id="무엇이_잘못되었을까">무엇이 잘못되었을까?</h2> + +<p>자바스크립트에서 일반 변수는 <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete">delete</a></code> 연산자를 사용하여 삭제할 수 없습니다. 엄격 모드에서 변수를 삭제하는 접근은 허용되지 않으므로 에러가 발생합니다.</p> + +<p><code>delete</code> 연산자는 오직 객체의 속성만을 삭제할 수 있습니다. 객체 속성은 설정할 수 있는 경우 "수식"될 수 있습니다.</p> + +<p>일반적인 생각과 다르게 <code>delete</code> 연산자는 메모리 해제와 직접적인 연관이 없습니다. 메모리 관리는 참조가 깨짐에 따라 간접적으로 수행됩니다. 자세한 내용은 <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Memory_Management">메모리 관리</a> 페이지와 <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete">delete</a></code> 연산자 페이지를 참조하십시오.</p> + +<p>이 에러는 오직 <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Strict_mode">엄격 모드 코드</a>에서만 발생합니다. 엄격하지 않은 모드에서 해당 연산자는 단순히 <code>false</code> 를 반환합니다.</p> + +<h2 id="예제">예제</h2> + +<p>자바스크립트에서 일반 변수를 삭제하려고 하면 동작하지 않습니다. 그리고 엄격 모드에서는 에러가 발생합니다:</p> + +<pre class="brush: js example-bad">'use strict'; + +var x; + +// ... + +delete x; + +// SyntaxError: applying the 'delete' operator to an unqualified name +// is deprecated +</pre> + +<p>변수의 내용을 비우려면 {{jsxref("null")}}을 설정하면 됩니다:</p> + +<pre class="brush: js example-good">'use strict'; + +var x; + +// ... + +x = null; + +// x는 가비지 컬렉터에 의해 메모리에서 해제됩니다 +</pre> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete">delete</a></code></li> + <li><a href="/en-US/docs/Web/JavaScript/Memory_Management">메모리 관리</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Errors/Cant_delete">TypeError: property "x" is non-configurable and can't be deleted</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/deprecated_caller_or_arguments_usage/index.html b/files/ko/web/javascript/reference/errors/deprecated_caller_or_arguments_usage/index.html new file mode 100644 index 0000000000..fc613db1d0 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/deprecated_caller_or_arguments_usage/index.html @@ -0,0 +1,70 @@ +--- +title: 'ReferenceError: deprecated caller or arguments usage' +slug: Web/JavaScript/Reference/Errors/Deprecated_caller_or_arguments_usage +translation_of: Web/JavaScript/Reference/Errors/Deprecated_caller_or_arguments_usage +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메시지">메시지</h2> + +<pre class="syntaxbox">Warning: ReferenceError: deprecated caller usage (Firefox) +Warning: ReferenceError: deprecated arguments usage (Firefox) +TypeError: 'callee' and 'caller' cannot be accessed in strict mode. (Safari) +</pre> + +<h2 id="에러_형식">에러 형식</h2> + +<p>엄격 모드에서만 {{jsxref("ReferenceError")}} 경고가 발생합니다. JavaScript 실행이 중단되지는 않을 것입니다. </p> + +<h2 id="무엇이_잘못되었을까">무엇이 잘못되었을까?</h2> + +<p>엄격모드에서, {{jsxref("Function.caller")}} 나 {{jsxref("Function.arguments")}} 속성이 사용되었고, 그러지 말아야 했습니다. 이 속성들은 사라지게 되었는데, 함수 호출자를 흘려보내거나, 비 표준이었으며, 최적화 하기 어렵고, 잠재적으로 퍼포먼스에 무리를 주었기 때문입니다.</p> + +<h2 id="예">예</h2> + +<h3 id="function.caller_or_arguments.callee.caller"><code>function.caller</code> or <code>arguments.callee.caller</code></h3> + +<p>{{jsxref("Function.caller")}} 와 <code><a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee">arguments.callee.caller</a></code> 는 사라지게 되었습니다. (자세한 정보는 레퍼런스 문서를 확인해 보세요.)</p> + +<pre class="brush: js example-bad">"use strict"; + +function myFunc() { + if (myFunc.caller == null) { + return 'The function was called from the top!'; + } else { + return 'This function\'s caller was ' + myFunc.caller; + } +} + +myFunc(); +// Warning: ReferenceError: deprecated caller usage +// "The function was called from the top!"</pre> + +<h3 id="Function.arguments"><code>Function.arguments</code></h3> + +<p>{{jsxref("Function.arguments")}} 는 사라졌습니다. (자세한 정보는 레퍼런스 문서를 확인해 주세요.) </p> + +<pre class="brush: js example-bad">"use strict"; + +function f(n) { g(n - 1); } + +function g(n) { + console.log('before: ' + g.arguments[0]); + if (n > 0) { f(n); } + console.log('after: ' + g.arguments[0]); +} + +f(2); + +console.log('returned: ' + g.arguments); +// Warning: ReferenceError: deprecated arguments usage +</pre> + +<h2 id="참조">참조</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features">Deprecated and obsolete features</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">Strict mode</a></li> + <li>{{jsxref("Function.arguments")}}</li> + <li>{{jsxref("Function.caller")}} and <code><a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee">arguments.callee.caller</a></code></li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/deprecated_octal/index.html b/files/ko/web/javascript/reference/errors/deprecated_octal/index.html new file mode 100644 index 0000000000..55d85cf7eb --- /dev/null +++ b/files/ko/web/javascript/reference/errors/deprecated_octal/index.html @@ -0,0 +1,64 @@ +--- +title: 'SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated' +slug: Web/JavaScript/Reference/Errors/Deprecated_octal +translation_of: Web/JavaScript/Reference/Errors/Deprecated_octal +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메시지">메시지</h2> + +<pre class="syntaxbox">SyntaxError: Octal numeric literals and escape characters not allowed in strict mode (Edge) +SyntaxError: +"0"-prefixed octal literals and octal escape sequences are deprecated; +for octal literals use the "0o" prefix instead +</pre> + +<h2 id="에러_타입">에러 타입</h2> + +<p>{{jsxref("SyntaxError")}} <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a> 내에서만.</p> + +<h2 id="무엇이_잘_못_되었을까">무엇이 잘 못 되었을까?</h2> + +<p>8진 리터럴과 8진수 이스케이프 시퀀스는 더 이상 사용하지 않으며, 엄격 모드(strict mode) 내에서는 {{jsxref("SyntaxError")}} 에러를 던질 것입니다. ECMAScript 2015와 이 후의 버전의 표준화된 구문은 0을 맨 앞자리에 두고 그 뒤를 대문자 또는 소문자의 라틴 문자 "O" 를 사용하도록 합니다. (<code>0o</code> 또는 <code>0O)</code></p> + +<h2 id="예제">예제</h2> + +<h3 id="0이_접두인_8진_리터럴">"0"이 접두인 8진 리터럴</h3> + +<pre class="brush: js example-bad">"use strict"; + +03; + +// SyntaxError: "0"-prefixed octal literals and octal escape sequences +// are deprecated (0으로 시작하는 8진수와 8진 이스케이프 시퀀스는 더 이상 사용되지 않습니다. ) +</pre> + +<h3 id="8진수_이스케이프_시퀀스">8진수 이스케이프 시퀀스</h3> + +<pre class="brush: js example-bad">"use strict"; + +"\251"; + +// SyntaxError: "0"-prefixed octal literals and octal escape sequences +// are deprecated (0으로 시작하는 8진수와 8진 이스케이프 시퀀스는 더 이상 사용되지 않습니다. ) +</pre> + +<h3 id="유효한_8진_수들">유효한 8진 수들</h3> + +<p>0뒤에 "o" 또는 "O"를 사용합니다. :</p> + +<pre class="brush: js example-good">0o3; +</pre> + +<p>8진수 이스케이프 시퀀스 대신 16진수 이스케이프 시퀀스를 사용할 수도 있습니다. :</p> + +<pre class="brush: js example-good">'\xA9';</pre> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Octal">Lexical grammar</a></li> + <li> + <p><a href="/en-US/docs/Web/JavaScript/Reference/Errors/Bad_octal">Warning: 08/09 is not a legal ECMA-262 octal constant</a></p> + </li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/identifier_after_number/index.html b/files/ko/web/javascript/reference/errors/identifier_after_number/index.html new file mode 100644 index 0000000000..14e5b336c7 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/identifier_after_number/index.html @@ -0,0 +1,57 @@ +--- +title: 'SyntaxError: identifier starts immediately after numeric literal' +slug: Web/JavaScript/Reference/Errors/Identifier_after_number +tags: + - 구문 에러 + - 변수 이름 + - 식별자 + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Errors/Identifier_after_number +--- +<div>{{JSSidebar("Errors")}}</div> + +<h2 id="메세지">메세지</h2> + +<pre class="syntaxbox">SyntaxError: Unexpected identifier after numeric literal (Edge) +SyntaxError: identifier starts immediately after numeric literal (Firefox) +SyntaxError: Unexpected number (Chrome) +</pre> + +<h2 id="에러_타입">에러 타입</h2> + +<p>{{jsxref("SyntaxError")}}</p> + +<h2 id="무엇이_잘못되었을까">무엇이 잘못되었을까?</h2> + +<p>{{Glossary("식별자", "식별자")}}라고 불리는 변수의 이름은 반드시 지켜야 하는 특정 규칙을 따라야 합니다.</p> + +<p>자바스크립트의 식별자는 반드시 문자, 언더스코어(_), 또는 달러 표시($)로 시작돼야 합니다. 숫자로 시작될 수 없습니다. 글자 뒤에만 숫자(0-9)가 올 수 있습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="숫자로_시작하는_변수_이름">숫자로 시작하는 변수 이름</h3> + +<p>자바스크립트에서 변수 이름은 숫자로 시작될 수 없습니다. 아래 예제는 에러가 발생합니다:</p> + +<pre class="brush: js example-bad">var 1life = 'foo'; +// SyntaxError: identifier starts immediately after numeric literal + +var foo = 1life; +// SyntaxError: identifier starts immediately after numeric literal + +alert(1.foo); +// SyntaxError: identifier starts immediately after numeric literal +</pre> + +<p>숫자가 뒤에 오도록 변수 이름을 변경해야 합니다.</p> + +<pre class="brush: js example-good">var life1 = 'foo'; +var foo = life1; +</pre> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Lexical_grammar">문법</a></li> + <li><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#%EB%B3%80%EC%88%98">변수</a>(<a href="/en-US/docs/Web/JavaScript/Guide">JavaScript Guide</a>)</li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/illegal_character/index.html b/files/ko/web/javascript/reference/errors/illegal_character/index.html new file mode 100644 index 0000000000..b3cd3a9750 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/illegal_character/index.html @@ -0,0 +1,81 @@ +--- +title: 'SyntaxError: illegal character' +slug: Web/JavaScript/Reference/Errors/Illegal_character +tags: + - ZWSP + - 구문 에러 + - 자바스크립트 + - 폭 없는 공백 +translation_of: Web/JavaScript/Reference/Errors/Illegal_character +--- +<p>{{jsSidebar("Errors")}}</p> + +<h2 id="메세지">메세지</h2> + +<pre class="syntaxbox">SyntaxError: Invalid character (Edge) +SyntaxError: illegal character (Firefox) +SyntaxError: Invalid or unexpected token (Chrome) +</pre> + +<h2 id="에러_타입">에러 타입</h2> + +<p>{{jsxref("SyntaxError")}}</p> + +<h2 id="무엇이_잘못되었을까">무엇이 잘못되었을까?</h2> + +<p>코드에 해당 구문에 맞지 않거나 예기치 않은 토큰이 있습니다. 마이너스 기호(<code> - </code>)와 대시(<code> – </code>) 또는 따옴표(<code> " </code>)와 비표준 따옴표(<code> “ </code>) 등이 잘못 사용된 경우에 대해 문법 체크를 해주는 편집기를 사용하여 코드를 주의 깊게 확인해야 합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="잘못_사용된_문자">잘못 사용된 문자</h3> + +<p>일부 문자들은 비슷하게 보이지만 파서가 코드 해석을 실패하게 만듭니다. 유명한 예로 따옴표, 마이너스 또는 세미콜론(<a href="https://en.wikipedia.org/wiki/Question_mark#Greek_question_mark">greek questionmark (U+37e)</a>과 동일하게 보입니다)이 있습니다.</p> + +<pre class="brush: js example-bad">“This looks like a string”; // SyntaxError: illegal character + // 비슷해 보이지만 “와 ”는 "이 아닙니다 + +42 – 13; // SyntaxError: illegal character + // 비슷해 보이지만 –은 -이 아닙니다 + +var foo = 'bar'; // SyntaxError: illegal character + // 비슷해 보이지만 <37e>은 ;이 아닙니다 +</pre> + +<p>아래 예제는 정상적으로 동작합니다:</p> + +<pre class="brush: js example-good">"This is actually a string"; +42 - 13; +var foo = 'bar'; +</pre> + +<p><span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body"><span class="objectBox objectBox-string">일부 편집기와 IDE는 문제가 있는 부분을 알려주거나 적어도 강조 표시를 해주지만 전부는 아닙니다. 이런 에러가 발생했을 때 무엇이 문제인지 찾을 수 없는 경우, 문제가 있는 줄을 지우고 다시 작성하는 것 가장 좋습니다.</span></span></span></span></p> + +<h3 id="문자_빠트리기">문자 빠트리기</h3> + +<p>앞이나 뒤에 오는 문자를 잊어버리기 쉽습니다.</p> + +<pre class="brush: js example-bad">var colors = ['#000', #333', '#666']; +// SyntaxError: illegal character +</pre> + +<p> <code><strong>'</strong>#333'</code>에 빠진 작은따옴표를 추가합니다.</p> + +<pre class="brush: js example-good">var colors = ['#000', '#333', '#666'];</pre> + +<h3 id="숨겨진_문자">숨겨진 문자</h3> + +<p>다른 곳에서 코드를 복사하여 붙여넣은 경우 잘못된 문자가 포함돼 있을 수 있습니다. 주의하세요!</p> + +<pre class="brush: js example-bad">var foo = 'bar'; +// SyntaxError: illegal character +</pre> + +<p>Vim과 같은 편집기에서 아래 코드를 체크하면 폭 없는 공백(<a href="https://en.wikipedia.org/wiki/Zero-width_space">zero-width space (ZWSP) (U+200B)</a>) 문자가 있는 것을 확인할 수 있습니다.</p> + +<pre class="brush: js">var foo = 'bar';<200b></pre> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Lexical_grammar">문법</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/index.html b/files/ko/web/javascript/reference/errors/index.html new file mode 100644 index 0000000000..79e24cc575 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/index.html @@ -0,0 +1,12 @@ +--- +title: JavaScript error reference +slug: Web/JavaScript/Reference/Errors +tags: + - JavaScript +translation_of: Web/JavaScript/Reference/Errors +--- +<p>{{jsSidebar("Errors")}}</p> + +<p>오류, 사방에 오류.</p> + +<p>{{ListSubPages("/ko/docs/Web/JavaScript/Reference/Errors")}}</p> diff --git a/files/ko/web/javascript/reference/errors/invalid_array_length/index.html b/files/ko/web/javascript/reference/errors/invalid_array_length/index.html new file mode 100644 index 0000000000..6ddeb58f06 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/invalid_array_length/index.html @@ -0,0 +1,73 @@ +--- +title: 'RangeError: invalid array length' +slug: Web/JavaScript/Reference/Errors/Invalid_array_length +translation_of: Web/JavaScript/Reference/Errors/Invalid_array_length +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메세지">메세지</h2> + +<pre class="syntaxbox">RangeError: invalid array length (Firefox) +RangeError: Invalid array length (Chrome) +RangeError: Invalid array buffer length (Chrome) +</pre> + +<h2 id="에러_형식">에러 형식</h2> + +<p>{{jsxref("RangeError")}}</p> + +<h2 id="무엇이_잘못_된_것일까">무엇이 잘못 된 것일까?</h2> + +<p>다음과 같은 원인 때문이다:</p> + +<ul> + <li>2<sup>32</sup>와 같거나 이보다 긴, 혹은 음수의 길이를 가진 {{jsxref("Array")}}나 {{jsxref("ArrayBuffer")}}를 생성했기 때문에, 혹은</li> + <li>{{jsxref("Array")}} 속성을 2<sup>32</sup>와 같거나 이보다 긴 값으로 설정했기 때문이다.</li> +</ul> + +<p><code>Array와 ArrayBuffer의 길이에 제한을 둔 이유는, Array나 ArrayBuffer의 length 속성은 사인되지 않은(unsigned) 32 비트 정수로 반영되기 때문이다.</code> 즉 <code>Array나 ArrayBuffer는 오직 0 ~ </code>2<sup>32</sup>-1 사이의 값만을 저장할 수 있다.</p> + +<p>Array의 length로 해석되는 첫번째 argument로서 문자열 표기를 통해 contructor를 사용하여 Array를 생성할 수 있다.</p> + +<p>다른 방법으로는, length 속성을 설정하기 전에 length의 길이에 제한을 두거나, constructor의 aurgment로서 사용할 수 있다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="잘못된_예제">잘못된 예제</h3> + +<pre class="brush: js example-bad">new Array(Math.pow(2, 40)) +new Array(-1) +new ArrayBuffer(Math.pow(2, 32)) +new ArrayBuffer(-1) + +let a = []; +a.length = a.length - 1; // set -1 to the length property + +let b = new Array(Math.pow(2, 32) - 1); +b.length = b.length + 1; // set 2^32 to the length property +</pre> + +<h3 id="올바른_예제">올바른 예제</h3> + +<pre class="brush: js example-good">[ Math.pow(2, 40) ] // [ 1099511627776 ] +[ -1 ] // [ -1 ] +new ArrayBuffer(Math.pow(2, 32) - 1) +new ArrayBuffer(0) + +let a = []; +a.length = Math.max(0, a.length - 1); + +let b = new Array(Math.pow(2, 32) - 1); +b.length = Math.min(0xffffffff, b.length + 1); + +// 0xffffffff is the hexadecimal notation for 2^32 - 1 +// which can also be written as (-1 >>> 0) +</pre> + +<h2 id="sect1"> </h2> + +<ul> + <li>{{jsxref("Array")}}</li> + <li>{{jsxref("Array.length")}}</li> + <li>{{jsxref("ArrayBuffer")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/invalid_assignment_left-hand_side/index.html b/files/ko/web/javascript/reference/errors/invalid_assignment_left-hand_side/index.html new file mode 100644 index 0000000000..7a7acf3ca2 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/invalid_assignment_left-hand_side/index.html @@ -0,0 +1,50 @@ +--- +title: 'ReferenceError: invalid assignment left-hand side' +slug: Web/JavaScript/Reference/Errors/Invalid_assignment_left-hand_side +translation_of: Web/JavaScript/Reference/Errors/Invalid_assignment_left-hand_side +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메시지">메시지</h2> + +<pre class="syntaxbox">ReferenceError: invalid assignment left-hand side +</pre> + +<h2 id="에러_타입">에러 타입</h2> + +<p>{{jsxref("ReferenceError")}}.</p> + +<h2 id="무엇이_잘못되었을까">무엇이 잘못되었을까?</h2> + +<p>예상치 못한 할당이 일어났습니다. 이것은 할당 연산자(<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators">assignment operator</a>)와 비교 연산자(<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">comparison operator</a>) 간의 불일치로 인한 것일 겁니다. 예를 들면, "<code>=</code>" 부호는 값을 변수에 할당합니다. "<code>==</code>" 나 "<code>===</code>"는 값을 비교하는 연산을 합니다.</p> + +<h2 id="예">예</h2> + +<pre class="brush: js example-bad">if (Math.PI = 3 || Math.PI = 4) { + console.log('no way!'); +} +// ReferenceError: invalid assignment left-hand side + +var str = 'Hello, ' ++= 'is it me ' ++= 'you\'re looking for?'; +// ReferenceError: invalid assignment left-hand side +</pre> + +<p><code>if </code>구문에서, 비교 연산자 ("==")로 비교하려 할 때, 문자열의 연속적인 결합의 경우에는, 플러스("+") 연산자가 필요합니다.</p> + +<pre class="brush: js example-good">if (Math.PI == 3 || Math.PI == 4) { + console.log('no way!'); +} + +var str = 'Hello, ' ++ 'from the ' ++ 'other side!'; +</pre> + +<h2 id="참조">참조</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators">Assignment operators</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">Comparison operators</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/invalid_date/index.html b/files/ko/web/javascript/reference/errors/invalid_date/index.html new file mode 100644 index 0000000000..32cf041e7e --- /dev/null +++ b/files/ko/web/javascript/reference/errors/invalid_date/index.html @@ -0,0 +1,50 @@ +--- +title: 'RangeError: invalid date' +slug: Web/JavaScript/Reference/Errors/Invalid_date +translation_of: Web/JavaScript/Reference/Errors/Invalid_date +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메시지">메시지</h2> + +<pre class="syntaxbox">RangeError: invalid date (Firefox) +RangeError: invalid time value (Chrome) +RangeError: Provided date is not in valid range (Chrome) +</pre> + +<h2 id="에러_종류">에러 종류</h2> + +<p>{{jsxref("RangeError")}}</p> + +<h2 id="무엇이_잘못_된_걸까">무엇이 잘못 된 걸까?</h2> + +<p>유효하지 않은 String이 {{jsxref("Date")}} 나 {{jsxref("Date.parse()")}}에 입력되었습니다.</p> + +<h2 id="예시">예시</h2> + +<h3 id="올바르지_않은_사용_예시">올바르지 않은 사용 예시</h3> + +<p>인식 할 수 없는 string이나 잘못된 요소 값을 포함하는 ISO 형식의 날짜 string은 일반적으로 {{jsxref ( "NaN")}}을 반환합니다. 그러나 구현 방식에 따라 ISO 형식 string을 따르지 않는 경우 <code>RangeError: invalid date</code>가 표시 될 수 있습니다. Firefox의 경우:</p> + +<pre class="brush: js example-bad">new Date('foo-bar 2014'); +new Date('2014-25-23').toISOString(); +new Date('foo-bar 2014').toString(); +</pre> + +<p>그러나 이 경우, Firefox에서는 {{jsxref("NaN")}} 을 반환합니다:</p> + +<pre class="brush: js example-bad">Date.parse('foo-bar 2014'); // NaN</pre> + +<p>더 자세한 사항은 {{jsxref("Date.parse()")}} 문서를 참고하세요.</p> + +<h3 id="올바른_사용_예시">올바른 사용 예시</h3> + +<pre class="brush: js example-good">new Date('05 October 2011 14:48 UTC');</pre> + +<h2 id="더_보기">더 보기</h2> + +<ul> + <li>{{jsxref("Date")}}</li> + <li>{{jsxref("Date.prototype.parse()")}}</li> + <li>{{jsxref("Date.prototype.toISOString()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/invalid_for-in_initializer/index.html b/files/ko/web/javascript/reference/errors/invalid_for-in_initializer/index.html new file mode 100644 index 0000000000..7dd5e15a9a --- /dev/null +++ b/files/ko/web/javascript/reference/errors/invalid_for-in_initializer/index.html @@ -0,0 +1,75 @@ +--- +title: 'SyntaxError: for-in loop head declarations may not have initializers' +slug: Web/JavaScript/Reference/Errors/Invalid_for-in_initializer +tags: + - for...in 구문 + - 구문 에러 + - 배열 반복 + - 자바스크립트 + - 초기화 +translation_of: Web/JavaScript/Reference/Errors/Invalid_for-in_initializer +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메세지">메세지</h2> + +<pre class="syntaxbox">SyntaxError: for-in loop head declarations cannot have an initializer (Edge) +SyntaxError: for-in loop head declarations may not have initializers (Firefox) +SyntaxError: for-in loop variable declaration may not have an initializer. (Chrome) +</pre> + +<h2 id="에러_타입">에러 타입</h2> + +<p>엄격(Strict) 모드에서의 {{jsxref("SyntaxError")}}.</p> + +<h2 id="무엇이_잘못되었을까">무엇이 잘못되었을까?</h2> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in">for...in</a> 반복문의 선언부에 초기화 구문이 포함되어 있습니다. 즉, |<code>for (var i = 0 in obj)</code>| 구문을 통해 변수가 정의되고 값이 할당된 것을 말합니다. 비엄격 모드(non-strict) 모드에서는 이 초기화 구문이 무시되어 <code>|for (var i in obj)|</code> 처럼 동작합니다. 하지만 엄격 모드에서는 <code>SyntaxError</code> 가 발생합니다.</p> + +<h2 id="예제">예제</h2> + +<p>이 예제는 <code>SyntaxError</code>를 발생시킵니다.</p> + +<pre class="brush: js example-bad">"use strict"; + +var obj = {a: 1, b: 2, c: 3 }; + +for (var i = 0 in obj) { + console.log(obj[i]); +} + +// SyntaxError: for-in loop head declarations may not have initializers +</pre> + +<h3 id="올바른_for-in_반복문">올바른 for-in 반복문</h3> + +<p>for-in 반복문의 선언부에서 초기화 구문(<code>i = 0</code>)을 삭제합니다.</p> + +<pre class="brush: js example-good">"use strict"; + +var obj = {a: 1, b: 2, c: 3 }; + +for (var i in obj) { + console.log(obj[i]); +} +</pre> + +<h3 id="배열_반복">배열 반복</h3> + +<p>for...in 반복문은 <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/for...in#Array_iteration_and_for...in">배열을 반복하는데에는 사용하지 않습니다</a>. 배열({{jsxref("Array")}})을 반복하기 위해 <code>for-in</code> 반복문 대신에 <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for">for</a></code> 반복문을 사용하려고 한 적이 있습니까? <code>for</code> 반복문은 선언부에서 초기화도 할 수 있습니다:</p> + +<pre class="brush: js example-good">var arr = [ "a", "b", "c" ] + +for (var i = 2; i < arr.length; i++) { + console.log(arr[i]); +} + +// "c"</pre> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in">for...in</a></code></li> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a></code> – 엄격 모드와 비엄격 모드에서 모두 초기화를 허용하지 않습니다.</li> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for">for</a></code> – 배열 반복에 적합하고 초기화도 가능합니다.</li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/invalid_for-of_initializer/index.html b/files/ko/web/javascript/reference/errors/invalid_for-of_initializer/index.html new file mode 100644 index 0000000000..0e60e242e8 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/invalid_for-of_initializer/index.html @@ -0,0 +1,64 @@ +--- +title: >- + SyntaxError: a declaration in the head of a for-of loop can't have an + initializer +slug: Web/JavaScript/Reference/Errors/Invalid_for-of_initializer +tags: + - For문 초기화 + - 구문 에러 + - 반복문 + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Errors/Invalid_for-of_initializer +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메세지">메세지</h2> + +<pre class="syntaxbox">SyntaxError: for-of loop head declarations cannot have an initializer (Edge) +SyntaxError: a declaration in the head of a for-of loop can't have an initializer (Firefox) +SyntaxError: for-of loop variable declaration may not have an initializer. (Chrome) +</pre> + +<h2 id="에러_타입">에러 타입</h2> + +<p>{{jsxref("SyntaxError")}}</p> + +<h2 id="무엇이_잘못되었을까">무엇이 잘못되었을까?</h2> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a> 반복문의 식이 초기화 구문을 포함한 것이 문제입니다. 즉, |<code>for (var i = 0 of iterable)</code>| 구문을 통해 변수가 정의되고 값이 할당된 것을 말합니다. 이 구문은 for-of 반복문에서 허용되지 않습니다. 이 경우 초기화를 할 수 있는 for 반복문이 필요합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="잘못된_for-of_반복문">잘못된 for-of 반복문</h3> + +<pre class="brush: js example-bad">let iterable = [10, 20, 30]; + +for (let value = 50 of iterable) { + console.log(value); +} + +// SyntaxError: a declaration in the head of a for-of loop can't +// have an initializer</pre> + +<h3 id="올바른_for-of_반복문">올바른 <code>for-of</code> 반복문</h3> + +<p>for-of 반복문에서 초기화 구문(<code>value = 50</code>)을 삭제해야 합니다. 50을 더하고 싶다면 다음 예제와 같이 반복문 안에 추가할 수 있습니다.</p> + +<pre class="brush: js example-good">let iterable = [10, 20, 30]; + +for (let value of iterable) { + value += 50; + console.log(value); +} +// 60 +// 70 +// 80 +</pre> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a></code></li> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in">for...in</a></code> – 엄격(Strict) 모드에서는 마찬가지로 초기화를 허용하지 않습니다. (<a href="/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_for-in_initializer">SyntaxError: for-in loop head declarations may not have initializers</a>)</li> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for">for</a></code> – 초기화를 허용합니다.</li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/is_not_iterable/index.html b/files/ko/web/javascript/reference/errors/is_not_iterable/index.html new file mode 100644 index 0000000000..8e00501d54 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/is_not_iterable/index.html @@ -0,0 +1,106 @@ +--- +title: 'TypeError: ''x'' is not iterable' +slug: Web/JavaScript/Reference/Errors/is_not_iterable +tags: + - JavaScript + - 레퍼런스 + - 에러 + - 타입에러 +translation_of: Web/JavaScript/Reference/Errors/is_not_iterable +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메시지">메시지</h2> + +<pre class="syntaxbox">TypeError: 'x' is not iterable (Firefox, Chrome) +TypeError: 'x' is not a function or its return value is not iterable (Chrome) +</pre> + +<h2 id="에러_타입">에러 타입</h2> + +<p>{{jsxref("TypeError")}}</p> + +<h2 id="무엇이_문제인가요">무엇이 문제인가요?</h2> + +<p>{{jsxref("Promise.all")}} 또는 {{jsxref("TypedArray.from")}} 과 같은 함수의 아규먼트 또는 <a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...of_statement">for…of</a> 의 right hand-side 로 주어진 값이 <a href="/ko/docs/Web/JavaScript/Reference/Iteration_protocols">iterable 객체</a>가 아닙니다. iterable 은 {{jsxref("Array")}}, {{jsxref("String")}} 또는 {{jsxref("Map")}}, 생성자 결과, 또는 <a href="/ko/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol">iterable protocol</a> 구현 객체와 같은 내장 iterable 타입이 될 수 있습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="모든_객체_프로퍼티_iterating">모든 객체 프로퍼티 iterating</h3> + +<p>JavaScript 에서 <a href="/ko/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol">iterable protocol</a> 을 구현하지 않은 {{jsxref("Object")}} 는 iterable 이 아닙니다.<br> + 그러므로, 객체의 프로퍼티를 반복하기 위해 <a href="/ko/docs/Web/JavaScript/Guide/Loops_and_iteration#for...of_statement">for…of</a> 를 사용하면 안됩니다.</p> + +<pre class="brush: js example-bad">var obj = { 'France': 'Paris', 'England': 'London' }; +for (let p of obj) { // TypeError: obj is not iterable + // … +} +</pre> + +<p>객체의 모든 항목 또는 프로퍼티를 반복하려면 대신 {{jsxref("Object.keys")}} 또는 {{jsxref("Object.entries")}} 를 사용해야 합니다.</p> + +<pre class="brush: js example-good">var obj = { 'France': 'Paris', 'England': 'London' }; +// 모든 프로퍼티 이름을 iterate: +for (let country of Object.keys(obj)) { + var capital = obj[country]; + console.log(country, capital); +} + +for (const [country, capital] of Object.entries(obj)) + console.log(country, capital); + + +</pre> + +<p>이 유즈 케이스에 대한 다른 옵션은 {{jsxref("Map")}} 을 사용하는 것입니다.</p> + +<pre class="brush: js example-good">var map = new Map; +map.set('France', 'Paris'); +map.set('England', 'London'); +// 모든 프로퍼티 이름 iterate +for (let country of map.keys()) { + let capital = map[country]; + console.log(country, capital); +} + +for (let capital of map.values()) + console.log(capital); + +for (const [country, capital] of map.entries()) + console.log(country, capital); +</pre> + +<h3 id="Generator_iterating">Generator iterating</h3> + +<p><a href="/ko/docs/Web/JavaScript/Guide/Iterators_and_Generators#Generators">Generators</a> 는 iterable 객체를 생성하기 위해 호출하는 함수입니다.</p> + +<pre class="brush: js example-bad">function* generate(a, b) { + yield a; + yield b; +} + +for (let x of generate) // TypeError: generate is not iterable + console.log(x); +</pre> + +<p>generator 가 호출되지 않으면, generator 에 해당하는 {{jsxref("Function")}} 객체를 호출할수는 있지만 interable 하지는 않습니다. generator 호출은 generator 실행동안 yield 된 모든 값을 iterate 하는 iterable 객체를 생성합니다.</p> + +<pre class="brush: js example-good">function* generate(a, b) { + yield a; + yield b; +} + +for (let x of generate(1,2)) + console.log(x); +</pre> + +<h2 id="함께_보기">함께 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol">iterable protocol</a></li> + <li>{{jsxref("Object.keys")}}</li> + <li>{{jsxref("Object.entries")}}</li> + <li>{{jsxref("Map")}}</li> + <li><a href="/ko/docs/Web/JavaScript/Guide/Iterators_and_Generators#Generators">generators</a></li> + <li><a href="/ko/docs/Web/JavaScript/Guide/Loops_and_iteration#for...of_statement">for…of</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/json_bad_parse/index.html b/files/ko/web/javascript/reference/errors/json_bad_parse/index.html new file mode 100644 index 0000000000..c73b082dbb --- /dev/null +++ b/files/ko/web/javascript/reference/errors/json_bad_parse/index.html @@ -0,0 +1,105 @@ +--- +title: 'SyntaxError: JSON.parse: bad parsing' +slug: Web/JavaScript/Reference/Errors/JSON_bad_parse +translation_of: Web/JavaScript/Reference/Errors/JSON_bad_parse +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메시지">메시지</h2> + +<pre class="syntaxbox">SyntaxError: JSON.parse: unterminated string literal +SyntaxError: JSON.parse: bad control character in string literal +SyntaxError: JSON.parse: bad character in string literal +SyntaxError: JSON.parse: bad Unicode escape +SyntaxError: JSON.parse: bad escape character +SyntaxError: JSON.parse: unterminated string +SyntaxError: JSON.parse: no number after minus sign +SyntaxError: JSON.parse: unexpected non-digit +SyntaxError: JSON.parse: missing digits after decimal point +SyntaxError: JSON.parse: unterminated fractional number +SyntaxError: JSON.parse: missing digits after exponent indicator +SyntaxError: JSON.parse: missing digits after exponent sign +SyntaxError: JSON.parse: exponent part is missing a number +SyntaxError: JSON.parse: unexpected end of data +SyntaxError: JSON.parse: unexpected keyword +SyntaxError: JSON.parse: unexpected character +SyntaxError: JSON.parse: end of data while reading object contents +SyntaxError: JSON.parse: expected property name or '}' +SyntaxError: JSON.parse: end of data when ',' or ']' was expected +SyntaxError: JSON.parse: expected ',' or ']' after array element +SyntaxError: JSON.parse: end of data when property name was expected +SyntaxError: JSON.parse: expected double-quoted property name +SyntaxError: JSON.parse: end of data after property name when ':' was expected +SyntaxError: JSON.parse: expected ':' after property name in object +SyntaxError: JSON.parse: end of data after property value in object +SyntaxError: JSON.parse: expected ',' or '}' after property value in object +SyntaxError: JSON.parse: expected ',' or '}' after property-value pair in object literal +SyntaxError: JSON.parse: property names must be double-quoted strings +SyntaxError: JSON.parse: expected property name or '}' +SyntaxError: JSON.parse: unexpected character +SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data +</pre> + +<h2 id="에러_타입">에러 타입</h2> + +<p>{{jsxref("SyntaxError")}}</p> + +<h2 id="뭐가_잘못됬나요">뭐가 잘못됬나요?</h2> + +<p>{{jsxref("JSON.parse()")}} 는 문자열을 JSON으로 파싱한다. 이 문자열은 유효한 JSON 형태의 문자열이어야 하며, 유효하지 않을 경우 에러가 발생한다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="JSON.parse()_는_여분의_콤마를_허용하지_않는다."><code>JSON.parse()</code> 는 여분의 콤마를 허용하지 않는다.</h3> + +<p>다음 두 줄은 SyntaxError를 발생시킨다:</p> + +<pre class="brush: js example-bad">JSON.parse('[1, 2, 3, 4,]'); +JSON.parse('{"foo": 1,}'); +// SyntaxError JSON.parse: unexpected character +// at line 1 column 14 of the JSON data +</pre> + +<p>끝에 오는 콤마를 제거하면 정확하게 JSON으로 파싱한다:</p> + +<pre class="brush: js example-good">JSON.parse('[1, 2, 3, 4]'); +JSON.parse('{"foo": 1}');</pre> + +<h3 id="프로퍼티_이름은_반드시_쌍따옴표로_표현해야_한다.">프로퍼티 이름은 반드시 쌍따옴표로 표현해야 한다.</h3> + +<p>'foo'처럼 프로퍼티를 작은 따옴표로 감싸서는 안된다.</p> + +<pre class="brush: js example-bad">JSON.parse("{'foo': 1}"); +// SyntaxError: JSON.parse: expected property name or '}' +// at line 1 column 2 of the JSON data</pre> + +<p>대신에 "foo" 처럼 써야 한다:</p> + +<pre class="brush: js example-good">JSON.parse('{"foo": 1}');</pre> + +<h3 id="리딩_제로와_십진_소수점">리딩 제로와 십진 소수점</h3> + +<p>01 처럼 리딩제로를 사용할 수 없고, 십진 소수점 뒤에는 최소한 하나의 숫자는 등장해야 한다.</p> + +<pre class="brush: js example-bad">JSON.parse('{"foo": 01}'); +// SyntaxError: JSON.parse: expected ',' or '}' after property value +// in object at line 1 column 2 of the JSON data + +JSON.parse('{"foo": 1.}'); +// SyntaxError: JSON.parse: unterminated fractional number +// at line 1 column 2 of the JSON data +</pre> + +<p>대신에 리딩제로를 없애고 1 이라고 쓰고, 십진 소수점 뒤에는 반드시 하나 이상의 숫자를 적도록 한다:</p> + +<pre class="brush: js example-good">JSON.parse('{"foo": 1}'); +JSON.parse('{"foo": 1.0}'); +</pre> + +<h2 id="또다른_내용">또다른 내용</h2> + +<ul> + <li>{{jsxref("JSON")}}</li> + <li>{{jsxref("JSON.parse()")}}</li> + <li>{{jsxref("JSON.stringify()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/malformed_formal_parameter/index.html b/files/ko/web/javascript/reference/errors/malformed_formal_parameter/index.html new file mode 100644 index 0000000000..e258ba49e6 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/malformed_formal_parameter/index.html @@ -0,0 +1,57 @@ +--- +title: 'SyntaxError: Malformed formal parameter' +slug: Web/JavaScript/Reference/Errors/Malformed_formal_parameter +translation_of: Web/JavaScript/Reference/Errors/Malformed_formal_parameter +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="Message">Message</h2> + +<pre class="syntaxbox">SyntaxError: malformed formal parameter (Firefox) +</pre> + +<h2 id="Error_type">Error type</h2> + +<p>{{jsxref("SyntaxError")}}</p> + +<h2 id="무엇이_잘못_되었을까요">무엇이 잘못 되었을까요?</h2> + +<p>코드에는 최소한 두 개의 인수가 전달 된 <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function">Function()</a></code> 생성자가 있습니다. 마지막 인수는 작성중인 새 함수의 소스코드 입니다. 나머지는 모두 새 함수의 인수 목록을 구성합니다.</p> + +<p>인수 목록이 어딘가 잘못되었습니다. 아마도 실수로 인수 이름으로 if 또는 var와 같은 키워드를 선택했거나 인수 목록에 갈곳 잃은 구두점이 있을 수 있습니다. 또는 실수로 숫자나 개체와 같은 잘못된 값을 전달한 것일 수 있습니다.</p> + +<h2 id="그래_내_문제가_해결됐어._근데_왜_말_안해줬어">그래, 내 문제가 해결됐어. 근데 왜 말 안해줬어?</h2> + +<p>틀림 없이 오류 메세지의 표현은 다소 이상한 부분이 있습니다. "공식 매개 변수"는 "함수 인수"를 말하는 좋은 방법입니다. 우리는 "잘못된 형식의 단어를 사용했다"라고 표현 합니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Invalid_cases">Invalid cases</h3> + +<pre class="brush: js example-bad">var f = Function('x y', 'return x + y;'); +// SyntaxError (missing a comma) + +var f = Function('x,', 'return x;'); +// SyntaxError (extraneous comma) + +var f = Function(37, "alert('OK')"); +// SyntaxError (numbers can't be argument names) +</pre> + +<h3 id="Valid_cases">Valid cases</h3> + +<pre class="brush: js example-good">var f = Function('x, y', 'return x + y;'); // correctly punctuated + +var f = Function('x', 'return x;'); + +// if you can, avoid using Function - this is much faster +var f = function(x) { return x; }; +</pre> + +<h2 id="See_also">See also</h2> + +<ul> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function">Function()</a></code></li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Functions">About functions</a></li> + <li><a href="https://www.gutenberg.org/ebooks/84"><em>Frankenstein</em> by Mary Wollstonecraft Shelley, full e-text</a> ("Cursed (although I curse myself) be the hands that formed you! You have made me wretched beyond expression. You have left me no power to consider whether I am just to you or not. Begone! Relieve me from the sight of your detested form.")</li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/missing_bracket_after_list/index.html b/files/ko/web/javascript/reference/errors/missing_bracket_after_list/index.html new file mode 100644 index 0000000000..b9149ac159 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/missing_bracket_after_list/index.html @@ -0,0 +1,56 @@ +--- +title: 'SyntaxError: missing ] after element list' +slug: Web/JavaScript/Reference/Errors/Missing_bracket_after_list +tags: + - 구문 에러 + - 배열 초기자 + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Errors/Missing_bracket_after_list +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메세지">메세지</h2> + +<pre class="syntaxbox">SyntaxError: missing ] after element list +</pre> + +<h2 id="에러_타입">에러 타입</h2> + +<p>{{jsxref("SyntaxError")}}.</p> + +<h2 id="무엇이_잘못되었을까">무엇이 잘못되었을까?</h2> + +<p>배열 초기자 구문에 오류가 있습니다. 닫는 대괄호("<code>]</code>") 또는 콤마("<code>,</code>")가 빠진 것 같습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="완성되지_않은_배열_초기자">완성되지 않은 배열 초기자</h3> + +<pre class="brush: js example-bad">var list = [1, 2, + +var instruments = [ + 'Ukulele', + 'Guitar', + 'Piano' +}; + +var data = [{foo: 'bar'} {bar: 'foo'}]; +</pre> + +<p>바르게 고치면:</p> + +<pre class="brush: js example-good">var list = [1, 2]; + +var instruments = [ + 'Ukulele', + 'Guitar', + 'Piano' +]; + +var data = [{foo: 'bar'}, {bar: 'foo'}];</pre> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/missing_colon_after_property_id/index.html b/files/ko/web/javascript/reference/errors/missing_colon_after_property_id/index.html new file mode 100644 index 0000000000..4fe7865664 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/missing_colon_after_property_id/index.html @@ -0,0 +1,78 @@ +--- +title: 'SyntaxError: missing : after property id' +slug: Web/JavaScript/Reference/Errors/Missing_colon_after_property_id +tags: + - 객체 초기자 + - 계산된 속성 + - 구문 에러 + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Errors/Missing_colon_after_property_id +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메세지">메세지</h2> + +<pre class="syntaxbox">SyntaxError: Expected ':' (Edge) +SyntaxError: missing : after property id (Firefox) +</pre> + +<h2 id="에러_타입">에러 타입</h2> + +<p>{{jsxref("SyntaxError")}}</p> + +<h2 id="무엇이_문제일까">무엇이 문제일까?</h2> + +<p><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Object_initializer">객체 초기자</a> 구문으로 객체를 만들 때 콜론(<code>:</code>)은 객체의 속성을 키와 값으로 분리합니다.</p> + +<pre class="brush: js">var obj = { propertyKey: 'value' }; +</pre> + +<h2 id="예제">예제</h2> + +<h3 id="콜론_vs._등호">콜론 vs. 등호</h3> + +<p>객체 초기자 구문에는 등호를 사용할 수 없으므로 아래 예제는 실패합니다.</p> + +<pre class="brush: js example-bad">var obj = { propertyKey = 'value' }; +// SyntaxError: missing : after property id +</pre> + +<p>콜론을 사용하거나 객체를 생성한 뒤에 대괄호를 사용하여 새로운 속성을 할당하는 것이 바릅니다.</p> + +<pre class="brush: js example-good">var obj = { propertyKey: 'value' }; + +// 또는 + +var obj = { }; +obj['propertyKey'] = 'value'; +</pre> + +<h3 id="빈_속성">빈 속성</h3> + +<p>아래와 같이 빈 속성을 만들 수 없습니다:</p> + +<pre class="brush: js example-bad">var obj = { propertyKey; }; +// SyntaxError: missing : after property id +</pre> + +<p>만약 값 없이 속성을 정의해야 한다면 값으로 {{jsxref("null")}}을 지정할 수 있습니다.</p> + +<pre class="brush: js example-good">var obj = { propertyKey: null };</pre> + +<h3 id="계산된_속성">계산된 속성</h3> + +<p>식으로 속성의 키를 만드는 경우 대괄호를 사용해야 합니다. 그렇지 않으면 속성 이름에 계산된 값을 사용할 수 없습니다:</p> + +<pre class="brush: js example-bad">var obj = { 'b'+'ar': 'foo' }; +// SyntaxError: missing : after property id +</pre> + +<p>식에 대괄호를 넣으세요 <code>[]</code>:</p> + +<pre class="brush: js example-good">var obj = { ['b'+'ar']: 'foo' };</pre> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Object_initializer">객체 초기자</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/missing_curly_after_property_list/index.html b/files/ko/web/javascript/reference/errors/missing_curly_after_property_list/index.html new file mode 100644 index 0000000000..8e0abf94db --- /dev/null +++ b/files/ko/web/javascript/reference/errors/missing_curly_after_property_list/index.html @@ -0,0 +1,47 @@ +--- +title: 'SyntaxError: missing } after property list' +slug: Web/JavaScript/Reference/Errors/Missing_curly_after_property_list +translation_of: Web/JavaScript/Reference/Errors/Missing_curly_after_property_list +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메시지">메시지</h2> + +<pre class="syntaxbox">SyntaxError: missing } after property list +</pre> + +<h2 id="에러_유형">에러 유형</h2> + +<p>{{jsxref("SyntaxError")}}</p> + +<h2 id="무엇이_잘못_된_걸까">무엇이 잘못 된 걸까?</h2> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer">객체를 초기화 하는 부분</a> 어딘가에 구문에 실수가 있습니다. 실제로 빠진 중괄호 일 수도 있지만, 누락 된 쉼표 일 수도 있습니다. 또한 닫는 중괄호나 괄호가 올바른 순서인지 확인하세요. 코드를 들여쓰기하거나 서식을 지정하면 좀 더 보기 쉽습니다.</p> + +<h2 id="예시">예시</h2> + +<h3 id="쉼표를_까먹은_경우">쉼표를 까먹은 경우</h3> + +<p>종종 객체 초기화 과정에서 쉼표를 빠트리는 경우가 있습니다:</p> + +<pre class="brush: js example-bad">var obj = { + a: 1, + b: { myProp: 2 } + c: 3 +}; +</pre> + +<p>올바른 예시는 다음과 같습니다:</p> + +<pre class="brush: js example-good">var obj = { + a: 1, + b: { myProp: 2 }, + c: 3 +}; +</pre> + +<h2 id="더_보기">더 보기</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer">Object initializer</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/missing_initializer_in_const/index.html b/files/ko/web/javascript/reference/errors/missing_initializer_in_const/index.html new file mode 100644 index 0000000000..be116cf3a4 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/missing_initializer_in_const/index.html @@ -0,0 +1,55 @@ +--- +title: 'SyntaxError: missing = in const declaration' +slug: Web/JavaScript/Reference/Errors/Missing_initializer_in_const +translation_of: Web/JavaScript/Reference/Errors/Missing_initializer_in_const +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메시지">메시지</h2> + +<pre class="syntaxbox">SyntaxError: Const must be initalized (Edge) +SyntaxError: missing = in const declaration (Firefox) +SyntaxError: Missing initializer in const declaration (Chrome) +</pre> + +<h2 id="에러_유형">에러 유형</h2> + +<p>{{jsxref("SyntaxError")}}</p> + +<h2 id="무엇이_잘못되었나요">무엇이 잘못되었나요?</h2> + +<p>상수는 일반적인 실행 중에 프로그램에 의해 변경될 수 없는 값입니다. 상수는 재할당되거나 재선언될 수 없습니다. 자바스크립트에서 상수는 <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/const">const</a></code> 키워드를 사용해 선언됩니다. 상수는 이니셜라이저가 필요합니다. 다시말해, 한 문장 안에 선언과 동시에 초기화가 이루어져야 합니다 (따라서 추후 수정 불가).</p> + +<h2 id="예제">예제</h2> + +<h3 id="const_이니셜라이저가_빠진_경우">const 이니셜라이저가 빠진 경우</h3> + +<p><code>var</code> 또는 <code>let</code>과 달리, <code>const</code> 선언에서는 반드시 값을 정의해야 합니다.</p> + +<pre class="brush: js example-bad">const COLUMNS; +// SyntaxError: missing = in const declaration</pre> + +<h3 id="에러_수정">에러 수정</h3> + +<p>해당 에러를 수정하기 위해서 여러가지 방법이 존재합니다. 문제 상황에서 상수를 사용해 무엇을 하려 했는지 확인해보세요.</p> + +<h4 id="상수_값_추가">상수 값 추가</h4> + +<p>선언과 같은 문장에 상수 값을 정의합니다.</p> + +<pre class="brush: js example-good">const COLUMNS = 80;</pre> + +<h4 id="const_let_var"><code>const</code>, <code>let</code>, <code>var</code>?</h4> + +<p>상수를 선언할 목적이 아니었다면 <code>const</code>를 사용하지 마세요. <code>let</code> 키워드를 이용한 블록범위 변수, 또는 <code>var</code> 키워드를 이용한 전역 변수를 사용할 수 있습니다. 두 가지 경우 모두 초기값을 요구하지 않습니다.</p> + +<pre class="brush: js example-good">let columns; +</pre> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/const">const</a></code></li> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/let">let</a></code></li> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/var">var</a></code></li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/missing_name_after_dot_operator/index.html b/files/ko/web/javascript/reference/errors/missing_name_after_dot_operator/index.html new file mode 100644 index 0000000000..a549e48e51 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/missing_name_after_dot_operator/index.html @@ -0,0 +1,63 @@ +--- +title: 'SyntaxError: missing name after . operator' +slug: Web/JavaScript/Reference/Errors/Missing_name_after_dot_operator +translation_of: Web/JavaScript/Reference/Errors/Missing_name_after_dot_operator +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메시지">메시지</h2> + +<pre class="syntaxbox">SyntaxError: missing name after . operator +</pre> + +<h2 id="에러_타입">에러 타입</h2> + +<p>{{jsxref("SyntaxError")}}</p> + +<h2 id="무엇이_잘_못_되었을까">무엇이 잘 못 되었을까?</h2> + +<p>점 연산자 (<code>.</code>)는 <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors">프로퍼티 접근</a>을 위해 사용합니다. 접근해야 하는 프로퍼티 명은 제대로 명시 해야 합니다. 연산 프로퍼티에 접근하려면, 점 연산자를 사용하지 않고 대괄호를 사용하는 것으로 프로퍼티 접근 방식을 바꿔야 합니다. 이런 방식들이 표현식의 계산을 수행시켜줄 것입니다. 아마 당신은 연결을 하려고 했을 것입니다. 이 경우에는 더하기 연산자(<code>+</code>)가 필요합니다. 아래의 예제를 봐주세요. </p> + +<h2 id="예제">예제</h2> + +<h3 id="프로퍼티_접근">프로퍼티 접근</h3> + +<p>JavaScript <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors">프로퍼티 접근자</a>는 점(.) 또는 대괄호(<code>[]</code>) 중 하나만 사용한다. 대괄호는 연산 프로퍼티에 접근을 허용합니다. </p> + +<pre class="brush: js example-bad">var obj = { foo: { bar: "baz", bar2: "baz2" } }; +var i = 2; + +obj.[foo].[bar] +// SyntaxError: missing name after . operator + +obj.foo."bar"+i; +// SyntaxError: missing name after . operator +</pre> + +<p>이 코드를 고치려면, 오브젝트에 이런 식으로 접근해야 합니다.:</p> + +<pre class="brush: js example-good">obj.foo.bar; // "baz" +// 또는 대신에 +obj["foo"]["bar"]; // "baz" + +// 연산 프로퍼티는 대괄호가 필요합니다. +obj.foo["bar" + i]; // "baz2" +</pre> + +<h3 id="프로퍼티_접근_vs._연결">프로퍼티 접근 vs. 연결</h3> + +<p>다른 프로그램 언어를 사용하다 왔다면 ( {{Glossary("PHP")}} 같은), 점 연산자(<code>.</code>)와 연결 연산자(<code>+</code>)를 혼동해서 쓰기가 더 쉬울 것입니다.</p> + +<pre class="brush: js example-bad">console.log("Hello" . "world"); + +// SyntaxError: missing name after . operator</pre> + +<p>대신에 결합을 위해서는 더하기 표식을 사용해야 합니다.:</p> + +<pre class="brush: js example-good">console.log("Hello" + "World");</pre> + +<h2 id="참조">참조</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors">Property accessors</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/missing_parenthesis_after_argument_list/index.html b/files/ko/web/javascript/reference/errors/missing_parenthesis_after_argument_list/index.html new file mode 100644 index 0000000000..1f28ac1104 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/missing_parenthesis_after_argument_list/index.html @@ -0,0 +1,38 @@ +--- +title: 'SyntaxError: missing ) after argument list' +slug: Web/JavaScript/Reference/Errors/Missing_parenthesis_after_argument_list +translation_of: Web/JavaScript/Reference/Errors/Missing_parenthesis_after_argument_list +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="Message">Message</h2> + +<pre class="syntaxbox">SyntaxError: missing ) after argument list +</pre> + +<h2 id="Error_type">Error type</h2> + +<p>{{jsxref("SyntaxError")}}.</p> + +<h2 id="What_went_wrong">What went wrong?</h2> + +<p>function을 호출하는 방식에 에러가 있는 것입니다. 맞춤법, 연산자 누락 또는 이스케이프 처리를 하지 않는 문자열과 같은 것으로 발생될 수 있습니다.</p> + +<h2 id="Examples">Examples</h2> + +<p>문자열을 합치는 "+" 연산자가 없기 때문에, Javascript는 <code>log</code> function에 대한 인수를 <code>"PI: "</code>로 인식을 합니다. 이 경우, 닫침 괄호가 누락된 것으로 인식을 합니다.</p> + +<pre class="brush: js example-bad">console.log('PI: ' Math.PI); +// SyntaxError: missing ) after argument list +</pre> + +<p>You can correct the <code>log</code> call by adding the "<code>+</code>" operator:</p> + +<pre class="brush: js example-good">console.log('PI: ' + Math.PI); +// "PI: 3.141592653589793"</pre> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Functions">Functions</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/missing_parenthesis_after_condition/index.html b/files/ko/web/javascript/reference/errors/missing_parenthesis_after_condition/index.html new file mode 100644 index 0000000000..cd7b368aa4 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/missing_parenthesis_after_condition/index.html @@ -0,0 +1,65 @@ +--- +title: 'SyntaxError: missing ) after condition' +slug: Web/JavaScript/Reference/Errors/Missing_parenthesis_after_condition +translation_of: Web/JavaScript/Reference/Errors/Missing_parenthesis_after_condition +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메시지">메시지</h2> + +<pre class="syntaxbox">SyntaxError: missing ) after condition +</pre> + +<h2 id="에러_유형">에러 유형</h2> + +<p>{{jsxref("SyntaxError")}}</p> + +<h2 id="무엇이_잘못_된_걸까">무엇이 잘못 된 걸까?</h2> + +<p><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/if...else">if</a></code>조건문에 에러가 있습니다. 어떠한 프로그래밍 언어에서든 코드는 입력값에 따라 의사를 결정하고 행동을 수행해야합니다. 지정된 조건이 true이면 if 문이 명령문을 실행합니다. 자바스크립트에서는 이 조건이 <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/if...else">if</a></code>문 다음의 괄호에 있어야 합니다. 다음은 그 예시입니다.</p> + +<pre class="brush: js">if (condition) { + // do something if the condition is true +}</pre> + +<h2 id="예시">예시</h2> + +<p>실수가 있을 수 있으니, 모든 괄호를 주의깊게 확인하세요.</p> + +<pre class="brush: js example-bad">if (3 > Math.PI { + console.log("wait what?"); +} + +// SyntaxError: missing ) after condition +</pre> + +<p>이 코드를 고치기 위해선, 조건문을 괄호로 닫아야 합니다.</p> + +<pre class="brush: js example-good">if (3 > Math.PI) { + console.log("wait what?"); +}</pre> + +<p>다른 프로그래밍 언어를 배운 경우, 자바스크립트에서는 다르게 쓰이거나, 쓰이지 않는 키워드를 사용하기 쉽습니다.</p> + +<pre class="brush: js example-bad">if (done is true) { + console.log("we are done!"); +} + +// SyntaxError: missing ) after condition +</pre> + +<p>이 경우 올바른 <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">비교연산자</a>를 사용해야 합니다. 그 예시로:</p> + +<pre class="brush: js example-good">if (done === true) { + console.log("we are done!"); +}</pre> + +<h2 id="더_보기">더 보기</h2> + +<ul> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/if...else">if...else</a></code></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">Comparison operators</a></li> + <li> + <p><a href="/en-US/docs/Learn/JavaScript/Building_blocks/conditionals">Making decisions in your code — conditionals</a></p> + </li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/missing_semicolon_before_statement/index.html b/files/ko/web/javascript/reference/errors/missing_semicolon_before_statement/index.html new file mode 100644 index 0000000000..ec3334b52f --- /dev/null +++ b/files/ko/web/javascript/reference/errors/missing_semicolon_before_statement/index.html @@ -0,0 +1,63 @@ +--- +title: 'SyntaxError: missing ; before statement' +slug: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement +translation_of: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메시지">메시지</h2> + +<pre class="syntaxbox">SyntaxError: missing ; before statement +</pre> + +<h2 id="오류_타입">오류 타입</h2> + +<p>{{jsxref("SyntaxError")}}.</p> + +<h2 id="무엇이_잘_못_되었나">무엇이 잘 못 되었나?</h2> + +<p>어딘가에 세미 콜론(<code>;</code>)이 빠져 있습니다. <a href="/en-US/docs/Web/JavaScript/Reference/Statements">JavaScript 구문</a>은 반드시 세미 콜론으로 끝나야 합니다. 일부는 자동 세미콜론 삽입 (<a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion">automatic semicolon insertion (ASI)</a>)의 영향을 받습니다. 그러나 이 경우에는 직접 세미 콜론을 써주어야 합니다. 그래야 JavaScript가 올바르게 해석 될 수 있기 때문입니다.</p> + +<p>그러나, 가끔, 이 오류는 또 다른 오류의 결과로도 나타날 수도 있습니다. 문자열을 escape 문자로 적절히 처리해 주지 않았을 때, 또는 <code>var</code> 키워드를 잘 못 사용했을 때와 같은 경우 입니다. 또한 어딘가에 너무 많은 괄호 기호를 사용했을 것입니다. 이 오류가 발생했을 때에는 문법을 신중히 검토해야 합니다. </p> + +<h2 id="예제">예제</h2> + +<h3 id="Escape_처리되지_않은_문자열">Escape 처리되지 않은 문자열</h3> + +<p>이 오류는 문자열을 escape 처리 하지 않았을 때, JavaScript 엔진이 문자열 끝을 미리 예측하여 발생합니다. 예를 들자면 아래와 같습니다. :</p> + +<pre class="brush: js example-bad">var foo = 'Tom's bar'; +// SyntaxError: missing ; before statement</pre> + +<p>문자열을 묶어줄 때 쌍 따옴표를 사용하거나, 역슬래시를 이용해서 홑따옴표를 사용 할 수 있습니다. :</p> + +<pre class="brush: js example-good">var foo = "Tom's bar"; +var foo = 'Tom\'s bar'; +</pre> + +<h3 id="var와_함께_선언하는_것">var와 함께 선언하는 것</h3> + +<p>이미 <code>var</code> 선언된 object나 array의 요소를 새로 선언 할 수 없습니다.</p> + +<pre class="brush: js example-bad">var obj = {}; +var obj.foo = 'hi'; // SyntaxError missing ; before statement + +var array = []; +var array[0] = 'there'; // SyntaxError missing ; before statement +</pre> + +<p>대신에, <code>var</code> 키워드를 생략하고 정의합니다. :</p> + +<pre class="brush: js example-good">var obj = {}; +obj.foo = 'hi'; + +var array = []; +array[0] = 'there'; +</pre> + +<h2 id="참조_문서">참조 문서</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion">Automatic semicolon insertion (ASI)</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements">JavaScript statements</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/more_arguments_needed/index.html b/files/ko/web/javascript/reference/errors/more_arguments_needed/index.html new file mode 100644 index 0000000000..41137d2f63 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/more_arguments_needed/index.html @@ -0,0 +1,45 @@ +--- +title: 'TypeError: More arguments needed' +slug: Web/JavaScript/Reference/Errors/More_arguments_needed +translation_of: Web/JavaScript/Reference/Errors/More_arguments_needed +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메시지">메시지</h2> + +<pre class="syntaxbox">TypeError: argument is not an Object and is not null (Edge) +TypeError: Object.create requires at least 1 argument, but only 0 were passed +TypeError: Object.setPrototypeOf requires at least 2 arguments, but only 0 were passed +TypeError: Object.defineProperties requires at least 1 argument, but only 0 were passed +</pre> + +<h2 id="에러_타입">에러 타입</h2> + +<p>{{jsxref("TypeError")}}.</p> + +<h2 id="무엇이_잘_못_되었을까">무엇이 잘 못 되었을까?</h2> + +<p>함수 호출 시 에러가 있습니다. 더 많은 인수가 주어져야 합니다.</p> + +<h2 id="예제">예제</h2> + +<p>{{jsxref("Object.create()")}} 메서드는 적어도 1개의 인자가 필요하며, {{jsxref("Object.setPrototypeOf()")}} 메서드는 적어도 2개의 인자가 필요합니다.:</p> + +<pre class="brush: js example-bad">var obj = Object.create(); +// TypeError: Object.create requires at least 1 argument, but only 0 were passed + +var obj = Object.setPrototypeOf({}); +// TypeError: Object.setPrototypeOf requires at least 2 arguments, but only 1 were passed +</pre> + +<p>예를 들면, 이렇게 프로토 타입으로 {{jsxref("null")}}를 세팅해서 고칠 수 있습니다.:</p> + +<pre class="brush: js example-good">var obj = Object.create(null); + +var obj = Object.setPrototypeOf({}, null);</pre> + +<h2 id="참조">참조</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Functions">Functions</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/negative_repetition_count/index.html b/files/ko/web/javascript/reference/errors/negative_repetition_count/index.html new file mode 100644 index 0000000000..b2437c9ad8 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/negative_repetition_count/index.html @@ -0,0 +1,40 @@ +--- +title: 'RangeError: repeat count must be non-negative' +slug: Web/JavaScript/Reference/Errors/Negative_repetition_count +translation_of: Web/JavaScript/Reference/Errors/Negative_repetition_count +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메시지">메시지</h2> + +<pre class="syntaxbox">RangeError: repeat count must be non-negative (Firefox) +RangeError: Invalid count value (Chrome) +</pre> + +<h2 id="에러_형식">에러 형식</h2> + +<p>{{jsxref("RangeError")}}</p> + +<h2 id="무엇이_잘못되었을까">무엇이 잘못되었을까?</h2> + +<p>{{jsxref("String.prototype.repeat()")}} 메소드가 사용되었습니다. 이 메소드는 문자열이 반복되는 수를 예측하는 카운트 파라메터를 가지고 있었습니다. 이 파라메터는 0보다 크고, 양의 {{jsxref("Infinity")}} 보다는 작으며, 음수는 될수 없습니다. 이 범위는 이렇게 표현 될 수 있습니다. : [0, +∞)</p> + +<h2 id="예">예</h2> + +<h3 id="허용되지_않는_경우">허용되지 않는 경우</h3> + +<pre class="brush: js example-bad">'abc'.repeat(-1); // RangeError </pre> + +<h3 id="허용되는_경우">허용되는 경우</h3> + +<pre class="brush: js example-good">'abc'.repeat(0); // '' +'abc'.repeat(1); // 'abc' +'abc'.repeat(2); // 'abcabc' +'abc'.repeat(3.5); // 'abcabcabc' (수는 정수로 변환될 것입니다.) +</pre> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("String.prototype.repeat()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/no_variable_name/index.html b/files/ko/web/javascript/reference/errors/no_variable_name/index.html new file mode 100644 index 0000000000..e9d6ec6ee7 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/no_variable_name/index.html @@ -0,0 +1,79 @@ +--- +title: 'SyntaxError: missing variable name' +slug: Web/JavaScript/Reference/Errors/No_variable_name +translation_of: Web/JavaScript/Reference/Errors/No_variable_name +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메시지">메시지</h2> + +<pre class="syntaxbox">SyntaxError: missing variable name (Firefox) +SyntaxError: Unexpected token = (Chrome)</pre> + +<h2 id="에러_타입">에러 타입</h2> + +<p>{{jsxref("SyntaxError")}}</p> + +<h2 id="무엇이_잘_못_되었을까">무엇이 잘 못 되었을까?</h2> + +<p>변수에 이름이 없습니다. 이것은 코드 내의 구문 에러 때문일 수도 있습니다. 어쩌면 콤마를 잘 못 된 곳에 찍었거나, 변수명을 지을 때 애를 먹었을 수도 있습니다. 그럴 수도 있죠! 작명은 너무 어려우니까요. </p> + +<h2 id="예제">예제</h2> + +<h3 id="이름을_잃은_변수">이름을 잃은 변수</h3> + +<pre class="brush: js example-bad">var = "foo"; +</pre> + +<p>좋은 이름을 떠올리기 어려웠을 거예요. 우리 모두 겪는 일이죠.</p> + +<pre class="brush: js example-good">var ohGodWhy = "foo";</pre> + +<h3 id="예약어는_변수명이_될_수_없어요">예약어는 변수명이 될 수 없어요</h3> + +<p>예약어로 지정된 이름들이 변수로 쓰여 있습니다. 이것들은 사용할 수 없어요. 미안합니다. :(</p> + +<pre class="brush: js example-bad">var debugger = "whoop"; +// SyntaxError: missing variable name +</pre> + +<h3 id="여러_변수를_선언하기">여러 변수를 선언하기</h3> + +<p>여러 변수를 한 번에 선언할 때에는 콤마에 주의를 기울여야 합니다. 쓸 데없는 콤마를 더 찍지는 않았는지? 무심코 세미콜론 대신 콤마를 찍지는 않았는지? </p> + +<pre class="brush: js example-bad">var x, y = "foo", +var x, = "foo" + +var first = document.getElementById('one'), +var second = document.getElementById('two'), + +// SyntaxError: missing variable name +</pre> + +<p>올바르게 수정한 버전:</p> + +<pre class="brush: js example-good">var x, y = "foo"; +var x = "foo"; + +var first = document.getElementById('one'); +var second = document.getElementById('two');</pre> + +<h3 id="배열">배열</h3> + +<p>JavaScript 의 {{jsxref("Array")}} 리터럴은 대괄호로 감싸주어야 합니다. 이건 동작하지 않아요.</p> + +<pre class="brush: js example-bad">var arr = 1,2,3,4,5; +// SyntaxError: missing variable name +</pre> + +<p>이렇게 해야 맞습니다:</p> + +<pre class="brush: js example-good">var arr = [1,2,3,4,5];</pre> + +<h2 id="더_보기">더 보기</h2> + +<ul> + <li><a href="http://wiki.c2.com/?GoodVariableNames">Good variable names</a></li> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/var">var</a></code></li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Declarations">Variable declarations in the JavaScript Guide</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/not_a_codepoint/index.html b/files/ko/web/javascript/reference/errors/not_a_codepoint/index.html new file mode 100644 index 0000000000..782cea10f2 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/not_a_codepoint/index.html @@ -0,0 +1,51 @@ +--- +title: 'RangeError: argument is not a valid code point' +slug: Web/JavaScript/Reference/Errors/Not_a_codepoint +translation_of: Web/JavaScript/Reference/Errors/Not_a_codepoint +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메시지">메시지</h2> + +<pre class="syntaxbox">RangeError: {0} is not a valid code point (Firefox) +RangeError: Invalid code point {0} (Chrome) +</pre> + +<h2 id="에러_형식">에러 형식</h2> + +<p>{{jsxref("RangeError")}}</p> + +<h2 id="무엇이_잘못되었을까">무엇이 잘못되었을까?</h2> + +<p>{{jsxref("String.fromCodePoint()")}} 메소드는 유효한 코드 포인트(<a href="https://en.wikipedia.org/wiki/Code_point">code point</a>)만을 받아들입니다.</p> + +<p><a href="https://en.wikipedia.org/wiki/Code_point">code point</a>는 유니코드의 코드 스페이스 값으로, <code>0</code>부터 <code>0x10FFFF</code>까지의 정수 범위입니다.</p> + +<p>{{jsxref("NaN")}}을 사용하는 값, 음수 (<code>-1</code>), 정수가 아닌 수(3.14), 또는 <code>0x10FFFF</code> (<code>1114111</code>) 보다 큰 값은 이 함수에 적용될 수 없습니다.</p> + +<h2 id="예">예</h2> + +<h3 id="유효하지_않은_경우">유효하지 않은 경우</h3> + +<pre class="brush: js example-bad">String.fromCodePoint('_'); // RangeError +String.fromCodePoint(Infinity); // RangeError +String.fromCodePoint(-1); // RangeError +String.fromCodePoint(3.14); // RangeError +String.fromCodePoint(3e-2); // RangeError +String.fromCodePoint(NaN); // RangeError</pre> + +<h3 id="유효한_경우">유효한 경우</h3> + +<pre class="brush: js example-good">String.fromCodePoint(42); // "*" +String.fromCodePoint(65, 90); // "AZ" +String.fromCodePoint(0x404); // "\u0404" +String.fromCodePoint(0x2F804); // "\uD87E\uDC04" +String.fromCodePoint(194564); // "\uD87E\uDC04" +String.fromCodePoint(0x1D306, 0x61, 0x1D307) // "\uD834\uDF06a\uD834\uDF07" +</pre> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("String.fromCodePoint()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/not_a_constructor/index.html b/files/ko/web/javascript/reference/errors/not_a_constructor/index.html new file mode 100644 index 0000000000..80bc235779 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/not_a_constructor/index.html @@ -0,0 +1,91 @@ +--- +title: 'TypeError: "x" is not a constructor' +slug: Web/JavaScript/Reference/Errors/Not_a_constructor +translation_of: Web/JavaScript/Reference/Errors/Not_a_constructor +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메세지">메세지</h2> + +<pre class="syntaxbox">TypeError: "x" is not a constructor + +TypeError: Math is not a constructor +TypeError: JSON is not a constructor +TypeError: Symbol is not a constructor +TypeError: Reflect is not a constructor +TypeError: Intl is not a constructor +TypeError: SIMD is not a constructor +TypeError: Atomics is not a constructor +</pre> + +<h2 id="오류_유형">오류 유형</h2> + +<p>{{jsxref("TypeError")}}</p> + +<h2 id="뭐가_잘못된_거죠">뭐가 잘못된 거죠?</h2> + +<p>객체 혹은 변수를 생성자로 사용하려고 했습니다, 하지만 객체(혹은 변수)가 생성자가 아닙니다. 생성자가 무엇인지에 대한 자세한 정보는 {{Glossary("constructor")}} 혹은 <a href="/en-US/docs/Web/JavaScript/Reference/Operators/new"><code>new</code> operator</a> 를 참조하시기 바랍니다.</p> + +<p>{{jsxref("String")}} 혹은 {{jsxref("Array")}}와 같이 <code>new</code>,를 사용하여 생성할 수 있는 전역 객체들이 있습니다. 하지만 일부 전역 객체들은 그렇지 않고 속성과 메서드가 정적입니다. 다음의 자바스크립트 표준 내장 객체들은 생성자가 아닙니다: {{jsxref("Math")}}, {{jsxref("JSON")}}, {{jsxref("Symbol")}}, {{jsxref("Reflect")}}, {{jsxref("Intl")}}, {{jsxref("SIMD")}}, {{jsxref("Atomics")}}.</p> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Statements/function*">Generator functions</a> 또한 생성자로 사용될 수 없습니다.</p> + +<h2 id="예시">예시</h2> + +<h3 id="유효하지_않은_경우">유효하지 않은 경우</h3> + +<pre class="brush: js example-bad">var Car = 1; +new Car(); +// TypeError: Car is not a constructor + +new Math(); +// TypeError: Math is not a constructor + +new Symbol(); +// TypeError: Symbol is not a constructor + +function* f() {}; +var obj = new f; +// TypeError: f is not a constructor +</pre> + +<h3 id="car_생성자">car 생성자</h3> + +<p>자동차(car) 객체를 만들고자 한다고 가정합니다. 이 객체의 타입을 <code>car</code>라 하고 make, model, and year 세 개의 프로퍼티를 갖습니다. 이를 위해 다음과 같은 함수를 작성할 것입니다:</p> + +<pre class="brush: js">function Car(make, model, year) { + this.make = make; + this.model = model; + this.year = year; +} +</pre> + +<p>이제 다음과 같이 <code>mycar</code> 라 불리는 객체를 생성할 수 있습니다:</p> + +<pre class="brush: js">var mycar = new Car('Eagle', 'Talon TSi', 1993);</pre> + +<h3 id="프라미스_이용">프라미스 이용</h3> + +<p>즉시 실행되는 프라미스를 반환하는 경우에는 <em>새로운 Promise(...)</em>를 생성할 필요가 없습니다.</p> + +<p>아래는 올바른 방법이 아닙니다(<a href="https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise#Constructor">프라미스 생성자</a>가 제대로 호출되고 있지 않습니다). <code>TypeError: this is not a constructor</code> 예외를 던지게 됩니다:</p> + +<pre class="brush: js example-bad">return new Promise.resolve(true); +</pre> + +<p>대신, <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve">Promise.resolve()</a> 혹은 <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/reject">Promise.reject()</a> <a href="https://en.wikipedia.org/wiki/Method_(computer_programming)#Static_methods">정적 메서드</a>를 사용하십시오:</p> + +<pre class="brush: js">// This is legal, but unnecessarily long: +return new Promise((resolve, reject) => { resolve(true); }) + +// Instead, return the static method: +return Promise.resolve(true); +return Promise.reject(false); +</pre> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{Glossary("constructor")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/new"><code>new</code> operator</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/not_defined/index.html b/files/ko/web/javascript/reference/errors/not_defined/index.html new file mode 100644 index 0000000000..6b403dd848 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/not_defined/index.html @@ -0,0 +1,66 @@ +--- +title: 'ReferenceError: "x" is not defined' +slug: Web/JavaScript/Reference/Errors/Not_defined +translation_of: Web/JavaScript/Reference/Errors/Not_defined +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메시지">메시지</h2> + +<pre class="syntaxbox">ReferenceError: "x" is not defined +</pre> + +<h2 id="에러_타입">에러 타입</h2> + +<p>{{jsxref("ReferenceError")}}.</p> + +<h2 id="무엇이_잘못되었을까">무엇이 잘못되었을까?</h2> + +<p>존재하지 않는 변수를 참조하는 곳이 있습니다. 이 변수는 선언되어야 합니다. 또는, 현재 스크립트나 {{Glossary("scope")}} 에서 사용이 가능하도록 해야합니다.</p> + +<div class="note"> +<p><strong>Note:</strong> 라이브러리(예를 들면 jQuery와 같은)의 로딩은, 반드시 코드에서 "$"와 같은 라이브러리 변수에 접근하기 이전에 수행되어야 합니다. 라이브러리를 로딩하는 {{HTMLElement("script")}} 태그가 그 변수를 사용하는 코드보다 앞에 위치하도록 하세요.</p> +</div> + +<h2 id="예">예</h2> + +<h3 id="선언되지_않은_변수">선언되지 않은 변수</h3> + +<pre class="brush: js example-bad">foo.substring(1); // ReferenceError: foo is not defined +</pre> + +<p>"foo" 변수는 어디에도 선언되지 않았습니다. {{jsxref("String.prototype.substring()")}} 메소드가 작동하도록 하기 위해서는 문자열을 필요로 합니다.</p> + +<pre class="brush: js example-good">var foo = "bar"; +foo.substring(1); // "ar"</pre> + +<h3 id="잘못된_스코프">잘못된 스코프</h3> + +<p>변수는 현재의 실행 흐름 내에서 이용 가능해야합니다. 함수 내부에 정의된 변수는 다른 외부의 함수에서는 접근할 수 없습니다. 그 때문에, 변수는 함수의 스코프 내부에서만 정의 됩니다.</p> + +<pre class="brush: js example-bad">function numbers () { + var num1 = 2, + num2 = 3; + return num1 + num2; +} + +console.log(num1); // ReferenceError: num1 is not defined</pre> + +<p>그러나, 함수는 모든 변수와 정의된 스코프 안에 정의된 함수에 접근할 수 있습니다. 따라서, 전역으로 정의된 함수는 전역에 정의된 모든 변수에도 접근할 수 있습니다.</p> + +<pre class="brush: js example-good">var num1 = 2, + num2 = 3; + +function numbers () { + return num1 + num2; +} + +console.log(num1); // 2</pre> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{Glossary("Scope")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Declaring_variables">Declaring variables in the JavaScript Guide</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Functions#Function_scope/en-US/docs/">Function scope in the JavaScript Guide</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/precision_range/index.html b/files/ko/web/javascript/reference/errors/precision_range/index.html new file mode 100644 index 0000000000..43ab7392e4 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/precision_range/index.html @@ -0,0 +1,92 @@ +--- +title: 'RangeError: precision is out of range' +slug: Web/JavaScript/Reference/Errors/Precision_range +translation_of: Web/JavaScript/Reference/Errors/Precision_range +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메시지">메시지</h2> + +<pre class="syntaxbox">RangeError: precision {0} out of range (Firefox) +RangeError: toExponential() argument must be between 0 and 20 (Chrome) +RangeError: toFixed() digits argument must be between 0 and 20 (Chrome) +RangeError: toPrecision() argument must be between 1 and 21 (Chrome) +</pre> + +<h2 id="에러_형식">에러 형식</h2> + +<p>{{jsxref("RangeError")}}</p> + +<h2 id="무엇이_잘못되었을까">무엇이 잘못되었을까?</h2> + +<p>아래의 메소드들 중 하나에서, 실행 인자(argument)가 정확도의 범위를 벗어났습니다. :</p> + +<ul> + <li>{{jsxref("Number.prototype.toExponential()")}}</li> + <li>{{jsxref("Number.prototype.toFixed()")}}</li> + <li>{{jsxref("Number.prototype.toPrecision()")}}</li> +</ul> + +<p>이 메소드들에게 허용된 범위는 0부터 20 (또는 21)까지 입니다. 하지만, ECMAScript 스펙은 아래의 범위까지 확장하여 허용하고 있습니다.</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Method</th> + <th scope="col">Firefox (SpiderMonkey)</th> + <th scope="col">Chrome, Opera (V8)</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{jsxref("Number.prototype.toExponential()")}}</td> + <td>0 부터 100</td> + <td>0 부터 20</td> + </tr> + <tr> + <td>{{jsxref("Number.prototype.toFixed()")}}</td> + <td>-20 부터 100</td> + <td>0 부터 20</td> + </tr> + <tr> + <td>{{jsxref("Number.prototype.toPrecision()")}}</td> + <td>1 부터 100</td> + <td>1 부터 21</td> + </tr> + </tbody> +</table> + +<h2 id="예">예</h2> + +<h3 id="유효하지_않은_경우">유효하지 않은 경우</h3> + +<pre class="brush: js example-bad">77.1234.toExponential(-1); // RangeError +77.1234.toExponential(101); // RangeError + +2.34.toFixed(-100); // RangeError +2.34.toFixed(1001); // RangeError + +1234.5.toPrecision(-1); // RangeError +1234.5.toPrecision(101); // RangeError +</pre> + +<h3 id="유효한_경우">유효한 경우</h3> + +<pre class="brush: js example-good">77.1234.toExponential(4); // 7.7123e+1 +77.1234.toExponential(2); // 7.71e+1 + +2.34.toFixed(1); // 2.3 +2.35.toFixed(1); // 2.4 (note that it rounds up in this case) + +5.123456.toPrecision(5); // 5.1235 +5.123456.toPrecision(2); // 5.1 +5.123456.toPrecision(1); // 5 +</pre> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("Number.prototype.toExponential()")}}</li> + <li>{{jsxref("Number.prototype.toFixed()")}}</li> + <li>{{jsxref("Number.prototype.toPrecision()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/property_access_denied/index.html b/files/ko/web/javascript/reference/errors/property_access_denied/index.html new file mode 100644 index 0000000000..2468d0221a --- /dev/null +++ b/files/ko/web/javascript/reference/errors/property_access_denied/index.html @@ -0,0 +1,42 @@ +--- +title: 'Error: Permission denied to access property "x"' +slug: Web/JavaScript/Reference/Errors/Property_access_denied +translation_of: Web/JavaScript/Reference/Errors/Property_access_denied +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메시지">메시지</h2> + +<pre class="syntaxbox">Error: Permission denied to access property "x" +</pre> + +<h2 id="에러_형식">에러 형식</h2> + +<p>{{jsxref("Error")}}.</p> + +<h2 id="무엇이_잘못되었을까">무엇이 잘못되었을까?</h2> + +<p>접근이 허가되지 않은 객체에 접근하기 위한 시도가 있었습니다. 아마 동일 출처 정책(<a href="/en-US/docs/Web/Security/Same-origin_policy">same-origin policy</a>)을 침해하여 다른 도메인으로부터 로드된 {{HTMLElement("iframe")}} 엘리먼트에 대한 것이었을 겁니다.</p> + +<h2 id="예">예</h2> + +<pre class="brush: html"><!DOCTYPE html> +<html> + <head> + <iframe id="myframe" src="http://www1.w3c-test.org/common/blank.html"></iframe> + <script> + onload = function() { + console.log(frames[0].document); + // Error: Permission denied to access property "document" + } + </script> + </head> + <body></body> +</html></pre> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{HTMLElement("iframe")}}</li> + <li><a href="/en-US/docs/Web/Security/Same-origin_policy">Same-origin policy</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/read-only/index.html b/files/ko/web/javascript/reference/errors/read-only/index.html new file mode 100644 index 0000000000..7260fd71f8 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/read-only/index.html @@ -0,0 +1,77 @@ +--- +title: 'TypeError: "x" is read-only' +slug: Web/JavaScript/Reference/Errors/Read-only +translation_of: Web/JavaScript/Reference/Errors/Read-only +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메시지">메시지</h2> + +<pre class="syntaxbox">TypeError: "x" is read-only (Firefox) +TypeError: 0 is read-only (Firefox) +TypeError: Cannot assign to read only property 'x' of #<Object> (Chrome) +TypeError: Cannot assign to read only property '0' of [object Array] (Chrome) +</pre> + +<h2 id="에러_유형">에러 유형</h2> + +<p>{{jsxref("TypeError")}}</p> + +<h2 id="무엇이_잘못_된_걸까">무엇이 잘못 된 걸까?</h2> + +<p>전역변수 또는 객체 프로퍼티가 읽기 전용으로 할당된 경우입니다.(엄밀히 따지자면 <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#Writable_attribute">쓰기가 불가능한 데이터 속성입니다.</a>)</p> + +<p>이 에러는 <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">엄격모드</a>에서만 등장합니다. 엄격하지 않은 모드에서는 읽기전용 속성은 묵시적으로 무시됩니다.</p> + +<h2 id="예시">예시</h2> + +<h3 id="적절하지_않은_예">적절하지 않은 예</h3> + +<p>읽기 전용 속성은 아주 흔한 것은 아니지만, {{jsxref("Object.defineProperty()")}} 나 {{jsxref("Object.freeze()")}} 를 이용해 만들어 질 수 있습니다.</p> + +<pre class="brush: js example-bad">'use strict'; +var obj = Object.freeze({name: 'Elsa', score: 157}); +obj.score = 0; // TypeError + +'use strict'; +Object.defineProperty(this, 'LUNG_COUNT', {value: 2, writable: false}); +LUNG_COUNT = 3; // TypeError + +'use strict'; +var frozenArray = Object.freeze([0, 1, 2]); +frozenArray[0]++; // TypeError +</pre> + +<p>자바 스크립트에는 몇 가지 읽기 전용 속성이 내장되어 있습니다. 아마도 수학적 상수를 재정의하려고 한 것 같습니다.</p> + +<pre class="brush: js example-bad">'use strict'; +Math.PI = 4; // TypeError +</pre> + +<p>이렇게는 불가능합니다.</p> + +<p>전역변수 <code>undefined</code> 또한 읽기전용으로, 사람들이 모두 좋아하지 않는 "undefined is not a function" 에러가 다음과 같은 경우 등장합니다:</p> + +<pre class="brush: js example-bad">'use strict'; +undefined = function() {}; // TypeError: "undefined" is read-only +</pre> + +<h3 id="적절한_예">적절한 예</h3> + +<pre class="brush: js example-good">'use strict'; +var obj = Object.freeze({name: 'Score', points: 157}); +obj = {name: obj.name, points: 0}; // replacing it with a new object works + +'use strict'; +var LUNG_COUNT = 2; // a `var` works, because it's not read-only +LUNG_COUNT = 3; // ok (anatomically unlikely, though) +</pre> + +<h2 id="더보기">더보기</h2> + +<ul> + <li>{{jsxref("Object.defineProperty()")}}</li> + <li>{{jsxref("Object.freeze()")}}</li> + <li><a href="https://www.answers.com/Q/Which_animals_have_three_lungs">"Which animals have three lungs?" on answers.com</a></li> + <li><a href="https://aliens.wikia.com/wiki/Klingon">Klingons</a> (another answer to that query)</li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/reduce_of_empty_array_with_no_initial_value/index.html b/files/ko/web/javascript/reference/errors/reduce_of_empty_array_with_no_initial_value/index.html new file mode 100644 index 0000000000..53796ea87f --- /dev/null +++ b/files/ko/web/javascript/reference/errors/reduce_of_empty_array_with_no_initial_value/index.html @@ -0,0 +1,83 @@ +--- +title: 'TypeError: Reduce of empty array with no initial value' +slug: Web/JavaScript/Reference/Errors/Reduce_of_empty_array_with_no_initial_value +translation_of: Web/JavaScript/Reference/Errors/Reduce_of_empty_array_with_no_initial_value +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="Message">Message</h2> + +<pre class="syntaxbox">TypeError: 초기값이 없는 빈 배열에 대한 recude는 에러 +</pre> + +<h2 id="Error_type">Error type</h2> + +<p>{{jsxref("TypeError")}}</p> + +<h2 id="What_went_wrong">What went wrong?</h2> + +<p>자바스크립크에서 몇 몇의 reduce 함수들:</p> + +<ul> + <li>{{jsxref("Array.prototype.reduce()")}}, {{jsxref("Array.prototype.reduceRight()")}} and</li> + <li>{{jsxref("TypedArray.prototype.reduce()")}}, {{jsxref("TypedArray.prototype.reduceRight()")}}).</li> +</ul> + +<p>이러한 함수들은 선택적으로 초기값(<code>initialValue</code>)을 사용합니다.(콜백(<code>callback)</code>의 첫번째 호출에 대한 첫번째 인수로 사용됩니다.) 그러나, 만약에 초기값을 설정하지 않는다면, {{jsxref("Array")}} or {{jsxref("TypedArray")}}에 대한 첫번째 엘리먼트를 초기값으로 사용 합니다. 이런 경우에 초기값이 없기 때문에 빈 배열이 제공될 경우 오류가 발생 합니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Invalid_cases">Invalid cases</h3> + +<p>This problem appears frequently when combined with a filter ({{jsxref("Array.prototype.filter()")}}, {{jsxref("TypedArray.prototype.filter()")}}) which will remove all elements of the list. Thus leaving none to be used as the initial value.</p> + +<pre class="brush: js example-bad">var ints = [0, -1, -2, -3, -4, -5]; +ints.filter(x => x > 0) // removes all elements + .reduce((x, y) => x + y) // no more elements to use for the initial value.</pre> + +<p>Similarly, the same issue can happen if there is a typo in a selector, or an unexpected number of elements in a list:</p> + +<pre class="brush: js example-bad">var names = document.getElementsByClassName("names"); +var name_list = Array.prototype.reduce.call(names, (acc, name) => acc + ", " + name); +</pre> + +<h3 id="Valid_cases">Valid cases</h3> + +<p>These problems can be solved in two different ways.</p> + +<p>One way is to actually provide an <code>initialValue</code> as the neutral element of the operator, such as 0 for the addition, 1 for a multiplication, or an empty string for a concatenation.</p> + +<pre class="brush: js example-good">var ints = [0, -1, -2, -3, -4, -5]; +ints.filter(x => x > 0) // removes all elements + .reduce((x, y) => x + y, 0) // the initial value is the neutral element of the addition +</pre> + +<p>Another way would be two to handle the empty case, either before calling <code>reduce</code>, or in the callback after adding an unexpected dummy initial value.</p> + +<pre class="brush: js example-good">var names = document.getElementsByClassName("names"); + +var name_list1 = ""; +if (names1.length >= 1) + name_list1 = Array.prototype.reduce.call(names, (acc, name) => acc + ", " + name); +// name_list1 == "" when names is empty. + +var name_list2 = Array.prototype.reduce.call(names, (acc, name) => { + if (acc == "") // initial value + return name; + return acc + ", " + name; +}, ""); +// name_list2 == "" when names is empty. +</pre> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Array.prototype.reduce()")}}</li> + <li>{{jsxref("Array.prototype.reduceRight()")}}</li> + <li>{{jsxref("TypedArray.prototype.reduce()")}}</li> + <li>{{jsxref("TypedArray.prototype.reduceRight()")}}</li> + <li>{{jsxref("Array")}}</li> + <li>{{jsxref("TypedArray")}}</li> + <li>{{jsxref("Array.prototype.filter()")}}</li> + <li>{{jsxref("TypedArray.prototype.filter()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/reserved_identifier/index.html b/files/ko/web/javascript/reference/errors/reserved_identifier/index.html new file mode 100644 index 0000000000..8a1932d9cc --- /dev/null +++ b/files/ko/web/javascript/reference/errors/reserved_identifier/index.html @@ -0,0 +1,80 @@ +--- +title: 'SyntaxError: "x" is a reserved identifier' +slug: Web/JavaScript/Reference/Errors/Reserved_identifier +tags: + - 구문 에러 + - 예약어 + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Errors/Reserved_identifier +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메세지">메세지</h2> + +<pre class="syntaxbox">SyntaxError: The use of a future reserved word for an identifier is invalid (Edge) +SyntaxError: "x" is a reserved identifier (Firefox) +SyntaxError: Unexpected reserved word (Chrome)</pre> + +<h2 id="에러_타입">에러 타입</h2> + +<p>{{jsxref("SyntaxError")}}</p> + +<h2 id="무엇이_잘못되었을까">무엇이 잘못되었을까?</h2> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords">예약어</a>가 식별자로 쓰인 경우 발생하는 에러입니다. 이 키워드는 엄격(Strict) 모드와 느슨한(Sloppy) 모드에서 모두 예약어로 취급됩니다.</p> + +<ul> + <li><code>enum</code></li> +</ul> + +<p>다음은 엄격 모드의 코드에서만 예약어로 취급됩니다:</p> + +<ul class="threecolumns"> + <li><code>implements</code></li> + <li><code>interface</code></li> + <li>{{jsxref("Statements/let", "let")}}</li> + <li><code>package</code></li> + <li><code>private</code></li> + <li><code>protected</code></li> + <li><code>public</code></li> + <li><code>static</code></li> +</ul> + +<h2 id="예제">예제</h2> + +<h3 id="엄격_모드와_엄격하지_않은_모드에서의_예약어">엄격 모드와 엄격하지 않은 모드에서의 예약어</h3> + +<p><code>enum</code> 식별자는 일반적으로 예약되어 있습니다.</p> + +<pre class="brush: js example-bad">var enum = { RED: 0, GREEN: 1, BLUE: 2 }; +// SyntaxError: enum is a reserved identifier +</pre> + +<p>엄격 모드의 코드에선 더 많은 식별자들이 예약되어 있습니다.</p> + +<pre class="brush: js example-bad">"use strict"; +var package = ["potatoes", "rice", "fries"]; +// SyntaxError: package is a reserved identifier +</pre> + +<p>이 변수들의 이름을 변경해야 합니다.</p> + +<pre class="brush: js example-good">var colorEnum = { RED: 0, GREEN: 1, BLUE: 2 }; +var list = ["potatoes", "rice", "fries"];</pre> + +<h3 id="오래된_브라우저의_업데이트">오래된 브라우저의 업데이트</h3> + +<p>새로운 구문을 사용하기 위해서는 최근 버전의 브라우저로 업데이트 해야 합니다. 예를 들어, 오래된 브라우저를 사용하고 있다면 <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/let">let</a></code> 또는 <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/class">class</a></code> 구현할 수 없습니다.</p> + +<pre class="brush: js">"use strict"; +class DocArchiver {} + +// SyntaxError: class is a reserved identifier +// (오래된 버전의 브라우저에서만 에러가 발생합니다. 예) Firefox 44 이하) +</pre> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="http://wiki.c2.com/?GoodVariableNames">Good variable names</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/resulting_string_too_large/index.html b/files/ko/web/javascript/reference/errors/resulting_string_too_large/index.html new file mode 100644 index 0000000000..20e28cbe2b --- /dev/null +++ b/files/ko/web/javascript/reference/errors/resulting_string_too_large/index.html @@ -0,0 +1,46 @@ +--- +title: 'RangeError: repeat count must be less than infinity' +slug: Web/JavaScript/Reference/Errors/Resulting_string_too_large +translation_of: Web/JavaScript/Reference/Errors/Resulting_string_too_large +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메시지">메시지</h2> + +<pre class="syntaxbox">RangeError: repeat count must be less than infinity and not overflow maximum string size (Firefox) +(repeat count는 infinity보다 작아야하며, 최대 문자열 크기를 넘길 수 없습니다.) + +RangeError: Invalid count value (Chrome) +</pre> + +<h2 id="에러_형식">에러 형식</h2> + +<p>{{jsxref("RangeError")}}</p> + +<h2 id="무엇이_잘못되었을까">무엇이 잘못되었을까?</h2> + +<p> {{jsxref("String.prototype.repeat()")}} 메소드가 사용되었습니다. 이 메소드는 문자열을 반복하는 수를 예측하는 카운트 파라메터를 가지고 있었습니다. 그리고 이 파라메터는 0보다 커야하며, 양의 {{jsxref("Infinity")}} 보다 작아야 했으며, 음수는 허용되지 않았습니다. 이 값의 허용 범위는 이렇게 표현될 수 있습니다. : [0, +∞). </p> + +<p>결과인 문자열은 최대 문자열 크기보다 클 수 없지만, JavaScript 에서는 다를 수 있습니다. Firefox (SpiderMonkey) 에서의 최대 문자열 크기는 2<sup>28</sup> -1 (<code>0xFFFFFFF</code>)입니다.</p> + +<h2 id="예">예</h2> + +<h3 id="허용되지_않는_경우">허용되지 않는 경우</h3> + +<pre class="brush: js example-bad">'abc'.repeat(Infinity); // RangeError +'a'.repeat(2**28); // RangeError +</pre> + +<h3 id="허용되는_경우">허용되는 경우</h3> + +<pre class="brush: js example-good">'abc'.repeat(0); // '' +'abc'.repeat(1); // 'abc' +'abc'.repeat(2); // 'abcabc' +'abc'.repeat(3.5); // 'abcabcabc' (숫자는 정수로 변환될 것입니다.) +</pre> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("String.prototype.repeat()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/strict_non_simple_params/index.html b/files/ko/web/javascript/reference/errors/strict_non_simple_params/index.html new file mode 100644 index 0000000000..8c07f4b46a --- /dev/null +++ b/files/ko/web/javascript/reference/errors/strict_non_simple_params/index.html @@ -0,0 +1,107 @@ +--- +title: 'SyntaxError: "use strict" not allowed in function with non-simple parameters' +slug: Web/JavaScript/Reference/Errors/Strict_Non_Simple_Params +translation_of: Web/JavaScript/Reference/Errors/Strict_Non_Simple_Params +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="Message">Message</h2> + +<pre class="syntaxbox">Firefox: +SyntaxError: "use strict" not allowed in function with default parameter +SyntaxError: "use strict" not allowed in function with rest parameter +SyntaxError: "use strict" not allowed in function with destructuring parameter + +Chrome: +SyntaxError: Illegal 'use strict' directive in function with non-simple parameter list +</pre> + +<h2 id="Error_type">Error type</h2> + +<p>{{jsxref("SyntaxError")}}.</p> + +<h2 id="무엇이_잘못_되었을까요">무엇이 잘못 되었을까요?</h2> + +<p> <code>"use strict"</code> 지시문은 다음 매개변수 중 한 개가 있는 함수의 맨 위에 작성됩니다:</p> + +<ul> + <li>{{jsxref("Functions/Default_parameters", "Default parameters", "", 1)}}</li> + <li>{{jsxref("Functions/rest_parameters", "Rest parameters", "", 1)}}</li> + <li>{{jsxref("Operators/Destructuring_assignment", "Destructuring parameters", "", 1)}}</li> +</ul> + +<p><code>"use strict"</code> 지시문은 ECMAScript 동작에 따라 이러한 함수의 맨 위에 허용되지 않습니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="기능_명세서">기능 명세서</h3> + +<p>다음은 함수 <code>sum</code> 에는 기본 매개 변수 <code>a=1</code> 및 <code>b=2</code>가 있는 경우입니다:</p> + +<pre class="brush: js example-bad">function sum(a = 1, b = 2) { + // SyntaxError: "use strict" not allowed in function with default parameter + 'use strict'; + return a + b; +} +</pre> + +<p>함수가 <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a> 모드에 있어야 하고 전체 스크립트 또는 포함된 함수가 <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>에 있어도 괜찮으면 함수 외부에서 <code>"use strict"</code> 지시문을 이동할 수 있습니다:</p> + +<pre class="brush: js example-good">'use strict'; +function sum(a = 1, b = 2) { + return a + b; +} +</pre> + +<h3 id="함수_표현식">함수 표현식</h3> + +<p>함수 표현식은 또 다른 해결방법을 사용할 수 있습니다:</p> + +<pre class="brush: js example-bad">var sum = function sum([a, b]) { + // SyntaxError: "use strict" not allowed in function with destructuring parameter + 'use strict'; + return a + b; +}; +</pre> + +<p>이것은 다음 표현식으로 변환 될 수 있습니다:</p> + +<pre class="brush: js example-good">var sum = (function() { + 'use strict'; + return function sum([a, b]) { + return a + b; + }; +})(); +</pre> + +<h3 id="화살표_함수">화살표 함수</h3> + +<p>화살표 함수가 <code>this</code>에 접근해야 하는 경우에는, 둘러싼 함수로 화살표 함수를 사용할 수 있습니다:</p> + +<pre class="brush: js example-bad">var callback = (...args) => { + // SyntaxError: "use strict" not allowed in function with rest parameter + 'use strict'; + return this.run(args); +}; +</pre> + +<p>이것은 다음 표현식과 같이 변환될 수 있습니다:</p> + +<pre class="brush: js example-good">var callback = (() => { + 'use strict'; + return (...args) => { + return this.run(args); + }; +})(); +</pre> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Strict_mode", "Strict mode", "", 1)}}</li> + <li>{{jsxref("Statements/function", "function statement", "", 1)}}</li> + <li>{{jsxref("Operators/function", "function expression", "", 1)}}</li> + <li>{{jsxref("Functions/Default_parameters", "Default parameters", "", 1)}}</li> + <li>{{jsxref("Functions/rest_parameters", "Rest parameters", "", 1)}}</li> + <li>{{jsxref("Operators/Destructuring_assignment", "Destructuring parameters", "", 1)}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/too_much_recursion/index.html b/files/ko/web/javascript/reference/errors/too_much_recursion/index.html new file mode 100644 index 0000000000..90495a359b --- /dev/null +++ b/files/ko/web/javascript/reference/errors/too_much_recursion/index.html @@ -0,0 +1,50 @@ +--- +title: 'InternalError: too much recursion' +slug: Web/JavaScript/Reference/Errors/Too_much_recursion +translation_of: Web/JavaScript/Reference/Errors/Too_much_recursion +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메시지">메시지</h2> + +<pre class="syntaxbox">InternalError: too much recursion +</pre> + +<h2 id="에러_형식">에러 형식</h2> + +<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/InternalError" title='The InternalError object indicates an error that occurred internally in the JavaScript engine. For example: "InternalError: too much recursion".'><code>InternalError</code></a>.</p> + +<h2 id="무엇이_잘못되었을까">무엇이 잘못되었을까?</h2> + +<p>자신을 호출하는 함수를 재귀 함수라고 합니다. 어떤 면에서, 재귀는 반복과 유사합니다. 둘 다 같은 코드를 여러 번 실행하며, 조건(무한 반복 피하기, 더 정확히 여기서 말하는 무한 재귀)이 있습니다. 너무 많거나 무한 번의 재귀가 발생할 경우, JavaScript는 이 에러를 던질 것입니다.</p> + +<h2 id="예">예</h2> + +<p>이 재귀 함수는 exit 조건에 따라 10번을 실행합니다.</p> + +<pre class="brush: js">function loop(x) { + if (x >= 10) // "x >= 10" is the exit condition + return; + // do stuff + loop(x + 1); // the recursive call +} +loop(0);</pre> + +<p>이 조건에 대하여 너무 높은 값을 설정 하면 작동하지 않게 됩니다.</p> + +<pre class="brush: js example-bad">function loop(x) { + if (x >= 1000000000000) + return; + // do stuff + loop(x + 1); +} +loop(0); + +// InternalError: too much recursion</pre> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{Glossary("Recursion")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Functions#Recursion">Recursive functions</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/undeclared_var/index.html b/files/ko/web/javascript/reference/errors/undeclared_var/index.html new file mode 100644 index 0000000000..688c92473d --- /dev/null +++ b/files/ko/web/javascript/reference/errors/undeclared_var/index.html @@ -0,0 +1,62 @@ +--- +title: 'ReferenceError: assignment to undeclared variable "x"' +slug: Web/JavaScript/Reference/Errors/Undeclared_var +translation_of: Web/JavaScript/Reference/Errors/Undeclared_var +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메시지">메시지</h2> + +<pre class="syntaxbox">ReferenceError: assignment to undeclared variable "x" (Firefox) +ReferenceError: "x" is not defined (Chrome) +ReferenceError: Variable undefined in strict mode (Edge) +</pre> + +<h2 id="에러_형식">에러 형식</h2> + +<p>엄격 모드(<a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>)에서만 발생하는 {{jsxref("ReferenceError")}} 경고.</p> + +<h2 id="무엇이_잘못되었을까">무엇이 잘못되었을까?</h2> + +<p>선언되지 않은 변수로 값은 할당되었습니다. <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/var">var</a></code> 키워드가 없이 할당이 된 것입니다. 선언된 변수와 선언되지 않은 변수 사이에는 차이가 있는데, 이는 예상치 못한 결과를 가져오며, 때문에 JavaScript 엄격모드에서는 에러를 발생시키고 있습니다.</p> + +<p>선언된 변수와 선언되지 않은 변수에 대하여 기억해야 할 세 가지:</p> + +<ul> + <li>선언된 변수는 선언된 실행 맥락 내에서 요구됩니다. 선언되지 않은 변수는 항상 전역의 특성을 띱니다.</li> + <li>선언된 변수는 코드가 실행되기 전에 생성됩니다. 선언되지 않은 변수는 실행을 위해 할당이 일어날 때까지 존재하지 않습니다.</li> + <li>선언된 변수는 실행 맥락 내(함수나 전역적인)에서 변경 불가한 요소입니다. 선언되지 않은 변수는 변경이 가능합니다. (삭제 될 수도 있습니다.)</li> +</ul> + +<p>더 많은 설명과 예제를 필요로 한다면 이 <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/var">var</a></code> 참조문서 페이지를 보세요.</p> + +<p>선언되지 않은 변수 할당에 대한 에러는 엄격 모드(<a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode code</a>)에서만 발생합니다. 비-엄격 코드에서는 조용히 묵인됩니다.</p> + +<h2 id="예">예</h2> + +<h3 id="허용되지_않는_경우">허용되지 않는 경우</h3> + +<p>이런 경우에는, 변수 "bar"는 선언되지 않은 변수가 됩니다.</p> + +<pre class="brush: js example-bad">function foo() { + "use strict"; + bar = true; +} +foo(); // ReferenceError: assignment to undeclared variable bar +</pre> + +<h3 id="허용되는_경우">허용되는 경우</h3> + +<p>"bar" 를 선언된 변수로 만들기 위해서, <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/var">var</a> </code>키워드를 변수명 앞에 붙여줍니다.</p> + +<pre class="brush: js example-good">function foo() { + "use strict"; + var bar = true; +} +foo();</pre> + +<h2 id="참조">참조</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">Strict mode</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/undefined_prop/index.html b/files/ko/web/javascript/reference/errors/undefined_prop/index.html new file mode 100644 index 0000000000..7919ca877d --- /dev/null +++ b/files/ko/web/javascript/reference/errors/undefined_prop/index.html @@ -0,0 +1,58 @@ +--- +title: 'ReferenceError: reference to undefined property "x"' +slug: Web/JavaScript/Reference/Errors/Undefined_prop +translation_of: Web/JavaScript/Reference/Errors/Undefined_prop +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메시지">메시지</h2> + +<pre class="syntaxbox">ReferenceError: reference to undefined property "x" (Firefox) +</pre> + +<h2 id="에러_형식">에러 형식</h2> + +<p>엄격 모드(<a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>)에서만 발생하는 {{jsxref("ReferenceError")}} 경고.</p> + +<h2 id="무엇이_잘못되었을까">무엇이 잘못되었을까?</h2> + +<p>이 스크립트는 존재하지 않는 객체의 속성에 접근을 시도했습니다. 요소에 접근하는 방법에는 두 가지가 있습니다.; 더 자세히 알고 싶으시다면, 속성 접근자(<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors">property accessors</a>) 참조 문서를 봐주세요. </p> + +<p>정의되지 않은 속성 참조에 대한 에러는 엄격 모드 코드(<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode code</a>)에서만 발생합니다. 비-엄격모드의 코드에서는 존재하지 않는 속성에 대한 접근은 조용히 무시됩니다.</p> + +<h2 id="예">예</h2> + +<h3 id="허용되지_않는_경우">허용되지 않는 경우</h3> + +<p>이 경우에는, 속성 <code>bar</code> 는 정의되지 않은 속성으로, <code>ReferenceError</code> 가 발생합니다.</p> + +<pre class="brush: js example-bad">"use strict"; + +var foo = {}; +foo.bar; // ReferenceError: reference to undefined property "bar" +</pre> + +<h3 id="허용되는_경우">허용되는 경우</h3> + +<p>에러를 피하기 위해서는, 접근을 시도하기 앞서, 객체에 <code>bar</code> 에 대한 정의를 추가하거나 <code>bar</code> 속성의 존재 여부를 확인해야 합니다.; 아래와 같이 {{jsxref("Object.prototype.hasOwnProperty()")}} method)를 사용하는 것이 하나의 방법이 될 수 있습니다.:</p> + +<pre class="brush: js example-good">"use strict"; + +var foo = {}; + +// bar 속성을 정의한다. + +foo.bar = "moon"; +console.log(foo.bar); // "moon" + +// bar에 접근하기 전에 존재 하는지 확인한다. + +if (foo.hasOwnProperty("bar") { + console.log(foo.bar); +}</pre> + +<h2 id="참조">참조</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">Strict mode</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/unexpected_token/index.html b/files/ko/web/javascript/reference/errors/unexpected_token/index.html new file mode 100644 index 0000000000..91704a6006 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/unexpected_token/index.html @@ -0,0 +1,49 @@ +--- +title: 'SyntaxError: Unexpected token' +slug: Web/JavaScript/Reference/Errors/Unexpected_token +tags: + - 에러 + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Errors/Unexpected_token +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메시지">메시지</h2> + +<pre class="syntaxbox">SyntaxError: expected expression, got "x" +SyntaxError: expected property name, got "x" +SyntaxError: expected target, got "x" +SyntaxError: expected rest argument name, got "x" +SyntaxError: expected closing parenthesis, got "x" +SyntaxError: expected '=>' after argument list, got "x" +</pre> + +<h2 id="에러_타입">에러 타입</h2> + +<p>{{jsxref("SyntaxError")}}</p> + +<h2 id="무엇이_잘못되었나요">무엇이 잘못되었나요?</h2> + +<p>특정 언어 구조를 예상했지만 무언가 다른 것이 있었습니다. 아마도, 간단한 오타일 것입니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="예상하지_못한_표현식">예상하지 못한 표현식</h3> + +<p>예를 들어, 함수를 호출할 때, 인수에서 마지막 부분에 콤마는 허용되지 않습니다. 자바스크립트는 계속해서 다른 인자가 있을 것이라고 기대하기 때문입니다.</p> + +<pre class="brush: js example-bad">Math.max(2, 42,); +// SyntaxError: expected expression, got ')' +</pre> + +<p>콤마를 생략하거나 다른 인수를 추가해 수정할 수 있습니다.</p> + +<pre class="brush: js example-good">Math.max(2, 42); +Math.max(2, 42, 13+37); +</pre> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("Math.max()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/unexpected_type/index.html b/files/ko/web/javascript/reference/errors/unexpected_type/index.html new file mode 100644 index 0000000000..527411ab9a --- /dev/null +++ b/files/ko/web/javascript/reference/errors/unexpected_type/index.html @@ -0,0 +1,67 @@ +--- +title: 'TypeError: "x" is (not) "y"' +slug: Web/JavaScript/Reference/Errors/Unexpected_type +tags: + - Errors + - JavaScript + - TypeError +translation_of: Web/JavaScript/Reference/Errors/Unexpected_type +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="Message">Message</h2> + +<pre class="syntaxbox">TypeError: "x" is (not) "y" + +Examples: +TypeError: "x" is undefined +TypeError: "x" is null +TypeError: "undefined" is not an object +TypeError: "x" is not an object or null +TypeError: "x" is not a symbol +</pre> + +<h2 id="Error_type">Error type</h2> + +<p>{{jsxref("TypeError")}}.</p> + +<h2 id="What_went_wrong">What went wrong?</h2> + +<p>그것은 정확하지 않은 형태이다. 그것은 가끔{{jsxref("undefined")}} 나 {{jsxref("null")}} 값을 발생한다.</p> + +<p>또한, {{jsxref("Object.create()")}} 또는 {{jsxref("Symbol.keyFor()")}}와 같은 메서드는 반드시 제공되어야하는 특별한 형태를 요구한다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Invalid_cases">Invalid cases</h3> + +<pre class="brush: js example-bad">// undefined and null cases on which the substring method won't work +var foo = undefined; +foo.substring(1); // TypeError: foo is undefined + +var foo = null; +foo.substring(1); // TypeError: foo is null + + +// Certain methods might require a specific type +var foo = {} +Symbol.keyFor(foo); // TypeError: foo is not a symbol + +var foo = 'bar' +Object.create(foo); // TypeError: "foo" is not an object or null +</pre> + +<h3 id="Fixing_the_issue">Fixing the issue</h3> + +<p>undefined 나 null 값을 가진 null 포인터를 고치기 위해서 아래 예제와 같이 <a href="/en-US/docs/Web/JavaScript/Reference/Operators/typeof">typeof</a> 연산자를 사용할 수 있다.</p> + +<pre class="brush: js">if (typeof foo !== 'undefined') { + // Now we know that foo is defined, we are good to go. +}</pre> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("undefined")}}</li> + <li>{{jsxref("null")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/errors/unnamed_function_statement/index.html b/files/ko/web/javascript/reference/errors/unnamed_function_statement/index.html new file mode 100644 index 0000000000..b7afe67563 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/unnamed_function_statement/index.html @@ -0,0 +1,118 @@ +--- +title: 'SyntaxError: function statement requires a name' +slug: Web/JavaScript/Reference/Errors/Unnamed_function_statement +tags: + - IIEF + - 객체 메소드 + - 구문 에러 + - 자바스크립트 + - 콜백 함수 + - 함수 이름 +translation_of: Web/JavaScript/Reference/Errors/Unnamed_function_statement +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="메세지">메세지</h2> + +<pre class="syntaxbox">Syntax Error: Expected identifier (Edge) +SyntaxError: function statement requires a name [Firefox] +SyntaxError: Unexpected token ( [Chrome] +</pre> + +<h2 id="에러_타입">에러 타입</h2> + +<p>{{jsxref("SyntaxError")}}</p> + +<h2 id="무엇이_잘못되었을까">무엇이 잘못되었을까?</h2> + +<p><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/function">함수 구문</a>(Function statement)은 이름이 필수입니다. 함수가 정의된 방법에 따라 함수의 이름을 짓거나 함수 표현식(Function expression) {{Glossary("IIFE")}}으로 작성하거나, 함수가 맥락에 맞게 제대로 작성되었는지 확인해야 합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="구문_vs_표현식">구문 vs 표현식</h3> + +<p><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/function">함수 구문</a>(또는 함수 선언)은 이름이 필요하므로 아래 예제는 동작하지 않습니다:</p> + +<pre class="brush: js example-bad">function () { + return 'Hello world'; +} +// SyntaxError: function statement requires a name +</pre> + +<p>대신 <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/function">함수 표현식</a>을 사용할 수 있습니다:</p> + +<pre class="brush: js example-good">var greet = function() { + return 'Hello world'; +};</pre> + +<p>또는, 선언하자마자 바로 실행되는 <a href="https://en.wikipedia.org/wiki/Immediately-invoked_function_expression">IIFE</a> (Immediately Invoked Function Expression)를 사용할 수 있습니다. 이 경우 몇 개의 괄호가 더 필요합니다:</p> + +<pre class="brush: js example-good">(function () { + +})();</pre> + +<h3 id="레이블을_붙인_함수">레이블을 붙인 함수</h3> + +<p>만약 함수 <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/label">레이블</a>을 사용하는 경우 <code>function</code> 키워드 뒤에 함수 이름이 필요하므로 아래 예제는 동작하지 않습니다:</p> + +<pre class="brush: js example-bad">function Greeter() { + german: function () { + return "Moin"; + } +} +// SyntaxError: function statement requires a name +</pre> + +<p>아래 예제는 동작합니다:</p> + +<pre class="brush: js example-good">function Greeter() { + german: function g() { + return "Moin"; + } +}</pre> + +<h3 id="객체_메소드">객체 메소드</h3> + +<p>만약 객체 메소드를 만드는 경우 먼저 객체를 만들어야 합니다. 객체 메소드의 경우 아래 예제와 같이 <code>function</code> 키워드 뒤에 이름이 없어도 정상적으로 동작합니다.</p> + +<pre class="brush: js example-good">var greeter = { + german: function () { + return "Moin"; + } +};</pre> + +<h3 id="콜백_구문">콜백 구문</h3> + +<p>콜백을 사용하는 경우 구문을 확인해야 합니다. 괄호와 쉼표는 구문을 어렵게 만듭니다.</p> + +<pre class="brush: js example-bad">promise.then( + function() { + console.log("success"); + }); + function() { + console.log("error"); +} +// SyntaxError: function statement requires a name +</pre> + +<p>올바르게 변경하면:</p> + +<pre class="brush: json example-good">promise.then( + function() { + console.log("success"); + }, + function() { + console.log("error"); + } +); +</pre> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/%ED%95%A8%EC%88%98">함수</a></li> + <li><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/function">함수 구문</a></li> + <li><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/function">함수 표현식</a></li> + <li><a href="https://en.wikipedia.org/wiki/Immediately-invoked_function_expression">IIFE</a></li> + <li><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/label">레이블</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/functions/arguments/@@iterator/index.html b/files/ko/web/javascript/reference/functions/arguments/@@iterator/index.html new file mode 100644 index 0000000000..454c8111b8 --- /dev/null +++ b/files/ko/web/javascript/reference/functions/arguments/@@iterator/index.html @@ -0,0 +1,78 @@ +--- +title: 'arguments[@@iterator]()' +slug: Web/JavaScript/Reference/Functions/arguments/@@iterator +tags: + - Deprecated + - Functions + - JavaScript + - Property + - arguments +translation_of: Web/JavaScript/Reference/Functions/arguments/@@iterator +--- +<div>{{jsSidebar("Functions")}}</div> + +<p><code><strong>@@iterator</strong></code> 속성의 초기값은 {{jsxref("Array.prototype.values")}} 속성의 초기값과 같은 함수 객체입니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>arguments</var>[Symbol.iterator]()</pre> + +<h2 id="예제">예제</h2> + +<h3 id="for...of_반복문을_사용한_반복"><code>for...of</code> 반복문을 사용한 반복</h3> + +<pre class="brush: js">function f() { + // 브라우저가 for...of 반복문과 + // for 반복문 안의 let 범위의 변수를 지원해야 합니다. + for (let letter of arguments) { + console.log(letter); + } +} +f('w', 'y', 'k', 'o', 'p'); +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-createunmappedargumentsobject', ' CreateUnmappedArgumentsObject')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-createmappedargumentsobject', ' CreateMappedArgumentsObject')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-createunmappedargumentsobject', 'CreateUnmappedArgumentsObject')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-createmappedargumentsobject', 'CreateMappedArgumentsObject')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div> + + +<p>{{Compat("javascript.functions.arguments.@@iterator")}}</p> +</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.values()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/functions/arguments/callee/index.html b/files/ko/web/javascript/reference/functions/arguments/callee/index.html new file mode 100644 index 0000000000..13ab0c948d --- /dev/null +++ b/files/ko/web/javascript/reference/functions/arguments/callee/index.html @@ -0,0 +1,203 @@ +--- +title: arguments.callee +slug: Web/JavaScript/Reference/Functions/arguments/callee +tags: + - Deprecated + - Functions + - JavaScript + - Property + - arguments +translation_of: Web/JavaScript/Reference/Functions/arguments/callee +--- +<div>{{jsSidebar("Functions")}}</div> + +<p><strong><code>arguments.callee</code></strong> 속성(property)은 현재 실행 중인 함수를 포함합니다.</p> + +<h2 id="설명">설명</h2> + +<p><code>callee</code>는 <code>arguments</code> 객체의 속성입니다. 그 함수의 몸통(body) 내에서 현재 실행 중인 함수를 참조하는 데 쓰일 수 있습니다. 이는 함수의 이름을 알 수 없는 경우에 유용합니다, 가령 이름 없는 함수 식(또한 "익명 함수"라 함) 내에서.</p> + +<div class="warning"><strong>경고:</strong> ECMAScript 제5판(ES5) 은 <a href="/ko/docs/JavaScript/Reference/Functions_and_function_scope/Strict_mode" title="Strict mode">엄격 모드</a>에서 <code>arguments.callee()</code>의 사용을 금합니다. function 식(expression)에 이름을 주거나 함수 자체를 호출해야 하는 곳에 function 선언을 사용하여 <code>arguments.callee()</code> 사용을 피하세요.</div> + +<h3 id="arguments.callee는_왜_ES5_엄격_모드에서_제거되었나요"><code>arguments.callee</code>는 왜 ES5 엄격 모드에서 제거되었나요?</h3> + +<p>(<a href="http://stackoverflow.com/a/235760/578288" title="http://stackoverflow.com/a/235760/578288">olliej의 Stack Overflow 답변</a>에서 고쳐씀)</p> + +<p>초기 버전 JavaScript는 유명(named) 함수 식을 허용하지 않습니다. 그리고 이 때문에 재귀(recursive) 함수 식을 만들 수 없습니다.</p> + +<p>예를 들어, 이 구문은 작동됩니다:</p> + +<pre class="brush: js">function factorial (n) { + return !(n > 1) ? 1 : factorial(n - 1) * n; +} + +[1,2,3,4,5].map(factorial);</pre> + +<p>하지만 다음은:</p> + +<pre class="brush: js">[1,2,3,4,5].map(function (n) { + return !(n > 1) ? 1 : /* what goes here? */ (n - 1) * n; +});</pre> + +<p>아닙니다. 이를 우회하기 위해 <code>arguments.callee</code>가 추가되었고 이와 같이 할 수 있습니다</p> + +<pre class="brush: js">[1,2,3,4,5].map(function (n) { + return !(n > 1) ? 1 : arguments.callee(n - 1) * n; +});</pre> + +<p>그러나, 이는 실로 정말 나쁜 해결책이었습니다. 이는 (다른 <code>arguments</code>, <code>callee</code> 및 <code>caller</code> 문제와 함께) 일반적인 경우에 인라인 및 tail 재귀를 불가능케 하기에 (tracing 등을 통해 선택한 경우에 그것을 달성할 수 있지만 최고의 코드는 검사가 달리 필요하지 않기에 차선입니다.) 다른 주요 문제는 그 재귀 호출이 다른 <code>this</code> 값을 갖는 것입니다. 가령:</p> + +<pre class="brush: js">var global = this; + +var sillyFunction = function (recursed) { + if (!recursed) { return arguments.callee(true); } + if (this !== global) { + alert("This is: " + this); + } else { + alert("This is the global"); + } +} + +sillyFunction();</pre> + +<p>ECMAScript 3은 유명(named) 함수 식을 허용해서 이 문제를 해결했습니다. 예를 들면:</p> + +<pre class="brush: js">[1,2,3,4,5].map(function factorial (n) { + return !(n > 1) ? 1 : factorial(n-1)*n; +});</pre> + +<p>이는 많은 이점이 있습니다:</p> + +<ul> + <li>함수는 코드 내부에서 다른 함수처럼 호출될 수 있습니다</li> + <li>외부 범위(outer scope)에서 변수를 만들지 않습니다 (<a href="http://kangax.github.io/nfe/#example_1_function_expression_identifier_leaks_into_an_enclosing_scope">IE 8 아래는 제외하고</a>)</li> + <li>arguments 객체에 액세스하는 것보다 성능이 더 낫습니다</li> +</ul> + +<p>사라지게 됐던 또 다른 기능은 <code>arguments.callee.caller</code> 또는 더 명확하게 <code>Function.caller</code>였습니다. 이는 왜일까요? 자, 어느 시점에서든 당신은 모든 함수의 스택 상 가장 깊은 caller를 찾을 수 있고 위에서 말했듯이 호출 스택 보기는 한 가지 주요 효과가 있습니다: 이는 큰 수의 최적화를 불가능 또는 훨씬 훨씬 더 어렵게 합니다. 예를 들어, 함수 <code>f</code>가 익명(unknown) 함수를 호출하지 않음을 보장할 수 없는 경우, <code>f</code>를 인라인하는 게 가능하지 않습니다. 원래 사소하게 인라인 가능했을 지도 모를 모든 호출 사이트가 다수의 guard를 축적함을 뜻합니다:</p> + +<pre class="brush: js">function f (a, b, c, d, e) { return a ? b * c : d * e; }</pre> + +<p>JavaScript 인터프리터가 제공된 모든 인수가 호출이 행해진 그 시점에 숫자임을 보장할 수 없다면, 인라인된 코드 앞에 모든 인수에 대한 검사 삽입이 필요합니다. 그렇지 않으면 그 함수를 인라인할 수 없습니다. 이제 이 특정한 경우에 스마트 인터프리터는 더 최적이고 사용되지 않을 값은 확인하지 않을 검사를 재배열할 수 있어야 합니다. 그러나 많은 경우에 그건 그냥 가능하지 않고 그러므로 인라인은 불가능하게 됩니다.</p> + +<h2 id="예">예</h2> + +<h3 id="익명_재귀_함수에서_arguments.callee_사용하기">익명 재귀 함수에서 <code>arguments.callee</code> 사용하기</h3> + +<p>재귀 함수는 자신을 참조할 수 있어야 합니다. 보통, 함수는 그 이름으로 자신을 참조합니다. 그러나, 익명 함수(<a href="/ko/docs/Web/JavaScript/Reference/Operators/function" title="function expression">함수 식</a> 또는 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Function" title="Function constructor"><code>Function</code> 생성자</a>로 생성될 수 있는)는 이름이 없습니다. 그러므로 그를 참조하는 액세스 가능한 변수가 없는 경우, 함수가 자신을 참조할 수 있는 유일한 방법은 <code>arguments.callee</code>에 의해서입니다.</p> + +<p>다음 예는 차례로 팩토리얼 함수를 정의하고 반환하는 함수를 정의합니다. 이 예는 매우 실용적이지 않고 같은 결과가 <a href="/ko/docs/Web/JavaScript/Reference/Operators/function" title="named function expressions">유명 함수 식</a>으로 달성될 수 없는 경우가 거의 없습니다.</p> + +<pre class="brush: js">function create() { + return function(n) { + if (n <= 1) + return 1; + return n * arguments.callee(n - 1); + }; +} + +var result = create()(5); // 반환값 120 (5 * 4 * 3 * 2 * 1)</pre> + +<h3 id="좋은_대안_없는_arguments.callee의_사용">좋은 대안 없는 <code>arguments.callee</code>의 사용</h3> + +<p>그러나, 다음과 같은 경우에는 <code>arguments.callee</code>에 대안이 없습니다. 그래서 그 사라짐(deprecation)은 버그가 될 수 있습니다 ({{Bug("725398")}} 참조):</p> + +<pre class="brush: js">function createPerson (sIdentity) { + var oPerson = new Function("alert(arguments.callee.identity);"); + oPerson.identity = sIdentity; + return oPerson; +} + +var john = createPerson("John Smith"); + +john();</pre> + +<h2 id="스펙">스펙</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>초기 정의. JavaScript 1.2에서 구현됨</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-10.6', 'Arguments Object')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-arguments-exotic-objects', 'Arguments Exotic Objects')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-arguments-exotic-objects', 'Arguments Exotic Objects')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("Function")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/functions/arguments/caller/index.html b/files/ko/web/javascript/reference/functions/arguments/caller/index.html new file mode 100644 index 0000000000..bcdc54c7dc --- /dev/null +++ b/files/ko/web/javascript/reference/functions/arguments/caller/index.html @@ -0,0 +1,93 @@ +--- +title: arguments.caller +slug: Web/JavaScript/Reference/Functions/arguments/caller +translation_of: Archive/Web/JavaScript/arguments.caller +--- +<div>{{jsSidebar("Functions")}}</div> + +<p>이전의 <strong><code>arguments.caller</code></strong> 속성은 현재 실행한 함수를 적용하여 제공했었습니다. 이 속성은 삭제되었으며 더 이상 작동하지 않습니다.</p> + +<h2 id="설명">설명</h2> + +<p>이 속성은 더 이상 이용할 수 없습니다. 하지만 {{jsxref("Function.caller")}} 는 사용할 수 있습니다.</p> + +<pre class="brush: js">function whoCalled() { + if (whoCalled.caller == null) + console.log('I was called from the global scope.'); + else + console.log(whoCalled.caller + ' called me!'); +}</pre> + +<h2 id="예">예</h2> + +<p>다음의 코드는 함수 내에서 <code>arguments.caller </code>값을 확인하기 위해 사용되었지만, 더 이상 작동하지 않습니다.</p> + +<pre class="brush: js example-bad">function whoCalled() { + if (arguments.caller == null) + console.log('I was called from the global scope.'); + else + console.log(arguments.caller + ' called me!'); +} +</pre> + +<h2 id="스펙">스펙</h2> + +<p>초기 정의된 부분이 아닙니다. JavaScript 1.1에서 구현되었으며, 잠재적인 보안 취약의 우려로 ({{bug(7224)}}) 삭제되었습니다.</p> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("Function")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/functions/arguments/index.html b/files/ko/web/javascript/reference/functions/arguments/index.html new file mode 100644 index 0000000000..98b5f1385b --- /dev/null +++ b/files/ko/web/javascript/reference/functions/arguments/index.html @@ -0,0 +1,189 @@ +--- +title: arguments 객체 +slug: Web/JavaScript/Reference/Functions/arguments +tags: + - Functions + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Functions/arguments +--- +<div> +<div>{{jsSidebar("Functions")}}</div> +</div> + +<p><strong><code>arguments</code></strong> 객체는 함수에 전달된 인수에 해당하는 <code>Array</code> 형태의 객체입니다.</p> + +<div class="blockIndicator note"> +<p><strong>Note:</strong> ES6 호환 코드를 작성 중이라면 되도록 <a href="/ko/docs/Web/JavaScript/Reference/Functions/rest_parameters">나머지 매개변수</a> 구문을 사용해야 합니다.</p> +</div> + +<div class="blockIndicator note"> +<p><strong>참고</strong>: "<code>Array</code> 형태"란 <code>arguments</code>가 {{jsxref("Array.length", "length")}} 속성과 더불어 0부터 인덱스 된 다른 속성을 가지고 있지만, {{jsxref("Array")}}의 {{jsxref("Array.prototype.forEach()", "forEach")}}, {{jsxref("Array.prototype.map()", "map")}}과 같은 내장 메서드를 가지고 있지 않다는 뜻입니다.</p> +</div> + +<div>{{EmbedInteractiveExample("pages/js/functions-arguments.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">arguments</pre> + +<h2 id="설명">설명</h2> + +<p><code>arguments</code> 객체는 모든 함수 내에서 이용 가능한 지역 변수입니다. <code>arguments</code> 객체를 사용하여 함수 내에서 모든 인수를 참조할 수 있으며, 호출할 때 제공한 인수 각각에 대한 항목을 갖고 있습니다. 항목의 인덱스는 0부터 시작합니다.</p> + +<p>예를 들어, 함수가 세 개의 인수를 받은 경우 다음과 같이 접근할 수 있습니다.</p> + +<pre class="brush: js">arguments[0] +arguments[1] +arguments[2] +</pre> + +<p>각 인수를 설정하거나 재할당할 수도 있습니다.</p> + +<pre class="brush: js">arguments[1] = 'new value'; +</pre> + +<p><code>arguments</code> 객체는 {{jsxref("Array")}}가 아닙니다. <code>Array</code>와 비슷하지만, {{jsxref("Array.prototype.length", "length")}} 빼고는 {{jsxref("Array.prototype.pop", "pop()")}}과 같은 어떤 <code>Array</code> 속성도 없습니다. 그러나 실제 <code>Array</code>로 변환할 수 있습니다:</p> + +<pre class="brush: js">var args = Array.prototype.slice.call(arguments); +var args = [].slice.call(arguments); +</pre> + +<p><code>arguments</code>를 실제 <code>Array</code>로 변환하기 위해 ES2015의 {{jsxref("Array.from()")}} 메서드 또는 <a href="/ko/docs/Web/JavaScript/Reference/Operators/Spread_operator" title="spread operator">전개 연산자</a>를 사용할 수도 있습니다.</p> + +<pre class="brush: js">var args = Array.from(arguments); +var args = [...arguments]; +</pre> + +<p>당신이 형식상 받기로 선언된 것보다 많은 인수로 함수를 호출하는 경우 <code>arguments</code> 객체를 사용할 수 있습니다. 이 기법은 가변 인수가 전달될 수 있는 함수에 유용합니다. 함수에 전달된 인수의 수를 결정하기 위해 <code><a href="/ko/docs/JavaScript/Reference/Functions_and_function_scope/arguments/length">arguments.length</a></code>를 쓰세요, 그 뒤에 <code>arguments</code> 객체를 사용하여 각 인수를 처리하세요. 함수 <a href="/ko/docs/Glossary/Signature/Function">signature</a>에 매개변수의 수를 결정하기 위해서는, <code><a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Function/length">Function.length</a></code> 속성을 쓰세요.</p> + +<h2 id="속성">속성</h2> + +<dl> + <dt><code><a href="/ko/docs/Web/JavaScript/Reference/Functions/arguments/callee">arguments.callee</a></code></dt> + <dd>현재 실행 중인 함수를 가리킵니다.</dd> + <dt><code><a href="/ko/docs/Web/JavaScript/Reference/Functions/arguments/caller">arguments.caller</a></code> {{ Obsolete_inline() }}</dt> + <dd>현재 실행 중인 함수를 호출한 함수를 가리킵니다.</dd> + <dt><code><a href="/ko/docs/Web/JavaScript/Reference/Functions/arguments/length">arguments.length</a></code></dt> + <dd>함수에 전달된 인수의 수를 가리킵니다.</dd> + <dt><code><a href="/ko/docs/Web/JavaScript/Reference/Functions/arguments/@@iterator">arguments[@@iterator]</a></code></dt> + <dd>arguments의 각 인덱스 값을 포함하는 새로운 Array Iterator 객체를 반환합니다.</dd> +</dl> + +<h2 id="예제">예제</h2> + +<h3 id="여러_문자열을_연결하는_함수_정의하기">여러 문자열을 연결하는 함수 정의하기</h3> + +<p>이 예는 여러 문자열을 연결하는 함수를 정의합니다. 함수의 유일한 형식 인수는 연결할 항목을 구분하는 문자를 지정하는 문자열입니다. 함수는 다음과 같이 정의됩니다:</p> + +<pre class="brush:js">function myConcat(separator) { + var args = Array.prototype.slice.call(arguments, 1); + return args.join(separator); +}</pre> + +<p>이 함수에 인수를 얼마든지 전달할 수 있으며 리스트 내 항목처럼 각 인수를 사용하여 리스트를 만듭니다.</p> + +<pre class="brush:js">// "red, orange, blue" 반환 +myConcat(", ", "red", "orange", "blue"); + +// "elephant; giraffe; lion; cheetah" 반환 +myConcat("; ", "elephant", "giraffe", "lion", "cheetah"); + +// "sage. basil. oregano. pepper. parsley" 반환 +myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley");</pre> + +<h3 id="HTML_리스트를_만드는_함수_정의하기">HTML 리스트를 만드는 함수 정의하기</h3> + +<p>이 예는 리스트 HTML을 포함하는 문자열을 만드는 함수를 정의합니다. 함수의 유일한 형식 인수는 리스트가 정렬되지 않은(bulluet(글 머리 기호)가 붙는) 경우 "<code>u</code>" 또는 정렬된(번호가 매겨진) 경우 "<code>o</code>"인 문자열입니다. 함수는 다음과 같이 정의됩니다:</p> + +<pre class="brush:js">function list(type) { + var result = "<" + type + "l><li>"; + var args = Array.prototype.slice.call(arguments, 1); + result += args.join("</li><li>"); + result += "</li></" + type + "l>"; // end list + + return result; +}</pre> + +<p>이 함수에 인수를 얼마든지 전달할 수 있고, 표시된 유형의 리스트에 항목으로 각 인수를 추가합니다. 예를 들면:</p> + +<pre class="brush:js">var listHTML = list("u", "One", "Two", "Three"); + +/* listHTML은: + +"<ul><li>One</li><li>Two</li><li>Three</li></ul>" + +*/</pre> + +<h3 id="나머지_기본_및_비구조화된_매개변수">나머지, 기본 및 비구조화된 매개변수</h3> + +<p><code>arguments</code> 객체는 <a href="/ko/docs/Web/JavaScript/Reference/Functions/rest_parameters" title="rest parameters">나머지 매개변수</a>, <a href="/ko/docs/Web/JavaScript/Reference/Functions/Default_parameters" title="default parameters">기본 매개변수</a> 또는 <a href="/ko/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment" title="destructured parameters">비구조화된 매개변수</a>와 함께 사용될 수 있습니다.</p> + +<pre class="brush: js">function foo(...args) { + return arguments; +} +foo(1, 2, 3); // { "0": 1, "1": 2, "2": 3 } +</pre> + +<p>그러나, 비엄격 함수에서는 <strong>mapped <code>arguments</code> 객체</strong>는 함수가 어떤 <a href="/ko/docs/Web/JavaScript/Reference/Functions/rest_parameters" title="rest parameters">나머지 매개변수</a>, <a href="/ko/docs/Web/JavaScript/Reference/Functions/Default_parameters" title="default parameters">기본 매개변수</a> 또는 <a href="/ko/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment" title="destructured parameters">비구조화된 매개변수</a>든 포함하지 <strong>않는</strong> 경우에만 제공됩니다. 예를 들어, 기본 매개변수를 사용하는 다음 함수에서는, 100 대신에 <code>10</code>이 반환됩니다:</p> + +<pre class="brush: js">function bar(a=1) { + arguments[0] = 100; + return a; +} +bar(10); // 10 +</pre> + +<p>이 예에서, 어떤 <a href="/ko/docs/Web/JavaScript/Reference/Functions/rest_parameters" title="rest parameters">나머지 매개변수</a>, <a href="/ko/docs/Web/JavaScript/Reference/Functions/Default_parameters" title="default parameters">기본 매개변수</a> 또는 <a href="/ko/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment" title="destructured parameters">비구조화된 매개변수</a>가 없는 경우에는, 100이 반환됩니다:</p> + +<pre class="brush: js">function zoo(a) { + arguments[0] = 100; + return a; +} +zoo(10); // 100 + +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>초기 정의. JavaScript 1.1에서 구현됨</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-10.6', 'Arguments Object')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-arguments-exotic-objects', 'Arguments Exotic Objects')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-arguments-exotic-objects', 'Arguments Exotic Objects')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.functions.arguments")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Function")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/functions/arguments/length/index.html b/files/ko/web/javascript/reference/functions/arguments/length/index.html new file mode 100644 index 0000000000..d8ea3f0da4 --- /dev/null +++ b/files/ko/web/javascript/reference/functions/arguments/length/index.html @@ -0,0 +1,74 @@ +--- +title: arguments.length +slug: Web/JavaScript/Reference/Functions/arguments/length +translation_of: Web/JavaScript/Reference/Functions/arguments/length +--- +<div>{{jsSidebar("Functions")}}</div> + +<p><strong><code>arguments.length</code></strong> 속성은 함수에 전달된 인수의 수를 포함하고 있습니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">arguments.length</pre> + +<h2 id="설명">설명</h2> + +<p>arguments.length 속성은 실제로 함수에 전달된 arguments 의 수를 제공합니다. 이것은 정의된 매개변수의 수보다 작을 수도 클 수도 있습니다. ({{jsxref("Function.length")}} 보기).</p> + +<h2 id="예제">예제</h2> + +<h3 id="arguments.length_사용하기"><code>arguments.length</code> 사용하기</h3> + +<p>이 예시에서는 둘 또는 그 이상의 수를 더할 수 있는 함수를 정의합니다.</p> + +<pre class="brush: js">function adder(base /*, n2, ... */) { + base = Number(base); + for (var i = 1; i < arguments.length; i++) { + base += Number(arguments[i]); + } + return base; +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>초기 정의. JavaScript 1.1에서 구현됨.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-10.6', 'Arguments Object')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-arguments-exotic-objects', 'Arguments Exotic Objects')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-arguments-exotic-objects', 'Arguments Exotic Objects')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.functions.arguments.length")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("Function.length")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/functions/default_parameters/index.html b/files/ko/web/javascript/reference/functions/default_parameters/index.html new file mode 100644 index 0000000000..2783b65844 --- /dev/null +++ b/files/ko/web/javascript/reference/functions/default_parameters/index.html @@ -0,0 +1,239 @@ +--- +title: 기본값 매개변수 +slug: Web/JavaScript/Reference/Functions/Default_parameters +tags: + - ECMAScript2015 + - ECMAScript6 + - Functions + - JavaScript + - 기본값 매개변수 +translation_of: Web/JavaScript/Reference/Functions/Default_parameters +--- +<div>{{jsSidebar("Functions")}}</div> + +<p> 기본값 함수 매개변수 (<strong>default function parameter</strong>)를 사용하면 값이 없거나 <code>undefined</code>가 전달될 경우 이름붙은 매개변수를 기본값으로 초기화할 수 있습니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/functions-default.html")}}</p> + +<div class="hidden"> +<p>위의 상호작용가능한 예제의 소스는 깃허브 저장소에 저장됩니다. 상호작용 예제 프로젝트에 기여하고 싶다면 <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> 를 클론(clone)하여 풀 리퀘스트(pull request) 를 보내주세요.</p> +</div> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox notranslate">function [<em>name</em>]([<em>param1</em>[ = <em>defaultValue1</em> ][, ..., <em>paramN</em>[ = defaultValueN ]]]) { + <em>statements</em> +} +</pre> + +<h2 id="설명">설명</h2> + +<p>JavaScript에서, 함수의 매개변수는 <code>{{jsxref("undefined")}}</code>가 기본입니다. 그러나, 일부 상황에서는 다른 기본 값을 설정하는 것이 유용할 수 있습니다. 이때가 바로 기본값 매개변수 가 필요할 때 입니다.</p> + +<p>과거에 기본값 설정을 위한 일반적인 방법은 함수 내부(body)에서 매개변수 값을 검사해 <code>undefined</code>인 경우 값을 할당하는 것이었습니다.</p> + +<p>다음 예제에서, <code>multiply</code>호출시 <code>b</code>에 할당된 값이 없다면, <code>b</code> 값은 <code>a*b</code>를 평가할 때 <code>undefined</code>일 거고 <code>multiply</code> 호출은 <code>NaN</code>이 반환됩니다. </p> + +<pre class="notranslate"><code>function multiply(a, b) { + return a * b +} + +multiply(5, 2) // 10 +multiply(5) // NaN !</code></pre> + +<p>이를 방지하기 위해서, 아래 두번째 줄과 같이 <code>multiply</code> 함수가 오직 한 개의 인수만 있다면 <code>b</code>를 <code>1</code>로 설정하는 방식을 사용하곤 했습니다.</p> + +<pre class="brush: js notranslate">function multiply(a, b) { + b = (typeof b !== 'undefined') ? b : 1 + return a*b +} + +multiply(5, 2) // 10 +multiply(5) // 5 +</pre> + +<p>ES2015의 기본값 매개변수로 함수 내부 에서의 검사는 더 이상 필요치 않습니다. 이제, 간단히 함수 머리(head)에서 <code>b</code>의 기본값으로 <code>1</code> 로 설정할 수 있습니다:</p> + +<pre class="brush: js notranslate">function multiply(a, b = 1) { + return a*b +} + +multiply(5, 2) // 10 +multiply(5) // 5 +multiply(5, undefined) // 5 +</pre> + +<h2 id="예제">예제</h2> + +<h3 id="undefined_vs._다른_거짓같은_값falsy_values_전달하기"><code>undefined</code> vs. 다른 거짓같은 값(falsy values) 전달하기</h3> + +<p>아래 예제중 두 번째 호출에서, 설사 두 번째 인수를 호출할 때 명시해서 <code>undefined</code> (<code>null</code> 혹은 {{glossary("falsy")}} 값이 아니긴 하지만 )로 설정하더라도 , <code>num</code> 인수의 값은 여전히 기본값입니다.</p> + +<pre class="brush: js notranslate">function test(num = 1) { + console.log(typeof num) +} + +test() // 'number' (num 은 1로 설정됨) +test(undefined) // 'number' (num 이 역시 1로 설정됨) + +// 다른 falsy values로 테스트 하기: +test('') // 'string' (num 은 ''로 설정됨) +test(null) // 'object' (num 은 null로 설정됨) +</pre> + +<h3 id="호출_시_평가">호출 시 평가</h3> + +<p>기본 인수는 <em>호출</em> <em>시 </em>에 평가됩니다, 그래서 Python의 경우 와는 달리, 함수가 호출될 때마다 새로운 객체가 생성됩니다.</p> + +<pre class="brush: js notranslate">function append(value, array = []) { + array.push(value) + return array +} + +append(1) // [1] +append(2) // [2], [1, 2]가 아니라 + +</pre> + +<p>이는 심지어 함수 및 변수에도 적용됩니다:</p> + +<pre class="brush: js notranslate">function callSomething(thing = something()) { + return thing +} + +let numberOfTimesCalled = 0 +function something(){ + numberOfTimesCalled += 1 + return numberOfTimesCalled +} + +callSomething() // 1 +callSomething() // 2 +</pre> + +<h3 id="앞쪽_매개변수는_뒷쪽의_매개변수_기본값에_사용할_수_있습니다">앞쪽 매개변수는 뒷쪽의 매개변수 기본값에 사용할 수 있습니다</h3> + +<p>매개 변수가 여러개일 때 앞쪽에( 왼쪽 부분) 정의된 매개변수는 뒷쪽에 정의된 매개변수의 기본값에 바로 사용할 수 있습니다.</p> + +<pre class="brush: js notranslate">function greet(name, greeting, message = greeting + ' ' + name) { + return [name, greeting, message] +} + +greet('David', 'Hi') // ["David", "Hi", "HiDavid"] +greet('David', 'Hi', 'Happy Birthday!') // ["David", "Hi", "Happy Birthday!"] +</pre> + +<p>이 기능은, 얼마나 많은 경계 조건(edge case)를 다룰수 있는지 보여주는, 아래 예제로 거의 설명 가능합니다.</p> + +<pre class="brush: js notranslate">function go() { + return ':P' +} + +// 함수 정의가 간단해짐 +function withDefaults(a, b = 5, c = b, d = go(), e = this, + f = arguments, g = this.value) { + return [a,b,c,d,e,f,g] +} + +// 함수 정의가 길고 장황함 +function withoutDefaults(a, b, c, d, e, f, g){ + switch(arguments.length){ + case 0: + a; + case 1: + b = 5; + case 2: + c = b; + case 3: + d = go(); + case 4: + e = this; + case 5: + f = arguments; + case 6: + g = this.value; + default: + } + return [a,b,c,d,e,f,g]; +} + +// 아래와 같이 함수 호출하면 동일한 결과를 보임 + +withDefaults.call({value:"=^_^="}); +// [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="] + +withoutDefaults.call({value:"=^_^="}); +// [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="] +</pre> + +<h3 id="유효범위_효과_Scope_Effects">유효범위 효과 (Scope Effects)</h3> + +<p>한개 이상의 매개변수에 기본값이 지정되면 특별히 매개변수 목록내의 식별자들(identifiers) 대상으로, <a href="https://tc39.es/ecma262/#sec-functiondeclarationinstantiation">두번째 스코프</a> (Environment Record) 가 생성됩니다.</p> + +<p>이 말은 함수 내부에 선언된 함수와 변수들은 매개변수 기본값 초기화시에 참조할 수 없다는 말입니다; 그렇게 하려고 하면 실행시간 에러인 {{jsxref("ReferenceError")}} 를 유발합니다.</p> + +<p>이 말은 또한 함수 내부에서 <code>var</code> 로 선언된 변수는 동일한 이름을 가진 매개변수를 가리게 되는, 중첩 <code>var</code> 선언 으로 인한 일반적인 동작이 일어나지 않는다는 말입니다.</p> + +<p>아래 함수는 호출되면 <code>ReferenceError</code> 를 발생시킵니다. 매개변수 기본값이 함수 내부의 자식 유효범위를 참조할 수 없기 때문입니다.</p> + +<pre class="brush: js example-bad notranslate">function f(a = go()) { // `f`가 호출 되면 `ReferenceError` 발생 + function go() { return ':P' } +}</pre> + +<p>...그리고 아래 함수는 <code>undefined</code> 를 프린트 하는데, <code>var a</code> 가 함수 내부 대상의 유효범위내에서만 효과를 가지기 때문입니다. ( 매개변수 목록이 대상인 부모 스코프가 아니라)</p> + +<pre class="brush: js example-bad notranslate">function f(a, b = () => console.log(a)) { + var a = 1 + b() // `undefined`를 인쇄하는데, 매개변수 기본값이 자체 스코프에 있기 때문입니다 +} </pre> + +<h3 id="기본값_매개변수_뒤쪽의_기본값_없는_매개변수">기본값 매개변수 뒤쪽의 기본값 없는 매개변수</h3> + +<p>매개변수는 여전히 왼쪽에서 오른쪽으로 설정됩니다. 아래 예제에서 뒷쪽에 기본값이 없는 매개변수가 있지만 기본값 매개변수를 덮어씁니다.</p> + +<pre class="brush: js notranslate">function f(x=1, y) { + return [x, y]; +} + +f() // [1, undefined] +f(2) // [2, undefined] +</pre> + +<h3 id="기본값_할당_있는_해체된_매개변수">기본값 할당 있는 해체된 매개변수</h3> + +<p>기본값 할당을 {{jsxref("Operators/Destructuring_assignment", "destructuring assignment", "", 1)}} 표기와 함께 사용할 수 있습니다:</p> + +<pre class="brush: js notranslate">function f([x, y] = [1, 2], {z: z} = {z: 3}) { + return x + y + z +} + +f() // 6</pre> + +<h2 id="스펙">스펙</h2> + +<table> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-function-definitions', 'Function Definitions')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div class="hidden"> +<p>이 페이지의 호환성 표는 구조화된 데이타로 부터 생성됩니다. 해당 데이타 업데이트에 기여하고 싶다면 이 깃허브 <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> 를 체크아웃 해서 풀 리퀘스트를 보내주세요.</p> +</div> + +<p>{{Compat("javascript.functions.default_parameters")}}</p> + +<h2 id="참조">참조</h2> + +<ul> + <li><a class="external" href="http://wiki.ecmascript.org/doku.php?id=harmony:parameter_default_values" rel="external" title="http://wiki.ecmascript.org/doku.php?id=harmony:parameter_default_values">Original proposal at ecmascript.org</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/functions/get/index.html b/files/ko/web/javascript/reference/functions/get/index.html new file mode 100644 index 0000000000..fb64206dff --- /dev/null +++ b/files/ko/web/javascript/reference/functions/get/index.html @@ -0,0 +1,179 @@ +--- +title: getter +slug: Web/JavaScript/Reference/Functions/get +tags: + - 자바스크립트 + - 함수 +translation_of: Web/JavaScript/Reference/Functions/get +--- +<div>{{jsSidebar("Functions")}}</div> + +<p><strong><code>get</code></strong> 구문은 객체의 프로퍼티를 그 프로퍼티를 가져올 때 호출되는 함수로 바인딩합니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/functions-getter.html")}}</p> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">{get <em>prop</em>() { ... } } {get <em>[expression]</em>() { ... } }</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>prop</code></dt> + <dd>주어진 함수를 바인딩할 프로퍼티의 이름입니다.</dd> + <dt>expression</dt> + <dd>ECMAScript 2015가 도입되면서, 함수의 이름을 계산하기 위해 표현식을 사용할 수 있습니다.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p>어떤 프로퍼티에 접근할 때마다 그 값을 계산하도록 해야 하거나, 내부 변수의 상태를 명시적인 함수 호출 없이 보여주고 싶을 때, JavaScript의 <em>getter</em>를 이용할 수 있습니다. getter가 바인딩된 프로퍼티는 동시에 실제 값을 가질 수는 없지만, getter와 setter를 동시에 바인딩해 일종의 유사 프로퍼티(pseudo-property)를 만들 수는 있습니다.</p> + +<p><code>get</code> 구문을 이용할 때는 다음을 유의하세요.</p> + +<div> +<ul> + <li>숫자나 문자열로 구성된 식별자를 이용할 수 있습니다.</li> + <li>getter는 절대로 매개변수를 가져서는 안 됩니다. (<a class="external" href="http://whereswalden.com/2010/08/22/incompatible-es5-change-literal-getter-and-setter-functions-must-now-have-exactly-zero-or-one-arguments/" rel="external nofollow">Incompatible <abbr title="ECMAScript 5th edition">ES5</abbr> change: literal getter and setter functions must now have exactly zero or one arguments</a> 를 참조하세요.)</li> + <li>하나의 객체 리터럴에 또다른 getter나 데이터 바인딩은 불가능합니다. (<code>{ get x() { }, get x() { } }</code> 나 <code>{ x: ..., get x() { } }</code> 는 사용할 수 없습니다.)</li> +</ul> +</div> + +<p>getter는 <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete" title="en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/delete_Operator">delete</a></code> 연산자를 이용해 삭제할 수 있습니다.</p> + +<h2 id="예">예</h2> + +<h3 id="getter를_객체_초기자에서_정의하기">getter를 객체 초기자에서 정의하기</h3> + +<p>객체 <code>obj</code>에 유사 프로퍼티 <code>latest</code>를 생성합니다. <code>latest</code>는 배열 <code>log</code>의 마지막 요소를 반환합니다.</p> + +<pre><code>var obj = { + log: ['example','test'], + get latest() { + if (this.log.length == 0) return undefined; + return this.log[this.log.length - 1]; + } +} +console.log(obj.latest); // "test".</code></pre> + +<p><code>latest</code>에 어떤 값을 할당하려고 시도해도 그 값이 바뀌지 않는다는 점을 유의하세요.</p> + +<h3 id="delete연산자를_이용해_getter_삭제하기"><code>delete</code>연산자를 이용해 getter 삭제하기</h3> + +<p>getter를 삭제하고 싶다면, <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete">delete</a></code>를 이용하면 됩니다.</p> + +<pre class="brush: js">delete obj.latest; +</pre> + +<h3 id="defineProperty를_이용해_이미_존재하는_객체에_getter_정의하기"><code>defineProperty</code>를 이용해 이미 존재하는 객체에 getter 정의하기</h3> + +<p>이미 존재하는 객체에 getter를 추가하고자 한다면, {{jsxref("Object.defineProperty()")}}를 이용하면 됩니다.</p> + +<pre class="brush: js">var o = { a:0 } + +Object.defineProperty(o, "b", { get: function () { return this.a + 1; } }); + +console.log(o.b) // getter를 실행합니다. a + 1 (= 1)이 반환됩니다.</pre> + +<h3 id="계산된_(computed)_프로퍼티_이름">계산된 (computed) 프로퍼티 이름</h3> + +<pre class="brush: js">var expr = "foo"; + +var obj = { + get [expr]() { return "bar"; } +}; + +console.log(obj.foo); // "bar"</pre> + +<h3 id="똑똑한(Smart)_스스로_덮어쓰는(self-overwriting)_느긋한(lazy)_getter">똑똑한(Smart) / 스스로 덮어쓰는(self-overwriting) / 느긋한(lazy) getter</h3> + +<p>Getter는 객체에 프로퍼티를 정의할 수 있도록 하지만, 그 프로퍼티에 접근하기 전까지는 값을 계산하지 않습니다. getter는 값을 계산하는 비용을 실제 값이 필요할 때까지 미루며, 그 값이 필요없다면 계산 비용도 들지 않습니다.</p> + +<p>또다른 최적화 기법으로는 계산 미루기와 함께 프로퍼티 값을 나중에 접근하기 위해 캐싱하는 것이 있습니다. 이를<strong> 똑똑한(smart), 혹은 메모화된(<a href="https://en.wikipedia.org/wiki/Memoization">memoized</a>) getter</strong>라고 부릅니다. 값은 getter가 호출될 때 처음 계산되며, 캐싱됩니다. 이후의 호출에는 다시 계산하지 않고 이 캐시값을 반환합니다. 이는 다음과 같은 상황에 유용합니다.</p> + +<ul> + <li>값의 계산 비용이 큰 경우. (RAM이나 CPU 시간을 많이 소모하거나, worker thread를 생성하거나, 원격 파일을 불러오는 등)</li> + <li>값이 당장은 필요하지 않지만 나중에 사용되어야 할 경우, 혹은 절대로 이용되지 않을 수도 있는 경우.</li> + <li>값이 여러 차례 이용되지만 절대 변경되지 않아 매번 다시 계산할 필요가 없는 경우, 혹은 다시 계산되어서는 안 되는 경우.</li> +</ul> + +<p>똑똑한 getter는 값을 다시 계산하지 않기 때문에, 값의 변경이 예상되는 경우에는 똑똑한 getter를 이용해서는 안 됩니다.</p> + +<p>다음 예제에서, 객체는 원래 프로퍼티로 getter를 가집니다. 프로퍼티를 가져올 때, getter는 삭제되며 대신 명시적인 값이 저장됩니다. 최종적으로 값을 반환합니다.</p> + +<pre class="brush: js">get notifier() { + delete this.notifier; + return this.notifier = document.getElementById("bookmarked-notification-anchor"); +},</pre> + +<p>Firefox 코드의 경우, <code><a href="/en-US/docs/Mozilla/JavaScript_code_modules/XPCOMUtils.jsm#defineLazyGetter()">defineLazyGetter()</a></code> 함수를 정의하고 있는 XPCOMUtils.jsm 모듈을 참조하세요.</p> + +<h3 id="get_Vs._defineProperty"><code>get</code> Vs. <code>defineProperty</code></h3> + +<p>While using the <code>get</code> 키워드와 {{jsxref("Object.defineProperty()")}}를 사용하면 비슷한 결과를 얻지만, {{jsxref("classes")}}에서 사용되는 두 가지 경우에는 미묘한 차이가 있습니다.</p> + +<p>get을 사용할 때 속성은 {{jsxref("Object.defineProperty()")}} 를 사용하는 동안 객체의 프로토 타입에 정의 될 것이고, 속성은 그것이 적용되는 인스턴스에 정의 될 것입니다.</p> + +<pre class="brush: js"><code>class Example { + get hello() { + return 'world'; + } +} + +const obj = new Example(); +console.log(obj.hello); +// "world" +console.log(Object.getOwnPropertyDescriptor(obj, 'hello')); +// undefined +console.log(Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), 'hello')); +// { configurable: true, enumerable: false, get: function get hello() { return 'world'; }, set: undefined }</code></pre> + +<p> </p> + +<h2 id="스펙">스펙</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11.1.5', 'Object Initializer')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>최초로 정의되었습니다.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-method-definitions', 'Method definitions')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>계산된 프로퍼티 이름이 추가되었습니다.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-method-definitions', 'Method definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.functions.get")}}</p> + +<p> </p> + +<h2 id="참조">참조</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions/set">setter</a></li> + <li>{{jsxref("Operators/delete", "delete")}}</li> + <li>{{jsxref("Object.defineProperty()")}}</li> + <li>{{jsxref("Object.defineGetter", "__defineGetter__")}}</li> + <li>{{jsxref("Object.defineSetter", "__defineSetter__")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters">Defining Getters and Setters</a> in JavaScript Guide</li> +</ul> diff --git a/files/ko/web/javascript/reference/functions/index.html b/files/ko/web/javascript/reference/functions/index.html new file mode 100644 index 0000000000..2052b67a93 --- /dev/null +++ b/files/ko/web/javascript/reference/functions/index.html @@ -0,0 +1,596 @@ +--- +title: 함수 +slug: Web/JavaScript/Reference/Functions +tags: + - 생성자 + - 인자 + - 파라미터 + - 함수 +translation_of: Web/JavaScript/Reference/Functions +--- +<div>{{jsSidebar("Functions")}}</div> + +<p>일반적으로, 함수는 함수 외부 (또는 재귀(recursion)의 경우엔 내부) 코드에 의해 <em>호출될</em> 수 있는 "하위프로그램"입니다. 프로그램 그 자체처럼, 함수는 함수 몸통(<em>function body</em>)이라고 하는 일련의 구문(statement)으로 구성됩니다. 값은 함수에 <em>전달될</em> 수 있고 함수는 값을 <em>반환</em>합니다.</p> + +<p>JavaScript에서, 함수는 다른 객체처럼 속성 및 메서드를 가질 수 있기에 일급(first-class) 객체입니다. 다른 객체와 함수를 구별하는 것은 함수는 호출될 수 있다는 것입니다. 간단히 말해, 함수는 <code><a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Function">Function</a></code> 객체입니다.</p> + +<p>더 많은 예제와 설명은, <a href="/ko/docs/Web/JavaScript/Guide/함수" title="JavaScript guide about functions">JavaScript 함수 안내서</a>를 참조하세요.</p> + +<h2 id="설명">설명</h2> + +<p>JavaScript에서 모든 함수는 <code>Function</code> 객체입니다. <code>Function</code> 객체의 속성(property) 및 메서드에 관한 정보는 {{jsxref("Function")}} 참조.</p> + +<p>기본값 이외의 값을 반환하려면, 함수는 반환할 값을 지정하는 <code><a href="/ko/docs/Web/JavaScript/Reference/Statements/return">return</a></code> 문이 있어야 합니다. return 문이 없는 함수는 기본값을 반환합니다. <code><a href="/ko/docs/Web/JavaScript/Reference/Operators/new">new</a></code> 키워드로 호출되는 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor">생성자</a>의 경우에, 기본값은 자신의 <code>this</code> 매개변수 값입니다. 다른 모든 함수의 경우, 기본 반환값은 {{jsxref("undefined")}}입니다.</p> + +<p>함수 호출의 매개변수는 함수의 <em>인수</em>입니다. 인수는 함수에 <em>값으로</em> 전달됩니다. 함수가 인수값을 바꾸면, 이 변화는 전역 또는 호출한 함수에 반영되지 않습니다. 그러나, 객체 참조(reference)는 값이지만 특별합니다: 함수가 참조된 객체의 속성을 바꾸면, 그 변화는 다음 예에서와 같이 함수 밖에서도 바뀌는 것을 볼 수 있습니다:</p> + +<pre class="brush: js">/* 함수 'myFunc' 선언 */ +function myFunc(theObject) { + theObject.brand = "Toyota"; + } + + /* + * 변수 'mycar' 선언; + * 새 객체를 만들고 초기화; + * 'mycar'에 객체 참조를 할당 + */ + var mycar = { + brand: "Honda", + model: "Accord", + year: 1998 + }; + + /* Logs 'Honda' */ + console.log(mycar.brand); + + /* 객체 참조를 함수에 전달 */ + myFunc(mycar); + + /* + * 함수에 의해 바뀌었기에 객체의 + * 'brand' 속성의 값으로 'Toyota' 출력. + */ + console.log(mycar.brand); +</pre> + +<p><a href="/ko/docs/Web/JavaScript/Reference/Operators/this"><code>this</code> 키워드</a>는 현재 실행 중인 함수를 참조하지 않습니다, 그래서 심지어 함수 몸통 내에서도 이름으로 <code>Function</code> 객체를 참조해야 합니다.</p> + +<h2 id="함수_정의하기">함수 정의하기</h2> + +<p>함수를 정의하는 여러 방법이 있습니다:</p> + +<h3 id="함수_선언_function_문">함수 선언 (<code>function</code> 문)</h3> + +<p>함수 선언을 위한 특별한 구문이 있습니다 (자세한 사항은 <a href="/ko/docs/Web/JavaScript/Reference/Statements/function" title="function statement">function 문</a> 참조):</p> + +<pre class="brush: js">function <em>name</em>([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { + <em>statements</em> +} +</pre> + +<dl> + <dt><code>name</code></dt> + <dd>함수 이름.</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>함수에 전달되는 인수의 이름. 함수는 255개까지 인수를 가질 수 있습니다.</dd> +</dl> + +<dl> + <dt><code>statements</code></dt> + <dd>함수의 몸통을 구성하는 문.</dd> +</dl> + +<h3 id="함수_표현식_function_식">함수 표현식 (<code>function</code> 식)</h3> + +<p>함수 식(expression)은 함수 선언과 비슷하고 구문이 같습니다 (자세한 사항은 <a href="/ko/docs/Web/JavaScript/Reference/Operators/function" title="function expression">function 식</a> 참조):</p> + +<p>함수 표현식(expression)은 함수 선언과 비슷하고 구문이 같습니다 (자세한 내용은 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function">function expression</a> 참조). 함수 표현식은 더 큰 표현식의 일부일 수 있습니다. "이름이 붙은(named)"함수 표현식 (예 : 호출 스택에서 표현식 이름 사용하는경우) 또는 "익명"함수 표현식을 정의 할 수 있습니다. 함수 표현식은 선언이 되지 않은 상태에서 사용할 수 없기 때문에 함수를 사용하기 전에 코드에 함수코드가 존제해야 사용 할 수 있습니다.</p> + +<pre class="brush: js">function [<em>name</em>]([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { + <em>statements</em> +} +</pre> + +<dl> + <dt><code>name</code></dt> + <dd>함수 이름. 함수가 익명(anonymous) 함수로 알려진 경우, 생략될 수 있음.</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>함수에 전달되는 인수의 이름. 함수는 255개까지 인수를 가질 수 있습니다.</dd> + <dt><code>statements</code></dt> + <dd>함수의 몸통을 구성하는 문.</dd> +</dl> + +<p>다음은 익명 함수 표현식의 예입니다 (<font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">이름</span></font> 이 사용되지 않음):</p> + +<pre class="brush: js"><code>var myFunction = function() { + statements +}</code></pre> + +<p>It is also possible to provide a name inside the definition in order to create a <strong>named</strong> function expression:</p> + +<pre class="brush: js"><code>var myFunction = function namedFunction(){ + statements +}</code></pre> + +<p>One of the benefits of creating a named function expression is that in case we encountered an error, the stack trace will contain the name of the function, making it easier to find the origin of the error.</p> + +<p>As we can see, both examples do not start with the <code>function</code> keyword. Statements involving functions which do not start with <code>function</code> are function expressions.</p> + +<p>When functions are used only once, a common pattern is an <a href="https://developer.mozilla.org/en-US/docs/Glossary/IIFE">IIFE (Immediately Invokable Function Expression)</a>.</p> + +<pre class="brush: js"><code>(function() { + statements +})();</code></pre> + +<p>IIFE are function expressions that are invoked as soon as the function is declared.</p> + +<h3 id="생성기_함수_선언_function*_문">생성기 함수 선언 (<code>function*</code> 문)</h3> + +<p>생성기 함수 선언을 위한 특별한 구문이 있습니다 (자세한 사항은 {{jsxref('Statements/function*', 'function* statement')}} 참조):</p> + +<pre class="brush: js">function* <em>name</em>([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { + <em>statements</em> +} +</pre> + +<dl> + <dt><code>name</code></dt> + <dd>함수 이름.</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>함수에 전달되는 인수의 이름.</dd> +</dl> + +<dl> + <dt><code>statements</code></dt> + <dd>함수의 몸통을 구성하는 문.</dd> +</dl> + +<h3 id="생성기_함수_식_function*_식">생성기 함수 식 (<code>function*</code> 식)</h3> + +<p>생성기 함수 식은 생성기 함수 선언과 비슷하고 구문이 같습니다 (자세한 사항은 {{jsxref('Operators/function*', 'function* expression')}} 참조):</p> + +<pre class="brush: js">function* [<em>name</em>]([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { + <em>statements</em> +} +</pre> + +<dl> + <dt><code>name</code></dt> + <dd>함수 이름. 함수가 익명 함수인 경우 생략될 수 있음.</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>함수에 전달되는 인수의 이름.</dd> + <dt><code>statements</code></dt> + <dd>함수의 몸통을 구성하는 문.</dd> +</dl> + +<h3 id="화살표_함수_표현식_>">화살표 함수 표현식 (=>)</h3> + +<p>화살표 함수 식은 구문이 더 짧고 어휘상(lexically) <code>this</code> 값을 바인딩합니다 (자세한 사항은 <a href="/ko/docs/Web/JavaScript/Reference/Functions/애로우_펑션" title="arrow functions">화살표 함수</a> 참조):</p> + +<pre class="brush: js">([param[, param]]) => { + statements +} + +param => expression +</pre> + +<dl> + <dt><code>param</code></dt> + <dd>인수의 이름. 0개 인수는 <code>()</code>로 표시돼야 합니다. 인수가 1개뿐이면, 괄호는 필요치 않습니다. (<code>foo => 1</code>처럼)</dd> + <dt><code>statements or expression</code></dt> + <dd>선언문이 여러개인 경우 괄호로 묶여야 합니다. 단일 식(expression)은 괄호가 필요 없습니다. 그리고 식은 암시적으로(implicit) 함수의 반환값이 됩니다.</dd> +</dl> + +<h3 id="Function_constructor"><code>Function</code> constructor</h3> + +<div class="note"> +<p><strong>참고</strong> : <code>Function</code> constructor를 사용하여 함수를 만드는 것은 권장되지 않습니다. 함수 본문을 일부 JS 엔진 최적화를 방해 할 수있는 문자열로 사용해야하고 다른 문제를 유발할 수 있기 때문입니다.</p> +</div> + +<p>다른 모든 객체처럼, {{jsxref("Function")}} 객체는 <code>new</code> 연산자를 사용하여 생성될 수 있습니다:</p> + +<pre class="brush: js">new Function (<em>arg1</em>, <em>arg2</em>, ... <em>argN</em>, <em>functionBody</em>) +</pre> + +<dl> + <dt><code>arg1, arg2, ... arg<em>N</em></code></dt> + <dd>형식 매개변수로 함수에 의해 사용되는 0개 이상의 이름. 각각은 알맞은 JavaScript 식별자(identifier)여야 합니다.</dd> +</dl> + +<dl> + <dt><code>functionBody</code></dt> + <dd>함수 몸통을 구성하는 JavaScript 문을 포함하는 문자열.</dd> +</dl> + +<p>함수로 <code>Function</code> 생성자 호출(<code>new</code> 연산자 사용 없이)하는 것은 생성자로 호출하는 것과 같습니다.</p> + +<h3 id="GeneratorFunction_생성자"><code>GeneratorFunction</code> 생성자</h3> + +<div class="note"> +<p><strong>주의:</strong> <code>GeneratorFunction</code>은 전역 객체가 아니지만 생성기 함수 인스턴스로부터 얻을 수 있습니다(자세한 사항은 {{jsxref("GeneratorFunction")}} 참조).</p> +</div> + +<div class="note"> +<p><strong>주의:</strong> <code>GeneratorFunction</code> 생성자를 사용하여 함수를 만드는 것은 권장되지 않습니다. 함수 본문을 일부 JS 엔진 최적화를 방해 할 수있는 문자열로 사용해야하고 다른 문제를 유발할 수 있기 때문입니다.</p> +</div> + +<p>다른 모든 객체처럼, {{jsxref("GeneratorFunction")}} 객체는 <code>new</code> 연산자를 사용하여 생성될 수 있습니다:</p> + +<pre class="brush: js">new GeneratorFunction (<em>arg1</em>, <em>arg2</em>, ... <em>argN</em>, <em>functionBody</em>) +</pre> + +<dl> + <dt><code>arg1, arg2, ... arg<em>N</em></code></dt> + <dd>형식 인수명으로 함수에 의해 사용되는 0개 이상의 이름. 각각은 유효한 JavaScript 식별자 규칙을 따르는 문자열 또는 콤마로 구분된 그러한 문자열 목록이어야 합니다; 예를 들어 "<code>x</code>", "<code>theValue</code>" 또는 "<code>a,b</code>".</dd> +</dl> + +<dl> + <dt><code>functionBody</code></dt> + <dd>함수 정의를 구성하는 JavaScript 문을 포함하는 문자열.</dd> +</dl> + +<p>함수로서 <code>Function</code> 생성자 호출(<code>new</code> 연산자 사용 없이)은 생성자로서 호출하는 것과 같은 효과입니다.</p> + +<h2 id="Function_매개변수">Function 매개변수</h2> + +<h3 id="기본_매개변수">기본 매개변수</h3> + +<p>기본(default) 함수 매개변수는 전달된 값이 없거나 <code>undefined</code>인 경우 기본값으로 초기화되는 형식 매개변수를 허용합니다. 자세한 사항은, <a href="/ko/docs/Web/JavaScript/Reference/Functions/Default_parameters" title="default parameters">기본 매개변수</a> 참조.</p> + +<h3 id="나머지_매개변수">나머지 매개변수</h3> + +<p>나머지(rest) 매개변수 구문은 부정(indefinite)수인 인수를 배열로 나타내는 것을 허용합니다. 자세한 사항은, <a href="/ko/docs/Web/JavaScript/Reference/Functions/rest_parameters" title="rest parameters">나머지 매개변수</a> 참조.</p> + +<h2 id="arguments_객체"><code>arguments</code> 객체</h2> + +<p><code>arguments</code> 객체를 사용하여 함수 내에서 함수의 인수를 참조할 수 있습니다. <a href="/ko/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a> 참조.</p> + +<ul> + <li><code><a href="/ko/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a></code>: 현재 실행 중인 함수에 전달된 인수를 포함하는 배열 같은 객체.</li> + <li><code><a href="/ko/docs/Web/JavaScript/Reference/Functions/arguments/callee">arguments.callee</a></code> {{Deprecated_inline}} : 현재 실행 중인 함수.</li> + <li><code><a href="/ko/docs/Web/JavaScript/Reference/Functions/arguments/caller">arguments.caller</a></code> {{Obsolete_inline}} : 현재 실행 중인 함수를 호출한 함수.</li> + <li><code><a href="/ko/docs/Web/JavaScript/Reference/Functions/arguments/length">arguments.length</a></code>: 함수에 전달된 인수의 수.</li> +</ul> + +<h2 id="메서드_함수_정의하기">메서드 함수 정의하기</h2> + +<h3 id="getter_및_setter_함수">getter 및 setter 함수</h3> + +<p>모든 표준 내장 객체 또는 새로운 속성 추가를 지원하는 사용자 정의 객체에 getter(accessor 메서드) 및 setter(mutator 메서드)를 정의할 수 있습니다. getter 및 setter를 정의하는 구문은 객체 리터럴 구문을 사용합니다.</p> + +<dl> + <dt><a href="/ko/docs/Web/JavaScript/Reference/Functions/get">get</a></dt> + <dd> + <p>객체 속성을 그 속성이 검색되는 경우 호출되는 함수에 바인딩합니다.</p> + </dd> + <dt><a href="/ko/docs/Web/JavaScript/Reference/Functions/set">set</a></dt> + <dd>객체 속성을 그 속성을 설정하려는 시도가 있는 경우 호출되는 함수에 바인딩합니다.</dd> +</dl> + +<h3 id="메서드_정의_구문">메서드 정의 구문</h3> + +<p>ECMAScript 2015를 시작으로, getter 및 setter와 비슷한 단축 구문으로 자신의 메서드를 정의할 수 있습니다. 더 자세한 정보는 <a href="/ko/docs/Web/JavaScript/Reference/Functions/Method_definitions">메서드 정의</a> 참조.</p> + +<pre class="brush: js">var obj = { + foo() {}, + bar() {} +};</pre> + +<h2 id="생성자_vs._선언문_vs._표현식">생성자 vs. 선언문 vs. 표현식</h2> + +<p>다음을 비교해보세요:</p> + +<p><code>Function</code> <em>constructor로 정의된 함수를 </em>변수<code>multiply</code>에 할당.</p> + +<pre class="brush: js"><code>var multiply = new Function('x', 'y', 'return x * y');</code></pre> + +<p>이름이 <code>multiply</code>인 함수 선언:</p> + +<pre class="brush: js">function multiply(x, y) { + return x * y; +} +</pre> + +<p>변수 <code>multiply</code>에 할당된 익명(anonymous) 함수의 <em>function 식</em>:</p> + +<pre class="brush: js">var multiply = function(x, y) { + return x * y; +}; +</pre> + +<p>변수 <code>multiply</code>에 할당된 이름이 <code>func_name</code>인 함수의 <em>function 식</em>:</p> + +<pre class="brush: js">var multiply = function func_name(x, y) { + return x * y; +}; +</pre> + +<h3 id="차이">차이</h3> + +<p>모두 거의 같은 일을 하지만 약간 미묘한 차이가 있습니다:</p> + +<p>함수 이름과 함수가 할당 된 변수 사이에는 차이가 있습니다. 함수 이름을 변경할 수 없으며 함수가 할당 된 변수는 다시 할당 할 수 있습니다. 함수 이름은 함수 본문(body)내에서만 사용할 수 있습니다. 함수 본문(body) 외부에서 사용하려고 하면 오류가 발생합니다. (함수 이름이 <code>var</code> 문을 통해 이전에 선언 된 경우에는 정의되지 않습(<code>undefined</code>)니다.</p> + +<p>예를 들어:</p> + +<pre class="brush: js">var y = function x() {}; +alert(x); // 오류 발생 +</pre> + +<p>함수 이름은 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Function/toString"><code>Function</code>의 toString 메서드</a>를 통해 직렬화되는 경우에도 보입니다.</p> + +<p>반면에 함수가 할당 된 변수는 함수의 범위(scope)가 포함되도록 보장 된 범위로만 제한됩니다.</p> + +<p>예제 4에서 볼 수 있듯이 함수 이름은 함수가 할당 된 변수와 다를 수 있습니다. 그들은 서로에게 아무런 관련이 없습니다. 함수 선언은 함수 이름과 동일한 이름의 변수도 만듭니다. 따라서 함수 표현식으로 정의 된 함수와 달리 함수 선언으로 정의 된 함수는 정의 된 범위에서 함수 선언의 이름으로 액세스 할 수 있습니다.</p> + +<p>'<code>new Function</code>'으로 정의된 함수는 함수 이름이 없습니다. 그러나, <a href="/ko/docs/SpiderMonkey">SpiderMonkey</a> JavaScript 엔진에서는, 함수의 직렬화된 형태가 마치 그 이름이 "anonymous"인 것처럼 보입니다. 예를 들어, <code>alert(new Function())</code>은 다음을 출력합니다:</p> + +<pre class="brush: js">function anonymous() { +} +</pre> + +<p>함수가 실제로는 이름이 없기에, <code>anonymous</code>는 함수 내에서 액세스될 수 있는 변수가 아닙니다.</p> + +<p>다음 코드는 오류가 날 것입니다:</p> + +<pre class="brush: js">var foo = new Function("alert(anonymous);"); +foo(); +</pre> + +<p>function 식 또는 <code>Function</code> 생성자에 의해 정의된 함수와는 달리, function 선언으로 정의된 함수는 function 자체의 선언 전에 사용될 수 있습니다. 예를 들어:</p> + +<pre class="brush: js">foo(); // alerts FOO! +function foo() { + alert('FOO!'); +} +</pre> + +<p>함수 표현식(function expression)이나 함수 선언(function declaration)에 의해 정의 된 함수는 현재 범위를 상속합니다. 즉,이 함수는 클로저를 형성합니다. 반면에 <code>Function</code> 생성자가 정의한 함수는 전역 범위 (모든 함수가 상속) 이외의 다른 범위를 상속하지 않습니다.</p> + +<pre class="brush: js"><code>/* + * Declare and initialize a variable 'p' (global) + * and a function 'myFunc' (to change the scope) inside which + * declare a varible with same name 'p' (current) and + * define three functions using three different ways:- + * 1. function declaration + * 2. function expression + * 3. function constructor + * each of which will log 'p' + */ +var p = 5; +function myFunc() { + var p = 9; + + function decl() { + console.log(p); + } + var expr = function() { + console.log(p); + }; + var cons = new Function('\tconsole.log(p);'); + + decl(); + expr(); + cons(); +} +myFunc(); + +/* + * Logs:- + * 9 - for 'decl' by function declaration (current scope) + * 9 - for 'expr' by function expression (current scope) + * 5 - for 'cons' by Function constructor (global scope) + */</code></pre> + +<p>function 식 및 function 선언에 의해 정의된 함수는 한 번만 구문 분석됩니다, 반면에 <code>Function</code> 생성자에 의해 정의된 함수는 아닙니다. 즉, <code>Function</code> 생성자에 전달된 함수 몸통 문자열은 생성자가 호출될 때마다 구문 분석되어야 합니다. function 식이 매번 closure를 만들더라도, 함수 몸통은 다시 구문 분석되지 않습니다, 그래서 function 식은 "<code>new Function(...)</code>"보다 여전히 더 빠릅니다. 따라서 <code>Function</code> 생성자는 보통 가능한 한 피해야 합니다.</p> + +<p>함수 식과 함수 선언으로 정의 된 함수는 한 번만 구문 분석되지만 <code>Function</code> 생성자로 정의 된 함수는 구문 분석되지 않습니다. 즉, <code>Function</code> 생성자에 전달 된 함수 본문 문자열은 생성자가 호출 될 때마다 파싱되어야합니다. 함수식이 매번 클로저(closure)를 만들지만 함수 본문은 다시 파싱되지 않으므로 함수 식은 여전히 "<code>new Function (...)</code>"보다 빠릅니다. 따라서 <code>Function</code> 생성자는 가능한 피하는 것이 좋습니다.</p> + +<p>그러나 <code>Function constructor</code>의 문자열을 구문 분석하여 생성된 함수 내에 중첩된 function 식 및 function 선언은 반복해서 구문 분석되지 않음에 주의해야 합니다. 예를 들면:</p> + +<pre class="brush: js">var foo = (new Function("var bar = \'FOO!\';\nreturn(function() {\n\talert(bar);\n});"))(); +foo(); // 함수 몸통 문자열의 "function() {\n\talert(bar);\n}" 부분은 다시 구문 분석되지 않습니다.</pre> + +<p>function 선언은 매우 쉽게 (그리고 종종 무심코) function 식으로 바뀝니다. function 선언은 다음 어느 쪽이든 function 식이 되는 것을 중단합니다:</p> + +<ul> + <li>식의 일부가 된 경우</li> + <li>더 이상 함수 또는 스크립트 자체의 "source 요소"가 아닌 경우. "source 요소"는 스크립트 또는 함수 몸통에서 중첩되지 않은 문입니다:</li> +</ul> + +<pre class="brush: js">var x = 0; // source 요소 +if (x == 0) { // source 요소 + x = 10; // source 요소가 아님 + function boo() {} // source 요소가 아님 +} +function foo() { // source 요소 + var y = 20; // source 요소 + function bar() {} // source 요소 + while (y == 10) { // source 요소 + function blah() {} // source 요소가 아님 + y++; // source 요소가 아님 + } +} +</pre> + +<h3 id="예">예</h3> + +<pre class="brush: js">// function 선언 +function foo() {} + +// function 식 +(function bar() {}) + +// function 식 +x = function hello() {} + + +if (x) { + // function 식 + function world() {} +} + + +// function 선언 +function a() { + // function 선언 + function b() {} + if (0) { + // function 식 + function c() {} + } +} +</pre> + +<h2 id="블록_레벨_함수">블록 레벨 함수</h2> + +<p>ES2015 (ES6)를 시작으로 <a href="/ko/docs/Web/JavaScript/Reference/Strict_mode" title="strict mode">엄격 모드</a>에서, 블록 내부 함수는 이제 그 블록 범위가 됩니다. ES6 이전에, 블록 레벨 함수는 엄격 모드에서 금지됐습니다.</p> + +<pre class="brush: js">'use strict'; + +function f() { + return 1; +} + +{ + function f() { + return 2; + } +} + +f() === 1; // true + +// 비엄격 모드에서는 f() === 2 +</pre> + +<h3 id="비엄격_코드에서_블록_레벨_함수">비엄격 코드에서 블록 레벨 함수</h3> + +<p>한 마디로: 안됩니다.</p> + +<p>비엄격 코드에서, 블록 내부 function 선언은 이상하게 동작합니다. 예를 들면:</p> + +<pre class="brush: js">if (shouldDefineZero) { + function zero() { // 위험: 호환성 위험 + console.log("This is zero."); + } +} +</pre> + +<p>ES2015는 <code>shouldDefineZero</code>가 false인 경우, 그러면 <code>zero</code>는 결코 정의되어서는 안된다고 합니다, 그 블록이 실행된 적이 없기에. 그러나, 이는 표준의 새로운 일부입니다. 역사상, 이는 지정되지 않은 채 방치되었고 일부 브라우저는 블록이 실행됐든 아니든 <code>zero</code>를 정의할 겁니다.</p> + +<p><a href="/ko/docs/Web/JavaScript/Reference/Strict_mode" title="strict mode">엄격 모드</a>에서, ES2015를 지원하는 모든 브라우저는 이를 같은 식으로 다룹니다: <code>zero</code>는 <code>shouldDefineZero</code>가 true이고 <code>if</code> 블록 범위인 경우에만 정의됩니다.</p> + +<p>조건부 함수를 정의하는 더 안전한 방법은 function 식을 변수에 할당하는 것입니다:</p> + +<pre class="brush: js">var zero; +if (0) { + zero = function() { + console.log("This is zero."); + }; +} +</pre> + +<h2 id="예제">예제</h2> + +<h3 id="형식_갖춘_숫자_반환하기">형식 갖춘 숫자 반환하기</h3> + +<p>다음 함수는 선행 0으로 채워진 형식 갖춘(formatted) 숫자 표현을 포함하는 문자열을 반환합니다.</p> + +<pre class="brush: js">// 이 함수는 선행 0으로 채워진 문자열을 반환 +function padZeros(num, totalLen) { + var numStr = num.toString(); // 문자열로 반환값을 초기화 + var numZeros = totalLen - numStr.length; // 0의 개수 계산 + for (var i = 1; i <= numZeros; i++) { + numStr = "0" + numStr; + } + return numStr; +} +</pre> + +<p>다음 문은 padZeros 함수를 호출합니다.</p> + +<pre class="brush: js">var result; +result = padZeros(42,4); // 반환값 "0042" +result = padZeros(42,2); // 반환값 "42" +result = padZeros(5,4); // 반환값 "0005" +</pre> + +<h3 id="함수_존재_여부_결정하기">함수 존재 여부 결정하기</h3> + +<p><code>typeof</code> 연산자를 사용하여 함수가 존재하는지 여부를 결정할 수 있습니다. 다음 예에서, <code>window</code> 객체가 함수인 <code>noFunc</code>이라고 하는 속성이 있는지 결정하기 위해 테스트가 수행됩니다. 있으면, 사용됩니다; 그렇지 않으면 무언가 다른 행동을 취합니다.</p> + +<pre class="brush: js"> if ('function' == typeof window.noFunc) { + // noFunc() 사용 + } else { + // 뭔가 다른 것 수행 + } +</pre> + +<p><code>if</code> 테스트에는, <code>noFunc</code>에 대한 참조가 사용되고—실제 함수가 호출되지 않도록 함수 이름 뒤에 괄호 "()"가 없음을 주의하세요.</p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>초기 정의. JavaScript 1.0에서 구현됨</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-13', 'Function Definition')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>신규: 화살표 함수, 생성기 함수, 기본 매개변수, 나머지 매개변수.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.functions")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Statements/function", "function 문")}}</li> + <li>{{jsxref("Operators/function", "function 식")}}</li> + <li>{{jsxref("Statements/function*", "function* 문")}}</li> + <li>{{jsxref("Operators/function*", "function* 식")}}</li> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("GeneratorFunction")}}</li> + <li>{{jsxref("Functions/애로우_펑션", "화살표 함수")}}</li> + <li>{{jsxref("Functions/Default_parameters", "기본 매개변수")}}</li> + <li>{{jsxref("Functions/rest_parameters", "나머지 매개변수")}}</li> + <li>{{jsxref("Functions/arguments", "arguments 객체")}}</li> + <li>{{jsxref("Functions/get", "getter")}}</li> + <li>{{jsxref("Functions/set", "setter")}}</li> + <li>{{jsxref("Functions/Method_definitions", "메서드 정의")}}</li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Functions" title="Functions and function scope">함수 및 함수 범위</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/functions/method_definitions/index.html b/files/ko/web/javascript/reference/functions/method_definitions/index.html new file mode 100644 index 0000000000..ff1b67956a --- /dev/null +++ b/files/ko/web/javascript/reference/functions/method_definitions/index.html @@ -0,0 +1,230 @@ +--- +title: 메서드 정의 +slug: Web/JavaScript/Reference/Functions/Method_definitions +tags: + - ECMAScript 2015 + - Functions + - JavaScript + - Object + - Syntax +translation_of: Web/JavaScript/Reference/Functions/Method_definitions +--- +<div>{{JsSidebar("Functions")}}</div> + +<p>ECMAScript 2015 를 시작으로, 객체 초기자(initializer)에 메서드 정의를 위한 더 짧은 구문이 도입되었습니다. 이는 메서드 명에 할당된 함수를 위한 단축입니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">var obj = { + <var>property</var>( <var>parameters…</var> ) {}, + *<var>generator</var>( <var>parameters…</var> ) {}, +// 키(속성) 계산값과도 함께: + [property]( <var>parameters…</var> ) {}, + *[generator]( <var>parameters…</var> ) {}, +// ES5 getter/setter 구문과 비교해 보세요: + get <var>property</var>() {}, + set <var>property</var>(<var>value</var>) {} +}; +</pre> + +<h2 id="설명">설명</h2> + +<p>단축 구문은 ECMAScript 5에 도입된 <a href="/ko/docs/Web/JavaScript/Reference/Functions/get">getter</a> 및 <a href="/ko/docs/Web/JavaScript/Reference/Functions/set">setter</a> 구문과 비슷합니다.</p> + +<p>다음 코드가 주어지면:</p> + +<pre class="brush: js">var obj = { + foo: function() {}, + bar: function() {} +};</pre> + +<p>이제 이를 아래로 줄일 수 있습니다:</p> + +<pre class="brush: js">var obj = { + foo() {}, + bar() {} +};</pre> + +<div class="note"> +<p><strong>주의 :</strong> 단축 구문은 익명(anonymous) 함수 (…<code>foo: function() {}</code>… 에서처럼) 대신 유명(named) 함수를 사용합니다. 유명 함수는 함수 본체에서 호출될 수 있습니다 (이는 참조할 식별자가 없기에 익명 함수에게는 불가능합니다). 자세한 사항은, {{jsxref("Operators/function","function","#Examples")}} 참조.</p> +</div> + +<h3 id="단축_생성기_메서드">단축 생성기 메서드</h3> + +<p><a href="/ko/docs/Web/JavaScript/Reference/Statements/function*">생성기 메서드</a>는 단축 구문을 사용해서도 정의될 수 있습니다. 단축 구문 내 별표(*)는 생성기 속성명 앞에 와야 함을 주의하세요. 즉, <code>* g(){}</code>는 작동하지만 <code>g *(){}</code>는 아닙니다.</p> + +<pre class="brush: js;highlight[12]">// 유명 속성 사용 (ES2015 이전) +var obj2 = { + g: function*() { + var index = 0; + while(true) + yield index++; + } +}; + +// 단축 구문을 쓰는 같은 객체 +var obj2 = { + * g() { + var index = 0; + while(true) + yield index++; + } +}; + +var it = obj2.g(); +console.log(it.next().value); // 0 +console.log(it.next().value); // 1</pre> + +<h3 id="메서드_정의는_생성_불가능합니다">메서드 정의는 생성 불가능합니다</h3> + +<p>모든 메서드 정의는 생성자가 아니고 인스턴스화하려고 하는 경우 {{jsxref("TypeError")}} 예외가 발생합니다.</p> + +<pre class="brush: js example-bad">var obj = { + method() {}, +}; +new obj.method; // TypeError: obj.method는 생성자가 아닙니다 + +var obj = { + * g() {} +}; +new obj.g; // TypeError: obj.g는 생성자가 아닙니다 (ES2016에서 바뀜) +</pre> + +<h2 id="예">예</h2> + +<h3 id="간단한_테스트_사례">간단한 테스트 사례</h3> + +<pre class="brush: js;highlight[3]">var obj = { + a : "foo", + b(){ return this.a; } +}; +console.log(obj.b()); // "foo" +</pre> + +<h3 id="속성_계산명">속성 계산명</h3> + +<p>단축 구문은 속성 계산명(computed property name)도 지원합니다.</p> + +<pre class="brush: js;highlight[4]">var bar = { + foo0 : function (){return 0;}, + foo1(){return 1;}, + ["foo" + 2](){return 2;}, +}; + +console.log(bar.foo0()); // 0 +console.log(bar.foo1()); // 1 +console.log(bar.foo2()); // 2</pre> + +<h2 id="스펙">스펙</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-method-definitions', 'Method definitions')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ES7', '#sec-method-definitions', 'Method definitions')}}</td> + <td>{{Spec2('ES7')}}</td> + <td>생성기 메서드 역시 [[Construct]] 트랩이 없어야 하고 <code>new</code>와 함께 사용되는 경우 예외 발생으로 바뀜.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-method-definitions', 'Method definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Method definition shorthand</td> + <td>{{CompatChrome("39")}}</td> + <td>{{CompatGeckoDesktop("34")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatOpera("26")}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Generator methods are not constructable (ES2016)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("43")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Method definition shorthand</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile("34")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Generator methods are not constructable (ES2016)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("43")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="SpiderMonkey_전용_주의사항">SpiderMonkey 전용 주의사항</h2> + +<ul> + <li>SpiderMonkey 38 {{geckoRelease(38)}} 이전에, "<code>get</code>" 및 "<code>set</code>"은 생성기 메서드에 무효한 이름이었습니다. 이는 {{bug(1073809)}}에서 해결됐습니다.</li> + <li>SpiderMonkey 41 {{geckoRelease(41)}} 이전에, 중괄호는 메서드 정의에 필요하지 않았습니다. ES2015 스펙을 따르기 위해 이제부터 필요하고 이번과 이후 버전에서 {{jsxref("SyntaxError")}}가 발생합니다 ({{bug(1150855)}}). + <pre class="brush: js example-bad">var o = {x() 12}; // SyntaxError</pre> + </li> + <li>오직 생성기 메서드만이 생성자인 제한은 SpiderMonkey 41 {{geckoRelease(41)}}에서 구현되었습니다. {{bug(1059908)}} 및 {{bug(1166950)}} 참조.</li> +</ul> + +<h2 id="참조">참조</h2> + +<ul> + <li><code><a href="/ko/docs/Web/JavaScript/Reference/Functions/get">get</a></code></li> + <li><code><a href="/ko/docs/Web/JavaScript/Reference/Functions/set">set</a></code></li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Lexical_grammar" title="Lexical grammar">어휘 문법</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/functions/rest_parameters/index.html b/files/ko/web/javascript/reference/functions/rest_parameters/index.html new file mode 100644 index 0000000000..eee5528b38 --- /dev/null +++ b/files/ko/web/javascript/reference/functions/rest_parameters/index.html @@ -0,0 +1,223 @@ +--- +title: Rest 파라미터 +slug: Web/JavaScript/Reference/Functions/rest_parameters +tags: + - Functions + - JavaScript + - Rest + - Rest parameters +translation_of: Web/JavaScript/Reference/Functions/rest_parameters +--- +<div>{{jsSidebar("Functions")}}</div> + +<p><strong>Rest 파라미터</strong> 구문은 정해지지 않은 수(an indefinite number, 부정수) 인수를 배열로 나타낼 수 있게 합니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/functions-restparameters.html")}}</p> + +<div class="hidden"> +<p>The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p> +</div> + +<p> </p> + +<h2 id="구문">구문</h2> + +<pre class="brush: js">function f(a, b, ...theArgs) { + // ... +} +</pre> + +<h2 id="설명">설명</h2> + +<p>함수의 마지막 파라미터의 앞에 <code>...</code> 를 붙여 (사용자가 제공한) 모든 나머지 인수를 "표준" 자바스크립트 배열로 대체합니다. 마지막 파라미터만 "Rest 파라미터" 가 될 수 있습니다.</p> + +<pre class="brush: js">function myFun(a, b, ...manyMoreArgs) { + console.log("a", a); + console.log("b", b); + console.log("manyMoreArgs", manyMoreArgs); +} + +myFun("one", "two", "three", "four", "five", "six"); + +// Console Output: +// a, one +// b, two +// manyMoreArgs, [three, four, five, six]</pre> + +<p> </p> + +<h3 id="Rest_파라미터_및_arguments_객체간_차이">Rest 파라미터 및 <code>arguments</code> 객체간 차이</h3> + +<p>Rest 파라미터와 <a href="/ko/docs/Web/JavaScript/Reference/Functions/arguments" title="arguments"><code>arguments</code></a> 객체 사이에 세 가지 주요 차이점이 있습니다:</p> + +<ul> + <li>Rest 파라미터는 구분된 이름(예, 함수 표현에 정식으로 정의된 것)이 주어지지 않은 유일한 대상인 반면, <code>arguments</code> 객체는 함수로 전달된 모든 인수를 포함합니다.</li> + <li><code>arguments</code> 객체는 실제 배열이 아니고 rest 파라미터는 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Array" title="Array"><code>Array</code></a> 인스턴스로, <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/sort" title="Array sort method"><code>sort</code></a>, <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/map" title="Array map method"><code>map</code></a>, <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach" title="Array forEach method"><code>forEach</code></a> 또는 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/pop" title="Array pop method"><code>pop</code></a> 같은 메서드가 바로 인스턴스에 적용될 수 있음을 뜻합니다.</li> + <li>즉 <code>arguments</code> 객체는 자체에 특정 추가 기능이 있습니다 (<code>callee</code> 속성처럼).</li> +</ul> + +<h3 id="arguments에서_배열까지">arguments에서 배열까지</h3> + +<p>Rest 파라미터는 인수에 의해 유발된 상용구(boilerplate) 코드를 줄이기 위해 도입되었습니다.</p> + +<pre class="brush: js">// Rest 파라미터 이전에, "arguments" 는 다음을 사용해 일반적인 배열로 변환될 수 있음 + +function f(a, b) { + + var normalArray = Array.prototype.slice.call(arguments); + // -- 또는 -- + var normalArray = [].slice.call(arguments); + // -- 또는 -- + var normalArray = Array.from(arguments); + + var first = normalArray.shift(); // OK, 첫 번째 인수를 반환 + var first = arguments.shift(); // ERROR (arguments 가 일반적인 배열이 아님) + +} + +// 이제 rest 파라미터를 사용해 쉽게 일반적인 배열에 접근할 수 있음 + +function f(...args) { + var normalArray = args; + var first = normalArray.shift(); // OK, 첫 번째 인수를 반환 +}</pre> + +<h3 id="Rest_파라미터_해체">Rest 파라미터 해체</h3> + +<p>Rest 파라미터는 해체될 수 있습니다(배열로만). 이는 데이터가 구분된 변수로 해체될 수 있음을 의미합니다. <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">구조 분해 할당</a> 문서를 보세요.</p> + +<pre class="brush: js">function f(...[a, b, c]) { + return a + b + c; +} + +f(1) // NaN (b 와 c 는 undefined) +f(1, 2, 3) // 6 +f(1, 2, 3, 4) // 6 (4번 째 파라미터는 해체되지 않음)</pre> + +<h2 id="예제">예제</h2> + +<p>이 예제에서, 첫 번째 인수는 <code>"a"</code>, 두 번째 인수는 <code>"b"</code> 로 매핑되어, 일반적인 유명 인수와 같이 사용됩니다. 반면에 3번 째 인수 <code>"manyMoreArgs"</code> 는 사용자가 포함시킨 인수를 포함하는 배열이 됩니다.</p> + +<pre class="brush: js">function myFun(a, b, ...manyMoreArgs) { + console.log("a", a); + console.log("b", b); + console.log("manyMoreArgs", manyMoreArgs); +} + +myFun("one", "two", "three", "four", "five", "six"); + +// a, one +// b, two +// manyMoreArgs, [three, four, five, six]</pre> + +<p>아래를 보면, 하나의 값만 있더라도 마지막 인수는 여전히 배열을 갖습니다.</p> + +<pre class="brush: js">// 위 예제와 동일한 함수 정의를 사용 + +myFun("one", "two", "three"); + +// a, one +// b, two +// manyMoreArgs, [three]</pre> + +<p>아래를 보면, 3번 째 인수가 제공되지 않더라도, "manyMoreArgs" 는 여전히 배열입니다(비어있긴하지만).</p> + +<pre class="brush: js">// 위 예제와 동일한 함수 정의를 사용 + +myFun("one", "two"); + +// a, one +// b, two +// manyMoreArgs, []</pre> + +<p><code>theArgs</code> 가 배열이므로, <code>length</code> 프로퍼티를 사용해 엘리먼트의 수를 얻을 수 있습니다.</p> + +<pre class="brush: js">function fun1(...theArgs) { + console.log(theArgs.length); +} + +fun1(); // 0 +fun1(5); // 1 +fun1(5, 6, 7); // 3</pre> + +<p>다음 예제에서, rest 파라미터는 첫 번째 인수 다음의 모든 인수를 배열로 모으는데 사용됩니다. 각각은 첫 번째 파라미터와 곱해져 배열로 반환됩니다.</p> + +<pre class="brush: js">function multiply(multiplier, ...theArgs) { + return theArgs.map(function(element) { + return multiplier * element; + }); +} + +var arr = multiply(2, 1, 2, 3); +console.log(arr); // [2, 4, 6]</pre> + +<p><code>Array</code> 메소드는 rest 파라미터에서 사용될 수 있지만, <code>arguments</code> 객체에서는 그렇지 않습니다.</p> + +<pre class="brush: js">function sortRestArgs(...theArgs) { + var sortedArgs = theArgs.sort(); + return sortedArgs; +} + +console.log(sortRestArgs(5, 3, 7, 1)); // 1, 3, 5, 7 + +function sortArguments() { + var sortedArgs = arguments.sort(); + return sortedArgs; // this will never happen +} + + +console.log(sortArguments(5, 3, 7, 1)); // TypeError (arguments.sort is not a function)</pre> + +<p><code>arguments</code> 객체에서 <code>Array</code> 메소드를 사용하려면, 이를 먼저 실제 배열로 변환해야합니다.</p> + +<pre class="brush: js">function sortArguments() { + var args = Array.from(arguments); + var sortedArgs = args.sort(); + return sortedArgs; +} +console.log(sortArguments(5, 3, 7, 1)); // 1, 3, 5, 7 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-function-definitions', 'Function Definitions')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-function-definitions', 'Function Definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p> </p> + +<div class="hidden"> +<p>The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> +</div> + +<p>{{Compat("javascript.functions.rest_parameters")}}</p> + +<h2 id="함께_보기">함께 보기</h2> + +<ul> + <li><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Spread_syntax" title="spread operator">Spread 문법</a> (또한 ‘<code>...</code>’)</li> + <li><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/arguments" title="arguments">Arguments 객체</a></li> + <li><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array" title="Array">Array</a></li> + <li><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions" title="Functions and function scope">함수</a></li> + <li><a href="http://wiki.ecmascript.org/doku.php?id=harmony:rest_parameters">Original proposal at ecmascript.org</a></li> + <li><a href="http://javascriptweblog.wordpress.com/2011/01/18/javascripts-arguments-object-and-beyond/">JavaScript arguments object and beyond</a></li> + <li><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">구조 분해 할당</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/functions/set/index.html b/files/ko/web/javascript/reference/functions/set/index.html new file mode 100644 index 0000000000..248a218c37 --- /dev/null +++ b/files/ko/web/javascript/reference/functions/set/index.html @@ -0,0 +1,208 @@ +--- +title: setter +slug: Web/JavaScript/Reference/Functions/set +translation_of: Web/JavaScript/Reference/Functions/set +--- +<div>{{jsSidebar("Functions")}}</div> + +<p><strong><code>set</code></strong> syntax는 어떤 객체의 속성에 이 속성을 설정하려고 할 때 호출되는 함수를 바인드한다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">{set <em>prop</em>(<em>val</em>) { . . . }} +{set [expression](<em>val</em>) { . . . }}</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>prop</code></dt> + <dd>주어진 함수를 바인드할 속성의 이름</dd> +</dl> + +<dl> + <dt><code>val</code></dt> + <dd><code>prop에 설정될 값을 가지고 있는 변수의 별명.</code></dd> + <dt>expression</dt> + <dd>ECMAScript 6부터는, 주어진 함수에 바인드 되는 속성 이름은 계산(computed)을 통해 얻을 수 있고 이것을 위한 expressions을 사용할 수 있다.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p> 자바스크립트에서, setter는 특정한 속성에 값이 변경되어 질 때마다 함수를 실행하는데 사용될 수 있다. Setter는 유사(pseudo)-property 타입을 생성하는 getter와 함께 가장 자주 사용된다. 실제 값을 가지는 property와 이 property의 setter 를 동시에 갖는 것은 불가능하다.</p> + +<p><code>set</code> 문법을 사용할 때 다음을 주의한다:</p> + +<div> +<ul> + <li>숫자혹은 문자로된 식별자를 가질 수 있다;</li> + <li>한 개의 파라메터만 가질 수 있다.(더 자세한 정보는 <a class="external" href="http://whereswalden.com/2010/08/22/incompatible-es5-change-literal-getter-and-setter-functions-must-now-have-exactly-zero-or-one-arguments/" rel="external nofollow">Incompatible <abbr title="ECMAScript 5th edition">ES5</abbr> change: literal getter and setter functions must now have exactly zero or one arguments</a>를 본다);</li> + <li>오브젝트 리터럴에 동일한 property에 대한 다른 set나 데이터 항목이 올 수 없다.<br> + ( <code>{ set x(v) { }, set x(v) { } }</code> 그리고 <code>{ x: ..., set x(v) { } }</code> 는 허용되지 않는다.)</li> +</ul> +</div> + +<p>setter는 <a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete" title="en-US/docs/JavaScript/Reference/Operators/Special/delete"><code>delete</code></a> operator를 사용하여 제거할 수 있다.</p> + +<h2 id="예">예</h2> + +<h3 id="새로운_객체의_setter를_객체의_initializer에서_정의하기">새로운 객체의 setter를 객체의 initializer에서 정의하기 </h3> + +<p>다음은 객체 o의 유사 프로러티(pseudo-property )인 <code>current를 정의한다. 이것은 값이 설정될 때, 이 값으로 로그를 갱신 한다.</code></p> + +<pre class="brush: js">var o = { + set current (str) { + this.log[this.log.length] = str; + }, + log: [] +} +</pre> + +<p><code><font face="Open Sans, Arial, sans-serif">다음 사항에 주의한다. </font>current는 정의 되지 않았고 이것에 접근하는 모든 시도는 undefined 값을 얻게될 것이다.</code></p> + +<h3 id="delete_operator로_setter를_제거하기"><code>delete</code> operator로 setter를 제거하기</h3> + +<p>만약 setter를 제거하기 원한다면, 그냥 그것을 <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete">delete</a></code> 하면 된다:</p> + +<pre class="brush: js">delete o.current; +</pre> + +<h3 id="defineProperty를_사용하여_이미_존재하는_객체에_setter를_정의하기"><code>defineProperty를 사용하여 이미 존재하는 객체에 </code>setter를 정의하기</h3> + +<p>setter를 이미 존재하는 object에 나중에 언제라도 추가하기 위해서, {{jsxref("Object.defineProperty()")}}를 사용한다.</p> + +<pre class="brush: js">var o = { a:0 }; + +Object.defineProperty(o, "b", { set: function (x) { this.a = x / 2; } }); + +o.b = 10; // Runs the setter, which assigns 10 / 2 (5) to the 'a' property +console.log(o.a) // 5</pre> + +<h3 id="연산된(computed)_property_name_사용하기">연산된(computed) property name 사용하기</h3> + +<div class="note"> +<p><strong>Note:</strong> 계산된(Computed) properties는 실험적인 기술이고, ECMAScript 6 proposal의 부분이다. 아직 많은 브라우저가 지원하지 않는다. 이것 때문에 지원하지 않는 환경에서는 문법 오류가 발생할 것이다.</p> +</div> + +<pre class="brush: js">var expr = "foo"; + +var obj = { + baz: "bar", + set [expr](v) { this.baz = v; } +}; + +console.log(obj.baz); // "bar" +obj.foo = "baz"; // run the setter +console.log(obj.baz); // "baz" +</pre> + +<h2 id="스펙">스펙</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11.1.5', 'Object Initializer')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-method-definitions', 'Method definitions')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Added computed property names.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-method-definitions', 'Method definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성CompatibilityTable">브라우저 호환성{{CompatibilityTable}}</h2> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(1)}}</td> + <td>{{ CompatGeckoDesktop("1.8.1") }}</td> + <td>{{ CompatIE(9) }}</td> + <td>9.5</td> + <td>3</td> + </tr> + <tr> + <td>Computed property names</td> + <td>{{CompatNo}}</td> + <td>{{ CompatGeckoDesktop("34") }}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{ CompatGeckoMobile("1.8.1") }}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Computed property names</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{ CompatGeckoMobile("34.0") }}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="SpiderMonkey-specific_notes">SpiderMonkey-specific notes</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/1.8.1"> JavaScript 1.8.1</a>부터, object와 array initializers에서 properties를 설정 할 때 setter는 더이상 호출되지 않는다.</li> + <li>SpiderMonkey 38 부터, {{jsxref("Functions/rest_parameters", "rest parameter", "", 1)}} 를 갖는 setter는 ES6 specification에 따라 {{jsxref("SyntaxError")}}이다.</li> +</ul> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions/get">getter</a></li> + <li>{{jsxref("Operators/delete", "delete")}}</li> + <li>{{jsxref("Object.defineProperty()")}}</li> + <li>{{jsxref("Object.defineGetter", "__defineGetter__")}}</li> + <li>{{jsxref("Object.defineSetter", "__defineSetter__")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters">Defining Getters and Setters</a> in JavaScript Guide</li> +</ul> diff --git a/files/ko/web/javascript/reference/functions/애로우_펑션/index.html b/files/ko/web/javascript/reference/functions/애로우_펑션/index.html new file mode 100644 index 0000000000..02dc0d55e4 --- /dev/null +++ b/files/ko/web/javascript/reference/functions/애로우_펑션/index.html @@ -0,0 +1,465 @@ +--- +title: 화살표 함수 +slug: Web/JavaScript/Reference/Functions/애로우_펑션 +tags: + - ECMAScript6 + - Functions + - Intermediate + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Functions/Arrow_functions +--- +<div>{{jsSidebar("Functions")}}</div> + +<p>화살표 함수 표현(<strong>arrow function expression</strong>)은 <a href="/ko/docs/Web/JavaScript/Reference/Operators/function" title="function expressions">function 표현</a>에 비해 구문이 짧고 자신의 <a href="/ko/docs/Web/JavaScript/Reference/Operators/this">this</a>, <a href="/ko/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a>, <a href="/ko/docs/Web/JavaScript/Reference/Operators/super">super</a> 또는 <a href="/ko/docs/Web/JavaScript/Reference/Operators/new.target">new.target</a>을 바인딩 하지 않습니다. 화살표 함수는 항상 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Function/name" title="anonymous">익명</a>입니다. 이 함수 표현은 메소드 함수가 아닌 곳에 가장 적합합니다. 그래서 생성자로서 사용할 수 없습니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/functions-arrow.html")}}</p> + +<h2 id="구문">구문</h2> + +<h3 id="기본_구문">기본 구문</h3> + +<pre class="syntaxbox notranslate"><strong>(</strong><em>param1</em>, <em>param2</em>, …, <em>paramN</em><strong>) => {</strong> <em>statements</em> <strong>}</strong> +<strong>(</strong><em>param1</em>, <em>param2</em>, …, <em>paramN</em><strong>) =></strong> <em>expression</em> +// 다음과 동일함: => { return expression; } + +// 매개변수가 하나뿐인 경우 괄호는 선택사항: +<em>(singleParam)</em> <strong>=> {</strong> <em>statements</em> <strong>}</strong> +<em>singleParam</em> <strong>=></strong> { <em>statements }</em> + +// 매개변수가 없는 함수는 괄호가 필요: +<strong>() => {</strong> <em>statements</em> <strong>}</strong></pre> + +<h3 id="고급_구문">고급 구문</h3> + +<pre class="syntaxbox notranslate">// 객체 리터럴 표현을 반환하기 위해서는 함수 본문(body)을 괄호 속에 넣음: +<em>params</em> => ({<em>foo: bar</em>}) + +// <a href="/ko/docs/Web/JavaScript/Reference/Functions/rest_parameters" title="Rest parameter">나머지 매개변수</a> 및 <a href="/ko/docs/Web/JavaScript/Reference/Functions/Default_parameters" title="Default parameter">기본 매개변수</a>를 지원함 +(<em>param1</em>, <em>param2</em>, <strong>...rest</strong>) => { <em>statements</em> } +(<em>param1</em> <strong>= defaultValue1</strong>, <em>param2</em>, …, paramN <strong>= defaultValueN</strong>) => { <em>statements</em> } + +// 매개변수 목록 내 <a href="/ko/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment" title="Destructuring">구조분해할당</a>도 지원됨 +var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c; +f(); // 6 +</pre> + +<p>상세한 구문 예는 <a href="http://wiki.ecmascript.org/doku.php?id=harmony:arrow_function_syntax">여기</a>에서 볼 수 있습니다.</p> + +<h2 id="설명">설명</h2> + +<p><a href="https://hacks.mozilla.org/2015/06/es6-in-depth-arrow-functions/">Hacks 블로그 "ES6 In Depth: Arrow functions" 포스트</a> 참조.</p> + +<p>화살표 함수 도입에 영향을 준 두 요소: 보다 짧아진 함수 및 <code>바인딩하지 않은 this.</code></p> + +<h3 id="짧은_함수">짧은 함수</h3> + +<p>일부 함수 패턴에서는, 짧은 함수가 환영받습니다. 비교해 보세요:</p> + +<pre class="notranslate">var elements = [ + 'Hydrogen', + 'Helium', + 'Lithium', + 'Beryllium' +]; + +// 이 문장은 배열을 반환함: [8, 6, 7, 9] +elements.<a href="https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a>(function(element) { + return element.length; +}); + +// 위의 일반적인 함수 표현은 아래 화살표 함수로 쓸 수 있다. +elements.map((element) => { + return element.length; +}); // [8, 6, 7, 9] + +// 파라미터가 하나만 있을 때는 주변 괄호를 생략할 수 있다. +elements.<a href="https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a>(element => { + return element.length; +}); // [8, 6, 7, 9] + +// 화살표 함수의 유일한 문장이 'return'일 때 'return'과 +// 중괄호({})를 생략할 수 있다. +elements.map(element => element.length); // [8, 6, 7, 9] + +// 이 경우 length 속성만 필요하므로 destructuring 매개변수를 사용할 수 있다. +// 'length'는 우리가 얻고자 하는 속성에 해당하는 반면, +// lengthFooBArX'는 변경 가능한 변수의 이름일 뿐이므로 +// 원하는 유효한 변수명으로 변경할 수 있다. +elements.<a href="https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a>(({ length: lengthFooBArX }) => lengthFooBArX); // [8, 6, 7, 9] + +// destructuring 파라미터 할당도 아래와 같이 작성할 수 있습니다. +// 이 예에서 정의한 객체내의 'length'에 값을 지정하지 않은 점에 주목하세요. 대신, "length" 변수의 +// 리터럴 이름은 우리가 해당 객체에서 꺼내오고 싶은 속성이름 자체로 사용됩니다. +elements.<a href="https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a>(({ length }) => length); // [8, 6, 7, 9] </pre> + +<h3 id="바인딩_되지_않은_this">바인딩 되지 않은 <code>this</code></h3> + +<p>화살표 함수가 나오기 전까지는, 모든 새로운 함수는, 어떻게 그 함수가 호출되는지에 따라 자신의 <code><a href="/ko/docs/Web/JavaScript/Reference/Operators/this">this</a></code> 값을 정의했습니다:</p> + +<ul> + <li>이 함수가 생성자인 경우는 새로운 객체</li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Strict_mode" title="strict mode">엄격 모드</a> 함수 호출에서는 <code>undefined</code> </li> + <li>함수가 "객체 메서드"로서 호출된 경우 문맥 객체</li> + <li>등등</li> +</ul> + +<p>이는 객체 지향 스타일로 프로그래밍할 때 별로 좋지않습니다.</p> + +<pre class="brush: js notranslate">function Person() { + // Person() 생성자는 `this`를 자신의 인스턴스로 정의. + this.age = 0; + + setInterval(function growUp() { + // 비엄격 모드에서, growUp() 함수는 `this`를 + // 전역 객체로 정의하고, 이는 Person() 생성자에 + // 정의된 `this`와 다름. + this.age++; + }, 1000); +} + +var p = new Person();</pre> + +<p>ECMAScript 3/5 에서는, 이 문제를 <code>this</code> 값을 폐쇄될 수 있는 (비전역) 변수에 할당하여 해결했습니다.</p> + +<pre class="brush: js notranslate">function Person() { + var that = this; + that.age = 0; + + setInterval(function growUp() { + // 콜백은 `that` 변수를 참조하고 이것은 값이 기대한 객체이다. + that.age++; + }, 1000); +}</pre> + +<p>이렇게 하는 대신에, <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Function/bind" title="bound function">바인딩한 함수</a>는 적절한 <code>this</code> 값이 <code>growUp()</code> 함수에 전달될 수 있도록 생성될 수 있습니다.</p> + +<p>화살표 함수는 자신의 <code>this</code>가 없습니다. 대신 화살표 함수를 둘러싸는 렉시컬 범위(lexical scope)의 <code>this</code>가 사용됩니다; 화살표 함수는 일반 변수 조회 규칙(normal variable lookup rules)을 따릅니다. 때문에 현재 범위에서 존재하지 않는 <code>this</code>를 찾을 때, 화살표 함수는 바로 바깥 범위에서 <code>this</code>를 찾는것으로 검색을 끝내게 됩니다.</p> + +<p>따라서 다음 코드에서 <code>setInterval</code>에 전달 된 함수 내부의 <code>this</code>는 <code>setInterval</code>을 포함한 function의 <code>this</code>와 동일한 값을 갖습니다.</p> + +<pre class="brush: js notranslate">function Person(){ + this.age = 0; + + setInterval(() => { + this.age++; // |this|는 Person 객체를 참조 + }, 1000); +} + +var p = new Person();</pre> + +<h4 id="엄격_모드와의_관계">엄격 모드와의 관계</h4> + +<p><code>this</code>가 렉시컬(lexical, 정적)임을 감안하면, <code>this</code>에 관한 <a href="/ko/docs/Web/JavaScript/Reference/Strict_mode" title="strict mode">엄격 모드</a> 규칙은 그냥 무시됩니다.</p> + +<pre class="notranslate">var f = () => { 'use strict'; return this; }; +f() === window; // 혹은 전역객체</pre> + +<p>엄격 모드의 나머지 규칙은 평소대로 적용합니다.</p> + +<p><strong>CORRECTION: START</strong></p> + +<p>NOTE: the previous statement seems false.</p> + +<p>Strict mode should prevent creating global variables when assigning to an undeclared identifier in a function.</p> + +<p>This code sample using Chrome 81 demonstrates that arrow functions allow the creation of global variables in such situations (both for a concise body and for a normal function body):</p> + +<pre class="notranslate">> f1 = x => { y = x; console.log(`x: ${x}, y: ${y}`); return x + 1; } +x => { y = x; console.log(`x: ${x}, y: ${y}`); return x + 1; } + +> y +VM51587:1 Uncaught ReferenceError: y is not defined + at <anonymous>:1:1 +(anonymous) @ VM51587:1 + +> f1(3) +VM51533:1 x: 3, y: 3 +4 + +> y +3 + +> f2 = x => { 'use strict'; z = x; console.log(`x: ${x}, z: ${z}`); return x + 1; } +x => { 'use strict'; z = x; console.log(`x: ${x}, z: ${z}`); return x + 1; } + +> z +VM51757:1 Uncaught ReferenceError: z is not defined + at <anonymous>:1:1 +(anonymous) @ VM51757:1 + +> f2(4) +VM51712:1 Uncaught ReferenceError: z is not defined + at f2 (<anonymous>:1:29) + at <anonymous>:1:1 +f2 @ VM51712:1 +(anonymous) @ VM51800:1 + +> f3 = x => (z1 = x + 1) +x => (z1 = x + 1) + +> z1 +VM51891:1 Uncaught ReferenceError: z1 is not defined + at <anonymous>:1:1 +(anonymous) @ VM51891:1 + +> f3(10) +11 + +> z1 +11 +</pre> + +<p>f2 illustrates that when explicitly setting the arrow function to apply strict mode, it does throw an error when attempting to assign an undeclared variable.</p> + +<p>https://www.ecma-international.org/ecma-262/10.0/index.html#sec-strict-mode-code</p> + +<p>https://www.ecma-international.org/ecma-262/10.0/index.html#sec-arrow-function-definitions-runtime-semantics-evaluation</p> + +<p><strong>CORRECTION: END</strong></p> + +<h4 id="call_또는_apply를_통한_피호출">call 또는 apply를 통한 피호출</h4> + +<p>화살표 함수에서는 <code>this가 </code> 바인딩되지 않았기 때문에, <code>call()</code> 또는 <code>apply()</code> 메서드는 인자만 전달 할 수 있습니다. this는 무시됩니다.</p> + +<pre class="brush: js notranslate">var adder = { + base : 1, + + add : function(a) { + var f = v => v + this.base; + return f(a); + }, + + addThruCall: function(a) { + var f = v => v + this.base; + var b = { + base : 2 + }; + + return f.call(b, a); + } +}; + +console.log(adder.add(1)); // 이는 2가 콘솔에 출력될 것임 +console.log(adder.addThruCall(1)); // 이도 2가 콘솔에 출력될 것임</pre> + +<h3 id="바인딩_되지_않은_arguments">바인딩 되지 않은 <code>arguments</code></h3> + +<p>화살표 함수는 <a href="/ko/docs/Web/JavaScript/Reference/Functions/arguments"><code>arguments</code> 객체</a>를 바인드 하지 않습니다. 때문에, <code>arguments는</code> 그저 둘러싸는 범위(scope) 내 이름에 대한 참조입니다.</p> + +<pre class="brush: js notranslate"><code>var arguments = [1, 2, 3]; +var arr = () => arguments[0]; + +arr(); // 1 + +function foo(n) { + var f = () => arguments[0] + n; // foo's implicit arguments binding. arguments[0] is n + return f(); +} + +foo(1); // 2</code></pre> + +<p>화살표 함수는 자신의 <code>arguments</code> 객체가 없지만, 대부분의 경우에 <a href="/ko/docs/Web/JavaScript/Reference/Functions/rest_parameters" title="rest parameters">나머지 매개변수</a>가 좋은 대안입니다:</p> + +<pre class="brush: js notranslate">function foo(n) { + var f = (...args) => args[0] + n; + return f(2); +} + +foo(1); // 3</pre> + +<h3 id="메소드로_사용되는_화살표_함수">메소드로 사용되는 화살표 함수</h3> + +<p>이야기 했듯이, 화살표 함수 표현은 메소드 함수가 아닌 형태로 사용 할 수 있습니다. 메소드로 사용하려고 한면 무슨일이 발생하는지 봅시다.</p> + +<pre class="brush: js notranslate"><code>'use strict'; + +var obj = { // does not create a new scope + i: 10, + b: () => console.log(this.i, this), + c: function() { + console.log( this.i, this) + } +} +obj.b(); // prints undefined, Window {...} (or the global object) +obj.c(); // prints 10, Object {...}</code> +</pre> + +<p>화살표 함수는 자신의 this를 가지고("bind" 바인드)있지 않습니다.{{jsxref("Object.defineProperty()")}}</p> + +<pre class="brush: js notranslate"><code>'use strict'; + +var obj = { + a: 10 +}; + +Object.defineProperty(obj, 'b', { + get: () => { + console.log(this.a, typeof this.a, this); // undefined 'undefined' Window {...} (or the global object) + return this.a + 10; // represents global object 'Window', therefore 'this.a' returns 'undefined' + } +});</code></pre> + +<h3 id="new_연산자_사용"><code>new</code> 연산자 사용</h3> + +<p>화살표 함수는 생성자로서 사용될 수 없으며 <code>new</code>와 함께 사용하면 오류가 발생합니다.</p> + +<pre class="brush: js notranslate"><code>var Foo = () => {}; +var foo = new Foo(); // TypeError: Foo is not a constructor</code></pre> + +<h3 id="prototype_속성_사용"><code>prototype</code> 속성 사용</h3> + +<p>화살표 함수는 <code>prototype</code> 속성이 없습니다.</p> + +<pre class="brush: js notranslate"><code>var Foo = () => {}; +console.log(Foo.prototype); // undefined</code></pre> + +<h3 id="yield_키워드_사용"><code>yield</code> 키워드 사용</h3> + +<p><code><a href="/ko/docs/Web/JavaScript/Reference/Operators/yield">yield</a></code> 키워드는 화살표 함수의 본문(그 안에 더 중첩된 함수 내에서 허용한 경우를 제외하고)에 사용될 수 없습니다. 그 결과, 화살표 함수는 생성기(generator)로서 사용될 수 없습니다.</p> + +<h3 id="함수_본문">함수 본문</h3> + +<p>화살표 함수는 "concise 바디"든 보통 "block 바디"든 하나를 가질 수 있습니다.</p> + +<div class="note"> +<p>concise바디는 중괄호'{}'로 묶이지않은 한줄짜리 바디이고 block바디는 중괄호로 묶인 바디입니다. 보통 여러줄 쓸때 block바디를 사용합니다.</p> +</div> + +<p>block바디는 자동으로 값을 반환하지 않습니다. <code>return</code>을 사용해서 값을 반환해야 합니다.</p> + +<pre class="brush: js notranslate">var func = x => x * x; // concise 바디, 생략된 "return" 여기서는 x * x +var func = (x, y) => { return x + y; }; // block 바디, "return"이 필요 +</pre> + +<h3 id="객체_리터럴_반환">객체 리터럴 반환</h3> + +<p>간결한 구문 <code>params => {object:literal}</code>을 사용한 객체 리터럴 반환은 예상대로 작동하지 않음을 명심하세요:</p> + +<pre class="brush: js notranslate">var func = () => { foo: 1 }; +// func() 호출은 undefined를 반환! + +var func = () => { foo: function() {} }; +// SyntaxError: function 문은 이름이 필요함</pre> + +<p>이는 중괄호({}) 안 코드가 일련의 문(즉 <code>foo</code>는 라벨처럼 취급됩니다, 객체 리터럴 내 키가 아니라)으로 파싱(parse, 구문 분석)되기 때문입니다.</p> + +<p>객체 리터럴를 괄호로 감싸는 것을 기억하세요:</p> + +<pre class="brush: js notranslate">var func = () => ({ foo: 1 });</pre> + +<h3 id="줄바꿈">줄바꿈</h3> + +<p>화살표 함수는 파라메터와 화살표 사이에 개행 문자를 포함 할 수 없습니다.</p> + +<pre class="brush: js notranslate"><code>var func = (a, b, c) + => 1; +// SyntaxError: expected expression, got '=>'</code></pre> + +<p>하지만, 보기 좋은 코드를 유지하고 싶다면, 아래에 보는 것처럼 괄호나 개행을 둠으로써 이를 수정할 수 있습니다.</p> + +<pre class="notranslate">var func = (a, b, c) => + 1; + +var func = (a, b, c) => ( + 1 +); + +var func = (a, b, c) => { + return 1 +}; + +<code>var func = ( + a, + b, + c +) => 1; + +// SyntaxError가 발생하지 않습니다.</code></pre> + +<h3 id="파싱순서">파싱순서</h3> + +<p>화살표 함수 내의 화살표는 연산자가 아닙니다. 그러나 화살표 함수는 평범한 함수와 비교했을 때 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">operator precedence</a>와 다르게 반응하는 특별한 파싱룰을 가지고 있습니다.</p> + +<pre class="brush: js notranslate"><code>let callback; + +callback = callback || function() {}; // ok + +callback = callback || () => {}; +// SyntaxError: invalid arrow-function arguments + +callback = callback || (() => {}); // ok</code> +</pre> + +<h2 id="다른_예">다른 예</h2> + +<h3 id="기본_사용법">기본 사용법</h3> + +<pre class="brush: js notranslate"><code>// </code> empty 화살표 함수는 undefined를 반환 <code> +let empty = () => {}; + +(() => 'foobar')(); +// "foobar" 반환 +// (this is an Immediately Invoked Function Expression + +var simple = a => a > 15 ? 15 : a; +simple(16); // 15 +simple(10); // 10 + +let max = (a, b) => a > b ? a : b; + +// Easy array filtering, mapping, ... + +var arr = [5, 6, 13, 0, 1, 18, 23]; + +var sum = arr.reduce((a, b) => a + b); +// 66 + +var even = arr.filter(v => v % 2 == 0); +// [6, 0, 18] + +var double = arr.map(v => v * 2); +// [10, 12, 26, 0, 2, 36, 46] + +// 더 간결한 promise 체인 +promise.then(a => { + // ... +}).then(b => { + // ... +}); + +// 매개변수가 없는 경우에도 더 읽기 쉬움 +setTimeout( () => { + console.log('I happen sooner'); + setTimeout( () => { + // deeper code + console.log('I happen later'); + }, 1); +}, 1);</code></pre> + +<h2 id="스펙">스펙</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div class="hidden"> +<p><span style="">The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out </span><a href="https://github.com/mdn/browser-compat-data" style="">https://github.com/mdn/browser-compat-data</a><span style=""> and send us a pull request.</span></p> +</div> + +<p>{{Compat("javascript.functions.arrow_functions")}}</p> + +<h2 id="참조">참조</h2> + +<ul> + <li><a href="https://hacks.mozilla.org/2015/06/es6-in-depth-arrow-functions/">Hacks 블로그 "ES6 In Depth: Arrow functions" 포스트</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/aggregateerror/index.html b/files/ko/web/javascript/reference/global_objects/aggregateerror/index.html new file mode 100644 index 0000000000..b83db1139e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/aggregateerror/index.html @@ -0,0 +1,87 @@ +--- +title: AggregateError +slug: Web/JavaScript/Reference/Global_Objects/AggregateError +tags: + - AggregateError + - 실험적 + - 인터페이스 + - 자바스크립트 + - 클래스 +translation_of: Web/JavaScript/Reference/Global_Objects/AggregateError +--- +<div>{{JSRef}}</div> + +<p><code><strong>AggregateError</strong></code> 객체는 다수의 에러가 한 에러로 랩핑되어야 할 때의 오류를 나타냅니다. 한 작업에서 여러개의 오류가 보고될 때 발생하는데, 대표적으로 {{JSxRef("Promise.any()")}}에 전달된 모든 promise들이 거부되었을 때 발생합니다.</p> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{jsxref("Global_Objects/AggregateError/AggregateError", "AggregateError()")}}</dt> + <dd>새로운 <code>AggregateError</code> 객체를 생성합니다.</dd> +</dl> + +<h2 id="Instance_properties">Instance properties</h2> + +<dl> + <dt>{{JSxRef("Error.prototype.message", "AggregateError.prototype.message")}}</dt> + <dd>에러 메시지, 기본값 <code>""</code>.</dd> + <dt>{{JSxRef("Error.prototype.name", "AggregateError.prototype.name")}}</dt> + <dd>에러 이름, 기본값 <code>AggregateError</code>.</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<h3 id="AggregateError_다루기">AggregateError 다루기</h3> + +<pre class="brush: js; notranslate">Promise.any([ + Promise.reject(new Error("some error")), +]).catch(e => { + console.log(e instanceof AggregateError); // true + console.log(e.message); // "All Promises rejected" + console.log(e.name); // "AggregateError" + console.log(e.errors); // [ Error: "some error" ] +}); +</pre> + +<h3 id="AggregateError_발생시키기">AggregateError 발생시키기</h3> + +<pre class="brush: js; notranslate">try { + throw new AggregateError([ + new Error("some error"), + ], 'Hello'); +} catch (e) { + console.log(e instanceof AggregateError); // true + console.log(e.message); // "Hello" + console.log(e.name); // "AggregateError" + console.log(e.errors); // [ Error: "some error" ] +} +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('Promise.any', '#sec-aggregate-error-objects', 'AggregateError')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.AggregateError")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{JSxRef("Error")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/@@iterator/index.html b/files/ko/web/javascript/reference/global_objects/array/@@iterator/index.html new file mode 100644 index 0000000000..89e08aa41e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/@@iterator/index.html @@ -0,0 +1,84 @@ +--- +title: 'Array.prototype[@@iterator]()' +slug: Web/JavaScript/Reference/Global_Objects/Array/@@iterator +tags: + - Array + - ECMAScript 2015 + - Iterator + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/@@iterator +--- +<div>{{JSRef}}</div> + +<p> <code><strong>@@iterator</strong></code> 속성의 초기 값은 {{jsxref("Array.prototype.values()", "values()")}} 속성의 초기 값과 같은 함수 객체입니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code>arr[Symbol.iterator]()</code></pre> + +<h3 id="반환_값">반환 값</h3> + +<p>{{jsxref("Array.prototype.values()", "values()")}} 반복기가 반환하는 초기 값. <code>arr[Symbol.iterator]</code>의 기본값은 {{jsxref("Array.prototype.values()", "values()")}} 입니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="for…of_반복문을_이용한_순회"><code>for…of</code> 반복문을 이용한 순회</h3> + +<pre class="brush: js"><code>var arr = ['w', 'y', 'k', 'o', 'p']; +var eArr = arr[Symbol.iterator](); +// your browser must support for..of loop +// and let-scoped variables in for loops +// const and var could also be used +for (let letter of eArr) { + console.log(letter); +}</code></pre> + +<h3 id="다른_방법">다른 방법</h3> + +<pre class="brush: js"><code>var arr = ['w', 'y', 'k', 'o', 'p']; +var eArr = arr[Symbol.iterator](); +console.log(eArr.next().value); // w +console.log(eArr.next().value); // y +console.log(eArr.next().value); // k +console.log(eArr.next().value); // o +console.log(eArr.next().value); // p</code></pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">비고</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype-@@iterator', 'Array.prototype[@@iterator]()')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype-@@iterator', 'Array.prototype[@@iterator]()')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.Array.@@iterator")}}</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.keys()")}}</li> + <li>{{jsxref("Array.prototype.entries()")}}</li> + <li>{{jsxref("Array.prototype.forEach()")}}</li> + <li>{{jsxref("Array.prototype.every()")}}</li> + <li>{{jsxref("Array.prototype.some()")}}</li> + <li>{{jsxref("Array.prototype.values()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/@@species/index.html b/files/ko/web/javascript/reference/global_objects/array/@@species/index.html new file mode 100644 index 0000000000..7b1bda0ca6 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/@@species/index.html @@ -0,0 +1,75 @@ +--- +title: 'get Array[@@species]' +slug: Web/JavaScript/Reference/Global_Objects/Array/@@species +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/@@species +--- +<div>{{JSRef}}</div> + +<p><strong><code>Array[@@species]</code> </strong>접근자 속성은 <code>Array</code> 생성자를 반환합니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">Array[Symbol.species] +</pre> + +<h3 id="반환_값">반환 값</h3> + +<p>{{jsxref("Array")}} 생성자.</p> + +<h2 id="설명">설명</h2> + +<p><code>species</code> 접근자 속성은 <code>Array</code> 객체의 기본 생성자를 반환합니다. 서브클래스 생성자는 생성자 할당을 변경하기 위해 이 속성을 재정의할 수 있습니다.</p> + +<h2 id="예제">예제</h2> + +<p><code>species</code> 속성은 <code>Array</code> 객체의 <code>Array</code> 생성자를 반환합니다.</p> + +<pre class="brush: js">Array[Symbol.species]; // function Array()</pre> + +<p>파생 콜렉션 개체(예시: 사용자 설정 배열인 <code>MyArray</code>)에서, <code>MyArray</code> 종<sup>species</sup>은 <code>MyArray</code> 생성자입니다. 그러나 이 속성을 재정의하면 파생 클래스 메서드에서 상위 <code>Array</code> 객체를 반환할 수 있습니다.</p> + +<pre class="brush: js">class MyArray extends Array { + // MyArray species를 부모 Array 생성자로 재설정 + static get [Symbol.species]() { return Array; } +}</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">비고</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-get-array-@@species', 'get Array [ @@species ]')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-get-array-@@species', 'get Array [ @@species ]')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Array.@@species")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array")}}</li> + <li>{{jsxref("Symbol.species")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/@@unscopables/index.html b/files/ko/web/javascript/reference/global_objects/array/@@unscopables/index.html new file mode 100644 index 0000000000..1ac7f0b29b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/@@unscopables/index.html @@ -0,0 +1,72 @@ +--- +title: 'Array.prototype[@@unscopables]' +slug: Web/JavaScript/Reference/Global_Objects/Array/@@unscopables +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Property + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Array/@@unscopables +--- +<div>{{JSRef}}</div> + +<p><strong><code>@@unscopable</code></strong> 기호 속성은 ES2015 이전 ECMAScript 표준에 포함되지 않은 속성 이름을 포함합니다. 해당 속성들은 {{jsxref("Statements/with", "with")}} 바인딩에서 제외됩니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>arr</var>[Symbol.unscopables]</pre> + +<h2 id="설명">설명</h2> + +<p>with 바인딩에서 제외되는 배열의 기본 속성은 copyWithin, entries, fill, find, findIndex, includes, keys, values입니다.</p> + +<p>자신의 객체에 대해 <code>unscopables</code>를 설정하는 방법은 {{jsxref("Symbol.unscopables")}}를 참고하세요.</p> + +<p>{{js_property_attributes (0,0,1)}}</p> + +<h2 id="예제">예제</h2> + +<p>아래 코드는 ES5 이하에서 잘 작동합니다. 그러나 ECMAScript 2015 이후 {{jsxref("Array.prototype.keys()")}} 메서드가 도입되었습니다. 이는 <code>with</code> 내부에서 "keys"가 변수가 아니라 메서드임을 의미합니다. 여기서 <code>Array.prototype[@@unscopables]</code>가 개입하여 일부 배열 메서드가 <code>with</code> 범위에 묶이는 일을 방지합니다.</p> + +<pre class="brush: js">var keys = []; + +with (Array.prototype) { + keys.push("something"); +} + +Object.keys(Array.prototype[Symbol.unscopables]); +// ["copyWithin", "entries", "fill", "find", "findIndex", +// "includes", "keys", "values"]</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype-@@unscopables', 'Array.prototype[@@unscopables]')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype-@@unscopables', 'Array.prototype[@@unscopables]')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.Array.@@unscopables")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Symbol.unscopables")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/array/index.html b/files/ko/web/javascript/reference/global_objects/array/array/index.html new file mode 100644 index 0000000000..3f3d60a4ec --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/array/index.html @@ -0,0 +1,86 @@ +--- +title: Array() 생성자 +slug: Web/JavaScript/Reference/Global_Objects/Array/Array +tags: + - Array + - Constructor + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/Array +--- +<div>{{JSRef}}</div> + +<p><strong><code>Array()</code></strong> 생성자는 새로운 {{jsxref("Array")}} 객체를 생성할 때 사용합니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">[<var>element0</var>, <var>element1</var>, ..., <var>elementN</var>] + +new Array(<var>element0</var>, <var>element1</var>[, ...[, <var>elementN</var>]]) +new Array(<var>arrayLength</var>)</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>element<em>N</em></code></dt> + <dd>JavaScript 배열을 초기화할 때 채워넣을 요소. 단, 항목이 하나 뿐이며 그 항목의 자료형이 숫자일 경우 아래의 <code>arrayLength</code> 매개변수로 간주합니다.</dd> + <dt><code>arrayLength</code></dt> + <dd><code>Array</code> 생성자에 제공한 유일한 매개변수가 0에서 2<sup>32</sup>-1 이하의 정수인 경우, <code>length</code> 속성이 해당 값인 새로운 JavaScript 배열을 생성합니다. (<strong>참고:</strong> 이렇게 생성한 배열은 <code>arrayLength</code> 만큼의 빈 슬롯을 가지는 것으로, 실제 {{jsxref("undefined")}}를 채우는 것이 아닙니다.) 값이 범위 밖이거나 정수가 아닌 경우 {{jsxref("RangeError")}}가 발생합니다.</dd> +</dl> + +<h2 id="예제">예제</h2> + +<h3 id="배열_리터럴_표기법">배열 리터럴 표기법</h3> + +<p>배열은 <a href="/ko/docs/Web/JavaScript/Reference/Lexical_grammar#배열_리터럴">리터럴 표기법</a>으로 생성할 수도 있습니다.</p> + +<pre class="brush: js">let fruits = ['사과', '바나나'] + +console.log(fruits.length) // 2 +console.log(fruits[0]) // "사과" +</pre> + +<h3 id="단일_매개변수_배열_생성자">단일 매개변수 배열 생성자</h3> + +<p>배열을 생성자와 하나의 숫자 매개변수로 생성할 수 있습니다. 그 결과는 <code>length</code>가 매개변수고, 길이만큼의 빈 슬롯을 가진 배열입니다.</p> + +<pre class="brush: js">let fruits = new Array(2) + +console.log(fruits.length) // 2 +console.log(fruits[0]) // undefined +</pre> + +<h3 id="복수_매개변수_배열_생성자">복수 매개변수 배열 생성자</h3> + +<p>생성자에 두 개 이상의 매개변수를 제공할 경우, 매개변수를 원소로 하는 새로운 배열을 생성합니다.</p> + +<pre class="brush: js">let fruits = new Array('사과', '바나나') + +console.log(fruits.length) // 2 +console.log(fruits[0]) // "사과" +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array-constructor', 'Array constructor')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Array.Array")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array")}} 클래스</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/concat/index.html b/files/ko/web/javascript/reference/global_objects/array/concat/index.html new file mode 100644 index 0000000000..b35f040632 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/concat/index.html @@ -0,0 +1,138 @@ +--- +title: Array.prototype.concat() +slug: Web/JavaScript/Reference/Global_Objects/Array/concat +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/concat +--- +<div>{{JSRef}}</div> + +<p><code><strong>concat()</strong></code> 메서드는 인자로 주어진 배열이나 값들을 기존 배열에 합쳐서 새 배열을 반환합니다. </p> + +<ul> + <li>기존배열을 변경하지 않습니다. </li> + <li> 추가된 새로운 배열을 반환합니다.</li> +</ul> + +<div>{{EmbedInteractiveExample("pages/js/array-concat.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>array</var>.concat([value1[, value2[, ...[, <var>valueN</var>]]]])</pre> + +<h3 id="매개변수">매개변수</h3> + +<ul> + <li>배열 또는 값 </li> + <li>만약 value1 ~ valueN 인자를 생략하면 기존배열의 얕은 복사본을 반환.</li> +</ul> + +<dl> + <dt><code>valueN</code> {{optional_inline}}</dt> + <dd>자세한 내용은 아래 설명을 참고하세요.</dd> +</dl> + +<h3 id="반환값">반환값</h3> + +<p>새로운 {{jsxref("Array")}} 객체.</p> + +<h2 id="설명">설명</h2> + +<p><code>concat</code>은 메서드를 호출한 배열 뒤에 각 인수를 순서대로 붙여 새로운 배열을 만듭니다. 인수가 배열이면 그 구성요소가 순서대로 붙고, 배열이 아니면 인수 자체가 붙습니다. 중첩 배열 내부로 재귀하지 않습니다.</p> + +<p><code>concat</code>은 <code>this</code>나 인수로 넘겨진 배열의 내용을 바꾸지 않고, 대신 주어진 배열을 합친 뒤 그 얕은 사본을 반환합니다. 새 배열에는 원본 배열의 요소를 다음과 같은 방법으로 복사합니다.</p> + +<ul> + <li>실제 객체가 아닌 객체 참조: <code>concat</code>은 새 배열에 참조를 복사합니다. 원본 배열과 새 배열에서 같은 객체를 가리키게 됩니다. 즉, 참조하는 객체를 수정하면 그 내용이 새 배열과 원본 배열 둘 다에서 나타납니다.</li> + <li>문자열, 숫자, 불리언 등 자료형({{jsxref("String")}}, {{jsxref("Number")}}, {{jsxref("Boolean")}} 객체 아님): <code>concat</code>은 새 배열에 문자열과 수의 값을 복사합니다.</li> +</ul> + +<div class="note"> +<p><strong>참고:</strong> 배열이나 값을 이어붙여도 원본은 변하지 않으며, 새로운 배열이나 원본 배열을 조작해도 서로 영향을 받지 않습니다.</p> +</div> + +<h2 id="예제">예제</h2> + +<h3 id="배열_두_개_이어붙이기">배열 두 개 이어붙이기</h3> + +<p>다음 예제는 두 개의 배열을 이어붙입니다.</p> + +<pre class="brush: js">const alpha = ['a', 'b', 'c']; +const numeric = [1, 2, 3]; + +alpha.concat(numeric); +// 결과: ['a', 'b', 'c', 1, 2, 3] +</pre> + +<h3 id="배열_세_개_이어붙이기">배열 세 개 이어붙이기</h3> + +<p>다음 예제는 세 개의 배열을 이어붙입니다.</p> + +<pre class="brush: js">const num1 = [1, 2, 3]; +const num2 = [4, 5, 6]; +const num3 = [7, 8, 9]; + +num1.concat(num2, num3); +// 결과: [1, 2, 3, 4, 5, 6, 7, 8, 9] +</pre> + +<h3 id="배열에_값_이어붙이기">배열에 값 이어붙이기</h3> + +<p>다음 코드는 배열에 세 개의 값을 이어붙입니다.</p> + +<pre class="brush: js">const alpha = ['a', 'b', 'c']; + +alpha.concat(1, [2, 3]); +// 결과: ['a', 'b', 'c', 1, 2, 3] +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">표준</th> + <th scope="col">상태</th> + <th scope="col">비고</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>최초 정의. JavaScript 1.2에서 구현됨.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.4', 'Array.prototype.concat')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.concat', 'Array.prototype.concat')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.concat', 'Array.prototype.concat')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.Array.concat")}}</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.push", "push")}} / {{jsxref("Array.pop", "pop")}} — 배열의 뒤에 요소 추가/제거</li> + <li>{{jsxref("Array.unshift", "unshift")}} / {{jsxref("Array.shift", "shift")}} — 배열의 앞에 요소 추가/제거</li> + <li>{{jsxref("Array.splice", "splice")}} — 배열의 특정 위치에 요소 추가/제거</li> + <li>{{jsxref("String.prototype.concat()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/copywithin/index.html b/files/ko/web/javascript/reference/global_objects/array/copywithin/index.html new file mode 100644 index 0000000000..7d6c2cdf8b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/copywithin/index.html @@ -0,0 +1,183 @@ +--- +title: Array.prototype.copyWithin() +slug: Web/JavaScript/Reference/Global_Objects/Array/copyWithin +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/copyWithin +--- +<div>{{JSRef}}</div> + +<p><strong><code>copyWithin()</code></strong> 메서드는 배열의 일부를 얕게 복사한 뒤, 동일한 배열의 다른 위치에 덮어쓰고 그 배열을 반환합니다. 이 때, 크기(배열의 길이)를 수정하지 않고 반환합니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/array-copywithin.html")}}</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>arr</var>.copyWithin(<var>target[, start[, end]]</var>) +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>target</code></dt> + <dd>복사한 시퀀스(값)를 넣을 위치를 가리키는 0 기반 인덱스. 음수를 지정하면 인덱스를 배열의 끝에서부터 계산합니다.<br> + <br> + <code>target</code>이 <code>arr.length</code>보다 크거나 같으면 아무것도 복사하지 않습니다. <code>target</code>이 <code>start</code> 이후라면 복사한 시퀀스를 <code>arr.length</code>에 맞춰 자릅니다.</dd> + <dt><code>start</code> {{optional_inline}}</dt> + <dd>복사를 시작할 위치를 가리키는 0 기반 인덱스. 음수를 지정하면 인덱스를 배열의 끝에서부터 계산합니다.<br> + <br> + 기본값은 0으로, <code>start</code>를 지정하지 않으면 배열의 처음부터 복사합니다.</dd> + <dt><code>end</code> {{optional_inline}}</dt> + <dd>복사를 끝낼 위치를 가리키는 0 기반 인덱스. <code>copyWithin</code>은 <code>end</code> 인덱스 이전까지 복사하므로 <code>end</code> 인덱스가 가리키는 요소는 제외합니다. 음수를 지정하면 인덱스를 배열의 끝에서부터 계산합니다.<br> + <br> + 기본값은 <code>arr.length</code>로, <code>end</code>를 지정하지 않으면 배열의 끝까지 복사합니다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>수정한 배열.</p> + +<h2 id="설명">설명</h2> + +<p><code>copyWithin</code>은 C와 C++의 <code>memmove</code>처럼 작동하고, 복사와 대입이 하나의 연산에서 이루어지므로 {{jsxref("Array")}}의 데이터를 이동할 때 사용할 수 있는 고성능 메서드입니다. {{jsxref("TypedArray.prototype.copyWithin()", "TypedArray")}}의 동명 메서드에서 이 특징이 두드러집니다. 붙여넣은 시퀀스의 위치가 복사한 범위와 겹치더라도 최종 결과는 원본 배열에서 복사한 것과 같습니다.</p> + +<p><code>copyWithin</code> 함수는 제네릭 함수로, <code>this</code> 값이 {{jsxref("Array")}} 객체일 필요는 없습니다.</p> + +<p><code>copyWithin</code> 메서드는 변경자 메서드로, <code>this</code>의 길이는 바꾸지 않지만 내용을 바꾸며 필요하다면 새로운 속성을 생성합니다.</p> + +<h2 id="예제">예제</h2> + +<pre class="brush: js">[1, 2, 3, 4, 5].copyWithin(-2); +// [1, 2, 3, 1, 2] + +[1, 2, 3, 4, 5].copyWithin(0, 3); +// [4, 5, 3, 4, 5] + +[1, 2, 3, 4, 5].copyWithin(0, 3, 4); +// [4, 2, 3, 4, 5] + +[1, 2, 3, 4, 5].copyWithin(-2, -3, -1); +// [1, 2, 3, 3, 4] + +[].copyWithin.call({length: 5, 3: 1}, 0, 3); +// {0: 1, 3: 1, length: 5} + +// ES2015 TypedArray는 Array의 하위 클래스 +var i32a = new Int32Array([1, 2, 3, 4, 5]); + +i32a.copyWithin(0, 2); +// Int32Array [3, 4, 5, 4, 5] + +// 아직 ES2015를 사용할 수 없는 환경에서 +[].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4); +// Int32Array [4, 2, 3, 4, 5] +</pre> + +<h2 id="폴리필">폴리필</h2> + +<pre><code>if (!Array.prototype.copyWithin) { + Array.prototype.copyWithin = function(target, start/*, end*/) { + // Steps 1-2. + if (this == null) { + throw new TypeError('this is null or not defined'); + } + + var O = Object(this); + + // Steps 3-5. + var len = O.length >>> 0; + + // Steps 6-8. + var relativeTarget = target >> 0; + + var to = relativeTarget < 0 ? + Math.max(len + relativeTarget, 0) : + Math.min(relativeTarget, len); + + // Steps 9-11. + var relativeStart = start >> 0; + + var from = relativeStart < 0 ? + Math.max(len + relativeStart, 0) : + Math.min(relativeStart, len); + + // Steps 12-14. + var end = arguments[2]; + var relativeEnd = end === undefined ? len : end >> 0; + + var final = relativeEnd < 0 ? + Math.max(len + relativeEnd, 0) : + Math.min(relativeEnd, len); + + // Step 15. + var count = Math.min(final - from, len - to); + + // Steps 16-17. + var direction = 1; + + if (from < to && to < (from + count)) { + direction = -1; + from += count - 1; + to += count - 1; + } + + // Step 18. + while (count > 0) { + if (from in O) { + O[to] = O[from]; + } else { + delete O[to]; + } + + from += direction; + to += direction; + count--; + } + + // Step 19. + return O; + }; +}</code></pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.copywithin', 'Array.prototype.copyWithin')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES7', '#sec-array.prototype.copywithin', 'Array.prototype.copyWithin')}}</td> + <td>{{Spec2('ES7')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.copywithin', 'Array.prototype.copyWithin')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.Array.copyWithin")}}</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/entries/index.html b/files/ko/web/javascript/reference/global_objects/array/entries/index.html new file mode 100644 index 0000000000..316886c261 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/entries/index.html @@ -0,0 +1,89 @@ +--- +title: Array.prototype.entries() +slug: Web/JavaScript/Reference/Global_Objects/Array/entries +tags: + - Array + - ECMAScript 2015 + - Iterator + - JavaScript + - Method + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Array/entries +--- +<div>{{JSRef}}</div> + +<p><code><strong>entries()</strong></code> 메서드는 배열의 각 인덱스에 대한 키/값 쌍을 가지는 새로운 <code><strong>Array Iterator</strong></code><strong> </strong>객체를 반환합니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/array-entries.html")}}</p> + +<div class="hidden"> +<p>The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p> +</div> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox notranslate"><code><var>arr</var>.entries()</code> +</pre> + +<h3 id="반환_값">반환 값</h3> + +<p>{{jsxref("Array")}} 반복자 인스턴스 객체.</p> + +<h2 id="예시">예시</h2> + +<h3 id="인덱스와_요소_이터레이팅">인덱스와 요소 이터레이팅</h3> + +<pre class="notranslate">const a = ['a', 'b', 'c']; + +for (const [index, element] of a.entries()) + console.log(index, element); + +// 0 'a' +// 1 'b' +// 2 'c'</pre> + +<h3 id="for…of_루프_사용"><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for…of</a> 루프 사용</h3> + +<pre class="brush:js notranslate">var a = ['a', 'b', 'c']; +var iterator = a.entries(); + +for (let e of iterator) { + console.log(e); +} +// [0, 'a'] +// [1, 'b'] +// [2, 'c'] +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.entries', 'Array.prototype.entries')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성"><span>브라우저 호환성</span></h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.entries")}}</p> +</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.keys()")}}</li> + <li>{{jsxref("Array.prototype.values()")}}</li> + <li>{{jsxref("Array.prototype.forEach()")}}</li> + <li>{{jsxref("Array.prototype.every()")}}</li> + <li>{{jsxref("Array.prototype.some()")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Iteration_protocols">Iteration protocols</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/every/index.html b/files/ko/web/javascript/reference/global_objects/array/every/index.html new file mode 100644 index 0000000000..827b81e760 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/every/index.html @@ -0,0 +1,191 @@ +--- +title: Array.prototype.every() +slug: Web/JavaScript/Reference/Global_Objects/Array/every +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/every +--- +<div>{{JSRef}}</div> + +<p><code><strong>every()</strong></code> 메서드는 배열 안의 모든 요소가 주어진 판별 함수를 통과하는지 테스트합니다.</p> + +<div class="blockIndicator note"> +<p><strong>참고</strong>: 빈 배열에서 호출하면 무조건 <code>true</code>를 반환합니다.</p> +</div> + +<div>{{EmbedInteractiveExample("pages/js/array-every.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>arr</var>.every(<var>callback</var>[, <var>thisArg</var>])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>각 요소를 시험할 함수. 다음 세 가지 인수를 받습니다. + <dl> + <dt><code>currentValue</code></dt> + <dd>처리할 현재 요소.</dd> + <dt><code>index</code> {{Optional_inline}}</dt> + <dd>처리할 현재 요소의 인덱스.</dd> + <dt><code>array</code> {{Optional_inline}}</dt> + <dd><font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">every</span></font>를 호출한 배열.</dd> + </dl> + </dd> + <dt><code>thisArg</code> {{Optional_inline}}</dt> + <dd><code>callback</code>을 실행할 때 <code>this</code>로 사용하는 값.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p><code>callback</code>이 모든 배열 요소에 대해 참({{Glossary("truthy")}})인 값을 반환하는 경우 <code><strong>true</strong></code>, 그 외엔 <code><strong>false</strong></code>.</p> + +<h2 id="설명">설명</h2> + +<p><code>every</code>는 <code>callback</code>이 {{glossary("falsy", "거짓")}}을 반환하는 요소를 찾을 때까지 배열에 있는 각 요소에 대해 한 번씩 <code>callback</code> 함수를 실행합니다. 해당하는 요소를 발견한 경우 <code>every</code>는 즉시 <code>false</code>를 반환합니다. 그렇지 않으면, 즉 모든 값에서 참을 반환하면 <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">true</span></font>를 반환합니다. 할당한 값이 있는 배열의 인덱스에서만 <code>callback</code>을 호출합니다. 삭제했거나 값을 할당한 적이 없는 인덱스에서는 호출하지 않습니다.</p> + +<p><code>callback</code>은 요소의 값, 해당 요소의 인덱스 및 순회하고 있는 배열 세 가지 인수와 함께 호출됩니다.</p> + +<p><code>thisArg</code> 매개변수를 <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">every</span></font>에 제공한 경우 <code>callback</code>의 <code>this</code>로 사용됩니다. 그 외엔 {{jsxref("undefined")}}값을 사용합니다. 최종적으로 <code>callback</code>이 볼 수 있는 <code>this</code>의 값은 <a href="/ko/docs/Web/JavaScript/Reference/Operators/this">함수가 볼 수 있는 <code>this</code>를 결정하는 평소 규칙</a>을 따릅니다.</p> + +<p><code>every</code>는 호출한 배열을 변형하지 않습니다.</p> + +<p><code>every</code>가 처리하는 요소의 범위는 <code>callback</code>의 첫 호출 전에 설정됩니다. <code>every</code> 호출 이후로 배열에 추가하는 요소는 <code>callback</code>이 방문하지 않습니다. 배열에 원래 있었지만 아직 방문하지 않은 요소가 <code>callback</code>에 의해 변경된 경우, 그 인덱스를 방문하는 시점의 값을 사용합니다. 삭제한 요소는 방문하지 않습니다.</p> + +<p><code>every</code>는 (이산)수학에서 전칭(∀) 정량자<sup>quantifier</sup>(한정자)처럼 행동합니다. 특히, 빈 배열에 대해서는 <code>true</code>를 반환합니다. (이는 <a href="http://en.wikipedia.org/wiki/Empty_set#Common_problems">공집합</a>의 모든 요소가 어떠한 주어진 조건도 만족하는 <a href="http://en.wikipedia.org/wiki/Vacuous_truth#Vacuous_truths_in_mathematics" title="vacuously true">공허한 참</a>입니다.)</p> + +<h2 id="예제">예제</h2> + +<h3 id="모든_배열_요소의_크기_테스트">모든 배열 요소의 크기 테스트</h3> + +<p>다음 예는 배열의 모든 요소가 10보다 더 큰지 테스트합니다.</p> + +<pre class="brush: js">function isBigEnough(element, index, array) { + return element >= 10; +} +[12, 5, 8, 130, 44].every(isBigEnough); // false +[12, 54, 18, 130, 44].every(isBigEnough); // true +</pre> + +<h3 id="화살표_함수_사용">화살표 함수 사용</h3> + +<p><a href="/ko/docs/Web/JavaScript/Reference/Functions/애로우_펑션">화살표 함수</a>는 같은 테스트에 대해 더 짧은 구문을 제공합니다.</p> + +<pre class="brush: js">[12, 5, 8, 130, 44].every(elem => elem >= 10); // false +[12, 54, 18, 130, 44].every(elem => elem >= 10); // true</pre> + +<h2 id="폴리필">폴리필</h2> + +<p><code>every</code>는 ECMA-262 표준 제5판에 추가됐으므로 어떤 표준 구현체에서는 사용하지 못할 수도 있습니다. 다른 모든 코드 이전에 아래 코드를 포함하면 <code>every</code>를 지원하지 않는 환경에서도 사용할 수 있습니다. 아래 알고리즘은 {{jsxref("Object")}}와 {{jsxref("TypeError")}}가 변형되지 않고, <code>callbackfn.call</code>의 계산 값이 원래의 {{jsxref("Function.prototype.call()")}}과 같은 경우 ECMA-262 제5판이 명시한 것과 동일합니다.</p> + +<pre class="brush: js">if (!Array.prototype.every) { + Array.prototype.every = function(callbackfn, thisArg) { + 'use strict'; + var T, k; + + if (this == null) { + throw new TypeError('this is null or not defined'); + } + + // 1. Let O be the result of calling ToObject passing the this + // value as the argument. + var O = Object(this); + + // 2. Let lenValue be the result of calling the Get internal method + // of O with the argument "length". + // 3. Let len be ToUint32(lenValue). + var len = O.length >>> 0; + + // 4. If IsCallable(callbackfn) is false, throw a TypeError exception. + if (typeof callbackfn !== 'function') { + throw new TypeError(); + } + + // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. + if (arguments.length > 1) { + T = thisArg; + } + + // 6. Let k be 0. + k = 0; + + // 7. Repeat, while k < len + while (k < len) { + + var kValue; + + // a. Let Pk be ToString(k). + // This is implicit for LHS operands of the in operator + // b. Let kPresent be the result of calling the HasProperty internal + // method of O with argument Pk. + // This step can be combined with c + // c. If kPresent is true, then + if (k in O) { + + // i. Let kValue be the result of calling the Get internal method + // of O with argument Pk. + kValue = O[k]; + + // ii. Let testResult be the result of calling the Call internal method + // of callbackfn with T as the this value and argument list + // containing kValue, k, and O. + var testResult = callbackfn.call(T, kValue, k, O); + + // iii. If ToBoolean(testResult) is false, return false. + if (!testResult) { + return false; + } + } + k++; + } + return true; + }; +}</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.16', 'Array.prototype.every')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>초기 정의. JavaScript 1.6에서 구현됨.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.every', 'Array.prototype.every')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.every', 'Array.prototype.every')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.Array.every")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.forEach()")}}</li> + <li>{{jsxref("Array.prototype.some()")}}</li> + <li>{{jsxref("Array.prototype.find()")}}</li> + <li>{{jsxref("TypedArray.prototype.every()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/fill/index.html b/files/ko/web/javascript/reference/global_objects/array/fill/index.html new file mode 100644 index 0000000000..5a18af7d24 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/fill/index.html @@ -0,0 +1,146 @@ +--- +title: Array.prototype.fill() +slug: Web/JavaScript/Reference/Global_Objects/Array/fill +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/fill +--- +<div>{{JSRef}}</div> + +<p><code><strong>fill()</strong></code> 메서드는 배열의 시작 인덱스부터 끝 인덱스의 이전까지 정적인 값 하나로 채웁니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/array-fill.html")}}</p> + +<h2 id="Syntax" name="Syntax">구문</h2> + +<pre class="syntaxbox"><code><var>arr</var>.fill(<var>value</var>[, <var>start<var>[, <var>end</var>]])</var></var></code></pre> + +<h3 id="Parameters" name="Parameters">매개변수</h3> + +<dl> + <dt><code>value</code></dt> + <dd>배열을 채울 값.</dd> + <dt><code>start</code> {{optional_inline}}</dt> + <dd>시작 인덱스, 기본 값은 0.</dd> + <dt><code>end</code> {{optional_inline}}</dt> + <dd>끝 인덱스, 기본 값은 <code>this.length</code>.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>변형한 배열.</p> + +<h2 id="Description" name="Description">설명 </h2> + +<p><code>fill</code> 메서드는 <code>value</code>, <code>start</code>, <code>end</code>의 3개 인자를 가집니다. <code>start</code>와 <code>end</code> 인자는 선택 사항으로써 기본값으로 각각 <code>0</code>과, <code>this</code> 객체의 <code>length</code>를 가집니다.</p> + +<p><code>length</code>가 배열의 길이일 때, <code>start</code>가 음수이면 시작 인덱스는 <code>length+start</code>입니다. <code>end</code>가 음수이면 끝 인덱스는 <code>length+end</code>입니다.</p> + +<p><code>fill</code>은 일반 함수이며, <code>this</code> 값이 배열 객체일 필요는 없습니다.</p> + +<p><code>fill</code> 메서드는 변경자 메서드로, 복사본이 아니라 <code>this</code> 객체를 변형해 반환합니다.</p> + +<p><code>value</code>에 객체를 받을 경우 그 참조만 복사해서 배열을 채웁니다.</p> + +<h2 id="Examples" name="Examples">예제</h2> + +<pre class="brush: js">[1, 2, 3].fill(4); // [4, 4, 4] +[1, 2, 3].fill(4, 1); // [1, 4, 4] +[1, 2, 3].fill(4, 1, 2); // [1, 4, 3] +[1, 2, 3].fill(4, 1, 1); // [1, 2, 3] +[1, 2, 3].fill(4, 3, 3); // [1, 2, 3] +[1, 2, 3].fill(4, -3, -2); // [4, 2, 3] +[1, 2, 3].fill(4, NaN, NaN); // [1, 2, 3] +[1, 2, 3].fill(4, 3, 5); // [1, 2, 3] +Array(3).fill(4); // [4, 4, 4] +[].fill.call({ length: 3 }, 4); // {0: 4, 1: 4, 2: 4, length: 3} + +// Objects by reference. +var arr = Array(3).fill({}); // [{}, {}, {}] +arr[0].hi = "hi"; // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }] +</pre> + +<h2 id="Polyfill" name="Polyfill">폴리필</h2> + +<pre><code>if (!Array.prototype.fill) { + Object.defineProperty(Array.prototype, 'fill', { + value: function(value) { + + // Steps 1-2. + if (this == null) { + throw new TypeError('this is null or not defined'); + } + + var O = Object(this); + + // Steps 3-5. + var len = O.length >>> 0; + + // Steps 6-7. + var start = arguments[1]; + var relativeStart = start >> 0; + + // Step 8. + var k = relativeStart < 0 ? + Math.max(len + relativeStart, 0) : + Math.min(relativeStart, len); + + // Steps 9-10. + var end = arguments[2]; + var relativeEnd = end === undefined ? + len : end >> 0; + + // Step 11. + var final = relativeEnd < 0 ? + Math.max(len + relativeEnd, 0) : + Math.min(relativeEnd, len); + + // Step 12. + while (k < final) { + O[k] = value; + k++; + } + + // Step 13. + return O; + } + }); +}</code></pre> + +<h2 id="Specifications" name="Specifications">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-array.prototype.fill', 'Array.prototype.fill')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.fill', 'Array.prototype.fill')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.Array.fill")}}</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array")}}</li> + <li>{{jsxref("TypedArray.prototype.fill()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/filter/index.html b/files/ko/web/javascript/reference/global_objects/array/filter/index.html new file mode 100644 index 0000000000..9d1b623fd0 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/filter/index.html @@ -0,0 +1,231 @@ +--- +title: Array.prototype.filter() +slug: Web/JavaScript/Reference/Global_Objects/Array/filter +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/filter +--- +<div>{{JSRef}}</div> + +<p><code><strong>filter()</strong></code> 메서드는 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-filter.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>arr.filter(callback(element[, index[, array]])[, thisArg])</var></code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>각 요소를 시험할 함수. <code>true</code>를 반환하면 요소를 유지하고, <code>false</code>를 반환하면 버립니다. 다음 세 가지 매개변수를 받습니다.</dd> + <dd> + <dl> + <dt><code>element</code></dt> + <dd>처리할 현재 요소.</dd> + <dt><code>index</code> {{optional_inline}}</dt> + <dd>처리할 현재 요소의 인덱스.</dd> + <dt><code>array</code> {{optional_inline}}</dt> + <dd><code>filter</code>를 호출한 배열.</dd> + </dl> + </dd> + <dt><code>thisArg</code> {{optional_inline}}</dt> + <dd><code>callback</code>을 실행할 때 <code>this</code>로 사용하는 값.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>테스트를 통과한 요소로 이루어진 새로운 배열. 어떤 요소도 테스트를 통과하지 못했으면 빈 배열을 반환합니다.</p> + +<h2 id="설명">설명</h2> + +<p><code>filter()</code>는 배열 내 각 요소에 대해 한 번 제공된 <code>callback</code> 함수를 호출해, <code>callback</code>이 <a href="/ko/docs/Glossary/Truthy"><code>true</code>로 강제하는 값</a>을 반환하는 모든 값이 있는 새로운 배열을 생성합니다. <code>callback</code>은 할당된 값이 있는 배열의 인덱스에 대해서만 호출됩니다; 삭제됐거나 값이 할당된 적이 없는 인덱스에 대해서는 호출되지 않습니다. <code>callback</code> 테스트를 통과하지 못한 배열 요소는 그냥 건너뛰며 새로운 배열에 포함되지 않습니다.</p> + +<p><code>callback</code>은 다음 세 인수와 함께 호출됩니다:</p> + +<ol> + <li>요소값</li> + <li>요소 인덱스</li> + <li>순회(traverse)되는 배열 객체</li> +</ol> + +<p><code>thisArg</code> 매개변수가 <code>filter</code>에 제공된 경우, 호출될 때 그 값은 <code>callback</code>의 <code>this</code> 값으로 전달됩니다. 그 이외에, <code>undefined</code>값도 <code>callback</code>의 <code>this</code> 값으로 쓰기 위해 전달됩니다. 결국 <code>callback</code>에 의해 관찰될 수 있는 <code>this</code> 값은 <a href="/ko/docs/Web/JavaScript/Reference/Operators/this"><code>this</code>를 결정하는 함수의 평소 규칙</a>에 따라 결정됩니다.</p> + +<p><code>filter()</code>는 호출되는 배열을 변화시키지(mutate) 않습니다.</p> + +<p><code>filter()</code>에 의해 처리되는 요소의 범위는 <code>callback</code>의 첫 호출 전에 설정됩니다. <code>filter()</code> 호출 시작 이후로 배열에 추가된 요소는 <code>callback</code>에 의해 방문되지 않습니다. 배열의 기존 요소가 변경 또는 삭제된 경우, <code>callback</code>에 전달된 그 값은 <code>filter()</code>가 그 요소를 방문한 시점에 값이 됩니다; 삭제된 요소는 반영되지 않습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="모든_작은_값_걸러내기">모든 작은 값 걸러내기</h3> + +<p>다음 예는 값이 10 이하인 모든 요소가 제거된 걸러진 배열을 만들기 위해 <code>filter()</code>를 사용합니다.</p> + +<pre class="brush: js">function isBigEnough(value) { + return value >= 10; +} + +var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); +// filtered 는 [12, 130, 44] +</pre> + +<h3 id="JSON에서_무효한_항목_거르기">JSON에서 무효한 항목 거르기</h3> + +<p>다음 예는 0이 아닌, 숫자 <code>id</code>인 모든 요소의 걸러진 json을 만들기 위해 <code>filter()</code>를 사용합니다.</p> + +<pre class="brush: js"><code>var arr = [ + { id: 15 }, + { id: -1 }, + { id: 0 }, + { id: 3 }, + { id: 12.2 }, + { }, + { id: null }, + { id: NaN }, + { id: 'undefined' } +]; + +var invalidEntries = 0; + +function isNumber(obj) { + return obj !== undefined && typeof(obj) === 'number' && !isNaN(obj); +} + +function filterByID(item) { + if (isNumber(item.id) && item.id !== 0) { + return true; + } + invalidEntries++; + return false; +} + +var arrByID = arr.filter(filterByID); + +console.log('Filtered Array\n', arrByID); +// Filtered Array +// [{ id: 15 }, { id: -1 }, { id: 3 }, { id: 12.2 }] + +console.log('Number of Invalid Entries = ', invalidEntries); +// Number of Invalid Entries = 5</code> +</pre> + +<h3 id="배열_내용_검색">배열 내용 검색</h3> + +<p>다음 예는 배열 내용을 조건에 따라 검색하기 위해 <code>filter()</code> 를 사용합니다.</p> + +<pre class="brush: js"><code>var fruits = ['apple', 'banana', 'grapes', 'mango', 'orange']; + +/** + * 검색 조건에 따른 배열 필터링(쿼리) + */ +function filterItems(query) { + return fruits.filter(function(el) { + return el.toLowerCase().indexOf(query.toLowerCase()) > -1; + }) +} + +console.log(filterItems('ap')); // ['apple', 'grapes'] +console.log(filterItems('an')); // ['banana', 'mango', 'orange']</code></pre> + +<h3 id="ES2015로_구현">ES2015로 구현</h3> + +<pre class="brush: js"><code>const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange']; + +/** + * 검색 조건에 따른 배열 필터링(쿼리) + */ +const filterItems = (query) => { + return fruits.filter((el) => + el.toLowerCase().indexOf(query.toLowerCase()) > -1 + ); +} + +console.log(filterItems('ap')); // ['apple', 'grapes'] +console.log(filterItems('an')); // ['banana', 'mango', 'orange']</code></pre> + +<h2 id="폴리필">폴리필</h2> + +<p><font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">filter</span></font>는 ECMA-262 표준 제5판에 추가됐습니다. 따라서 어떤 표준 구현체에서는 사용할 수 없을 수도 있습니다. 다른 모든 코드 이전에 아래 코드를 포함하면 지원하지 않는 환경에서도 <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">filter</span></font>를 사용할 수 있습니다. 아래 알고리즘은 <code>fn.call</code>의 계산 값이 원래의 <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Function/call" title="call() 메소드는 주어진 this 값 및 각각 전달된 인수와 함께 함수를 호출합니다."><code>Function.prototype.call()</code></a>과 같고, {{jsxref("Array.prototype.push()")}}가 변형되지 않은 경우 ECMA-262 제5판이 명시한 것과 동일합니다.</p> + +<pre class="brush: js">if (!Array.prototype.filter){ + Array.prototype.filter = function(func, thisArg) { + 'use strict'; + if ( ! ((typeof func === 'Function' || typeof func === 'function') && this) ) + throw new TypeError(); + + var len = this.length >>> 0, + res = new Array(len), // preallocate array + t = this, c = 0, i = -1; + if (thisArg === undefined){ + while (++i !== len){ + // checks to see if the key was set + if (i in this){ + if (func(t[i], i, t)){ + res[c++] = t[i]; + } + } + } + } + else{ + while (++i !== len){ + // checks to see if the key was set + if (i in this){ + if (func.call(thisArg, t[i], i, t)){ + res[c++] = t[i]; + } + } + } + } + + res.length = c; // shrink down array to proper size + return res; + }; +}</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.20', 'Array.prototype.filter')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>초기 정의. JavaScript 1.6에서 구현됨.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.filter', 'Array.prototype.filter')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.filter', 'Array.prototype.filter')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.Array.filter")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.forEach()")}}</li> + <li>{{jsxref("Array.prototype.every()")}}</li> + <li>{{jsxref("Array.prototype.some()")}}</li> + <li>{{jsxref("Array.prototype.reduce()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/find/index.html b/files/ko/web/javascript/reference/global_objects/array/find/index.html new file mode 100644 index 0000000000..92a0208a6b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/find/index.html @@ -0,0 +1,226 @@ +--- +title: Array.prototype.find() +slug: Web/JavaScript/Reference/Global_Objects/Array/find +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/find +--- +<div>{{JSRef}}</div> + +<p><code><strong>find()</strong></code><strong> </strong>메서드는 주어진 판별 함수를 만족하는 <strong>첫 번째 요소</strong>의 <strong>값</strong>을 반환합니다. 그런 요소가 없다면 {{jsxref("undefined")}}를 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-find.html")}}</div> + + + +<p>찾은 요소의 값 대신 <strong>인덱스</strong>를 반환하는 {{jsxref("Array.findIndex", "findIndex()")}} 메서드도 살펴보세요.</p> + +<p>배열 요소의 위치를 찾고자 하는 경우에는 {{jsxref("Array.prototype.indexOf()")}}를 사용하세요.</p> + +<p>배열 요소가 해당 배열에 존재하는지 확인하고자 하는 경우에는 {{jsxref("Array.prototype.indexOf()")}} 또는 {{jsxref("Array.prototype.includes()")}}를 사용세요.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>arr</var>.find(<var>callback</var>[, <var>thisArg</var>])</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>배열의 각 값에 대해 실행할 함수. 아래의 세 인자를 받습니다. + <dl> + <dt><code>element</code></dt> + <dd>콜백함수에서 처리할 현재 요소.</dd> + <dt><code>index</code>{{optional_inline}}</dt> + <dd>콜백함수에서 처리할 현재 요소의 인덱스.</dd> + <dt><code>array</code>{{optional_inline}}</dt> + <dd><code>find</code> 함수를 호출한 배열.</dd> + </dl> + </dd> + <dt><code>thisArg</code></dt> + <dd>선택 항목. 콜백이 호출될 때 <code>this</code>로 사용할 객체.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 판별 함수를 만족하는 <strong>첫 번째 요소</strong>의 <strong>값</strong>. 그 외에는 {{jsxref("undefined")}}.</p> + +<h2 id="설명">설명</h2> + +<p><code>find</code> 메서드는 <code>callback</code> 함수가 참을 반환 할 때까지 해당 배열의 각 요소에 대해서 <code>callback</code> 함수를 실행합니다. 만약 어느 요소를 찾았다면 <code>find</code> 메서드는 해당 요소의 값을 즉시 반환하고, 그렇지 않았다면 {{jsxref("undefined")}}를 반환합니다. <code>callback</code>은 <code>0</code> 부터 <code>length - 1</code> 까지 배열의 모든 인덱스에 대해 호출되며, 값이 지정되지 않은 요소도 포함하여 모든 인덱스에 대해 호출됩니다. 따라서, 희소 배열 (sparse arrays)의 경우에는 값이 지정된 요소만 탐색하는 다른 메소드에 비해 더 비효율적입니다.</p> + +<p><code>callback</code>은 다음의 세가지 인자를 가지고 호출됩니다: 요소의 값, 요소의 인덱스, 순회의 대상이 되는 배열. </p> + +<p><code>thisArg</code> 파라미터가 주어진 경우에는 제공되었다면 <code>thisArg</code>가 <code>callback</code>안에서 <code>this</code>로 사용되고, 그렇지 않은 경우 {{jsxref("undefined")}} 가 <code>this</code>로 사용됩니다. </p> + +<p><code>find</code>는 호출의 대상이 된 배열을 변경(mutate)하지 않습니다.</p> + +<p><code>find</code>가 처리할 배열 요소의 범위는 첫 <code>callback</code>이 호출되기 전에 먼저 결정됩니다. <code>find</code>메서드가 실행 된 이후에 배열에 추가된 요소들에 대해서는 <code>callback</code>이 호출되지 않습니다. 아직 <code>callback</code>이 호출되지 않았던 배열 요소가 <code>callback</code>에 의해서 변경된 경우, <code>find</code>가 해당 요소의 인덱스를 방문할 때의 값으로 <code>callback</code>함수에 전달될 것입니다. 즉, 삭제된 요소에도 <code>callback</code>이 호출됩니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="속성_중_하나를_사용하여_배열에서_객체_찾기">속성 중 하나를 사용하여 배열에서 객체 찾기</h3> + +<pre class="brush: js">var inventory = [ + {name: 'apples', quantity: 2}, + {name: 'bananas', quantity: 0}, + {name: 'cherries', quantity: 5} +]; + +function findCherries(fruit) { + return fruit.name === 'cherries'; +} + +console.log(inventory.find(findCherries)); // { name: 'cherries', quantity: 5 } +</pre> + +<h4 id="ES2015_화살표_함수_사용하기">ES2015 화살표 함수 사용하기</h4> + +<p> </p> + +<pre class="brush: js">const inventory = [ + {name: 'apples', quantity: 2}, + {name: 'bananas', quantity: 0}, + {name: 'cherries', quantity: 5} +]; + +const result = inventory.find(fruit => fruit.name === 'cherries'); + +console.log(result) // { name: 'cherries', quantity: 5 }</pre> + +<p> </p> + +<h3 id="배열에서_소수_찾기">배열에서 소수 찾기</h3> + +<p>다음 예제에서는 배열의 요소 중 소수인 요소를 찾습니다(소수가 없는 경우에는 {{jsxref("undefined")}}를 반환).</p> + +<pre class="brush: js">function isPrime(element, index, array) { + var start = 2; + while (start <= Math.sqrt(element)) { + if (element % start++ < 1) { + return false; + } + } + return element > 1; +} + +console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found +console.log([4, 5, 8, 12].find(isPrime)); // 5 +</pre> + +<h3 id="탐색_중_삭제된_배열_요소">탐색 중 삭제된 배열 요소</h3> + +<p>다음 예제에서는 삭제되어 존재하지 않는 배열의 요소에도 <code>callback</code>이 호출되어 해당 시점의 값이 <code>callback</code>에 전달되는 것을 보여줍니다.</p> + +<pre class="brush: js">// Declare array with no element at index 2, 3 and 4 +var a = [0,1,,,,5,6]; + +// Shows all indexes, not just those that have been assigned values +a.find(function(value, index) { + console.log('Visited index ' + index + ' with value ' + value); +}); +// Shows all indexes, including deleted + a.find(function(value, index) { + // Delete element 5 on first iteration + if (index == 0) { + console.log('Deleting a[5] with value ' + a[5]); + delete a[5]; + } + // Element 5 is still visited even though deleted + console.log('Visited index ' + index + ' with value ' + value); +}); +</pre> + +<h2 id="폴리필">폴리필</h2> + +<p><code>find</code>는 ECMAScript 2015 명세에 추가됐으므로 어떤 표준 구현체에서는 사용지 못할 수도 있습니다. 다른 모든 코드 이전에 아래 코드를 포함하면 <code>find</code>를 지원하지 않는 환경에서도 사용할 수 있습니다.</p> + +<pre class="brush: js">// https://tc39.github.io/ecma262/#sec-array.prototype.find +if (!Array.prototype.find) { + Object.defineProperty(Array.prototype, 'find', { + value: function(predicate) { + // 1. Let O be ? ToObject(this value). + if (this == null) { + throw new TypeError('"this" is null or not defined'); + } + + var o = Object(this); + + // 2. Let len be ? ToLength(? Get(O, "length")). + var len = o.length >>> 0; + + // 3. If IsCallable(predicate) is false, throw a TypeError exception. + if (typeof predicate !== 'function') { + throw new TypeError('predicate must be a function'); + } + + // 4. If thisArg was supplied, let T be thisArg; else let T be undefined. + var thisArg = arguments[1]; + + // 5. Let k be 0. + var k = 0; + + // 6. Repeat, while k < len + while (k < len) { + // a. Let Pk be ! ToString(k). + // b. Let kValue be ? Get(O, Pk). + // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)). + // d. If testResult is true, return kValue. + var kValue = o[k]; + if (predicate.call(thisArg, kValue, k, o)) { + return kValue; + } + // e. Increase k by 1. + k++; + } + + // 7. Return undefined. + return undefined; + }, + configurable: true, + writable: true + }); +}</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.find', 'Array.prototype.find')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.find', 'Array.prototype.find')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.Array.find")}}</div> + +<div id="compat-mobile"> </div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.findIndex()")}} – 찾기 이후 인덱스 반환</li> + <li>{{jsxref("Array.prototype.includes()")}} – 배열에 어떤 값이 존재하는지 검사</li> + <li>{{jsxref("Array.prototype.filter()")}} – 매칭되는 모든 요소 찾기</li> + <li>{{jsxref("Array.prototype.every()")}} – 모든 요소에 대해서 검사</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/findindex/index.html b/files/ko/web/javascript/reference/global_objects/array/findindex/index.html new file mode 100644 index 0000000000..9406439e6a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/findindex/index.html @@ -0,0 +1,146 @@ +--- +title: Array.prototype.findIndex() +slug: Web/JavaScript/Reference/Global_Objects/Array/findIndex +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/findIndex +--- +<div>{{JSRef}}</div> + +<p><strong><code>findIndex()</code></strong> 메서드는 <strong>주어진 판별 함수를 만족하는</strong> 배열의 첫 번째 요소에 대한 <strong>인덱스</strong>를 반환합니다. 만족하는 요소가 없으면 -1을 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-findindex.html")}}</div> + + + +<p>인덱스 대신 <strong>값</strong>을 반환하는 {{jsxref("Array.prototype.find", "find()")}} 메서드도 참고하세요.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>arr</var>.findIndex(<var>callback(element</var>[, index[, array]])[, <var>thisArg</var>])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>3개의 인수를 취하여 배열의 각 값에 대해 실행할 함수입니다.</dd> + <dd> + <dl> + <dt><code>element</code></dt> + <dd>배열에서 처리중인 현재 요소입니다.</dd> + <dt><code>index</code></dt> + <dd>배열에서 처리중인 현재 요소의 인덱스입니다.</dd> + <dt><code>array</code></dt> + <dd>findIndex 함수가 호출된 배열입니다.</dd> + </dl> + </dd> + <dt><code>thisArg</code></dt> + <dd>선택 사항. 콜백을 실행할 때 this로 사용할 객체입니다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>요소가 테스트를 통과하면 배열의 인덱스. 그렇지 않으면 -1입니다.</p> + +<h2 id="설명">설명</h2> + +<p>findIndex 메서드는 콜백 함수가 진리 값 (true를 반환하는 값)을 반환 할 때까지 배열의 모든 배열 인덱스 0..length-1 (포함)에 대해 한 번씩 콜백 함수를 실행합니다. 이러한 요소가 발견되면 findIndex는 해당 반복에 대한 색인을 즉시 반환합니다. 콜백이 진리 값을 반환하지 않거나 배열의 길이가 0 인 경우 findIndex는 -1을 반환합니다. Array # some과 같은 다른 배열 메소드와는 달리, 배열에 존재하지 않는 엔트리의 인덱스에 대해서조차 콜백이 호출됩니다.</p> + +<p>콜백은 요소의 값, 요소의 인덱스 및 가로 지르는 <code>Array</code> 객체의 세 가지 인수로 호출됩니다.</p> + +<p>thisArg 매개 변수가 findIndex에 제공되면 콜백 호출마다 thisArg 매개 변수가 사용됩니다. 제공되지 않으면 {{jsxref ( "undefined")}}가 사용됩니다.</p> + +<p><code>findIndex</code>는 호출 된 배열을 변경하지 않습니다.</p> + +<p>findIndex에 의해 처리되는 요소의 범위는 콜백의 첫 번째 호출 전에 설정됩니다. findIndex 호출이 시작된 후 배열에 추가되는 요소는 콜백에 의해 방문되지 않습니다. 배열의 기존의 방문하지 않은 요소가 콜백에 의해 변경되면 방문 콜백에 전달 된 값은 findIndex가 해당 요소의 인덱스를 방문 할 때의 값이됩니다. 삭제된 요소도 방문합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="배열에서_소수의_색인_찾기">배열에서 소수의 색인 찾기</h3> + +<p>다음 예제에서는 배열에서 소수 (소수가없는 경우 -1을 반환) 인 요소의 인덱스를 찾습니다.</p> + +<pre class="brush: js">function isPrime(element, index, array) { + var start = 2; + while (start <= Math.sqrt(element)) { + if (element % start++ < 1) { + return false; + } + } + return element > 1; +} + +console.log([4, 6, 8, 12].findIndex(isPrime)); // -1, not found +console.log([4, 6, 7, 12].findIndex(isPrime)); // 2 +</pre> + +<h2 id="폴리필">폴리필</h2> + +<pre class="brush: js">if (!Array.prototype.findIndex) { + Object.defineProperty(Array.prototype, 'findIndex', { + value: function(predicate) { + 'use strict'; + if (this == null) { + throw new TypeError('Array.prototype.findIndex called on null or undefined'); + } + if (typeof predicate !== 'function') { + throw new TypeError('predicate must be a function'); + } + var list = Object(this); + var length = list.length >>> 0; + var thisArg = arguments[1]; + var value; + + for (var i = 0; i < length; i++) { + value = list[i]; + if (predicate.call(thisArg, value, i, list)) { + return i; + } + } + return -1; + }, + enumerable: false, + configurable: false, + writable: false + }); +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.findIndex', 'Array.prototype.findIndex')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.findIndex', 'Array.prototype.findIndex')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.Array.findIndex")}}</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.find()")}}</li> + <li>{{jsxref("Array.prototype.indexOf()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/flat/index.html b/files/ko/web/javascript/reference/global_objects/array/flat/index.html new file mode 100644 index 0000000000..4d4af6dc36 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/flat/index.html @@ -0,0 +1,160 @@ +--- +title: Array.prototype.flat() +slug: Web/JavaScript/Reference/Global_Objects/Array/flat +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/flat +--- +<div>{{JSRef}}</div> + +<p><code><strong>flat()</strong></code> 메서드는 모든 하위 배열 요소를 지정한 깊이까지 재귀적으로 이어붙인 새로운 배열을 생성합니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">const <em>newArr</em> = <em>arr</em>.flat([<em>depth</em>])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>depth</code> {{optional_inline}}</dt> + <dd>중첩 배열 구조를 평탄화할 때 사용할 깊이 값. 기본값은 1입니다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>하위 배열을 이어붙인 새로운 배열.</p> + +<h2 id="예제">예제</h2> + +<h3 id="중첩_배열_평탄화">중첩 배열 평탄화</h3> + +<pre class="brush: js">const arr1 = [1, 2, [3, 4]]; +arr1.flat(); +// [1, 2, 3, 4] + +const arr2 = [1, 2, [3, 4, [5, 6]]]; +arr2.flat(); +// [1, 2, 3, 4, [5, 6]] + +const arr3 = [1, 2, [3, 4, [5, 6]]]; +arr3.flat(2); +// [1, 2, 3, 4, 5, 6] + +const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]]; +arr4.flat(Infinity); +// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</pre> + +<h3 id="배열_구멍_제거">배열 구멍 제거</h3> + +<p><code>flat</code> 메서드는 배열의 구멍도 제거합니다.</p> + +<pre class="brush: js">const arr5 = [1, 2, , 4, 5]; +arr5.flat(); +// [1, 2, 4, 5]</pre> + +<h2 id="대안">대안</h2> + +<h3 id="reduce와_concat"><code>reduce</code>와 <code>concat</code></h3> + +<pre class="brush: js">const arr = [1, 2, [3, 4]]; + +// To flat single level array +arr.flat(); +// is equivalent to +arr.reduce((acc, val) => acc.concat(val), []); +// [1, 2, 3, 4] + +// or with decomposition syntax +const flattened = arr => [].concat(...arr);</pre> + +<h3 id="reduce_concat_isArray_재귀"><code>reduce</code> + <code>concat</code> + <code>isArray</code> + 재귀</h3> + +<pre class="brush: js">const arr = [1, 2, [3, 4, [5, 6]]]; + +// to enable deep level flatten use recursion with reduce and concat +function flatDeep(arr, d = 1) { + return d > 0 ? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatDeep(val, d - 1) : val), []) + : arr.slice(); +}; + +flatDeep(arr, Infinity); +// [1, 2, 3, 4, 5, 6]</pre> + +<h3 id="스택">스택</h3> + +<pre class="brush: js">// non recursive flatten deep using a stack +// note that depth control is hard/inefficient as we will need to tag EACH value with its own depth +// also possible w/o reversing on shift/unshift, but array OPs on the end tends to be faster +function flatten(input) { + const stack = [...input]; + const res = []; + while(stack.length) { + // pop value from stack + const next = stack.pop(); + if(Array.isArray(next)) { + // push back array items, won't modify the original input + stack.push(...next); + } else { + res.push(next); + } + } + // reverse to restore input order + return res.reverse(); +} + +const arr = [1, 2, [3, 4, [5, 6]]]; +flatten(arr); +// [1, 2, 3, 4, 5, 6]</pre> + +<h3 id="Generator_함수"><code>Generator</code> 함수</h3> + +<pre class="brush: js">function* flatten(array, depth) { + if(depth === undefined) { + depth = 1; + } + for(const item of array) { + if(Array.isArray(item) && depth > 0) { + yield* flatten(item, depth - 1); + } else { + yield item; + } + } +} + +const arr = [1, 2, [3, 4, [5, 6]]]; +const flattened = [...flatten(arr, Infinity)]; +// [1, 2, 3, 4, 5, 6]</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.flat', 'Array.prototype.flat')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.flat")}}</p> +</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.flatMap()")}}</li> + <li>{{jsxref("Array.prototype.map()")}}</li> + <li>{{jsxref("Array.prototype.reduce()")}}</li> + <li>{{jsxref("Array.prototype.concat()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/flatmap/index.html b/files/ko/web/javascript/reference/global_objects/array/flatmap/index.html new file mode 100644 index 0000000000..9d762001e8 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/flatmap/index.html @@ -0,0 +1,148 @@ +--- +title: Array.prototype.flatMap() +slug: Web/JavaScript/Reference/Global_Objects/Array/flatMap +tags: + - Array + - Experimental + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/flatMap +--- +<div>{{JSRef}} {{SeeCompatTable}}</div> + +<p><code><strong>flatMap()</strong></code> 메서드는 먼저 매핑함수를 사용해 각 엘리먼트에 대해 map 수행 후, 결과를 새로운 배열로 평탄화합니다. 이는 깊이 1의 <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat">flat</a> 이 뒤따르는 <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a> 과 동일하지만, <code>flatMap</code> 은 아주 유용하며 둘을 하나의 메소드로 병합할 때 조금 더 효율적입니다.</p> + +<p class="hidden">\{{EmbedInteractiveExample("pages/js/array-flatmap.html")}}</p> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>arr</var>.flatMap(<var>callback(currentValue[, index[, array]])</var>[, <var>thisArg</var>])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>새로운 배열의 엘리먼트를 생성하는 함수. 3개의 아규먼트를 갖습니다. + <dl> + <dt></dt> + <dt><code>currentValue</code></dt> + <dd>배열에서 처리되는 현재 엘리먼트.</dd> + <dt><code>index</code>{{optional_inline}}</dt> + <dd>배열에서 처리되고 있는 현재 엘리먼트의 인덱스.</dd> + <dt><code>array</code>{{optional_inline}}</dt> + <dd><code>map</code> 이 호출된 배열.</dd> + </dl> + </dd> + <dt><code>thisArg</code>{{optional_inline}}</dt> + <dd><code>callback</code> 실행에서 <code>this</code> 로 사용할 값.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>각 엘리먼트가 callback 함수의 결과이고, 깊이 1로 평탄화된 새로운 배열.</p> + +<h2 id="설명">설명</h2> + +<p>callback 함수의 상세 설명은 {{jsxref("Array.prototype.map()")}} 문서를 보시기 바랍니다. <code>flatMap</code> 메소드는 깊이 1의 <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat">flat</a></code> 이 뒤따르는 <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a></code> 과 동일합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="map_과_flatMap"><code>map</code> 과 <code>flatMap</code></h3> + +<pre class="brush: js">let arr1 = <span class="js source"><span class="function-call js meta"><span class="js meta"><span class="brace js meta square"><span>[</span></span><span class="constant decimal js numeric"><span>1</span></span><span class="comma delimiter js meta object"><span>,</span></span><span> </span><span class="brace js meta square"><span>2, 3, 4]; + +arr1.map(</span></span></span></span></span>x => [x * 2]<span class="js source"><span class="function-call js meta"><span class="js meta"><span class="brace js meta square"><span>);</span></span></span></span></span> +// [[2], [4], [6], [8]] + +arr1.flatMap(x => [x * 2]<span class="js source"><span class="function-call js meta"><span class="js meta"><span class="brace js meta square"><span>); +// [2, 4, 6, 8]</span></span></span></span></span> + +// 한 레벨만 평탄화됨 +arr1.flatMap(x => [[x * 2]]); +// [[2], [4], [6], [8]] +</pre> + +<p>위 코드는 map 자체만을 사용해서 구현할 수 있지만, 다음은 <code>flatMap</code> 의 유즈케이스를 더 잘 보여주는 예시입니다.</p> + +<p>문장의 리스트로부터 단어의 리스트를 생성해봅시다.</p> + +<pre class="brush: js">let arr1 = ["it's Sunny in", "", "California"]; + +arr1.map(x=>x.split(" ")); +// [["it's","Sunny","in"],[""],["California"]] + +arr1.flatMap(x => x.split(" ")<span class="js source"><span class="function-call js meta"><span class="js meta"><span class="brace js meta square"><span>); +// ["it's","Sunny","in","California"]</span></span></span></span></span></pre> + +<p>출력 리스트의 길이는 입력 리스트의 길이와 다를 수 있습니다.</p> + +<h3 id="flatMap_을_이용한_아이템_추가_및_제거"><code>flatMap()</code> 을 이용한 아이템 추가 및 제거</h3> + +<p><code>flatMap</code>은 <code>map</code>을 하는 과정에서 아이템을 추가하거나 제거하여 아이템 개수를 바꿀 수 있습니다. 다른 말로는 각각의 아이템에 대하여 1:1대응관계 뿐만 아니라 다대다 대응도 가능하다는 것입니다. 이러한 측면에서 <a href="https://wiki.developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/filter">filter</a>가 하는 역할의 반대역할을 한다고 볼 수 있습니다. 단순히 아무런 변화를 주고 싶지 않을때에는 원소 하나를 가진 배열을 반환할 수도, 아이템을 추가하고 싶을 때는 다-원소 배열을 반환할 수도, 아이템을 제거하고 싶을 때에는 빈 배열을 반환할 수도 있습니다.</p> + +<pre><code>// 다음은 음수는 제거하고 홀수는 1과 짝수로 분리하는 예시입니다. +let a = [5, 4, -3, 20, 17, -33, -4, 18] +// |\ \ x | | \ x x | +// [4,1, 4, 20, 16, 1, 18] + +a.flatMap( (n) => + (n < 0) ? [] : + (n % 2 == 0) ? [n] : + [n-1, 1] +) + +// expected output: [4, 1, 4, 20, 16, 1, 18]</code></pre> + +<div class="line"><span class="js source"><span class="comment double-slash js line"><span class="comment definition js punctuation"><span>//</span></span><span>=> [1, 2, 3, 4, 5, 6, 7, 8, 9]</span></span></span></div> + +<h2 id="대안">대안</h2> + +<h3 id="reduce_와_concat"><code>reduce</code> 와 <code>concat</code></h3> + +<pre class="brush: js">var arr1 = <span class="js source"><span class="function-call js meta"><span class="js meta"><span class="brace js meta square"><span>[</span></span><span class="constant decimal js numeric"><span>1</span></span><span class="comma delimiter js meta object"><span>,</span></span><span> </span><span class="brace js meta square"><span>2, 3, 4]; +</span></span></span></span></span> +arr1.flatMap(x => [x * 2]<span class="js source"><span class="function-call js meta"><span class="js meta"><span class="brace js meta square"><span>);</span></span></span></span></span> +// 다음과 동일합니다 +arr1.reduce((acc, x) => acc.concat([x * 2]<span class="js source"><span class="function-call js meta"><span class="js meta"><span class="brace js meta square"><span>), []);</span></span></span></span></span> +<span class="js source"><span class="function-call js meta"><span class="js meta"><span class="brace js meta square"><span>// [2, 4, 6, 8]</span></span></span></span></span> +</pre> + +<div class="line"><span class="js source"><span class="comment double-slash js line"><span class="comment definition js punctuation"><span>//</span></span><span>=> [1, 2, 3, 4, 5, 6, 7, 8, 9]</span></span></span></div> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td><a href="https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flatMap"><code>Array.prototype.flatMap</code> proposal</a></td> + <td>Finished (4)</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.flatMap")}}</p> +</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.flat()")}}</li> + <li>{{jsxref("Array.prototype.map()")}}</li> + <li>{{jsxref("Array.prototype.reduce()")}}</li> + <li>{{jsxref("Array.prototype.concat()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/foreach/index.html b/files/ko/web/javascript/reference/global_objects/array/foreach/index.html new file mode 100644 index 0000000000..809bc4d269 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/foreach/index.html @@ -0,0 +1,264 @@ +--- +title: Array.prototype.forEach() +slug: Web/JavaScript/Reference/Global_Objects/Array/forEach +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - Referennce +translation_of: Web/JavaScript/Reference/Global_Objects/Array/forEach +--- +<div>{{JSRef}}</div> + +<p><code><strong>forEach()</strong></code> 메서드는 주어진 함수를 배열 요소 각각에 대해 실행합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-foreach.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>arr</var>.forEach(<var>callback(currentvalue[, index[, array]])</var>[, <var>thisArg</var>])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>각 요소에 대해 실행할 함수. 다음 세 가지 매개변수를 받습니다.</dd> + <dd> + <dl> + <dt><code>currentValue</code></dt> + <dd>처리할 현재 요소.</dd> + <dt><code>index</code> {{optional_inline}}</dt> + <dd>처리할 현재 요소의 인덱스.</dd> + <dt><code>array</code> {{optional_inline}}</dt> + <dd><font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">forEach()</span></font>를 호출한 배열.</dd> + </dl> + </dd> + <dt><code>thisArg</code> {{optional_inline}}</dt> + <dd><code>callback</code>을 실행할 때 <code>this</code>로 사용할 값.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>{{jsxref("undefined")}}.</p> + +<h2 id="설명">설명</h2> + +<p><code>forEach()</code>는 주어진 <code>callback</code>을 배열에 있는 각 요소에 대해 오름차순으로 한 번씩 실행합니다. 삭제했거나 초기화하지 않은 인덱스 속성에 대해서는 실행하지 않습니다. (예: 희소 배열)</p> + +<p><code>callback</code>은 다음 세 인수와 함께 호출됩니다.</p> + +<ul> + <li><strong>요소 값</strong></li> + <li><strong>요소 인덱스</strong></li> + <li><strong>순회 중인 배열</strong></li> +</ul> + +<p><code>thisArg</code> 매개변수를 <code>forEach()</code>에 제공한 경우 <code>callback</code>을 호출할 때 전달해 <code>this</code>의 값으로 쓰입니다. 전달하지 않으면 <code>undefined</code>를 사용하며, 최종 <code>this</code> 값은 {{jsxref("Operators/this", "함수의 <code>this</code>를 결정하는 평소 규칙", "", 0)}}을 따릅니다.</p> + +<p><code>forEach()</code>로 처리할 요소의 범위는 최초 <code>callback</code> 호출 전에 설정됩니다. <code>forEach()</code> 호출을 시작한 뒤 배열에 추가한 요소는 <code>callback</code>이 방문하지 않습니다. 배열의 기존 요소값이 바뀐 경우, <code>callback</code>에 전달하는 값은 <code>forEach()</code>가 요소를 방문한 시점의 값을 사용합니다. 방문하기 전에 삭제한 요소는 방문하지 않습니다.</p> + +<p><code>forEach()</code>는 각 배열 요소에 대해 한 번씩 <code>callback</code> 함수를 실행합니다. {{jsxref("Array.prototype.map()", "map()")}}과 {{jsxref("Array.prototype.reduce()", "reduce()")}}와는 달리 {{jsxref("undefined")}}를 반환하기 때문에 메서드 체인의 중간에 사용할 수 없습니다. 대표적인 사용처는 메서드 체인 끝에서 부작용<sup>side effect</sup>을 실행하는 겁니다.</p> + +<p><code>forEach()</code>는 배열을 변형하지 않습니다. 그러나 <code>callback</code>이 변형할 수는 있습니다.</p> + +<div class="note"> +<p>예외를 던지지 않고는 <code>forEach()</code>를 중간에 멈출 수 없습니다. 중간에 멈춰야 한다면 <code>forEach()</code>가 적절한 방법이 아닐지도 모릅니다.</p> + +<p>다음 방법으로는 조기에 반복을 종료할 수 있습니다.</p> + +<ul> + <li>간단한 <a href="/ko/docs/Web/JavaScript/Reference/Statements/for">for</a> 반복문</li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a>, <a href="/ko/docs/Web/JavaScript/Reference/Statements/for...in">for...in</a> 반복문</li> + <li>{{jsxref("Array.prototype.every()")}}</li> + <li>{{jsxref("Array.prototype.some()")}}</li> + <li>{{jsxref("Array.prototype.find()")}}</li> + <li>{{jsxref("Array.prototype.findIndex()")}}</li> +</ul> + +<p>다른 배열 메서드 {{jsxref("Array.prototype.every()", "every()")}}, {{jsxref("Array.prototype.some()", "some()")}}, {{jsxref("Array.prototype.find()", "find()")}}, {{jsxref("Array.prototype.findIndex()", "findIndex()")}}는 배열 요소를 판별 함수에 전달하고, 그 결과의 참/거짓 여부에 따라 반복의 종료 여부를 결정합니다.</p> +</div> + +<h2 id="예제">예제</h2> + +<h3 id="초기화하지_않은_값의_반복_생략">초기화하지 않은 값의 반복 생략</h3> + +<pre class="brush: js">const arraySparse = [1,3,,7] +let numCallbackRuns = 0 + +arraySparse.forEach(function(element){ + console.log(element) + numCallbackRuns++ +}) + +console.log("numCallbackRuns: ", numCallbackRuns) + +// 1 +// 3 +// 7 +// numCallbackRuns: 3 +// comment: as you can see the missing value between 3 and 7 didn't invoke callback function.</pre> + +<h3 id="for_반복문을_forEach로_바꾸기"><code>for</code> 반복문을 <code>forEach()</code>로 바꾸기</h3> + +<pre class="brush: js">const items = ['item1', 'item2', 'item3']; +const copy = []; + +// 이전 +for (let i=0; i<items.length; i++) { + copy.push(items[i]); +} + +// 이후 +items.forEach(function(item){ + copy.push(item); +});</pre> + +<h3 id="배열_콘텐츠_출력">배열 콘텐츠 출력</h3> + +<div class="blockIndicator note"> +<p><strong>참고:</strong> {{domxref("console.table()")}}을 사용하면 배열 내용물을 서식에 맞춰 출력할 수 있습니다.</p> + +<p>다음 예제는 <code>forEach()</code>를 사용한 다른 방법을 소개합니다.</p> +</div> + +<p>다음 코드는 배열의 각 요소에 대해 한 줄을 기록합니다:</p> + +<pre class="brush:js">function logArrayElements(element, index, array) { + console.log('a[' + index + '] = ' + element); +} + +// 인덱스 2는 배열의 그 위치에 항목이 없기에 +// 건너뜀을 주의하세요. +[2, 5, , 9].forEach(logArrayElements); +// 기록: +// a[0] = 2 +// a[1] = 5 +// a[3] = 9 +</pre> + +<h3 id="thisArg_사용"><code>thisArg</code> 사용</h3> + +<p>다음 예제는 배열의 각 항목에서 객체의 속성을 갱신합니다:</p> + +<pre class="brush:js">function Counter() { + this.sum = 0 + this.count = 0 +} +Counter.prototype.add = function(array) { + array.forEach(function(entry) { + this.sum += entry + ++this.count + }, this) + // ^---- 주의 +} + +const obj = new Counter() +obj.add([2, 5, 9]) +obj.count +// 3 +obj.sum +// 16</pre> + +<p><code>thisArg</code> 매개변수(<code>this</code>)를 <code>forEach()</code>에 제공했기에, <code>callback</code>은 전달받은 <code>this</code>의 값을 자신의 <code>this</code> 값으로 사용할 수 있습니다. </p> + +<div class="note"> +<p><a href="/ko/docs/Web/JavaScript/Reference/Functions/애로우_펑션">화살표 함수 표현식</a>을 사용하여 함수 인수를 전달하는 경우 <code>thisArg</code> 매개변수는 화살표 함수가 {{jsxref("Operators/this", "this")}} 값을 렉시컬(lexical, 정적) 바인딩하기에 생략될 수 있습니다.</p> +</div> + +<h3 id="객체_복사_함수">객체 복사 함수</h3> + +<p>다음 코드는 주어진 객체의 사본을 만듭니다.</p> + +<p>객체 사본을 만드는 방법에는 여러가지가 있습니다, 다음은 그 중 한 방법으로, ECMAScript 5 <code>Object.*</code> 메타 속성 함수를 사용하여 <code>Array.prototype.forEach()</code>가 작동하는 법을 설명하기 위한 코드입니다.</p> + +<pre class="brush: js">function copy(obj) { + const copy = Object.create(Object.getPrototypeOf(obj)) + const propNames = Object.getOwnPropertyNames(obj) + + propNames.forEach(function(name) { + const desc = Object.getOwnPropertyDescriptor(obj, name) + Object.defineProperty(copy, name, desc) + }) + + return copy +} + +const obj1 = { a: 1, b: 2 } +const obj2 = copy(obj1) // obj2 looks like obj1 now</pre> + +<h3 id="반복_중_배열이_변경으로_인한_반복_생략">반복 중 배열이 변경으로 인한 반복 생략</h3> + +<p>다음 예제에서는 <code>"one"</code>, <code>"two"</code>, <code>"four"</code>를 기록합니다.</p> + +<p><code>forEach()</code>가 값 <code>"two"</code>를 포함하는 항목에 도달하면 전체 배열의 첫 번째 항목을 제거하여, 나머지 모든 항목이 한 위치 앞으로 이동합니다. 요소 <code>"four"</code>는 이제 배열에서 보다 앞에 위치하므로 <code>"three"</code>는 건너 뜁니다.</p> + +<p><code>forEach()</code>는 반복 전에 배열의 복사본을 만들지 않습니다.</p> + +<pre class="brush:js">let words = ['one', 'two', 'three', 'four'] +words.forEach(function(word) { + console.log(word) + if (word === 'two') { + words.shift() + } +}) +// one +// two +// four</pre> + +<h3 id="배열_평탄화">배열 평탄화</h3> + +<p>다음 예제는 오직 시연 용으로만 추가한 것으로, 평탄화를 하려면 {{jsxref("Array.prototype.flat()")}}을 사용하세요.</p> + +<pre class="brush: js">function flatten(arr) { + const result = [] + + arr.forEach((i) => { + if (Array.isArray(i)) { + result.push(...flatten(i)) + } else { + result.push(i) + } + }) + + return result +} + +// Usage +const nested = [1, 2, 3, [4, 5, [6, 7], 8, 9]] + +flatten(nested) // [1, 2, 3, 4, 5, 6, 7, 8, 9]</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Array.forEach")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.find()")}}</li> + <li>{{jsxref("Array.prototype.findIndex()")}}</li> + <li>{{jsxref("Array.prototype.map()")}}</li> + <li>{{jsxref("Array.prototype.every()")}}</li> + <li>{{jsxref("Array.prototype.some()")}}</li> + <li>{{jsxref("Map.prototype.forEach()")}}</li> + <li>{{jsxref("Set.prototype.forEach()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/from/index.html b/files/ko/web/javascript/reference/global_objects/array/from/index.html new file mode 100644 index 0000000000..487cc36848 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/from/index.html @@ -0,0 +1,244 @@ +--- +title: Array.from() +slug: Web/JavaScript/Reference/Global_Objects/Array/from +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Method + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/from +--- +<div>{{JSRef}}</div> + +<p><code><strong>Array.from()</strong></code> 메서드는 유사 배열 객체(array-like object)나반복 가능한 객체(iterable object)를 얕게 복사해새로운<code>Array</code> 객체를 만듭니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-from.html")}}</div> + + + +<h2 id="Syntax" name="Syntax">구문</h2> + +<pre class="syntaxbox">Array.from(<em>arrayLike</em>[, <em>mapFn</em>[, <em>thisArg</em>]]) +</pre> + +<h3 id="Parameters" name="Parameters"><span>매개변수</span></h3> + +<dl> + <dt><code>arrayLike</code></dt> + <dd>배열로 변환하고자 하는유사 배열 객체나 반복 가능한 객체.</dd> + <dt><code>mapFn</code>{{Optional_inline}}</dt> + <dd>배열의 모든 요소에 대해 호출할 맵핑 함수.</dd> + <dt><code>thisArg</code>{{Optional_inline}}</dt> + <dd><code>mapFn</code> 실행 시에 <code>this</code>로 사용할 값.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>새로운 {{jsxref("Array")}} 인스턴스.</p> + +<h2 id="Description" name="Description">설명</h2> + +<p>다음과 같은 경우에 <code>Array.from()</code>으로새<code>Array</code>를 만들 수 있습니다.</p> + +<ul> + <li>유사 배열 객체 (<code>length</code> 속성과 인덱싱된 요소를 가진 객체)</li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/iterable">순회 가능한 객체</a> ({{jsxref("Map")}}, {{jsxref("Set")}} 등객체의 요소를 얻을 수 있는 객체)</li> +</ul> + +<p><code>Array.from()</code>은 선택 매개변수인 <code>mapFn</code>를 가지는데,배열(혹은 배열 서브클래스)의 각 요소를{{jsxref("Array.prototype.map", "맵핑", "", 0)}}할 때 사용할 수 있습니다. 즉,<code>Array.from(obj, mapFn, thisArg)</code>는 중간에 다른 배열을 생성하지 않는다는 점을 제외하면<code>Array.from(obj).map(mapFn, thisArg)</code>와 같습니다. 이 특징은 <a href="/ko/docs/Web/JavaScript/Typed_arrays">typed arrays</a>와 같은 특정 배열 서브클래스에서 중간 배열 값이 적절한 유형에 맞게 생략되기 때문에 특히 중요합니다.</p> + +<p><code>from()</code> 메서드의 <code>length</code> 속성은 1입니다.</p> + +<p>ES2015 이후, 클래스 구문은 내장 및 새 클래스의 상속을 가능케 했습니다. 그 결과로 <code>Array.from</code>과 같은 정적 메서드는 <code>Array</code>의 서브클래스에 의해 상속되며, <code>Array</code> 대신 자신의 인스턴스를 만듭니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="String에서_배열_만들기"><code>String</code>에서 배열 만들기</h3> + +<pre class="brush: js">Array.from('foo'); +// ["f", "o", "o"] +</pre> + +<h3 id="Set에서_배열_만들기"><code>Set</code>에서 배열 만들기</h3> + +<pre class="brush: js">const s = new Set(['foo', window]); +Array.from(s); +// ["foo", window] +</pre> + +<h3 id="Map에서_배열_만들기"><code>Map</code>에서 배열 만들기</h3> + +<pre class="brush: js">const m = new Map([[1, 2], [2, 4], [4, 8]]); +Array.from(m); +// [[1, 2], [2, 4], [4, 8]] + +const mapper = new Map([['1', 'a'], ['2', 'b']]); +Array.from(mapper.values()); +// ['a', 'b']; + +Array.from(mapper.keys()); +// ['1', '2']; +</pre> + +<h3 id="배열_형태를_가진_객체(arguments)에서_배열_만들기">배열 형태를 가진 객체(<code>arguments</code>)에서 배열 만들기</h3> + +<pre class="brush: js">function f() { + return Array.from(arguments); +} + +f(1, 2, 3); + +// [1, 2, 3] +</pre> + +<h3 id="Array.from과_화살표_함수_사용하기"><code>Array.from</code>과 화살표 함수 사용하기</h3> + +<pre class="brush: js">// Using an arrow function as the map function to +// manipulate the elements +Array.from([1, 2, 3], x => x + x); +// [2, 4, 6] + +// Generate a sequence of numbers +// Since the array is initialized with `undefined` on each position, +// the value of `v` below will be `undefined` +Array.from({length: 5}, (v, i) => i); +// [0, 1, 2, 3, 4] +</pre> + +<h3 id="시퀀스_생성기(range)">시퀀스 생성기(range)</h3> + +<pre class="brush: js">// Sequence generator function (commonly referred to as "range", e.g. Clojure, PHP etc) +const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step)); + +// Generate numbers range 0..4 +range(0, 4, 1); +// [0, 1, 2, 3, 4] + +// Generate numbers range 1..10 with step of 2 +range(1, 10, 2); +// [1, 3, 5, 7, 9] + +// Generate the alphabet using Array.from making use of it being ordered as a sequence +range('A'.charCodeAt(0), 'Z'.charCodeAt(0), 1).map(x => String.fromCharCode(x)); +// ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]</pre> + +<h2 id="폴리필">폴리필</h2> + +<p><code><font face="consolas, Liberation Mono, courier, monospace">Array.from</font></code>은 ECMA-262 표준 제6판에 추가됐습니다.따라서 어떤 표준 구현체에서는 사용할 수없을 수도 있습니다. 다른 모든 코드 이전에 아래 코드를 포함하면 지원하지 않는 플랫폼에서도<code>Array.from</code>을사용할 수 있습니다. 아래 알고리즘은<a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Object" title="객체(object) 생성자(constructor)는 객체 레퍼(wrapper)를 생성합니다."><code>Object</code></a>와<a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/TypeError" title="TypeError 객체는 변수의 값이 원하는 타입이 아닐 때 발생하는 에러를 표현합니다."><code>TypeError</code></a>가 변형되지 않고,<code>callback.call</code>의 계산 값이 원래의<a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Function/call" title="call() 메소드는 주어진 this 값 및 각각 전달된 인수와 함께 함수를 호출합니다."><code>Function.prototype.call()</code></a>과 같은 경우ECMA-262 제6판이 명시한 것과 동일합니다.<span style="letter-spacing: -0.00278rem;">또한 반복가능자(iterable)는 완벽하게 폴리필할 수없기에 본 구현은 ECMA-262 제6판의 제네릭 반복가능자를 지원하지 않습니다.</span></p> + +<pre class="brush: js">// Production steps of ECMA-262, Edition 6, 22.1.2.1 +if (!Array.from) { + Array.from = (function () { + var toStr = Object.prototype.toString; + var isCallable = function (fn) { + return typeof fn === 'function' || toStr.call(fn) === '[object Function]'; + }; + var toInteger = function (value) { + var number = Number(value); + if (isNaN(number)) { return 0; } + if (number === 0 || !isFinite(number)) { return number; } + return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number)); + }; + var maxSafeInteger = Math.pow(2, 53) - 1; + var toLength = function (value) { + var len = toInteger(value); + return Math.min(Math.max(len, 0), maxSafeInteger); + }; + + // The length property of the from method is 1. + return function from(arrayLike/*, mapFn, thisArg */) { + // 1. Let C be the this value. + var C = this; + + // 2. Let items be ToObject(arrayLike). + var items = Object(arrayLike); + + // 3. ReturnIfAbrupt(items). + if (arrayLike == null) { + throw new TypeError('Array.from requires an array-like object - not null or undefined'); + } + + // 4. If mapfn is undefined, then let mapping be false. + var mapFn = arguments.length > 1 ? arguments[1] : void undefined; + var T; + if (typeof mapFn !== 'undefined') { + // 5. else + // 5. a If IsCallable(mapfn) is false, throw a TypeError exception. + if (!isCallable(mapFn)) { + throw new TypeError('Array.from: when provided, the second argument must be a function'); + } + + // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined. + if (arguments.length > 2) { + T = arguments[2]; + } + } + + // 10. Let lenValue be Get(items, "length"). + // 11. Let len be ToLength(lenValue). + var len = toLength(items.length); + + // 13. If IsConstructor(C) is true, then + // 13. a. Let A be the result of calling the [[Construct]] internal method + // of C with an argument list containing the single item len. + // 14. a. Else, Let A be ArrayCreate(len). + var A = isCallable(C) ? Object(new C(len)) : new Array(len); + + // 16. Let k be 0. + var k = 0; + // 17. Repeat, while k < len… (also steps a - h) + var kValue; + while (k < len) { + kValue = items[k]; + if (mapFn) { + A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k); + } else { + A[k] = kValue; + } + k += 1; + } + // 18. Let putStatus be Put(A, "length", len, true). + A.length = len; + // 20. Return A. + return A; + }; + }()); +}</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.from', 'Array.from')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.from', 'Array.from')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Array.from")}}</p> + +<h2 id="See_also" name="See_also">같이 보기</h2> + +<ul> + <li>{{jsxref("Array")}}</li> + <li>{{jsxref("Array.prototype.map()")}}</li> + <li>{{jsxref("TypedArray.from()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/includes/index.html b/files/ko/web/javascript/reference/global_objects/array/includes/index.html new file mode 100644 index 0000000000..a646fd3bb4 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/includes/index.html @@ -0,0 +1,173 @@ +--- +title: Array.prototype.includes() +slug: Web/JavaScript/Reference/Global_Objects/Array/includes +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/includes +--- +<div>{{JSRef}}</div> + +<p><strong><code>includes()</code></strong> 메서드는 배열이 특정 요소를 포함하고 있는지 판별합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-includes.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>arr</var>.includes(<em>valueToFind</em>[, <em>fromIndex</em>]) +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">valueToFind</span></font></dt> + <dd>탐색할 요소. + <div class="blockIndicator note"> + <p><strong>참고</strong>: 문자나 문자열을 비교할 때, <code>includes()</code>는 <strong>대소문자를 구분</strong>합니다.</p> + </div> + </dd> + <dt><code>fromIndex</code> {{optional_inline}}</dt> + <dd>이 배열에서 searchElement 검색을 시작할 위치입니다. 음의 값은 array.length + fromIndex의 인덱스를 asc로 검색합니다. 기본값은 0입니다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>{{jsxref("Boolean")}}.</p> + +<h2 id="예제">예제</h2> + +<pre class="brush: js">[1, 2, 3].includes(2); // true +[1, 2, 3].includes(4); // false +[1, 2, 3].includes(3, 3); // false +[1, 2, 3].includes(3, -1); // true +[1, 2, NaN].includes(NaN); // true +</pre> + +<h3 id="fromIndex_가_배열의_길이보다_같거나_큰_경우"><code>fromIndex</code> 가 배열의 길이보다 같거나 큰 경우</h3> + +<p><code>fromIndex</code> 가 배열의 길이보다 같거나 크다면, <code>false</code> 를 반환합니다. 배열은 검색되지 않을 것입니다.</p> + +<pre class="brush: js">var arr = ['a', 'b', 'c']; + +arr.includes('c', 3); // false +arr.includes('c', 100); // false</pre> + +<h3 id="0보다_작은_인덱스의_계산">0보다 작은 인덱스의 계산</h3> + +<p><code>fromIndex</code> 가 음수라면, 이 계산된 인덱스는 <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">valueToFind</span></font> 를 찾기 시작할 배열의 위치로 사용되기 위해 연산됩니다. 만약 계산된 인덱스가 <code>-1 * array.length</code> 보다 작거나 같다면, 전체 배열이 검색될 것입니다.</p> + +<pre class="brush: js">// array length is 3 +// fromIndex is -100 +// computed index is 3 + (-100) = -97 + +var arr = ['a', 'b', 'c']; + +arr.includes('a', -100); // true +arr.includes('b', -100); // true +arr.includes('c', -100); // true +arr.includes('a', -2); // false</pre> + +<h3 id="제네릭_메소드로_사용되는_includes">제네릭 메소드로 사용되는 <code>includes()</code></h3> + +<p><code>includes()</code> 메서드는 의도적으로 제네릭입니다. 배열 객체가 되기 위한 <code>this</code> 값을 요구하지 않아, 다른 종류의 객체에 적용될 수 있습니다 (e.g. 유사 배열 객체). 아래 예시는 이 함수의 <a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a> 객체로 호출되는 <code>includes()</code> 메소드를 보여줍니다.</p> + +<pre class="brush: js">(function() { + console.log([].includes.call(arguments, 'a')); // true + console.log([].includes.call(arguments, 'd')); // false +})('a','b','c');</pre> + +<h2 id="폴리필">폴리필</h2> + +<pre class="brush: js"><code>// https://tc39.github.io/ecma262/#sec-array.prototype.includes +if (!Array.prototype.includes) { + Object.defineProperty(Array.prototype, 'includes', { + value: function(searchElement, fromIndex) { + + if (this == null) { + throw new TypeError('"this" is null or not defined'); + } + + // 1. Let O be ? ToObject(this value). + var o = Object(this); + + // 2. Let len be ? ToLength(? Get(O, "length")). + var len = o.length >>> 0; + + // 3. If len is 0, return false. + if (len === 0) { + return false; + } + + // 4. Let n be ? ToInteger(fromIndex). + // (If fromIndex is undefined, this step produces the value 0.) + var n = fromIndex | 0; + + // 5. If n ≥ 0, then + // a. Let k be n. + // 6. Else n < 0, + // a. Let k be len + n. + // b. If k < 0, let k be 0. + var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); + + function sameValueZero(x, y) { + return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y)); + } + + // 7. Repeat, while k < len + while (k < len) { + // a. Let elementK be the result of ? Get(O, ! ToString(k)). + // b. If SameValueZero(searchElement, elementK) is true, return true. + if (sameValueZero(o[k], searchElement)) { + return true; + } + // c. Increase k by 1. + k++; + } + + // 8. Return false + return false; + } + }); +}</code></pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES7', '#sec-array.prototype.includes', 'Array.prototype.includes')}}</td> + <td>{{Spec2('ES7')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.includes', 'Array.prototype.includes')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.Array.includes")}}</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("TypedArray.prototype.includes()")}}</li> + <li>{{jsxref("String.prototype.includes()")}}</li> + <li>{{jsxref("Array.prototype.indexOf()")}}</li> + <li>{{jsxref("Array.prototype.find()")}}</li> + <li>{{jsxref("Array.prototype.findIndex()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/index.html b/files/ko/web/javascript/reference/global_objects/array/index.html new file mode 100644 index 0000000000..4bb18af837 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/index.html @@ -0,0 +1,493 @@ +--- +title: Array +slug: Web/JavaScript/Reference/Global_Objects/Array +tags: + - Array + - Example + - Global Objects + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array +--- +<div>{{JSRef}}</div> + +<p>JavaScript <strong><code>Array</code></strong> 전역 객체는 배열을 생성할 때 사용하는 리스트 형태의 고수준 객체입니다.</p> + +<h2 id="설명">설명</h2> + +<p>배열은 프로토타입으로 탐색과 변형 작업을 수행하는 메서드를 갖는, 리스트와 비슷한 객체입니다. JavaScript에서 배열의 길이와 요소의 자료형은 고정되어 있지 않습니다. 배열의 길이가 언제든지 늘어나거나 줄어들 수 있기 때문에 JavaScript 배열들은 밀집도가 보장되지 않습니다. 보통 이 성질은 편리하지만, 목적에 맞지 않는다면 형식화 배열(typed array)을 사용하는 것을 고려해보세요.</p> + +<p>배열은 요소 인덱스로 문자열(<a href="https://ko.wikipedia.org/wiki/%EC%97%B0%EA%B4%80_%EB%B0%B0%EC%97%B4">연관 배열</a>)을 사용할 수 없으며 무조건 정수만 허용합니다. <a href="/ko/docs/Web/JavaScript/Reference/Operators/Property_Accessors">속성 접근자</a>를 사용해 정수 외 키에 접근할 경우 배열 리스트의 요소가 아니라 배열 객체의 속성 변수를 설정하거나 회수합니다. 배열 객체의 속성과 배열 요소의 리스트의 요소는 서로 다른 별개의 항목으로, <a href="/ko/docs/Web/JavaScript/Guide/Indexed_collections#배열_객체의_메서드">순회 및 변형 작업</a>은 객체 속성에 적용되지 않습니다.</p> + +<h3 id="자주_사용하는_연산">자주 사용하는 연산</h3> + +<h4 id="배열_만들기">배열 만들기</h4> + +<pre class="brush: js">let fruits = ['사과', '바나나'] + +console.log(fruits.length) +// 2 +</pre> + +<h4 id="인덱스로_배열의_항목에_접근하기">인덱스로 배열의 항목에 접근하기</h4> + +<pre class="brush: js">let first = fruits[0] +// 사과 + +let last = fruits[fruits.length - 1] +// 바나나 +</pre> + +<h4 id="배열의_항목들을_순환하며_처리하기">배열의 항목들을 순환하며 처리하기</h4> + +<pre class="brush: js">fruits.forEach(function (item, index, array) { + console.log(item, index) +}) +// 사과 0 +// 바나나 1 +</pre> + +<h4 id="배열_끝에_항목_추가하기">배열 끝에 항목 추가하기</h4> + +<pre class="brush: js">let newLength = fruits.push('오렌지') +// ["사과", "바나나", "오렌지"] +</pre> + +<h4 id="배열_끝에서부터_항목_제거하기">배열 끝에서부터 항목 제거하기</h4> + +<pre class="brush: js">let last = fruits.pop() // 끝에있던 '오렌지'를 제거 +// ["사과", "바나나"] +</pre> + +<h4 id="배열_앞에서부터_항목_제거하기">배열 앞에서부터 항목 제거하기</h4> + +<pre class="brush: js">let first = fruits.shift() // 제일 앞의 '사과'를 제거 +// ["바나나"] +</pre> + +<h4 id="배열_앞에_항목_추가하기">배열 앞에 항목 추가하기</h4> + +<pre class="brush: js">let newLength = fruits.unshift('딸기') // 앞에 추가 +// ["딸기", "바나나"] +</pre> + +<h4 id="배열_안_항목의_인덱스_찾기">배열 안 항목의 인덱스 찾기</h4> + +<pre class="brush: js">fruits.push('망고') +// ["딸기", "바나나", "망고"] + +let pos = fruits.indexOf("바나나") +// 1 +</pre> + +<h4 id="인덱스_위치에_있는_항목_제거하기">인덱스 위치에 있는 항목 제거하기</h4> + +<pre class="brush: js">let removedItem = fruits.splice(pos, 1) // 항목을 제거하는 방법 + +// ["딸기", "망고"] +</pre> + +<h4 id="인덱스_위치에서부터_여러개의_항목_제거하기">인덱스 위치에서부터 여러개의 항목 제거하기</h4> + +<pre class="brush: js">let vegetables = ['양배추', '순무', '무', '당근'] +console.log(vegetables) +// ["양배추", "순무", "무", "당근"] + +let pos = 1 +let n = 2 + +let removedItems = vegetables.splice(pos, n) +// 배열에서 항목을 제거하는 방법 +// pos 인덱스부터 n개의 항목을 제거함 + +console.log(vegetables) +// ["양배추", "당근"] (원 배열 vegetables의 값이 변함) + +console.log(removedItems) +// ["순무", "무"] +</pre> + +<h4 id="배열_복사하기">배열 복사하기</h4> + +<pre class="brush: js">let shallowCopy = fruits.slice() // 사본을 만드는 방법 +// ["딸기", "망고"] +</pre> + +<h3 id="배열_요소에_접근하기">배열 요소에 접근하기</h3> + +<p>JavaScript 배열의 인덱스는 0부터 시작합니다. 즉, 배열 첫 번째 요소의 인덱스는 0이고, 마지막 요소의 인덱스는 배열의 {{jsxref("Array.length", "length")}} 속성에서 1을 뺀 것과 같습니다.</p> + +<p>잘못된 인덱스를 사용하면 <code>undefined</code>를 반환합니다.</p> + +<pre class="brush: js">let arr = ['첫 번재 요소입니다', '두 번째 요소입니다', '마지막 요소입니다'] +console.log(arr[0]) // '첫 번재 요소입니다'를 기록 +console.log(arr[1]) // '두 번재 요소입니다'를 기록 +console.log(arr[arr.length - 1]) // '마지막 요소입니다'를 기록 +</pre> + +<p><code>toString</code>이 속성인 것과 마찬가지로(정확히 하자면, <code>toString()</code>은 메서드입니다) 배열의 요소도 속성입니다. 하지만 아래의 예시처럼 배열 요소에 접근하려 하면, 속성 이름이 유효하지 않기 때문에 구문 오류가 발생합니다.</p> + +<pre class="brush: js">console.log(arr.0) // 구문 오류 +</pre> + +<p>이 점에는 JavaScript 배열과 속성에 특별한 점이 없습니다. 숫자로 시작하는 JavaScript 속성은 마침표 구문으로 접근할 수 없으며, 반드시 괄호 표기법으로 접근해야 합니다.</p> + +<p>예를 들어 <code>'3d'</code>라는 이름의 속성을 가진 객체에서 해당 속성에 접근할 땐 괄호 표기법을 사용해야만 합니다.</p> + +<pre class="brush: js">let years = [1950, 1960, 1970, 1980, 1990, 2000, 2010] +console.log(years.0) // 구문 오류 +console.log(years[0]) // 정상 작동 +</pre> + +<pre class="brush: js">renderer.3d.setTexture(model, 'character.png') // 구문 오류 +renderer['3d'].setTexture(model, 'character.png') // 정상 작동 +</pre> + +<p><code>3d</code> 예시에서 <code>'3d'</code>를 따옴표로 감싸야 함에 유의하세요. JavaScript 배열 인덱스도 따옴표로 둘러쌀 수는 있지만(<code>years[2]</code> 대신에 <code>years['2']</code>처럼), 굳이 필요하지는 않습니다.</p> + +<p><code>years[2]</code>의 2는 JavaScript 엔진이 암시적인 <code>toString</code> 변환을 사용해 문자열로 변환합니다. 그 결과로서 <code>'2'</code>와 <code>'02'</code>는 <code>years</code> 객체에서 서로 다른 칸을 가리키며, 다음 코드는 <code>true</code>가 될 수 있습니다.</p> + +<pre class="brush: js">console.log(years['2'] != years['02']); +</pre> + +<h3 id="length_와_숫자형_속성의_관계"><code>length</code> 와 숫자형 속성의 관계</h3> + +<p>JavaScript 배열의 {{jsxref("Array.length", "length")}} 속성과 숫자형 속성은 연결되어 있습니다.</p> + +<p>몇몇 배열 내장 메서드({{jsxref("Array.join", "join")}}, {{jsxref("Array.slice", "slice")}}, {{jsxref("Array.indexOf", "indexOf")}} 등)은 호출했을 때 배열의 {{jsxref("Array.length", "length")}} 속성의 값을 참조합니다.</p> + +<p>다른 메서드({{jsxref("Array.push", "push")}}, {{jsxref("Array.splice", "splice")}} 등) 또한 배열의 {{jsxref("Array.length", "length")}} 속성의 업데이트를 유발합니다.</p> + +<pre class="brush: js">const fruits = [] +fruits.push('banana', 'apple', 'peach') + +console.log(fruits.length) // 3 +</pre> + +<p>JavaScript 배열의 속성을 설정할 때 그 속성이 유효한 배열 인덱스이고 그 인덱스가 현재 배열의 경계를 넘어간다면, JavaScript 엔진은 배열의 {{jsxref("Array.length", "length")}} 속성을 그에 맞춰 업데이트 합니다.</p> + +<pre class="brush: js">fruits[5] = 'mango' +console.log(fruits[5]) // 'mango' +console.log(Object.keys(fruits)) // ['0', '1', '2', '5'] +console.log(fruits.length) // 6 +</pre> + +<p>{{jsxref("Array.length", "length")}}를 직접 늘릴 수 있습니다.</p> + +<pre class="brush: js">fruits.length = 10; +console.log(Object.keys(fruits)); // ['0', '1', '2', '5'] +console.log(fruits.length); // 10 +</pre> + +<p>하지만, {{jsxref("Array.length", "length")}} 속성을 감소시키면 요소를 지웁니다.</p> + +<pre class="brush: js">fruits.length = 2 +console.log(Object.keys(fruits)) // ['0', '1'] +console.log(fruits.length) // 2 +</pre> + +<p>{{jsxref("Array.length")}} 문서에 더 자세한 설명이 있습니다.</p> + +<h3 id="매치_결과를_이용한_배열_생성">매치 결과를 이용한 배열 생성</h3> + +<p>정규표현식과 문자열 사이의 매치 결과로 JavaScript 배열을 만들 수 있습니다. 이 배열은 매치에 대한 정보를 제공하는 속성들과 요소들을 가집니다. 이러한 배열은 {{jsxref("RegExp.exec")}}, {{jsxref("String.match")}}, {{jsxref("String.replace")}}로부터 반환됩니다. 이 속성들과 요소들에 대한 설명을 돕기위해, 다음 예제를 보고 아래 테이블을 참조해주세요.</p> + +<pre class="brush: js">// 하나의 d와 하나 이상의 b에 하나의 d가 뒤따라 일치해야 합니다. +// 일치한 b와 다음 d를 기억하십시오. +// 대소문자 구분은 무시됩니다. + +var myRe = /d(b+)(d)/i; +var myArray = myRe.exec('cdbBdbsbz'); +</pre> + +<p>매치로부터 반환되는 속성들과 요소들은 다음과 같습니다:</p> + +<table class="fullwidth-table standard-table"> + <tbody> + <tr> + <td class="header">속성/요소</td> + <td class="header">설명</td> + <td class="header">예시</td> + </tr> + <tr> + <td><code>input </code> {{ReadOnlyInline}}</td> + <td>정규 표현식과 일치시키는 원본 문자열을 나타내는 읽기 전용 속성입니다.</td> + <td><code>"cdbBdbsbz"</code></td> + </tr> + <tr> + <td><code>index </code> {{ReadOnlyInline}}</td> + <td>원본 문자열에서 정규 표현식이 처음 일치하는 문자열의 위치(원본 문자열의 첫 문자 위치를 0으로 하는)를 나타내는 읽기 전용 속성입니다.</td> + <td><code>1</code></td> + </tr> + <tr> + <td><code>[0]</code> {{ReadOnlyInline}}</td> + <td>원본 문자열에서 정규 표현식이 처음 일치하는 문자열을 지정하는 읽기 전용 요소입니다.</td> + <td><code>"dbBd"</code></td> + </tr> + <tr> + <td><code>[1], ...[n] </code> {{ReadOnlyInline}}</td> + <td>만약 정규 표현식에 괄호가 포함돼 있다면 괄호에 일치하는 부분 문자열을 나타내는 읽기 전용 요소들입니다. 가능한 괄호 안의 부분 문자열의 수는 무제한입니다.</td> + <td><code>[1]: bB</code><br> + <code>[2]: d</code></td> + </tr> + </tbody> +</table> + +<h2 id="생성자">생성자</h2> + +<dl> + <dt>{{jsxref("Array.Array", "Array()")}}</dt> + <dd><code>Array</code> 객체를 생성합니다.</dd> +</dl> + +<h2 id="정적_속성">정적 속성</h2> + +<dl> + <dt><code>Array.length</code></dt> + <dd>값이 1인 <code>Array</code> 생성자의 길이 속성입니다.</dd> + <dt>{{jsxref("Array.@@species", "get Array[@@species]")}}</dt> + <dd>파생 객체를 생성하는데 사용하는 생성자 함수입니다.</dd> +</dl> + +<h2 id="정적_메서드">정적 메서드</h2> + +<dl> + <dt>{{jsxref("Array.from()")}}</dt> + <dd>유사 배열 또는 반복 가능한 객체로부터 새로운 <code>Array</code> 인스턴스를 생성합니다.</dd> + <dt>{{jsxref("Array.isArray()")}}</dt> + <dd>만약 변수가 배열이면 참을, 아니면 거짓을 반환합니다.</dd> + <dt>{{jsxref("Array.of()")}}</dt> + <dd>전달인자의 개수나 데이터 타입에 관계없이 새 <code>Array</code> 인스턴스를 생성합니다.</dd> +</dl> + +<h2 id="Array_인스턴스"><code>Array</code> 인스턴스</h2> + +<p>모든 <code>Array</code> 인스턴스는 <code>Array.prototype</code>을 상속합니다. 다른 생성자와 마찬가지로, <code>Array()</code> 생성자의 프로토타입을 수정하면 모든 <code>Array</code> 인스턴스도 수정의 영향을 받습니다. 예를 들면, 새로운 메서드와 속성을 추가해 모든 <code>Array</code>를 확장할 수 있으므로, {{glossary("polyfill", "폴리필")}}에 쓰입니다.</p> + +<p>그러나 배열 객체에 비표준 메서드를 추가하면 나중에 스스로, 혹은 <a href="https://developers.google.com/web/updates/2018/03/smooshgate">JavaScript에 기능이 추가</a>될 경우 문제가 될 수 있습니다.</p> + +<p>잘 모를 법한 사실: <code>Array.prototype</code>은 그 스스로 <code>Array</code>입니다.</p> + +<pre class="brush: js">Array.isArray(Array.prototype) // true</pre> + +<h2 id="인스턴스_속성">인스턴스 속성</h2> + +<div> +<dl> + <dt><code>Array.prototype.constructor</code></dt> + <dd>객체의 프로토타입을 생성하는 함수를 지정합니다.</dd> + <dt>{{jsxref("Array.prototype.length")}}</dt> + <dd>배열의 원소 수를 나타냅니다.</dd> + <dt>{{jsxref("Array.@@unscopables", "Array.prototype[@@unscopables]")}}</dt> + <dd>{{jsxref("Statements/with", "with")}} 결속 범위로부터 제외하려는 속성 이름이 들어있는 기호입니다.</dd> +</dl> +</div> + +<h2 id="인스턴스_메서드">인스턴스 메서드</h2> + +<h4 id="변경자_메서드">변경자 메서드</h4> + +<div> +<p>변경자 메서드는 배열을 수정합니다.</p> + +<dl> + <dt>{{jsxref("Array.prototype.copyWithin()")}}</dt> + <dd>배열 내의 지정된 요소들을 동일한 배열 내에서 복사합니다.</dd> + <dt>{{jsxref("Array.prototype.fill()")}}</dt> + <dd>배열 안의 시작 인덱스부터 끝 인덱스까지의 요소값을 지정된 정적 값으로 채웁니다.</dd> + <dt>{{jsxref("Array.prototype.pop()")}}</dt> + <dd>배열에서 마지막 요소를 뽑아내고, 그 요소를 반환합니다.</dd> + <dt>{{jsxref("Array.prototype.push()")}}</dt> + <dd>배열의 끝에 하나 이상의 요소를 추가하고, 변경된 배열의 길이를 반환합니다.</dd> + <dt>{{jsxref("Array.prototype.reverse()")}}</dt> + <dd>배열의 요소 순서를 반전시킵니다. 첫 번째가 마지막이 되고 마지막이 첫 번째가 됩니다.</dd> + <dt>{{jsxref("Array.prototype.shift()")}}</dt> + <dd>배열에서 첫 번째 요소를 삭제하고 그 요소를 반환합니다.</dd> + <dt>{{jsxref("Array.prototype.sort()")}}</dt> + <dd>배열의 요소를 정렬하고 그 배열을 반환합니다.</dd> + <dt>{{jsxref("Array.prototype.splice()")}}</dt> + <dd>배열에서 요소를 추가/삭제합니다.</dd> + <dt>{{jsxref("Array.prototype.unshift()")}}</dt> + <dd>배열의 앞에 하나 이상의 요소를 추가하고 새로운 길이를 반환합니다.</dd> +</dl> +</div> + +<h4 id="접근자_메서드">접근자 메서드</h4> + +<div> +<p>접근자 메서드는 배열을 수정하지 않고, 기존 배열의 일부에 기반한 새로운 배열 또는 값을 반환합니다.</p> + +<dl> + <dt>{{jsxref("Array.prototype.concat()")}}</dt> + <dd>배열을 매개변수로 주어진 배열/값과 이어붙인 새로운 배열을 반환합니다.</dd> + <dt>{{jsxref("Array.prototype.filter()")}}</dt> + <dd>지정한 콜백의 반환 결과가 <code>true</code>인 요소만 모은 새로운 배열을 반환합니다.</dd> + <dt>{{jsxref("Array.prototype.includes()")}}</dt> + <dd>배열이 주어진 값을 포함하는지 판별해 <code>true</code> 또는 <code>false</code>를 반환합니다.</dd> + <dt>{{jsxref("Array.prototype.indexOf()")}}</dt> + <dd>배열에서 주어진 값과 일치하는 제일 앞의 인덱스를 반환합니다. 없으면 <code>-1</code>을 반환합니다.</dd> + <dt>{{jsxref("Array.prototype.join()")}}</dt> + <dd>배열의 모든 요소를 문자열로 합칩니다.</dd> + <dt>{{jsxref("Array.prototype.lastIndexOf()")}}</dt> + <dd>배열에서 주어진 값과 일치하는 제일 뒤의 인덱스를 반환합니다. 없으면 <code>-1</code>을 반환합니다.</dd> + <dt>{{jsxref("Array.prototype.slice()")}}</dt> + <dd>배열의 일부를 추출한 새 배열을 반환합니다.</dd> + <dt>{{jsxref("Array.prototype.toSource()")}} {{non-standard_inline}}</dt> + <dd>지정한 배열을 나타내는 배열 리터럴을 반환합니다. 새로운 배열을 만들기 위해 이 값을 사용할 수 있습니다. {{jsxref("Object.prototype.toSource()")}} 메서드를 재정의합니다.</dd> + <dt>{{jsxref("Array.prototype.toString()")}}</dt> + <dd>배열과 그 요소를 나타내는 문자열을 반환합니다. {{jsxref("Object.prototype.toString()")}} 메서드를 재정의합니다.</dd> + <dt>{{jsxref("Array.prototype.toLocaleString()")}}</dt> + <dd>배열과 그 요소를 나타내는 지역화된 문자열을 반환합니다. {{jsxref("Object.prototype.toLocaleString()")}} 메서드를 재정의합니다.</dd> +</dl> +</div> + +<h4 id="순회_메서드">순회 메서드</h4> + +<p>배열을 처리하면서 호출할 콜백 함수를 받는 메서드 여럿이 존재합니다. 이런 메서드를 호출하면 배열의 <code>length</code>를 기억하므로, 아직 순회를 끝내지 않았을 때 요소를 더 추가하면 콜백이 방문하지 않습니다.</p> + +<p>요소의 값을 바꾸거나, 요소를 제거하는 등 다른 변경점은 콜백 방문 시점에 따라 최종 값에 영향을 줄 수 있습니다. 비록 이런 동작 방식은 잘 정의되어 있으나, 여러분의 코드를 다른 사람이 읽을 때 헷갈리지 않도록 여기에 의존하면 안됩니다.</p> + +<p>반드시 배열을 변형해야 한다면, 새로운 배열로 복사하세요.</p> + +<div> +<dl> + <dt>{{jsxref("Array.prototype.entries()")}}</dt> + <dd>배열의 각 인덱스에 대한 키/값 쌍을 포함하는 새로운 배열 반복자 객체를 반환합니다.</dd> + <dt>{{jsxref("Array.prototype.every()")}}</dt> + <dd>배열의 모든 요소가 주어진 판별 콜백을 만족할 경우 <code>true</code>를 반환합니다.</dd> + <dt>{{jsxref("Array.prototype.find()")}}</dt> + <dd>주어진 판별 콜백을 만족하는 첫 번째 요소를 반환합니다. 만족하는 요소가 없으면 <code>undefined</code>를 반환합니다.</dd> + <dt>{{jsxref("Array.prototype.findIndex()")}}</dt> + <dd>주어진 판별 콜백을 만족하는 첫 번째 요소의 인덱스를 반환합니다. 만족하는 요소가 없으면 <code>undefined</code>를 반환합니다.</dd> + <dt>{{jsxref("Array.prototype.forEach()")}}</dt> + <dd>배열의 각각의 요소에 대해 콜백을 호출합니다.</dd> + <dt>{{jsxref("Array.prototype.keys()")}}</dt> + <dd>배열의 각 인덱스에 대한 키를 가지는 새로운 배열 반복자 객체를 반환합니다.</dd> + <dt>{{jsxref("Array.prototype.map()")}}</dt> + <dd>배열의 모든 요소 각각에 대하여 주어진 콜백 함수를 호출하고, 그 반환값을 모은 새로운 배열을 반환합니다.</dd> + <dt>{{jsxref("Array.prototype.reduce()")}}</dt> + <dd><span class="short_text" id="result_box" lang="ko"><span>주어진 콜백 함수를 가산기와 요소 각각에 대해 왼쪽에서 오른쪽으로 호출하여 하나의 값으로 줄인(reduce) 결과를 반환합니다.</span></span></dd> + <dt>{{jsxref("Array.prototype.reduceRight()")}}</dt> + <dd><span class="short_text" id="result_box" lang="ko"><span>주어진 콜백 함수를 가산기와 요소 각각에 대해 오른쪽에서 왼쪽으로 호출하여 하나의 값으로 줄인(reduce) 결과를 반환합니다.</span></span></dd> + <dt>{{jsxref("Array.prototype.some()")}}</dt> + <dd>배열의 어떤 요소가 주어진 판별 콜백을 만족할 경우 <code>true</code>를 반환합니다.</dd> + <dt>{{jsxref("Array.prototype.values()")}}</dt> + <dd>배열의 각 인덱스에 대한 값을 가지는 새로운 배열 반복자 객체를 반환합니다.</dd> + <dt>{{jsxref("Array.prototype.@@iterator()", "Array.prototype[@@iterator]()")}}</dt> + <dd>배열의 각 인덱스에 대한 값을 가지는 새로운 배열 반복자 객체를 반환합니다.</dd> +</dl> +</div> + +<h2 id="예제">예제</h2> + +<h3 id="배열_생성">배열 생성</h3> + +<p>아래 예제는 길이 0의 배열 <code>msgArray</code> 을 생성하고, <code>msgArray[0]</code> 와 <code>msgArray[99]</code> 에 값을 할당하여, 배열의 길이를 100으로 변경합니다.</p> + +<pre class="brush: js">let msgArray = [] +msgArray[0] = 'Hello' +msgArray[99] = 'world' + +if (msgArray.length === 100) { + console.log('The length is 100.') +}</pre> + +<h3 id="2차원_배열_생성">2차원 배열 생성</h3> + +<p>아래의 예제는 2차원 문자열 배열로 체스보드를 생성합니다. 첫번째 이동은 (6,4)의 'p'를 (4,4)로 복사하여 이루어집니다. 이전 위치 (6,4)는 빈공간으로 만듭니다.</p> + +<pre class="brush: js">let board = [ + ['R','N','B','Q','K','B','N','R'], + ['P','P','P','P','P','P','P','P'], + [' ',' ',' ',' ',' ',' ',' ',' '], + [' ',' ',' ',' ',' ',' ',' ',' '], + [' ',' ',' ',' ',' ',' ',' ',' '], + [' ',' ',' ',' ',' ',' ',' ',' '], + ['p','p','p','p','p','p','p','p'], + ['r','n','b','q','k','b','n','r'] ] + +console.log(board.join('\n') + '\n\n') + +// Move King's Pawn forward 2 +board[4][4] = board[6][4] +board[6][4] = ' ' +console.log(board.join('\n'))</pre> + +<p>결과는 다음과 같습니다.</p> + +<pre class="eval">R,N,B,Q,K,B,N,R +P,P,P,P,P,P,P,P + , , , , , , , + , , , , , , , + , , , , , , , + , , , , , , , +p,p,p,p,p,p,p,p +r,n,b,q,k,b,n,r + +R,N,B,Q,K,B,N,R +P,P,P,P,P,P,P,P + , , , , , , , + , , , , , , , + , , , ,p, , , + , , , , , , , +p,p,p,p, ,p,p,p +r,n,b,q,k,b,n,r +</pre> + +<h3 id="배열을_사용하여_일련의_값을_테이블처럼_표시하기">배열을 사용하여 일련의 값을 테이블처럼 표시하기</h3> + +<pre class="brush: js">const values = [] +for (let x = 0; x < 10; x++){ + values.push([ + 2 ** x, + 2 * x ** 2 + ]) +} +console.table(values)</pre> + +<p>결과는 다음과 같습니다.</p> + +<pre class="eval line-numbers language-html">0 1 0 +1 2 2 +2 4 8 +3 8 18 +4 16 32 +5 32 50 +6 64 72 +7 128 98 +8 256 128 +9 512 162 +</pre> + +<p>(첫번째 열은 (인덱스))</p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Initial publication</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array-objects', 'Array')}}</td> + <td>ECMAScript 1</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Array")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Indexing_object_properties">JavaScript Guide: “Indexing object properties”</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Predefined_Core_Objects#Array_Object">JavaScript Guide: “Predefined Core Objects: <code>Array</code> Object”</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Array_comprehensions">Array comprehensions</a></li> + <li><a href="https://github.com/plusdude/array-generics">Polyfill for JavaScript 1.8.5 Array Generics and ECMAScript 5 Array Extras</a></li> + <li><a href="/en-US/docs/JavaScript_typed_arrays">Typed Arrays</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/indexof/index.html b/files/ko/web/javascript/reference/global_objects/array/indexof/index.html new file mode 100644 index 0000000000..9748918d5a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/indexof/index.html @@ -0,0 +1,196 @@ +--- +title: Array.prototype.indexOf() +slug: Web/JavaScript/Reference/Global_Objects/Array/indexOf +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/indexOf +--- +<div>{{JSRef}}</div> + +<p><code>indexOf()</code> 메서드는 배열에서 지정된 요소를 찾을 수 있는 첫 번째 인덱스를 반환하고 존재하지 않으면 -1을 반환합니다.</p> + +<div class="blockIndicator note"> +<p><strong>참고</strong>: 문자열은 {{jsxref("String.prototype.indexOf()")}}를 참고하세요.</p> +</div> + +<p>{{EmbedInteractiveExample("pages/js/array-indexof.html")}}</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>arr</var>.indexOf(<var>searchElement[, fromIndex]</var>) +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>searchElement</code></dt> + <dd>배열에서 찾을 요소입니다.</dd> + <dt><code>fromIndex</code> {{optional_inline}}</dt> + <dd>검색을 시작할 색인입니다. 인덱스가 배열의 길이보다 크거나 같은 경우 -1이 반환되므로 배열이 검색되지 않습니다. 제공된 색인 값이 음수이면 배열 끝에서부터의 오프셋 값으로 사용됩니다. 참고 : 제공된 색인이 음수이면 배열은 여전히 앞에서 뒤로 검색됩니다. 계산 된 인덱스가 0보다 작 으면 전체 배열이 검색됩니다. 기본값 : 0 (전체 배열 검색).</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>배열 내의 요소의 최초의 인덱스. 발견되지 않으면 -1.</p> + +<h2 id="설명">설명</h2> + +<p><code>indexOf()</code>는 엄격한 동등성 (<code>===</code> 또는 triple-equals 연산자에서 사용하는 것과 같은 메서드)을 사용하여 검색 요소를 <code>Array</code>의 요소와 비교합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="indexOf_사용하기"><code>indexOf()</code> 사용하기</h3> + +<p>다음 예제에서는 indexOf ()를 사용하여 배열의 값을 찾습니다.</p> + +<pre class="brush: js">var array = [2, 9, 9]; +array.indexOf(2); // 0 +array.indexOf(7); // -1 +array.indexOf(9, 2); // 2 +array.indexOf(2, -1); // -1 +array.indexOf(2, -3); // 0 +</pre> + +<h3 id="요소의_모든_항목_찾기">요소의 모든 항목 찾기</h3> + +<pre class="brush: js">var indices = []; +var array = ['a', 'b', 'a', 'c', 'a', 'd']; +var element = 'a'; +var idx = array.indexOf(element); +while (idx != -1) { + indices.push(idx); + idx = array.indexOf(element, idx + 1); +} +console.log(indices); +// [0, 2, 4] +</pre> + +<h3 id="요소가_배열에_존재하는지_확인하고_배열을_업데이트">요소가 배열에 존재하는지 확인하고 배열을 업데이트</h3> + +<pre class="brush: js">function updateVegetablesCollection (veggies, veggie) { + if (veggies.indexOf(veggie) === -1) { + veggies.push(veggie); + console.log('새로운 veggies 컬렉션 : ' + veggies); + } else if (veggies.indexOf(veggie) > -1) { + console.log(veggie + ' 은 이미 veggies 컬렉션에 존재합니다.'); + } +} + +var veggies = ['potato', 'tomato', 'chillies', 'green-pepper']; + +updateVegetablesCollection(veggies, 'spinach'); +// 새로운 veggies 컬렉션 : potato, tomato, chillies, green-pepper, spinach +updateVegetablesCollection(veggies, 'spinach'); +// spinach 은 이미 veggies 컬렉션에 존재합니다. +</pre> + +<h2 id="폴리필">폴리필</h2> + +<pre class="brush: js">// ECMA-262, 제 5 판, 15.4.4.14의 생산 단계 +// 참조 : http://es5.github.io/#x15.4.4.14 +if (!Array.prototype.indexOf) { + Array.prototype.indexOf = function(searchElement, fromIndex) { + + var k; + + // 1. 이 값을 인수로 전달하는 ToObject를 호출 한 결과를 + // o라고합니다. + if (this == null) { + throw new TypeError('"this" is null or not defined'); + } + + var o = Object(this); + + // 2. lenValue를 Get 함수를 호출 한 결과로 둡니다. + // 인수가 "length"인 o의 내부 메소드. + // 3. len을 ToUint32 (lenValue)로 지정합니다. + var len = o.length >>> 0; + + // 4. len이 0이면 -1을 반환합니다. + if (len === 0) { + return -1; + } + + // 5.Index에서 인수가 전달 된 경우 n을 + // ToInteger (fromIndex); 그렇지 않으면 n은 0이됩니다. + var n = fromIndex | 0; + + // 6. If n >= len, return -1. + if (n >= len) { + return -1; + } + + // 7. n> = 0 인 경우 k를 n이라고 합니다. + // 8. 그렇지 않으면 n <0, k는 len - abs (n)이됩니다. + // k가 0보다 작은 경우 k를 0으로 만듭니다. + k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); + + // 9. k <len 인 동안 반복한다. + while (k < len) { + // a. Pk를 ToString (k)이라고합시다. + // 이것은 in 연산자의 LHS 피연산자에 대해 암시 적입니다. + // b. kPresent를 호출 한 결과라고합시다. + // Hasproperty 인수에 Pk가있는 o의 내부 메소드. + //이 단계는 c와 결합 될 수 있습니다. + // c. kPresent가 참이면 + // i. elementK를 Get을 호출 한 결과로합시다. + // ToString (k) 인수를 가진 o의 내부 메쏘드. + // ii. 적용한 결과와 동일하게 봅시다. + // 엄격한 평등 비교 알고리즘 + // searchElement 및 elementK. + // iii. 동일하면 k를 반환합니다. + if (k in o && o[k] === searchElement) { + return k; + } + k++; + } + return -1; + }; +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.14', 'Array.prototype.indexOf')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.6.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.indexof', 'Array.prototype.indexOf')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.indexof', 'Array.prototype.indexOf')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div> +<p>{{Compat("javascript.builtins.Array.indexOf")}}</p> +</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.lastIndexOf()")}}</li> + <li>{{jsxref("TypedArray.prototype.indexOf()")}}</li> + <li>{{jsxref("String.prototype.indexOf()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/isarray/index.html b/files/ko/web/javascript/reference/global_objects/array/isarray/index.html new file mode 100644 index 0000000000..0a3a074a3d --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/isarray/index.html @@ -0,0 +1,131 @@ +--- +title: Array.isArray() +slug: Web/JavaScript/Reference/Global_Objects/Array/isArray +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Reference + - polyfill + - 자바스크립트 + - 폴리필 +translation_of: Web/JavaScript/Reference/Global_Objects/Array/isArray +--- +<div>{{JSRef}}</div> + +<p><code><strong>Array.isArray()</strong></code> 메서드는 인자가 {{jsxref("Array")}}인지 판별합니다.</p> + +<pre><code>Array.isArray([1, 2, 3]); // true +Array.isArray({foo: 123}); // false +Array.isArray('foobar'); // false +Array.isArray(undefined); // false</code> +</pre> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code>Array.isArray(<var>obj</var>)</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>검사할 객체.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>객체가 {{jsxref("Array")}}라면 <code>true</code>, 아니라면 <code>false</code>.</p> + +<h2 id="설명">설명</h2> + +<p>객체가 {{jsxref("Array")}}라면 <code>true</code>를 반환하고, 아니라면 <code>false</code>를 반환합니다.</p> + +<p>자세한 정보는 <a href="http://web.mit.edu/jwalden/www/isArray.html">“Determining with absolute accuracy whether or not a JavaScript object is an array”</a>(자바스크립트 객체가 배열인지 정확히 판별하는 방법) 문서를 참조하세요.</p> + +<h2 id="예제">예제</h2> + +<pre><code>// 모두 true 반환 +Array.isArray([]); +Array.isArray([1]); +Array.isArray(new Array()); +Array.isArray(new Array('a', 'b', 'c', 'd')); +Array.isArray(new Array(3)); +// Array.prototype은 스스로도 배열입니다 +Array.isArray(Array.prototype); + +// 모두 false 반환 +Array.isArray(); +Array.isArray({}); +Array.isArray(null); +Array.isArray(undefined); +Array.isArray(17); +Array.isArray('Array'); +Array.isArray(true); +Array.isArray(false); +Array.isArray({ __proto__: Array.prototype });</code></pre> + +<h3 id="instanceof_vs_isArray"><code>instanceof</code> vs <code>isArray</code></h3> + +<p><code>Array</code> 객체를 판별할 때, <code>Array.isArray</code>는 <code>iframe</code>을 통해서도 작동하기 때문에 <code>instanceof</code> 보다 적합합니다.</p> + +<pre><code>var iframe = document.createElement('iframe'); +document.body.appendChild(iframe); +xArray = window.frames[window.frames.length-1].Array; +var arr = new xArray(1,2,3); // [1,2,3] + +// 올바른 Array 판별 +Array.isArray(arr); // true +// iframe을 통해서 작동하지 않기 때문에 올바르지 않은 방법 +arr instanceof Array; // false</code> +</pre> + +<h2 id="폴리필">폴리필</h2> + +<p>아래 코드를 실행하면 지원하지 않는 환경에서도 <code>Array.isArray()</code>를 사용할 수 있습니다.</p> + +<pre class="brush: js">if (!Array.isArray) { + Array.isArray = function(arg) { + return Object.prototype.toString.call(arg) === '[object Array]'; + }; +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">주석</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.3.2', 'Array.isArray')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>초안. 자바스크립트 1.8.5 에 구현됨.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.isarray', 'Array.isArray')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> + <p> </p> + </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.isarray', 'Array.isArray')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.Array.isArray")}}</div> + +<h2 id="참고">참고</h2> + +<ul> + <li>{{jsxref("Array")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/join/index.html b/files/ko/web/javascript/reference/global_objects/array/join/index.html new file mode 100644 index 0000000000..7a78c568ab --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/join/index.html @@ -0,0 +1,91 @@ +--- +title: Array.prototype.join() +slug: Web/JavaScript/Reference/Global_Objects/Array/join +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/join +--- +<div>{{JSRef}}</div> + +<p><code><strong>join()</strong></code> 메서드는 배열의 모든 요소를 연결해 하나의 문자열로 만듭니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/array-join.html")}}</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>arr</var>.join([<var>separator</var>])</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>separator</code> {{optional_inline}}</dt> + <dd>배열의 각 요소를 구분할 문자열을 지정합니다. 이 구분자는 필요한 경우 문자열로 변환됩니다. 생략하면 배열의 요소들이 쉼표로 구분됩니다. <code>separator</code>가 빈 문자열이면 모든 요소들이 사이에 아무 문자도 없이 연결됩니다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>배열의 모든 요소들을 연결한 하나의 문자열을 반환합니다. 만약 <code><em>arr</em>.length</code> 가 <code>0</code>이라면, 빈 문자열을 반환합니다.</p> + +<h2 id="설명">설명</h2> + +<p>모든 배열 요소가 문자열로 변환된 다음 하나의 문자열로 연결됩니다.</p> + +<div class="blockIndicator warning"> +<p>요소가 <code>undefined</code> 또는 <code>null</code>이면 빈 문자열로 변환합니다.</p> +</div> + +<h2 id="예제">예제</h2> + +<h3 id="네_가지_다른_방법으로_배열_연결하기">네 가지 다른 방법으로 배열 연결하기</h3> + +<p>다음 예제에서는 3개의 요소를 가진 배열 <code>a</code>를 만들고, 기본 구분자, 쉼표와 공백, 더하기 기호, 빈 문자열의 네 가지 구분자를 사용해 배열을 연결합니다.</p> + +<pre class="brush: js">var a = ['바람', '비', '불']; +var myVar1 = a.join(); // myVar1에 '바람,비,불'을 대입 +var myVar2 = a.join(', '); // myVar2에 '바람, 비, 불'을 대입 +var myVar3 = a.join(' + '); // myVar3에 '바람 + 비 + 불'을 대입 +var myVar4 = a.join(''); // myVar4에 '바람비불'을 대입 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">표준</th> + <th scope="col">상태</th> + <th scope="col">비고</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>최초 정의. JavaScript 1.1에 구현됨.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.5', 'Array.prototype.join')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.join', 'Array.prototype.join')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.Array.join")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("String.prototype.split()")}}</li> + <li>{{jsxref("Array.prototype.toString()")}}</li> + <li>{{jsxref("TypedArray.prototype.join()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/keys/index.html b/files/ko/web/javascript/reference/global_objects/array/keys/index.html new file mode 100644 index 0000000000..4afb826a3e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/keys/index.html @@ -0,0 +1,69 @@ +--- +title: Array.prototype.keys() +slug: Web/JavaScript/Reference/Global_Objects/Array/keys +tags: + - Array + - ECMAScript 2015 + - Iterator + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/keys +--- +<div>{{JSRef}}</div> + +<p><code><strong>keys()</strong></code> 메서드는 배열의 각 인덱스를 키 값으로 가지는 새로운 <code><strong>Array Iterator</strong></code> 객체를 반환합니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/array-keys.html")}}</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>arr</var>.keys()</code></pre> + +<h3 id="반환_값">반환 값</h3> + +<p>새로운 {{jsxref("Array")}} 반복기 객체.</p> + +<h2 id="예제">예제</h2> + +<h3 id="키_반복기는_빈_인덱스를_무시하지_않음">키 반복기는 빈 인덱스를 무시하지 않음</h3> + +<pre><code>var arr = ['a', , 'c']; +var sparseKeys = Object.keys(arr); +var denseKeys = [...arr.keys()]; +console.log(sparseKeys); // ['0', '2'] +console.log(denseKeys); // [0, 1, 2]</code></pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.keys', 'Array.prototype.keys')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.keys', 'Array.prototype.keys')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.Array.keys")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.values()")}}</li> + <li>{{jsxref("Array.prototype.entries()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/lastindexof/index.html b/files/ko/web/javascript/reference/global_objects/array/lastindexof/index.html new file mode 100644 index 0000000000..7e1519ae78 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/lastindexof/index.html @@ -0,0 +1,103 @@ +--- +title: Array.prototype.lastIndexOf() +slug: Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf +--- +<div>{{JSRef}}</div> + +<p><strong><code>lastIndexOf()</code></strong> 메서드는 배열에서 주어진 값을 발견할 수 있는 마지막 인덱스를 반환하고, 요소가 존재하지 않으면 -1을 반환합니다. 배열 탐색은 <code>fromIndex</code>에서 시작하여 뒤로 진행합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-lastindexof.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>arr</var>.lastIndexOf(<var>searchElement[</var>, <var>fromIndex]</var>)</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>searchElement</code></dt> + <dd>배열에서 찾을 요소.</dd> + <dt><code>fromIndex</code> {{optional_inline}}</dt> + <dd>역순으로 검색을 시작할 인덱스. 배열의 길이에서 1을 뺀 값(<code>arr.length - 1</code>)이 기본값이므로 지정하지 않을 경우 전체 배열을 검색합니다. 주어진 값이 배열의 길이 이상이면 전체 배열을 검색합니다. 값이 음수인 경우, 배열의 마지막부터 시작하는 인덱스로 처리합니다. 다만, 음수를 제공하더라도 검색 순서는 뒤에서 앞입니다. 위의 모든 절차를 거친 최종 계산값이 0 미만인 경우, <code>lastIndexOf()</code>는 항상 -1을 반환합니다. 즉, 배열을 탐색하지 않습니다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 값과 일치하는 마지막 요소의 인덱스, 없으면 -1.</p> + +<h2 id="설명">설명</h2> + +<p><code>lastIndexOf</code>는 일치 연산(<code>===</code> 연산자와 동일)을 사용해 <code>searchElement</code>와 각 요소를 비교합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="lastIndexOf_사용하기"><code>lastIndexOf</code> 사용하기</h3> + +<p>다음 예제에서는 <code>lastIndexOf</code>를 사용하여 배열의 값을 찾습니다.</p> + +<pre class="brush: js">var array = [2, 5, 9, 2]; +array.lastIndexOf(2); // 3 +array.lastIndexOf(7); // -1 +array.lastIndexOf(2, 3); // 3 +array.lastIndexOf(2, 2); // 0 +array.lastIndexOf(2, -2); // 0 +array.lastIndexOf(2, -1); // 3 +</pre> + +<h3 id="요소의_모든_항목_찾기">요소의 모든 항목 찾기</h3> + +<p>다음 예제에서는 <code>lastIndexOf</code>를 사용하여 {{jsxref("Array.prototype.push", "push")}}를 사용하여 지정된 배열의 요소 색인을 모두 찾아서 다른 배열에 추가합니다.</p> + +<pre class="brush: js">var indices = []; +var array = ['a', 'b', 'a', 'c', 'a', 'd']; +var element = 'a'; +var idx = array.lastIndexOf(element); +while (idx != -1) { + indices.push(idx); + idx = (idx > 0 ? array.lastIndexOf(element, idx - 1) : -1); +} + +console.log(indices); +// [4, 2, 0] +</pre> + +<p>배열의 첫 번째 요소 인 경우 요소가 fromIndex 매개 변수와 관계없이 항상 발견되므로 idx == 0 사례를 여기에서 개별적으로 처리해야합니다. 이는 {{jsxref ( "Array.prototype.indexOf", "indexOf")}} 메소드와 다릅니다.</p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.lastindexof', 'Array.prototype.lastIndexOf')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.Array.lastIndexOf")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.indexOf()")}}</li> + <li>{{jsxref("TypedArray.prototype.lastIndexOf()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/length/index.html b/files/ko/web/javascript/reference/global_objects/array/length/index.html new file mode 100644 index 0000000000..b241e88045 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/length/index.html @@ -0,0 +1,135 @@ +--- +title: Array.length +slug: Web/JavaScript/Reference/Global_Objects/Array/length +tags: + - Array + - JavaScript + - Property + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/length +--- +<div>{{JSRef}}</div> + +<p><code>Array</code> 인스턴스의 <code><strong>length</strong></code> 속성은 배열의 길이를 반환합니다. 반환값은 부호 없는 32비트 정수형이며, 배열의 최대 인덱스보다 항상 큽니다. <strong><code>length</code></strong> 속성에 값을 설정할 경우 배열의 길이를 변경합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-length.html")}}</div> + + + +<h2 id="설명">설명</h2> + +<p><code>length</code> 속성의 값은 양의 정수이며 2<sup>32</sup> 미만의 값을 가집니다.</p> + +<pre class="brush: js line-numbers language-js">var namelistA = new Array(4294967296); // 2의 32제곱 = 4294967296 +var namelistC = new Array(-100) // 음수 + +console.log(namelistA.length); // RangeError: Invalid array length +console.log(namelistC.length); // RangeError: Invalid array length + +var namelistB = []; +namelistB.length = Math.pow(2,32)-1; // 길이를 2의 32제곱 미만으로 설정 +console.log(namelistB.length); + +// 4294967295</pre> + +<p>아무 때나 <code>length</code> 속성에 값을 설정해 배열을 절단할 수 있습니다. <code>length</code> 속성으로 배열의 길이를 늘리면 실제 원소의 수가 증가합니다. 예를 들어 길이가 2인 배열의 <code>length</code>를 3으로 설정한다면 마지막에 <code>undefined</code>가 추가돼 총 3개의 요소를 갖게 됩니다.</p> + +<pre class="brush: js line-numbers language-js">var arr = [1, 2, 3]; +printEntries(arr); + +arr.length = 5; // set array length to 5 while currently 3. +printEntries(arr); + +function printEntries(arr) { + var length = arr.length; + for (var i = 0; i < length; i++) { + console.log(arr[i]); + } + console.log('=== printed ==='); +} + +// 1 +// 2 +// 3 +// === printed === +// 1 +// 2 +// 3 +// undefined +// undefined +// === printed === +</pre> + +<p>그러나 <code>length</code> 속성의 값이 꼭 배열에 정의된 원소의 수를 나타내진 않습니다. <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Array#length_%EC%99%80_%EC%88%AB%EC%9E%90%ED%98%95_%EC%86%8D%EC%84%B1%EC%9D%98_%EA%B4%80%EA%B3%84"><code>length</code>와 숫자형 속성의 관계</a>를 참고하세요.</p> + +<p>{{js_property_attributes(1, 0, 0)}}</p> + +<h2 id="예제">예제</h2> + +<h3 id="배열_순회">배열 순회</h3> + +<p>다음 예제는 <code>numbers</code> 배열을 length 속성의 크기만큼 순회합니다. 각 원소의 값은 두 배가 됩니다.</p> + +<pre class="brush: js line-numbers language-js">var numbers = [1, 2, 3, 4, 5]; +var length = numbers.length; +for (var i = 0; i < length; i++) { + numbers[i] *= 2; +} +// numbers is now [2, 4, 6, 8, 10] +</pre> + +<h3 id="배열_단축">배열 단축</h3> + +<p>다음 예제는 <code>numbers</code> 배열의 현재 길이가 3보다 클 경우 3으로 줄입니다.</p> + +<pre class="brush: js line-numbers language-js">var numbers = [1, 2, 3, 4, 5]; + +if (numbers.length > 3) { + numbers.length = 3; +} + +console.log(numbers); // [1, 2, 3] +console.log(numbers.length); // 3 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.5.2', 'Array.length')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-properties-of-array-instances-length', 'Array.length')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-properties-of-array-instances-length', 'Array.length')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.Array.length")}}</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/map/index.html b/files/ko/web/javascript/reference/global_objects/array/map/index.html new file mode 100644 index 0000000000..b3f494a8e3 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/map/index.html @@ -0,0 +1,293 @@ +--- +title: Array.prototype.map() +slug: Web/JavaScript/Reference/Global_Objects/Array/map +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/map +--- +<div>{{JSRef}}</div> + +<p><code><strong>map()</strong></code> 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환합니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/array-map.html")}}</p> + +<h2 id="Syntax" name="Syntax">구문</h2> + +<pre class="syntaxbox"><code><var>arr</var>.map(<var>callback(currentValue</var>[, index[, array]])[, <var>thisArg</var>])</code></pre> + +<h3 id="Parameters" name="Parameters">매개변수</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>새로운 배열 요소를 생성하는 함수. 다음 세 가지 인수를 가집니다.</dd> + <dd> + <dl> + <dt><code>currentValue</code></dt> + <dd>처리할 현재 요소.</dd> + <dt><code>index</code> {{optional_inline}}</dt> + <dd>처리할 현재 요소의 인덱스.</dd> + <dt><code>array</code> {{optional_inline}}</dt> + <dd><code>map()</code>을 호출한 배열.</dd> + </dl> + </dd> + <dt><code>thisArg</code> {{optional_inline}}</dt> + <dd><code>callback</code>을 실행할 때 <code>this</code>로 사용되는 값.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>배열의 각 요소에 대해 실행한 <code>callback</code>의 결과를 모은 새로운 배열.</p> + +<h2 id="Description" name="Description">설명</h2> + +<p><code>map</code>은 <code>callback</code> 함수를 <strong>각각의 요소에 대해 한번씩 </strong>순서대로 불러 그 함수의 반환값으로 새로운 배열을 만듭니다. <code>callback</code> 함수는 ({{jsxref("undefined")}}도 포함해서) 배열 값이 들어있는 인덱스에 대해서만 호출됩니다. 즉, 값이 삭제되거나 아직 값이 할당/정의되지 않은 인덱스에 대해서는 호출되지 않습니다.</p> + +<p><code>callback</code> 함수는 호출될 때 대상 요소의 값, 그 요소의 인덱스, 그리고 <code>map</code>을 호출한 원본 배열<span style="font-family: courier,andale mono,monospace;"> </span>3개의 인수를 전달받습니다.</p> + +<p><code>thisArg</code> 매개변수가 <code>map</code>에 전달된 경우 <code>callback</code> 함수의 <code>this</code>값으로 사용됩니다. 그 외의 경우 {{jsxref("undefined")}}값이 <code>this</code> 값으로 사용됩니다.<font face="Consolas, Liberation Mono, Courier, monospace"> </font><code>callback</code> 함수에서 최종적으로 볼 수 있는 <code>this</code> 값은 <a href="/ko/docs/Web/JavaScript/Reference/Operators/this">함수 내 <code>this</code>를 정하는 일반적인 규칙</a>에 따라 결정됩니다.</p> + +<p><code>map</code>은 호출한 배열의 값을 변형하지 않습니다. 단, <code>callback</code> 함수에 의해서 변형될 수는 있습니다.</p> + +<p><code>map</code>이 처리할 요소의 범위는 첫 <code>callback</code>을 호출하기 전에 정해집니다. <code>map</code>이 시작한 이후 배열에 추가되는 요소들은 <code>callback</code>을 호출하지 않습니다. 배열에 존재하는 요소들의 값이 바뀐 경우 <code>map</code>이 방문하는 시점의 값이 <code>callback</code>에 전달됩니다. <code>map</code>이 시작되고, 방문하기 전에 삭제된 요소들은 방문하지 않습니다.</p> + +<p>명세서에 정의된 알고리즘으로 인해 <code>map</code>을 호출한 배열의 중간이 비어있는 경우, 결과 배열 또한 동일한 인덱스를 빈 값으로 유지합니다.</p> + +<h2 id="Examples" name="Examples">예제</h2> + +<h3 id="Example_Mapping_an_array_of_numbers_to_an_array_of_square_roots" name="Example:_Mapping_an_array_of_numbers_to_an_array_of_square_roots">배열에 들어있는 숫자들의 제곱근을 구하여 새로운 배열을 만들기</h3> + +<p>다음 코드는 숫자의 배열을 받아 각 숫자들의 제곱근이 들어있는 새로운 배열을 만듭니다.</p> + +<pre class="brush: js">var numbers = [1, 4, 9]; +var roots = numbers.map(Math.sqrt); +// roots는 [1, 2, 3] +// numbers는 그대로 [1, 4, 9] +</pre> + +<h3 id="Example_Using_map_to_reformat_objects_in_an_array" name="Example:_Using_map_to_reformat_objects_in_an_array"><code>map</code>을 활용해 배열 속 객체를 재구성하기</h3> + +<p>다음 코드는 오브젝트의 배열을 받아 각 오브젝트를 다른 형태으로 재구성해 새로운 배열을 만듭니다.</p> + +<pre class="brush: js">var kvArray = [{key:1, value:10}, + {key:2, value:20}, + {key:3, value: 30}]; + +var reformattedArray = kvArray.map(function(obj){ + var rObj = {}; + rObj[obj.key] = obj.value; + return rObj; +}); +// reformattedArray는 [{1:10}, {2:20}, {3:30}] + +// kvArray는 그대로 +// [{key:1, value:10}, +// {key:2, value:20}, +// {key:3, value: 30}] +</pre> + +<h3 id="Example_Mapping_an_array_of_numbers_using_a_function_containing_an_argument" name="Example:_Mapping_an_array_of_numbers_using_a_function_containing_an_argument">인자를 받는 함수를 사용하여 숫자 배열 재구성하기</h3> + +<p>다음 코드는 인자가 한개인 함수를 이용하여 map이 어떻게 동작하는지 나타냅니다. 인자인 배열과 안의 요소들은 map을 통해 순회하면서 원본 배열로 부터 자동으로 할당됩니다.</p> + +<pre class="brush: js">var numbers = [1, 4, 9]; +var doubles = numbers.map(function(num) { + return num * 2; +}); +// doubles는 이제 [2, 8, 18] +// numbers는 그대로 [1, 4, 9] +</pre> + +<h3 id="Example_using_map_generically" name="Example:_using_map_generically"><code>map</code>을 포괄적으로 사용하기</h3> + +<p>아래 예제는 {{jsxref("Global_Objects/String", "String")}}에 map을 사용해서 각 문자의 ASCII 인코딩 값을 요소로 갖는 배열을 얻는 방법을 보여줍니다.</p> + +<pre class="brush: js">var map = Array.prototype.map; +var a = map.call('Hello World', function(x) { return x.charCodeAt(0); }); +// a는 이제 [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100] +</pre> + +<h3 id="Example_using_map_generically_querySelectorAll" name="Example:_using_map_generically_querySelectorAll"><code>map</code>을 포괄적으로 사용하기 (<code>querySelectorAll</code>)</h3> + +<p>아래 예제는 <code>querySelectorAll</code>을 사용해서 수집된 객체들을 순회 처리하는 법을 보여줍니다. 이번 경우 체크한 옵션 박스를 콘솔에 프린트합니다.</p> + +<pre class="brush: js">var elems = document.querySelectorAll('select option:checked'); +var values = [].map.call(elems, function(obj) { + return obj.value; +}); +</pre> + +<p>더 쉬운 방법은 {{jsxref("Array.from()")}}을 사용하는 것입니다.</p> + +<h3 id="Example_Tricky_use_case" name="Example:_Tricky_use_case">까다로운 사례</h3> + +<p><a href="http://www.wirfs-brock.com/allen/posts/166">(참고한 블로그 포스트)</a></p> + +<p><code>map</code>에 하나의 인자(순회하는 원소)만 받는 콜백을 사용하는 경우가 많습니다. 그러나 어떤 함수는 대개 하나의 인자로 호출하지만 두 개 이상의 인자를 사용하는 경우도 있습니다. 이로 인해 어떤 경우 혼란스러울 수도 있습니다.</p> + +<pre class="brush: js">// 아래 라인을 보시면... +['1', '2', '3'].map(parseInt); +// 결과를 [1, 2, 3] 으로 기대할 수 있습니다. +// 그러나 실제 결과는 [1, NaN, NaN] 입니다. + +// parseInt 함수는 보통 하나의 인자만 사용하지만, 두 개를 받을 수 있습니다. +// 첫 번째 인자는 변환하고자 하는 표현이고 두 번째는 숫자로 변환할 때 사용할 진법입니다. +// Array.prototype.map은 콜백에 세 가지 인자를 전달합니다. +// 배열의 값, 값의 인덱스, 그리고 배열 +// 세 번째 인자는 parseInt가 무시하지만 두 번째 인자는 아닙니다. +// 따라서 혼란스러운 결과를 도출할 수 있습니다. 자세한 내용은 블로그 포스트를 참고하시길 바랍니다. + +function returnInt(element) { + return parseInt(element, 10); +} + +['1', '2', '3'].map(returnInt); // [1, 2, 3] +// 실제 결과가 예상한 대로 배열의 숫자와 같습니다. + +// 위와 같지만 더 간단한 화살표 표현식 +['1', '2', '3'].map(str => parseInt(str)); + +// 더 간단하게 해결할 수 있는 방법 +['1', '2', '3'].map(Number); // [1, 2, 3] +// 그러나 `parseInt`와 달리 float이나 지수표현도 반환합니다. +['1.1', '2.2e2', '3e300'].map(Number); // [1.1, 220, 3e+300] +</pre> + +<h2 id="Polyfill" name="Polyfill">폴리필</h2> + +<p><font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">map</span></font>은 ECMA-262 표준 제5판에 추가됐습니다. 따라서 어떤 표준 구현체에서는 사용할 수 없을 수도 있습니다. 다른 모든 코드 이전에 아래 코드를 포함하면 지원하지 않는 플랫폼에서도 <code>map</code>을 사용할 수 있습니다. 아래 알고리즘은 {{jsxref("Object")}}, {{jsxref("TypeError")}}, {{jsxref("Array")}}가 변형되지 않고, <code>callback.call</code>의 계산 값이 원래의 {{jsxref("Function.prototype.call()")}}과 같은 경우 ECMA-262 제5판이 명시한 것과 동일합니다.</p> + +<pre class="brush: js">// Production steps of ECMA-262, Edition 5, 15.4.4.19 +// Reference: http://es5.github.io/#x15.4.4.19 +if (!Array.prototype.map) { + + Array.prototype.map = function(callback, thisArg) { + + var T, A, k; + + if (this == null) { + throw new TypeError(' this is null or not defined'); + } + + // 1. Let O be the result of calling ToObject passing the |this| + // value as the argument. + var O = Object(this); + + // 2. Let lenValue be the result of calling the Get internal + // method of O with the argument "length". + // 3. Let len be ToUint32(lenValue). + var len = O.length >>> 0; + + // 4. If IsCallable(callback) is false, throw a TypeError exception. + // See: http://es5.github.com/#x9.11 + if (typeof callback !== 'function') { + throw new TypeError(callback + ' is not a function'); + } + + // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. + if (arguments.length > 1) { + T = thisArg; + } + + // 6. Let A be a new array created as if by the expression new Array(len) + // where Array is the standard built-in constructor with that name and + // len is the value of len. + A = new Array(len); + + // 7. Let k be 0 + k = 0; + + // 8. Repeat, while k < len + while (k < len) { + + var kValue, mappedValue; + + // a. Let Pk be ToString(k). + // This is implicit for LHS operands of the in operator + // b. Let kPresent be the result of calling the HasProperty internal + // method of O with argument Pk. + // This step can be combined with c + // c. If kPresent is true, then + if (k in O) { + + // i. Let kValue be the result of calling the Get internal + // method of O with argument Pk. + kValue = O[k]; + + // ii. Let mappedValue be the result of calling the Call internal + // method of callback with T as the this value and argument + // list containing kValue, k, and O. + mappedValue = callback.call(T, kValue, k, O); + + // iii. Call the DefineOwnProperty internal method of A with arguments + // Pk, Property Descriptor + // { Value: mappedValue, + // Writable: true, + // Enumerable: true, + // Configurable: true }, + // and false. + + // In browsers that support Object.defineProperty, use the following: + // Object.defineProperty(A, k, { + // value: mappedValue, + // writable: true, + // enumerable: true, + // configurable: true + // }); + + // For best browser support, use the following: + A[k] = mappedValue; + } + // d. Increase k by 1. + k++; + } + + // 9. return A + return A; + }; +} +</pre> + +<h2 id="Specifications" name="Specifications">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.19', 'Array.prototype.map')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.6.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.map', 'Array.prototype.map')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.map', 'Array.prototype.map')}}</td> + <td></td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.Array.map")}}</div> + +<h2 id="See_also" name="See_also">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.forEach()")}}</li> + <li>{{jsxref("Map")}} 객체</li> + <li>{{jsxref("Array.from()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/observe/index.html b/files/ko/web/javascript/reference/global_objects/array/observe/index.html new file mode 100644 index 0000000000..015ae049c5 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/observe/index.html @@ -0,0 +1,87 @@ +--- +title: Array.observe() +slug: Web/JavaScript/Reference/Global_Objects/Array/observe +tags: + - Array + - JavaScript + - Method + - Obsolete +translation_of: Archive/Web/JavaScript/Array.observe +--- +<div>{{JSRef}} {{obsolete_header}}</div> + +<p><strong><code>Array.observe()</code> </strong>메서드는 {{jsxref("Object.observe()")}}가 객체를 관찰하는 것과 비슷하게 , 배열의 변화를 비동기 적으로 관찰 하는데 사용 되었습니다. <font face="Consolas, Liberation Mono, Courier, monospace">그것은 </font>발생 순서에 따른 변화의 흐름을 제공합니다. <code>Object.observe()</code>가 accept type list <code>["add", "update", "delete", "splice"]</code>와 함께 호출되는 것과 같습니다. 하지만 이 API는 더이상 사용되지 않고 브라우저에서 제거 되었습니다. 대신, 더 일반적인 {{jsxref("Proxy")}} 객체를 사용하세요.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">Array.observe(<var>arr</var>, <var>callback</var>)</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>arr</code></dt> + <dd>관찰 할 배열</dd> + <dt><code>callback</code></dt> + <dd>이 함수는 변화가 일어날때 마다 다음과 같은 인수와 함께 호출됩니다. + <dl> + <dt><code>changes</code></dt> + <dd>변경을 나타내는 각 객체들의 배열입니다. 이 변경 객체들의 프로퍼티 들은: + <ul> + <li><strong><code>name</code></strong>: 변경된 프로퍼티의 이름</li> + <li><strong><code>object</code></strong>: 변경 후 배열</li> + <li><strong><code>type</code></strong>: 변경 타입을 나타내는 문자. <code>"add"</code>, <code>"update"</code>, <code>"delete"</code>, 또는 <code>"splice" 중 하나</code>.</li> + <li><strong><code>oldValue</code></strong>: <code>"update"</code> 나 <code>"delete"유형에만 해당합니다. 변경 전 값</code>.</li> + <li><strong><code>index</code></strong>: <code>"splice"유형에만 해당합니다</code>. 변경이 발생한 인덱스.</li> + <li><strong><code>removed</code></strong>: <code>"splice"유형에만 해당합니다</code>. 삭제 된 요소들의 배열.</li> + <li><strong><code>addedCount</code></strong>: <code>"splice"유형에만 해당합니다</code>. 추가 된 요소들의 숫자.</li> + </ul> + </dd> + </dl> + </dd> +</dl> + +<h2 id="설명">설명</h2> + +<p>콜백 함수는 arr이 변경 될 때마다 호출되며 발생하는 순서대로 모든 변경 사항의 배열로 호출됩니다</p> + +<div class="note"> +<p><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop">Array.prototype.pop()</a>이</code> <code>"splice"</code> 변경으로 보고되는 것처럼, 변경은 배열 메서드를 통해 일어납니다. 배열 길이를 변경하지 않는 인덱스 할당 변경은 "update" 변경으로 보고 될 수 있습니다.</p> +</div> + +<h2 id="예제">예제</h2> + +<h3 id="다른_변경_유형_로깅(Logging)">다른 변경 유형 로깅(Logging)</h3> + +<pre class="brush: js">var arr = ['a', 'b', 'c']; + +Array.observe(arr, function(changes) { + console.log(changes); +}); + +arr[1] = 'B'; +// [{type: 'update', object: <arr>, name: '1', oldValue: 'b'}] + +arr[3] = 'd'; +// [{type: 'splice', object: <arr>, index: 3, removed: [], addedCount: 1}] + +arr.splice(1, 2, 'beta', 'gamma', 'delta'); +// [{type: 'splice', object: <arr>, index: 1, removed: ['B', 'c'], addedCount: 3}] +</pre> + +<h2 id="명세">명세</h2> + +<p><a href="https://github.com/arv/ecmascript-object-observe">Strawman proposal specification</a>.</p> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Array.observe")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="//stackoverflow.com/q/29269057/778272">Under what condition would Array.observe's “add” event trigger?</a></li> + <li>{{jsxref("Array.unobserve()")}} {{obsolete_inline}}</li> + <li>{{jsxref("Object.observe()")}} {{obsolete_inline}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/of/index.html b/files/ko/web/javascript/reference/global_objects/array/of/index.html new file mode 100644 index 0000000000..edcd9bddc5 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/of/index.html @@ -0,0 +1,104 @@ +--- +title: Array.of() +slug: Web/JavaScript/Reference/Global_Objects/Array/of +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Method + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/of +--- +<div>{{JSRef}}</div> + +<p><code><strong>Array.of()</strong></code> 메서드는 인자의 수나 유형에 관계없이 가변 인자를 갖는 새 <code>Array</code> 인스턴스를 만듭니다.</p> + +<p><code>Array.of()</code>와 <code>Array</code> 생성자의 차이는 정수형 인자의 처리 방법에 있습니다. <code>Array.of(7)</code>은 하나의 요소 <code>7</code>을 가진 배열을 생성하지만 <code>Array(7)</code>은 <code>length</code> 속성이 7인 빈 배열을 생성합니다.</p> + +<pre class="brush: js">Array.of(7); // [7] +Array.of(1, 2, 3); // [1, 2, 3] + +Array(7); // [ , , , , , , ] +Array(1, 2, 3); // [1, 2, 3] +</pre> + +<h2 id="Syntax" name="Syntax">구문</h2> + +<pre class="syntaxbox">Array.of(<var>element0</var>[, <var>element1</var>[, ...[, <var>elementN</var>]]])</pre> + +<h3 id="Parameters" name="Parameters">매개변수</h3> + +<dl> + <dt><code>element<em>N</em></code></dt> + <dd>배열을 생성할 때 사용할 요소.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>새로운 {{jsxref("Array")}} 객체.</p> + +<h2 id="Description" name="Description">설명</h2> + +<p>이 함수는 ECMAScript 2015 표준 일부입니다. 자세한 정보는 <a href="https://gist.github.com/rwaldron/1074126"><code>Array.of</code>, <code>Array.from</code> 제안 사항</a>과 <a href="https://gist.github.com/rwaldron/3186576"><code>Array.of</code> 폴리필</a>에서 확인하실 수 있습니다.</p> + +<h2 id="Examples" name="Examples">예제</h2> + +<pre class="brush: js">Array.of(1); // [1] +Array.of(1, 2, 3); // [1, 2, 3] +Array.of(undefined); // [undefined] +</pre> + +<h2 id="Polyfill" name="Polyfill">폴리필</h2> + +<p>아래 코드를 다른 코드 이전에 포함하면 <code>Array.of</code>를 지원하지 않는 환경에서도 사용할 수 있습니다.</p> + +<pre class="brush: js">if (!Array.of) { + Array.of = function() { + return Array.prototype.slice.call(arguments); + }; +} +</pre> + +<h2 id="Specifications" name="Specifications">명세</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ES2015', '#sec-array.of', 'Array.of')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.of', 'Array.of')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<p> </p> + +<p> </p> + +<p> </p> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</div> + +<p>{{Compat("javascript.builtins.Array.of")}}</p> + +<h2 id="See_also" name="See_also">같이 보기</h2> + +<ul> + <li>{{jsxref("Array")}}</li> + <li>{{jsxref("Array.from()")}}</li> + <li>{{jsxref("TypedArray.of()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/pop/index.html b/files/ko/web/javascript/reference/global_objects/array/pop/index.html new file mode 100644 index 0000000000..d02df55262 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/pop/index.html @@ -0,0 +1,91 @@ +--- +title: Array.prototype.pop() +slug: Web/JavaScript/Reference/Global_Objects/Array/pop +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/pop +--- +<div>{{JSRef}}</div> + +<p><code><strong>pop()</strong></code> 메서드는 배열에서 <strong>마지막</strong> 요소를 제거하고 그 요소를 반환합니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/array-pop.html")}}</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>arr</var>.pop()</code></pre> + +<h3 id="반환_값">반환 값</h3> + +<p>배열에서 제거한 요소. 빈 배열의 경우 {{jsxref("undefined")}} 를 반환합니다.</p> + +<h2 id="설명">설명</h2> + +<p><code>pop</code> 메서드는 배열에서 마지막 요소를 제거하여 그 값을 호출자(caller)에게 반환합니다.</p> + +<p><code>pop</code>은 일부러 일반(generic)입니다; 이 메서드는 배열을 닮은 객체에 {{jsxref("Function.call", "호출", "", 1)}} 또는 {{jsxref("Function.apply", "적용", "", 1)}}될 수 있습니다. 0부터 시작하는 일련의 연속되는 숫자 속성 내 마지막을 반영하는 <code>length</code> 속성을 포함하지 않는 객체는 어떤 의미 있는 방식으로도 행동하지 않을 수 있습니다.</p> + +<p>빈 배열에 <code>pop()</code>을 호출하면, {{jsxref("undefined")}}를 반환합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="배열의_마지막_요소_제거">배열의 마지막 요소 제거</h3> + +<p>다음 코드는 요소 넷을 포함하는 <code>myFish</code> 배열을 생성하고 그 마지막 요소를 제거합니다.</p> + +<pre><code>var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; + +var popped = myFish.pop(); + +console.log(myFish); // ['angel', 'clown', 'mandarin' ] + +console.log(popped); // 'sturgeon'</code></pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>초기 정의. JavaScript 1.2에서 구현됨.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.6', 'Array.prototype.pop')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.pop', 'Array.prototype.pop')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.pop', 'Array.prototype.pop')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.Array.pop")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.push()")}}</li> + <li>{{jsxref("Array.prototype.shift()")}}</li> + <li>{{jsxref("Array.prototype.unshift()")}}</li> + <li>{{jsxref("Array.prototype.splice()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/push/index.html b/files/ko/web/javascript/reference/global_objects/array/push/index.html new file mode 100644 index 0000000000..73d9c9ad78 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/push/index.html @@ -0,0 +1,113 @@ +--- +title: Array.prototype.push() +slug: Web/JavaScript/Reference/Global_Objects/Array/push +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/push +--- +<div>{{JSRef}}</div> + +<p><code><strong>push()</strong></code> 메서드는 배열의 끝에 하나 이상의 요소를 추가하고, 배열의 새로운 길이를 반환합니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/array-push.html")}}</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>arr</var>.push(<var>element1[</var>, ...[, <var>elementN]]</var>)</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>element<em>N</em></code></dt> + <dd>배열의 끝에 추가할 요소.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>호출한 배열의 새로운 {{jsxref("Array.length", "length")}} 속성.</p> + +<h2 id="설명">설명</h2> + +<p><code>push</code> 메서드는 배열 끝에 여러 값을 추가합니다.</p> + +<p><code>push</code>는 의도적으로 <a href="https://en.wikipedia.org/wiki/Generic_programming">제네릭</a>합니다. 배열을 닯은 객체에 {{jsxref("Function.call", "call()")}} 또는 {{jsxref("Function.apply", "apply()")}}로 사용될 수 있다. <code>push</code> 메서드는 주어진 값을 입력하는 것을 어디에 시작할 것인지를 결정하기 위해 <code>length</code> 속성에 의존한다. 만약 <code>length</code> 속성이 숫자로 변환 될 수 없다면 인덱스는 0을 사용한다. <code>length</code> 가 생성되게 될 경우에 길이 값이 존재하지 않을 가능성을 포함한다. </p> + +<p>String(문자열)이 변경할 수 없는 것처럼 비록 이 명령어의 어플리케이션들이 적합하지 않다고 할지라도 단지 원래 배열 같은 객체는 {{jsxref("Global_Objects/String", "strings", "", 1)}}이다.</p> + +<h2 id="예시">예시</h2> + +<h3 id="배열에_엘리먼트를_추가_하기">배열에 엘리먼트를 추가 하기</h3> + +<p>다음 코드는 두가지 엘리먼트를 포함하는 스포츠 배열을 생성하고 두개의 엘리먼트를 추가 한다. <code>total</code> 변수는 추가한 배열의 새 길이 값을 포함한다. </p> + +<pre class="brush: js">var sports = ['축구', '야구']; +var total = sports.push('미식축구', '수영'); + +console.log(sports); // ['축구', '야구', '미식축구', '수영'] +console.log(total); // 4 +</pre> + +<h3 id="두개의_배열을_합치기">두개의 배열을 합치기</h3> + +<p>이 예제는 두번째 배열의 모든 엘리먼트를 push 하기 위해 {{jsxref("Function.apply", "apply()")}}를 사용한다.</p> + +<p>만약 두번째 배열( 아래 예제에서는 moreVegs )이 매우 클 경우, 이 메소드를 사용하지 말아야 한다. 실제로 한 함수가 사용가능한 매개변수의 최대 개수에는 제한이 있기 때문이다. 더 자세한 사항은 {{jsxref("Function.apply", "apply()")}} 에서 찾아볼 수 있다.</p> + +<pre class="brush: js">var vegetables = ['설탕당근', '감자']; +var moreVegs = ['셀러리', '홍당무']; + +// 첫번째 배열에 두번째 배열을 합친다. +// vegetables.push('셀러리', '홍당무'); 하는 것과 동일하다. +Array.prototype.push.apply(vegetables, moreVegs); + +console.log(vegetables); // ['설탕당근', '감자', '셀러리', '홍당무'] +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세서</th> + <th scope="col">상태</th> + <th scope="col">비고</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>초기 정의. JavaScript 1.2에서 구현되었음.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.7', 'Array.prototype.push')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.push', 'Array.prototype.push')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.push', 'Array.prototype.push')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.Array.push")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.pop()")}}</li> + <li>{{jsxref("Array.prototype.shift()")}}</li> + <li>{{jsxref("Array.prototype.unshift()")}}</li> + <li>{{jsxref("Array.prototype.concat()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/reduce/index.html b/files/ko/web/javascript/reference/global_objects/array/reduce/index.html new file mode 100644 index 0000000000..bd3516865e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/reduce/index.html @@ -0,0 +1,573 @@ +--- +title: Array.prototype.reduce() +slug: Web/JavaScript/Reference/Global_Objects/Array/Reduce +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/Reduce +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary"><code><strong>reduce()</strong></code><strong> </strong>메서드는 배열의 각 요소에 대해 주어진 <strong>리듀서</strong>(reducer) 함수를 실행하고, 하나의 결과값을 반환합니다.</span></p> + +<div>{{EmbedInteractiveExample("pages/js/array-reduce.html")}}</div> + + + +<p><strong>리듀서</strong> 함수는 네 개의 인자를 가집니다.</p> + +<ol> + <li>누산기<sup>accumulator</sup> (acc)</li> + <li>현재 값 (cur)</li> + <li>현재 인덱스 (idx)</li> + <li>원본 배열 (src)</li> +</ol> + +<p>리듀서 함수의 반환 값은 누산기에 할당되고, 누산기는 순회 중 유지되므로 결국 최종 결과는 하나의 값이 됩니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>arr</var>.reduce(<var>callback</var>[, <var>initialValue</var>])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>배열의 각 요소에 대해 실행할 함수. 다음 네 가지 인수를 받습니다.</dd> + <dd> + <dl> + <dt><code>accumulator</code></dt> + <dd>누산기<sup>accmulator</sup>는 콜백의 반환값을 누적합니다. 콜백의 이전 반환값 또는, 콜백의 첫 번째 호출이면서 <code>initialValue</code>를 제공한 경우에는 <code>initialValue</code>의 값입니다.</dd> + <dt><code>currentValue</code></dt> + <dd>처리할 현재 요소.</dd> + <dt><code>currentIndex</code> {{optional_inline}}</dt> + <dd>처리할 현재 요소의 인덱스. <code>initialValue</code>를 제공한 경우 0, 아니면 1부터 시작합니다.</dd> + <dt><code>array</code> {{optional_inline}}</dt> + <dd><code>reduce()</code>를 호출한 배열.</dd> + </dl> + </dd> + <dt><code>initialValue</code> {{optional_inline}}</dt> + <dd><code>callback</code>의 최초 호출에서 첫 번째 인수에 제공하는 값. 초기값을 제공하지 않으면 배열의 첫 번째 요소를 사용합니다. 빈 배열에서 초기값 없이 <code>reduce()</code>를 호출하면 오류가 발생합니다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>누적 계산의 결과 값.</p> + +<h2 id="설명">설명</h2> + +<p><code>reduce()</code>는 빈 요소를 제외하고 배열 내에 존재하는 각 요소에 대해 <code>callback</code> 함수를 한 번씩 실행하는데, 콜백 함수는 다음의 네 인수를 받습니다:</p> + +<ul> + <li><code>accumulator</code></li> + <li><code>currentValue</code></li> + <li><code>currentIndex</code></li> + <li><code>array</code></li> +</ul> + +<p>콜백의 최초 호출 때 <code>accumulator</code>와 <code>currentValue</code>는 다음 두 가지 값 중 하나를 가질 수 있습니다. 만약 <code>reduce()</code> 함수 호출에서 <code>initialValue</code>를 제공한 경우, <code>accumulator</code>는 <code>initialValue</code>와 같고 <code>currentValue</code>는 배열의 첫 번째 값과 같습니다. <code>initialValue</code>를 제공하지 않았다면, <code>accumulator</code>는 배열의 첫 번째 값과 같고 <code>currentValue</code>는 두 번째와 같습니다.</p> + +<div class="note"> +<p><strong>참고:</strong> <code>initialValue</code>를 제공하지 않으면, <code>reduce()</code>는 인덱스 1부터 시작해 콜백 함수를 실행하고 첫 번째 인덱스는 건너 뜁니다. <code>initialValue</code>를 제공하면 인덱스 0에서 시작합니다.</p> +</div> + +<p>배열이 비어있는데 <code>initialValue</code>도 제공하지 않으면 {{jsxref("TypeError")}}가 발생합니다. 배열의 요소가 (위치와 관계없이) 하나 뿐이면서 <code>initialValue</code>를 제공되지 않은 경우, 또는 <code>initialValue</code>는 주어졌으나 배열이 빈 경우엔 그 단독 값을 <code>callback</code> 호출 없이 반환합니다.</p> + +<p>다음의 예제처럼 <code>initialValue</code>을 제공하지 않으면 출력 가능한 형식이 세 가지이므로, 보통 초기값을 주는 것이 더 안전합니다.</p> + +<pre class="brush: js">var maxCallback = ( acc, cur ) => Math.max( acc.x, cur.x ); +var maxCallback2 = ( max, cur ) => Math.max( max, cur ); + +// initialValue 없이 reduce() +[ { x: 22 }, { x: 42 } ].reduce( maxCallback ); // 42 +[ { x: 22 } ].reduce( maxCallback ); // { x: 22 } +[ ].reduce( maxCallback ); // TypeError + +// map/reduce로 개선 - 비었거나 더 큰 배열에서도 동작함 +[ { x: 22 }, { x: 42 } ].map( el => el.x ) + .reduce( maxCallback2, -Infinity );</pre> + +<h3 id="reduce()_작동_방식"><code>reduce()</code> 작동 방식</h3> + +<p>다음의 예제를 생각해 봅시다.</p> + +<pre class="brush: js">[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) { + return accumulator + currentValue; +}); +</pre> + +<p>콜백은 4번 호출됩니다. 각 호출의 인수와 반환값은 다음과 같습니다.</p> + +<table> + <thead> + <tr> + <th scope="col"><code>callback</code></th> + <th scope="col"><code>accumulator</code></th> + <th scope="col"><code>currentValue</code></th> + <th scope="col"><code>currentIndex</code></th> + <th scope="col"><code>array</code></th> + <th scope="col">반환 값</th> + </tr> + </thead> + <tbody> + <tr> + <th scope="row">1번째 호출</th> + <td><code>0</code></td> + <td><code>1</code></td> + <td><code>1</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>1</code></td> + </tr> + <tr> + <th scope="row">2번째 호출</th> + <td><code>1</code></td> + <td><code>2</code></td> + <td><code>2</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>3</code></td> + </tr> + <tr> + <th scope="row">3번째 호출</th> + <td><code>3</code></td> + <td><code>3</code></td> + <td><code>3</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>6</code></td> + </tr> + <tr> + <th scope="row">4번째 호출</th> + <td><code>6</code></td> + <td><code>4</code></td> + <td><code>4</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>10</code></td> + </tr> + </tbody> +</table> + +<p><code>reduce()</code>가 반환하는 값으로는 마지막 콜백 호출의 반환값(<code>10</code>)을 사용합니다.</p> + +<p>완전한 함수 대신에 {{jsxref("Functions/애로우_펑션", "화살표 함수","",1)}}를 제공할 수도 있습니다. 아래 코드는 위의 코드와 같은 결과를 반환합니다.</p> + +<pre class="brush: js">[0, 1, 2, 3, 4].reduce( (prev, curr) => prev + curr ); +</pre> + +<p><code>reduce()</code>의 두 번째 인수로 초기값을 제공하는 경우, 결과는 다음과 같습니다:</p> + +<pre class="brush: js">[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) { + return accumulator + currentValue; +}, 10); +</pre> + +<table> + <thead> + <tr> + <th scope="col"> </th> + <th scope="col"><code>accumulator</code></th> + <th scope="col"><code>currentValue</code></th> + <th scope="col"><code>currentIndex</code></th> + <th scope="col"><code>array</code></th> + <th scope="col">반환값</th> + </tr> + </thead> + <tbody> + <tr> + <th scope="row">1번째 호출</th> + <td><code>10</code></td> + <td><code>0</code></td> + <td><code>0</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>10</code></td> + </tr> + <tr> + <th scope="row">2번째 호출</th> + <td><code>10</code></td> + <td><code>1</code></td> + <td><code>1</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>11</code></td> + </tr> + <tr> + <th scope="row">3번째 호출</th> + <td><code>11</code></td> + <td><code>2</code></td> + <td><code>2</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>13</code></td> + </tr> + <tr> + <th scope="row">4번째 호출</th> + <td><code>13</code></td> + <td><code>3</code></td> + <td><code>3</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>16</code></td> + </tr> + <tr> + <th scope="row">5번째 호출</th> + <td><code>16</code></td> + <td><code>4</code></td> + <td><code>4</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>20</code></td> + </tr> + </tbody> +</table> + +<p>이 때 <code>reduce()</code>가 결과로 반환하는 값은 <code>20</code>입니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="배열의_모든_값_합산">배열의 모든 값 합산</h3> + +<pre class="brush: js">var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) { + return accumulator + currentValue; +}, 0); +// sum is 6 + +</pre> + +<p>화살표 함수로도 작성할 수 있습니다.</p> + +<pre class="brush: js">var total = [ 0, 1, 2, 3 ].reduce( + ( accumulator, currentValue ) => accumulator + currentValue, + 0 +);</pre> + +<h3 id="객체_배열에서의_값_합산">객체 배열에서의 값 합산</h3> + +<p>객체로 이루어진 배열에 들어 있는 값을 합산하기 위해서는 <strong>반드시</strong> 초기값을 주어 각 항목이 여러분의 함수를 거치도록 해야 합니다.</p> + +<pre class="brush: js">var initialValue = 0; +var sum = [{x: 1}, {x:2}, {x:3}].reduce(function (accumulator, currentValue) { + return accumulator + currentValue.x; +},initialValue) + +console.log(sum) // logs 6 +</pre> + +<p>화살표 함수(arrow function)로도 작성할 수 있습니다: </p> + +<pre class="brush: js">var initialValue = 0; +var sum = [{x: 1}, {x:2}, {x:3}].reduce( + (accumulator, currentValue) => accumulator + currentValue.x + ,initialValue +); + +console.log(sum) // logs 6</pre> + +<h3 id="중첩_배열_펼치기flatten">중첩 배열 펼치기<sup>flatten</sup></h3> + +<pre class="brush: js">var flattened = [[0, 1], [2, 3], [4, 5]].reduce( + function(accumulator, currentValue) { + return accumulator.concat(currentValue); + }, + [] +); +// 펼친 결과: [0, 1, 2, 3, 4, 5] +</pre> + +<p>화살표 함수로도 작성할 수 있습니다:</p> + +<pre class="brush: js">var flattened = [[0, 1], [2, 3], [4, 5]].reduce( + ( accumulator, currentValue ) => accumulator.concat(currentValue), + [] +); +</pre> + +<h3 id="객체_내의_값_인스턴스_개수_세기">객체 내의 값 인스턴스 개수 세기</h3> + +<pre class="brush: js">var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice']; + +var countedNames = names.reduce(function (allNames, name) { + if (name in allNames) { + allNames[name]++; + } + else { + allNames[name] = 1; + } + return allNames; +}, {}); +// countedNames is: +// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 } +</pre> + +<h3 id="속성으로_객체_분류하기">속성으로 객체 분류하기</h3> + +<pre class="brush: js">var people = [ + { name: 'Alice', age: 21 }, + { name: 'Max', age: 20 }, + { name: 'Jane', age: 20 } +]; + +function groupBy(objectArray, property) { + return objectArray.reduce(function (acc, obj) { + var key = obj[property]; + if (!acc[key]) { + acc[key] = []; + } + acc[key].push(obj); + return acc; + }, {}); +} + +var groupedPeople = groupBy(people, 'age'); +// groupedPeople is: +// { +// 20: [ +// { name: 'Max', age: 20 }, +// { name: 'Jane', age: 20 } +// ], +// 21: [{ name: 'Alice', age: 21 }] +// } +</pre> + +<h3 id="확장_연산자와_초기값을_이용하여_객체로_이루어진_배열에_담긴_배열_연결하기">확장 연산자와 초기값을 이용하여 객체로 이루어진 배열에 담긴 배열 연결하기</h3> + +<pre class="brush: js">// friends - an array of objects +// where object field "books" - list of favorite books +var friends = [{ + name: 'Anna', + books: ['Bible', 'Harry Potter'], + age: 21 +}, { + name: 'Bob', + books: ['War and peace', 'Romeo and Juliet'], + age: 26 +}, { + name: 'Alice', + books: ['The Lord of the Rings', 'The Shining'], + age: 18 +}]; + +// allbooks - list which will contain all friends' books + +// additional list contained in initialValue +var allbooks = friends.reduce(function(accumulator, currentValue) { + return [...accumulator, ...currentValue.books]; +}, ['Alphabet']); + +// allbooks = [ +// 'Alphabet', 'Bible', 'Harry Potter', 'War and peace', +// 'Romeo and Juliet', 'The Lord of the Rings', +// 'The Shining' +// ] +</pre> + +<h3 id="배열의_중복_항목_제거">배열의 중복 항목 제거</h3> + +<div class="blockIndicator note"> +<p>참고: {{jsxref("Set")}}과 {{jsxref("Array.from()")}}을 사용할 수 있는 환경이라면, <code>let orderedArray = Array.from(new Set(myArray));</code>를 사용해 중복 요소를 제거할 수도 있습니다.</p> +</div> + +<pre class="brush: js">let arr = [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4, 4]; +let result = arr.sort().reduce((accumulator, current) => { + const length = accumulator.length + if (length === 0 || accumulator[length - 1] !== current) { + accumulator.push(current); + } + return accumulator; +}, []); +console.log(result); //[1,2,3,4,5] +</pre> + +<h3 id="프로미스를_순차적으로_실행하기">프로미스를 순차적으로 실행하기</h3> + +<pre class="brush: js">/** + * Runs promises from array of functions that can return promises + * in chained manner + * + * @param {array} arr - promise arr + * @return {Object} promise object + */ +function runPromiseInSequence(arr, input) { + return arr.reduce( + (promiseChain, currentFunction) => promiseChain.then(currentFunction), + Promise.resolve(input) + ); +} + +// promise function 1 +function p1(a) { + return new Promise((resolve, reject) => { + resolve(a * 5); + }); +} + +// promise function 2 +function p2(a) { + return new Promise((resolve, reject) => { + resolve(a * 2); + }); +} + +// function 3 - will be wrapped in a resolved promise by .then() +function f3(a) { + return a * 3; +} + +// promise function 4 +function p4(a) { + return new Promise((resolve, reject) => { + resolve(a * 4); + }); +} + +const promiseArr = [p1, p2, f3, p4]; +runPromiseInSequence(promiseArr, 10) + .then(console.log); // 1200 +</pre> + +<h3 id="함수_구성을_위한_파이프_함수">함수 구성을 위한 파이프 함수</h3> + +<pre class="brush: js">// Building-blocks to use for composition +const double = x => x + x; +const triple = x => 3 * x; +const quadruple = x => 4 * x; + +// Function composition enabling pipe functionality +const pipe = (...functions) => input => functions.reduce( + (acc, fn) => fn(acc), + input +); + +// Composed functions for multiplication of specific values +const multiply6 = pipe(double, triple); +const multiply9 = pipe(triple, triple); +const multiply16 = pipe(quadruple, quadruple); +const multiply24 = pipe(double, triple, quadruple); + +// Usage +multiply6(6); // 36 +multiply9(9); // 81 +multiply16(16); // 256 +multiply24(10); // 240 +</pre> + +<h3 id="reduce()로_map()_작성"><code>reduce()</code>로 <code>map()</code> 작성</h3> + +<pre class="brush: js">if (!Array.prototype.mapUsingReduce) { + Array.prototype.mapUsingReduce = function(callback, thisArg) { + return this.reduce(function(mappedArray, currentValue, index, array) { + mappedArray[index] = callback.call(thisArg, currentValue, index, array); + return mappedArray; + }, []); + }; +} + +[1, 2, , 3].mapUsingReduce( + (currentValue, index, array) => currentValue + index + array.length +); // [5, 7, , 10] + +</pre> + +<h2 id="폴리필">폴리필</h2> + +<pre class="brush: js">// ECMA-262의 진행 단계, 5판(Edition), 15.4.4.21 +// 참조: http://es5.github.io/#x15.4.4.21 +// https://tc39.github.io/ecma262/#sec-array.prototype.reduce +if (!Array.prototype.reduce) { + Object.defineProperty(Array.prototype, 'reduce', { + value: function(callback /*, initialValue*/) { + if (this === null) { + throw new TypeError( 'Array.prototype.reduce ' + + 'called on null or undefined' ); + } + if (typeof callback !== 'function') { + throw new TypeError( callback + + ' is not a function'); + } + + // 1. Let O be ? ToObject(this value). + var o = Object(this); + + // 2. Let len be ? ToLength(? Get(O, "length")). + var len = o.length >>> 0; + + // Steps 3, 4, 5, 6, 7 + var k = 0; + var value; + + if (arguments.length >= 2) { + value = arguments[1]; + } else { + while (k < len && !(k in o)) { + k++; + } + + // 3. If len is 0 and initialValue is not present, + // throw a TypeError exception. + if (k >= len) { + throw new TypeError( 'Reduce of empty array ' + + 'with no initial value' ); + } + value = o[k++]; + } + + // 8. Repeat, while k < len + while (k < len) { + // a. Let Pk be ! ToString(k). + // b. Let kPresent be ? HasProperty(O, Pk). + // c. If kPresent is true, then + // i. Let kValue be ? Get(O, Pk). + // ii. Let accumulator be ? Call( + // callbackfn, undefined, + // « accumulator, kValue, k, O »). + if (k in o) { + value = callback(value, o[k], k, o); + } + + // d. Increase k by 1. + k++; + } + + // 9. Return accumulator. + return value; + } + }); +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.21', 'Array.prototype.reduce()')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.8.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.reduce', 'Array.prototype.reduce()')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.reduce', 'Array.prototype.reduce()')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.reduce")}}</p> +</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.reduceRight()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/reduceright/index.html b/files/ko/web/javascript/reference/global_objects/array/reduceright/index.html new file mode 100644 index 0000000000..07bbdb800e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/reduceright/index.html @@ -0,0 +1,283 @@ +--- +title: Array.prototype.reduceRight() +slug: Web/JavaScript/Reference/Global_Objects/Array/ReduceRight +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/ReduceRight +--- +<div>{{JSRef}}</div> + +<p><strong><code>reduceRight()</code></strong> 메서드는 누적기에 대해 함수를 적용하고 배열의 각 값 (오른쪽에서 왼쪽으로)은 값을 단일 값으로 줄여야합니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/array-reduce-right.html")}}</p> + +<p>왼쪽에서 오른쪽으로 {{jsxref("Array.prototype.reduce()")}}도 참조하십시오.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>arr</var>.reduceRight(<var>callback</var>[, <var>initialValue</var>])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>4 개의 인수를 취하여 배열의 각 값에 대해 실행할 함수입니다. + <dl> + <dt><code>previousValue</code></dt> + <dd>콜백의 마지막 호출에서 이전에 리턴 된 값 또는 제공된 경우 initialValue. (아래 참조).</dd> + <dt><code>currentValue</code></dt> + <dd>배열에서 처리중인 현재 요소입니다.</dd> + <dt><code>index</code></dt> + <dd>배열에서 처리중인 현재 요소의 인덱스입니다.</dd> + <dt><code>array</code></dt> + <dd>배열 reduce가 호출되었습니다.</dd> + </dl> + </dd> + <dt><code>initialValue</code></dt> + <dd>선택 과목. 콜백의 최초의 호출의 최초의 인수로서 사용하는 객체입니다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>누적 계산의 결과를 반환합니다.</p> + +<h2 id="설명">설명</h2> + +<p><code>reduceRight는 배열의 구멍을 제외하고 배열에있는 각 요소에 대해 콜백 함수를 한 번 실행합니다.이 인수는 초기 값 (또는 이전 콜백 호출의 값), 현재 요소의 값, 현재 인덱스 및 반복이 일어나는 배열.</code></p> + +<p>reduceRight 콜백 호출은 다음과 같습니다.</p> + +<pre class="brush: js">array.reduceRight(function(previousValue, currentValue, index, array) { + // ... +}); +</pre> + +<p>함수가 처음 호출 될 때 previousValue 및 currentValue는 두 값 중 하나가 될 수 있습니다. reduceValue에 대한 호출에 initialValue가 제공된 경우 previousValue는 initialValue와 같고 currentValue는 배열의 마지막 값과 같습니다. initialValue가 제공되지 않으면 previousValue는 배열의 마지막 값과 같고 currentValue는 두 번째 - 마지막 값과 같습니다.</p> + +<p>배열이 비어 있고 initialValue가 제공되지 않으면 {{jsxref ( "TypeError")}}가 발생합니다. 배열에 요소가 1 개만 있어도 (위치에 관계없이) initialValue가 제공되지 않았던 경우, 또는 initialValue가 준비되어 있지만 배열이 비어있는 경우, 콜백을 호출하지 않고 솔로 값이 반환됩니다.</p> + +<p>함수의 일부 실행 예제는 다음과 같습니다.</p> + +<pre class="brush: js">[0, 1, 2, 3, 4].reduceRight(function(previousValue, currentValue, index, array) { + return previousValue + currentValue; +}); +</pre> + +<p>콜백은 네 번 호출되며 각 호출의 인수와 반환 값은 다음과 같습니다.</p> + +<table> + <thead> + <tr> + <th scope="col"><code>previousValue</code></th> + <th scope="col"><code>currentValue</code></th> + <th scope="col"><code>index</code></th> + <th scope="col"><code>array</code></th> + <th scope="col">return value</th> + </tr> + </thead> + <tbody> + <tr> + <th scope="row">first call</th> + <td><code>4</code></td> + <td><code>3</code></td> + <td><code>3</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>7</code></td> + </tr> + <tr> + <th scope="row">second call</th> + <td><code>7</code></td> + <td><code>2</code></td> + <td><code>2</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>9</code></td> + </tr> + <tr> + <th scope="row">third call</th> + <td><code>9</code></td> + <td><code>1</code></td> + <td><code>1</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>10</code></td> + </tr> + <tr> + <th scope="row">fourth call</th> + <td><code>10</code></td> + <td><code>0</code></td> + <td><code>0</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>10</code></td> + </tr> + </tbody> +</table> + +<p>reduceRight에 의해 반환 된 값은 마지막 콜백 호출 (10)의 값이됩니다.</p> + +<p>initialValue를 제공하면 결과는 다음과 같습니다.</p> + +<pre class="brush: js">[0, 1, 2, 3, 4].reduceRight(function(previousValue, currentValue, index, array) { + return previousValue + currentValue; +}, 10); +</pre> + +<table> + <thead> + <tr> + <th scope="col"><code>previousValue</code></th> + <th scope="col"><code>currentValue</code></th> + <th scope="col"><code>index</code></th> + <th scope="col"><code>array</code></th> + <th scope="col">return value</th> + </tr> + </thead> + <tbody> + <tr> + <th scope="row">first call</th> + <td><code>10</code></td> + <td><code>4</code></td> + <td><code>4</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>14</code></td> + </tr> + <tr> + <th scope="row">second call</th> + <td><code>14</code></td> + <td><code>3</code></td> + <td><code>3</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>17</code></td> + </tr> + <tr> + <th scope="row">third call</th> + <td><code>17</code></td> + <td><code>2</code></td> + <td><code>2</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>19</code></td> + </tr> + <tr> + <th scope="row">fourth call</th> + <td><code>19</code></td> + <td><code>1</code></td> + <td><code>1</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>20</code></td> + </tr> + <tr> + <th scope="row">fifth call</th> + <td><code>20</code></td> + <td><code>0</code></td> + <td><code>0</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>20</code></td> + </tr> + </tbody> +</table> + +<p>reduceRight에 의해 이번에 반환 된 값은 물론 20입니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="배열_내_모든_값의_합계_구하기">배열 내 모든 값의 합계 구하기</h3> + +<pre class="brush: js">var sum = [0, 1, 2, 3].reduceRight(function(a, b) { + return a + b; +}); +// sum is 6 +</pre> + +<h3 id="이중_배열_전개하기">이중 배열 전개하기</h3> + +<pre class="brush: js">var flattened = [[0, 1], [2, 3], [4, 5]].reduceRight(function(a, b) { + return a.concat(b); +}, []); +// flattened is [4, 5, 2, 3, 0, 1] +</pre> + +<h3 id="reduce와_reduceRight의_차이점">reduce와 reduceRight의 차이점</h3> + +<pre class="brush: js">var a = ["1", "2", "3", "4", "5"]; +var left = a.reduce(function(prev, cur) { return prev + cur; }); +var right = a.reduceRight(function(prev, cur) { return prev + cur; }); + +console.log(left); // "12345" +console.log(right); // "54321"</pre> + +<h2 id="폴리필">폴리필</h2> + +<p><code>reduceRight</code>는 5 판에서 ECMA-262 표준에 추가되었습니다. 표준의 모든 구현에 존재하지 않을 수도 있습니다. 이 문제를 해결하려면 스크립트 시작 부분에 다음 코드를 삽입하여 reduceRight를 기본적으로 지원하지 않는 구현에서 사용할 수있게하십시오.</p> + +<pre class="brush: js">// ECMA-262, 5 판, 15.4.4.22의 제작 단계 +// 참조 : http://es5.github.io/#x15.4.4.22 +if ('function' !== typeof Array.prototype.reduceRight) { + Array.prototype.reduceRight = function(callback /*, initialValue*/) { + 'use strict'; + if (null === this || 'undefined' === typeof this) { + throw new TypeError('Array.prototype.reduce called on null or undefined' ); + } + if ('function' !== typeof callback) { + throw new TypeError(callback + ' is not a function'); + } + var t = Object(this), len = t.length >>> 0, k = len - 1, value; + if (arguments.length >= 2) { + value = arguments[1]; + } else { + while (k >= 0 && !(k in t)) { + k--; + } + if (k < 0) { + throw new TypeError('Reduce of empty array with no initial value'); + } + value = t[k--]; + } + for (; k >= 0; k--) { + if (k in t) { + value = callback(value, t[k], k, t); + } + } + return value; + }; +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.22', 'Array.prototype.reduceRight')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.8.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.reduceright', 'Array.prototype.reduceRight')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.reduceright', 'Array.prototype.reduceRight')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.Array.reduceRight")}}</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.reduce()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/reverse/index.html b/files/ko/web/javascript/reference/global_objects/array/reverse/index.html new file mode 100644 index 0000000000..95b4c1a348 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/reverse/index.html @@ -0,0 +1,87 @@ +--- +title: Array.prototype.reverse() +slug: Web/JavaScript/Reference/Global_Objects/Array/reverse +tags: + - Array + - JavaScript + - Method + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Array/reverse +--- +<div>{{JSRef}}</div> + +<p><code><strong>reverse()</strong></code> 메서드는 배열의 순서를 반전합니다. 첫 번째 요소는 마지막 요소가 되며 마지막 요소는 첫 번째 요소가 됩니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/array-reverse.html")}}</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>a</var>.reverse()</code></pre> + +<h3 id="반환_값">반환 값</h3> + +<p>순서가 반전된 배열.</p> + +<h2 id="설명">설명</h2> + +<p><code>reverse</code> 메서드는 호출한 배열을 반전하고 원본 배열을 변형하며 그 참조를 반환합니다.</p> + +<h2 id="예시">예시</h2> + +<h3 id="배열의_요소를_반전하기">배열의 요소를 반전하기</h3> + +<p>다음 예시는 3개의 요소가 든 myArray 배열을 만든 후, 반전시킵니다.</p> + +<pre><code>const a = [1, 2, 3]; +console.log(a); // [1, 2, 3] + +a.reverse(); +console.log(a); // [3, 2, 1]</code></pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.8', 'Array.prototype.reverse')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.Array.reverse")}}</div> + +<div id="compat-desktop"> </div> + +<div id="compat-mobile"> </div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.join()")}}</li> + <li>{{jsxref("Array.prototype.sort()")}}</li> + <li>{{jsxref("TypedArray.prototype.reverse()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/shift/index.html b/files/ko/web/javascript/reference/global_objects/array/shift/index.html new file mode 100644 index 0000000000..bf610b95f9 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/shift/index.html @@ -0,0 +1,102 @@ +--- +title: Array.prototype.shift() +slug: Web/JavaScript/Reference/Global_Objects/Array/shift +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/shift +--- +<div>{{JSRef}}</div> + +<p><strong><code>shift()</code></strong> 메서드는 배열에서 첫 번째 요소를 제거하고, 제거된 요소를 반환합니다. 이 메서드는 배열의 길이를 변하게 합니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/array-shift.html")}}</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>arr</var>.shift()</code> +</pre> + +<h3 id="반환_값">반환 값</h3> + +<p>배열에서 제거한 요소. 빈 배열의 경우 {{jsxref("undefined")}} 를 반환합니다.</p> + +<h2 id="설명">설명</h2> + +<p><code>shift</code> 메서드는 0번째 위치의 요소를 제거 하고 연이은 나머지 값들의 위치를 한칸 씩 앞으로 당깁니다. 그리고 제거된 값을 반환 합니다. 만약 배열의 {{jsxref("Array.length", "length")}}가 0이라면 {{jsxref("undefined")}}를 리턴 합니다.</p> + +<p><code>shift</code>는 의도적인 일반형태로써; 이 메서드는 배열과 유사한 형태의 객체에서 {{jsxref("Function.call", "호출", "", 1)}} 하거나 {{jsxref("Function.apply", "적용", "", 1)}} 할 수 있습니다. 연속된 일련의 마지막 항목을 나타내는 길이 속성을 가지고 있지 않은 객체의 제로베이스 수치 속성에는 의미 있는 작동을 하지 않을 수 있습니다. (<em>Objects which do not contain a <code>length</code> property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner</em>.)</p> + +<h2 id="예제">예제</h2> + +<h3 id="배열에서_한_요소_제거하기">배열에서 한 요소 제거하기</h3> + +<p>아래 코드는 <code>myFish</code> 라는 배열에서 첫번째 요소를 제거 하기 전과 후를 보여 줍니다. 그리고 제거된 요소도 보여줍니다.</p> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'mandarin', 'surgeon']; + +console.log('myFish before: ' + myFish); +// "제거전 myFish 배열: angel,clown,mandarin,surgeon" + +var shifted = myFish.shift(); + +console.log('myFish after: ' + myFish); +// "제거후 myFish 배열: clown,mandarin,surgeon" + +console.log('Removed this element: ' + shifted); +// "제거된 배열 요소: angel" +</pre> + +<h3 id="while_반복문_안에서_shift()_사용하기">while 반복문 안에서 shift() 사용하기</h3> + +<p>shift() 메서드는 while 문의 조건으로 사용되기도 합니다. 아래 코드에서는 while 문을 한번 돌 때 마다 배열의 다음 요소를 제거하고, 이는 빈 배열이 될 때까지 반복됩니다.</p> + +<pre><code>var names = ["Andrew", "Edward", "Paul", "Chris" ,"John"]; + +while( (i = names.shift()) !== undefined ) { + console.log(i); +} +// Andrew, Edward, Paul, Chris, John</code> +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.9', 'Array.prototype.shift')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.shift', 'Array.prototype.shift')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.Array.shift")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.push()")}}</li> + <li>{{jsxref("Array.prototype.pop()")}}</li> + <li>{{jsxref("Array.prototype.unshift()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/slice/index.html b/files/ko/web/javascript/reference/global_objects/array/slice/index.html new file mode 100644 index 0000000000..a5264b1f86 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/slice/index.html @@ -0,0 +1,155 @@ +--- +title: Array.prototype.slice() +slug: Web/JavaScript/Reference/Global_Objects/Array/slice +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/slice +--- +<div>{{JSRef}}</div> + +<p><code><strong>slice()</strong></code><strong> </strong>메서드는 어떤 배열의 <code>begin</code>부터 <code>end</code>까지(<code>end</code> 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환합니다. 원본 배열은 바뀌지 않습니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-slice.html")}}</div> + +<p class="hidden">The source for this interactive demo is stored in a GitHub repository. If you'd like to contribute to the interactive demo project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>arr</var>.slice([<em>begin</em>[, <em>end</em>]]) +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>begin</code> {{optional_inline}}</dt> + <dd>0을 시작으로 하는 추출 시작점에 대한 인덱스를 의미합니다.</dd> + <dd>음수 인덱스는 배열의 끝에서부터의 길이를 나타냅니다. <code>slice(-2)</code> 는 배열에서 마지막 두 개의 엘리먼트를 추출합니다.</dd> + <dd><code>begin</code>이 <code>undefined</code>인 경우에는, 0번 인덱스부터 <code>slice</code> 합니다.</dd> + <dd><code>begin</code>이 배열의 길이보다 큰 경우에는, 빈 배열을 반환합니다.</dd> + <dt><code>end</code> {{optional_inline}}</dt> + <dd>추출을 종료 할 0 기준 인덱스입니다. <code>slice</code> 는 <code>end</code> 인덱스를 제외하고 추출합니다.</dd> + <dd>예를 들어, <code>slice(1,4)</code>는 두번째 요소부터 네번째 요소까지 (1, 2 및 3을 인덱스로 하는 요소) 추출합니다.</dd> + <dd>음수 인덱스는 배열의 끝에서부터의 길이를 나타냅니다. 예를들어 <code>slice(2,-1)</code> 는 세번째부터 끝에서 두번째 요소까지 추출합니다.</dd> + <dd><code>end</code>가 생략되면 <code>slice()</code>는 배열의 끝까지(<code>arr.length</code>) 추출합니다.</dd> +</dl> + +<p> 만약 <code>end</code> 값이 배열의 길이보다 크다면, <code>silce()</code>는 배열의 끝까지(<code>arr.length</code>) 추출합니다.</p> + +<dl> + <dt> + <h3 id="반환_값">반환 값</h3> + </dt> +</dl> + +<p>추출한 요소를 포함한 새로운 배열.</p> + +<h2 id="설명">설명</h2> + +<p><code>slice()</code>는 원본을 대체하지 않습니다. 원본 배열에서 요소의 얕은 복사본을 반환합니다. 원본 배열의 요소는 다음과 같이 반환 된 배열에 복사됩니다:</p> + +<ul> + <li>객체 참조(및 실제 객체가 아님)의 경우, <code>slice()</code>는 객체 참조를 새 배열로 복사합니다. 원본 배열과 새 배열은 모두 동일한 객체를 참조합니다. 참조 된 객체가 변경되면 변경 내용은 새 배열과 원래 배열 모두에서 볼 수 있습니다.</li> + <li>{{jsxref ("String")}} 및 {{jsxref("Number")}} 객체가 아닌 문자열과 숫자의 경우 <code>slice()</code>는 문자열과 숫자를 새 배열에 복사합니다. 한 배열에서 문자열이나 숫자를 변경해도 다른 배열에는 영향을 주지 않습니다.</li> +</ul> + +<p>새 요소를 두 배열 중 하나에 추가해도 다른 배열은 영향을 받지 않습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="기존_배열의_일부_반환">기존 배열의 일부 반환</h3> + +<pre class="brush: js">let fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'] +let citrus = fruits.slice(1, 3) + +// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'] +// citrus contains ['Orange','Lemon']</pre> + +<h3 id="slice_사용하기"><code>slice</code> 사용하기</h3> + +<p>다음 예제에서 <code>slice()</code>는 <code>myCar</code>에서 <code>newCar</code>라는 새 배열을 만듭니다. 두 가지 모두 <code>myHonda</code> 객체에 대한 참조를 포함합니다. <code>myHonda</code>의 색상이 자주색으로 변경되면 두 배열 모두 변경 사항을 반영합니다.</p> + +<pre class="brush: js">// Using slice, create newCar from myCar. +let myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } } +let myCar = [myHonda, 2, 'cherry condition', 'purchased 1997'] +let newCar = myCar.slice(0, 2) + +// Display the values of myCar, newCar, and the color of myHonda +// referenced from both arrays. +console.log('myCar = ' + JSON.stringify(myCar)) +console.log('newCar = ' + JSON.stringify(newCar)) +console.log('myCar[0].color = ' + myCar[0].color) +console.log('newCar[0].color = ' + newCar[0].color) + +// Change the color of myHonda. +myHonda.color = 'purple' +console.log('The new color of my Honda is ' + myHonda.color) + +// Display the color of myHonda referenced from both arrays. +console.log('myCar[0].color = ' + myCar[0].color) +console.log('newCar[0].color = ' + newCar[0].color)</pre> + +<p>스크립트를 실행하면 다음과 같은 기록을 남깁니다.</p> + +<pre>myCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2, + 'cherry condition', 'purchased 1997'] +newCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2] +myCar[0].color = red +newCar[0].color = red +The new color of my Honda is purple +myCar[0].color = purple +newCar[0].color = purple</pre> + +<h3 id="배열형_객체">배열형 객체</h3> + +<p><code>slice()</code> 메서드를 호출하여 배열형 객체와 콜렉션을 새로운 <code>Array</code>로 변환할 수 있습니다. 단순히 {{jsxref("Function.prototype.bind()")}}를 사용해 객체에 <code>slice()</code>를 바인딩 하면 됩니다. 대표적인 "배열형 객체"의 예시는 함수 내의 {{jsxref("Functions/arguments", "arguments")}}입니다.</p> + +<pre class="brush: js">function list() { + return Array.prototype.slice.call(arguments); +} + +let list1 = list(1, 2, 3); // [1, 2, 3] +</pre> + +<p>{{jsxref("Function.prototype.call()")}} 메서드를 사용해서도 바인딩을 할 수 있으며, <code>Array.prototype.slice.call</code> 대신 더 짧게 <code>[].slice.call</code>로 작성할 수도 있습니다.</p> + +<p>아무튼, 다음과 같이 {{jsxref("Function.prototype.bind", "bind()")}}를 사용해 줄일 수 있습니다.</p> + +<pre class="brush: js">let unboundSlice = Array.prototype.slice +let slice = Function.prototype.call.bind(unboundSlice) + +function list() { + return slice(arguments) +} + +let list1 = list(1, 2, 3) // [1, 2, 3]</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.slice', 'Array.prototype.slice')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Array.slice")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.splice()")}}</li> + <li>{{jsxref("Function.prototype.call()")}}</li> + <li>{{jsxref("Function.prototype.bind()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/some/index.html b/files/ko/web/javascript/reference/global_objects/array/some/index.html new file mode 100644 index 0000000000..8fbe19bcda --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/some/index.html @@ -0,0 +1,202 @@ +--- +title: Array.prototype.some() +slug: Web/JavaScript/Reference/Global_Objects/Array/some +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/some +--- +<div>{{JSRef}}</div> + +<p><code><strong>some()</strong></code> 메서드는 배열 안의 어떤 요소라도 주어진 판별 함수를 통과하는지 테스트합니다.</p> + +<div class="note"> +<p><strong>참고</strong>: 빈 배열에서 호출하면 무조건 <code>false</code>를 반환합니다.</p> +</div> + +<p>{{EmbedInteractiveExample("pages/js/array-some.html")}}</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>arr</var>.some(<var>callback</var>[, <var>thisArg</var>])</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>각 요소를 시험할 함수. 다음 세 가지 인수를 받습니다. + <dl> + <dt><code>currentValue</code></dt> + <dd>처리할 현재 요소.</dd> + <dt><code>index</code> {{Optional_inline}}</dt> + <dd>처리할 현재 요소의 인덱스.</dd> + <dt><code>array</code> {{Optional_inline}}</dt> + <dd><code>some</code>을 호출한 배열.</dd> + </dl> + </dd> + <dt><code>thisArg</code> {{Optional_inline}}</dt> + <dd><code>callback</code>을 실행할 때 <code>this</code>로 사용하는 값.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p><code>callback</code>이 어떤 배열 요소라도 대해 참인({{Glossary("truthy")}}) 값을 반환하는 경우 <code><strong>true</strong></code>, 그 외엔 <code><strong>false</strong></code>.</p> + +<h2 id="설명">설명</h2> + +<p><code>some</code>은 <code>callback</code>이 참(불린으로 변환했을 때 <code>true</code>가 되는 값)을 반환하는 요소를 찾을 때까지 배열에 있는 각 요소에 대해 한 번씩 <code>callback</code> 함수를 실행합니다. 해당하는 요소를 발견한 경우 <code>some</code>은 즉시 <code>true</code>를 반환합니다. 그렇지 않으면, 즉 모든 값에서 거짓을 반환하면 <code>false</code>를 반환합니다. 할당한 값이 있는 배열의 인덱스에서만 <code>callback</code>을 호출합니다. 삭제했거나 값을 할당한 적이 없는 인덱스에서는 호출하지 않습니다.</p> + +<p><code>callback</code>은 요소의 값, 해당 요소의 인덱스 및 순회하고 있는 배열 세 가지 인수와 함께 호출됩니다.</p> + +<p><code>thisArg</code> 매개변수를 <code>some</code>에 제공한 경우 <code>callback</code>의 <code>this</code>로 사용됩니다. 그 외엔 {{jsxref("undefined")}}값을 사용합니다. 최종적으로 <code>callback</code>이 볼 수 있는 <code>this</code>의 값은 <a href="/ko/docs/Web/JavaScript/Reference/Operators/this">함수가 볼 수 있는 <code>this</code>를 결정하는 평소 규칙</a>을 따릅니다.</p> + +<p><code>some</code>은 호출한 배열을 변형하지 않습니다.</p> + +<p><code>some</code>이 처리하는 요소의 범위는 <code>callback</code>의 첫 호출 전에 설정됩니다. <code>some</code> 호출 이후로 배열에 추가하는 요소는 <code>callback</code>이 방문하지 않습니다. 배열에 원래 있었지만 아직 방문하지 않은 요소가 <code>callback</code>에 의해 변경된 경우, 그 인덱스를 방문하는 시점의 값을 사용합니다. 삭제한 요소는 방문하지 않습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="배열의_요소_테스트">배열의 요소 테스트</h3> + +<p>다음 예제는 배열 내 요소 중 하나라도 10보다 큰지 판별합니다.</p> + +<pre class="brush: js">function isBiggerThan10(element, index, array) { + return element > 10; +} +[2, 5, 8, 1, 4].some(isBiggerThan10); // false +[12, 5, 8, 1, 4].some(isBiggerThan10); // true +</pre> + +<h3 id="화살표_함수를_사용한_배열의_요소_테스트">화살표 함수를 사용한 배열의 요소 테스트</h3> + +<p><a href="/ko/docs/Web/JavaScript/Reference/Functions/애로우_펑션">화살표 함수</a>는 같은 테스트에 대해 더 짧은 구문을 제공합니다.</p> + +<pre class="brush: js">[2, 5, 8, 1, 4].some(elem => elem > 10); // false +[12, 5, 8, 1, 4].some(elem => elem > 10); // true +</pre> + +<h3 id="값이_배열_내_존재하는지_확인">값이 배열 내 존재하는지 확인</h3> + +<p>다음 예제는 요소가 하나라도 배열 내 존재하는 경우 <code>true</code>를 반환합니다.</p> + +<pre class="brush: js">var fruits = ['apple', 'banana', 'mango', 'guava']; + +function checkAvailability(arr, val) { + return arr.some(function(arrVal) { + return val === arrVal; + }); +} + +checkAvailability(fruits, 'kela'); //false +checkAvailability(fruits, 'banana'); //true</pre> + +<h3 id="화살표_함수를_사용하여_값이_존재하는지_확인">화살표 함수를 사용하여 값이 존재하는지 확인</h3> + +<pre class="brush: js">var fruits = ['apple', 'banana', 'mango', 'guava']; + +function checkAvailability(arr, val) { + return arr.some(arrVal => val === arrVal); +} + +checkAvailability(fruits, 'kela'); //false +checkAvailability(fruits, 'banana'); //true</pre> + +<h3 id="모든_값을_불린으로_변환">모든 값을 불린으로 변환</h3> + +<pre class="brush: js">var TRUTHY_VALUES = [true, 'true', 1]; + +function getBoolean(a) { + 'use strict'; + + var value = a; + + if (typeof value === 'string') { + value = value.toLowerCase().trim(); + } + + return TRUTHY_VALUES.some(function(t) { + return t === value; + }); +} + +getBoolean(false); // false +getBoolean('false'); // false +getBoolean(1); // true +getBoolean('true'); // true</pre> + +<h2 id="폴리필">폴리필</h2> + +<p><code><font face="consolas, Liberation Mono, courier, monospace">some</font></code>은 ECMA-262 표준 제5판에 추가됐습니다. 따라서 어떤 표준 구현체에서는 사용할 수 없을 수도 있습니다. 다른 모든 코드 이전에 아래 코드를 포함하면 지원하지 않는 환경에서도 <code>some</code>을 사용할 수 있습니다. 아래 알고리즘은 {{jsxref("Object")}}와 {{jsxref("TypeError")}}가 변형되지 않고, <code>fun.call</code>의 계산 값이 원래의 {{jsxref("Function.prototype.call()")}}과 같은 경우 ECMA-262 제5판이 명시한 것과 동일합니다.</p> + +<pre class="brush: js">// ECMA-262 5판, 15.4.4.17항의 작성 과정 +// 출처: http://es5.github.io/#x15.4.4.17 +if (!Array.prototype.some) { + Array.prototype.some = function(fun/*, thisArg*/) { + 'use strict'; + + if (this == null) { + throw new TypeError('Array.prototype.some called on null or undefined'); + } + + if (typeof fun !== 'function') { + throw new TypeError(); + } + + var t = Object(this); + var len = t.length >>> 0; + + var thisArg = arguments.length >= 2 ? arguments[1] : void 0; + for (var i = 0; i < len; i++) { + if (i in t && fun.call(thisArg, t[i], i, t)) { + return true; + } + } + + return false; + }; +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.17', 'Array.prototype.some')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>초기 정의. JavaScript 1.6에서 구현됨.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.some', 'Array.prototype.some')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.some', 'Array.prototype.some')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.Array.some")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.find()")}}</li> + <li>{{jsxref("Array.prototype.forEach()")}}</li> + <li>{{jsxref("Array.prototype.every()")}}</li> + <li>{{jsxref("TypedArray.prototype.some()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/sort/index.html b/files/ko/web/javascript/reference/global_objects/array/sort/index.html new file mode 100644 index 0000000000..ddab9a428f --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/sort/index.html @@ -0,0 +1,245 @@ +--- +title: Array.prototype.sort() +slug: Web/JavaScript/Reference/Global_Objects/Array/sort +tags: + - Array + - JavaScript + - Method + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Array/sort +--- +<div>{{JSRef}}</div> + +<p><code><strong>sort()</strong></code> 메서드는 배열의 요소를 적절한 위치에 정렬한 후 그 배열을 반환합니다. 정렬은 <a href="https://en.wikipedia.org/wiki/Sorting_algorithm#Stability">stable sort</a>가 아닐 수 있습니다. 기본 정렬 순서는 문자열의 유니코드 코드 포인트를 따릅니다.</p> + +<p>정렬 속도와 복잡도는 각 구현방식에 따라 다를 수 있습니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/array-sort.html")}}</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>arr</var>.sort([<var>compareFunction]</var>) +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>compareFunction</code> {{optional_inline}}</dt> + <dd>정렬 순서를 정의하는 함수. 생략하면 배열은 각 요소의 문자열 변환에 따라 각 문자의 유니 코드 코드 포인트 값에 따라 정렬됩니다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>정렬한 배열. 원 배열이 정렬되는 것에 유의하세요. 복사본이 만들어지는 것이 아닙니다.</p> + +<h2 id="설명">설명</h2> + +<p><code>compareFunction</code>이 제공되지 않으면 요소를 문자열로 변환하고 유니 코드 코드 포인트 순서로 문자열을 비교하여 정렬됩니다. 예를 들어 "바나나"는 "체리"앞에옵니다. 숫자 정렬에서는 9가 80보다 앞에 오지만 숫자는 문자열로 변환되기 때문에 "80"은 유니 코드 순서에서 "9"앞에옵니다.</p> + +<p><code>compareFunction</code>이 제공되면 배열 요소는 compare 함수의 반환 값에 따라 정렬됩니다. a와 b가 비교되는 두 요소라면,</p> + +<ul> + <li><code>compareFunction(a, b)</code>이 0보다 작은 경우 a를 b보다 낮은 색인으로 정렬합니다. 즉, a가 먼저옵니다.</li> + <li><code>compareFunction(a, b)</code>이 0을 반환하면 a와 b를 서로에 대해 변경하지 않고 모든 다른 요소에 대해 정렬합니다. 참고 : ECMAscript 표준은 이러한 동작을 보장하지 않으므로 모든 브라우저(예 : Mozilla 버전은 적어도 2003 년 이후 버전 임)가 이를 존중하지는 않습니다.</li> + <li><code>compareFunction(a, b)</code>이 0보다 큰 경우, b를 a보다 낮은 인덱스로 소트합니다.</li> + <li><code>compareFunction(a, b)</code>은 요소 a와 b의 특정 쌍이 두 개의 인수로 주어질 때 항상 동일한 값을 반환해야합니다. 일치하지 않는 결과가 반환되면 정렬 순서는 정의되지 않습니다.</li> +</ul> + +<p>따라서 compare 함수의 형식은 다음과 같습니다.</p> + +<pre class="brush: js">function compare(a, b) { + if (a is less than b by some ordering criterion) { + return -1; + } + if (a is greater than b by the ordering criterion) { + return 1; + } + // a must be equal to b + return 0; +} +</pre> + +<p>문자열 대신 숫자를 비교하기 위해 compare 함수는 a에서 b를 뺄 수 있습니다. 다음 함수는 배열을 오름차순으로 정렬합니다 (Infinity 및 NaN이 포함되어 있지 않은 경우).</p> + +<pre class="brush: js">function compareNumbers(a, b) { + return a - b; +} +</pre> + +<p>sort 메소드는 {{jsxref ( "연산자 / 함수", "함수식", "", 1)}} (및 클로저)와 함께 편리하게 사용할 수 있습니다.</p> + +<pre class="brush: js">var numbers = [4, 2, 5, 1, 3]; +numbers.sort(function(a, b) { + return a - b; +}); +console.log(numbers); + +// [1, 2, 3, 4, 5] +</pre> + +<p>개체는 해당 속성 중 하나의 값을 기준으로 정렬 할 수 있습니다.</p> + +<pre class="brush: js">var items = [ + { name: 'Edward', value: 21 }, + { name: 'Sharpe', value: 37 }, + { name: 'And', value: 45 }, + { name: 'The', value: -12 }, + { name: 'Magnetic', value: 13 }, + { name: 'Zeros', value: 37 } +]; + +// value 기준으로 정렬 +items.sort(function (a, b) { + if (a.value > b.value) { + return 1; + } + if (a.value < b.value) { + return -1; + } + // a must be equal to b + return 0; +}); + +// name 기준으로 정렬 +items.sort(function(a, b) { + var nameA = a.name.toUpperCase(); // ignore upper and lowercase + var nameB = b.name.toUpperCase(); // ignore upper and lowercase + if (nameA < nameB) { + return -1; + } + if (nameA > nameB) { + return 1; + } + + // 이름이 같을 경우 + return 0; +});</pre> + +<h2 id="예제">예제</h2> + +<h3 id="배열_만들기_표시_및_정렬">배열 만들기, 표시 및 정렬</h3> + +<p>다음 예제에서는 네 개의 배열을 만들고 원래 배열을 표시 한 다음 정렬 된 배열을 표시합니다. 숫자 배열은 비교 함수없이 정렬 된 다음 비교 함수로 정렬됩니다.</p> + +<pre class="brush: js">var stringArray = ['Blue', 'Humpback', 'Beluga']; +var numericStringArray = ['80', '9', '700']; +var numberArray = [40, 1, 5, 200]; +var mixedNumericArray = ['80', '9', '700', 40, 1, 5, 200]; + +function compareNumbers(a, b) { + return a - b; +} + +console.log('stringArray:', stringArray.join()); +console.log('Sorted:', stringArray.sort()); + +console.log('numberArray:', numberArray.join()); +console.log('Sorted without a compare function:', numberArray.sort()); +console.log('Sorted with compareNumbers:', numberArray.sort(compareNumbers)); + +console.log('numericStringArray:', numericStringArray.join()); +console.log('Sorted without a compare function:', numericStringArray.sort()); +console.log('Sorted with compareNumbers:', numericStringArray.sort(compareNumbers)); + +console.log('mixedNumericArray:', mixedNumericArray.join()); +console.log('Sorted without a compare function:', mixedNumericArray.sort()); +console.log('Sorted with compareNumbers:', mixedNumericArray.sort(compareNumbers)); +</pre> + +<p>이 예제는 다음 출력을 생성합니다. 결과가 보여 주듯이 비교 함수가 사용되면 숫자는 숫자 또는 숫자 문자열인지 여부에 관계없이 올바르게 정렬됩니다.</p> + +<pre>stringArray: Blue,Humpback,Beluga +Sorted: Beluga,Blue,Humpback + +numberArray: 40,1,5,200 +Sorted without a compare function: 1,200,40,5 +Sorted with compareNumbers: 1,5,40,200 + +numericStringArray: 80,9,700 +Sorted without a compare function: 700,80,9 +Sorted with compareNumbers: 9,80,700 + +mixedNumericArray: 80,9,700,40,1,5,200 +Sorted without a compare function: 1,200,40,5,700,80,9 +Sorted with compareNumbers: 1,5,9,40,80,200,700 +</pre> + +<h3 id="비_ASCII_문자_정렬">비 ASCII 문자 정렬</h3> + +<p>ASCII 이외의 문자, 즉 악센트 부호가있는 문자 (e, é, è, a, ä 등)가있는 문자열을 정렬하려면 영어가 아닌 다른 언어의 문자열에 {{jsxref ( "String.localeCompare")}}를 사용하십시오. 이 함수는 해당 문자를 비교하여 올바른 순서로 나타낼 수 있습니다.</p> + +<pre class="brush: js">var items = ['réservé', 'premier', 'cliché', 'communiqué', 'café', 'adieu']; +items.sort(function (a, b) { + return a.localeCompare(b); +}); + +// items is ['adieu', 'café', 'cliché', 'communiqué', 'premier', 'réservé'] +</pre> + +<h3 id="map을_사용한_정렬">map을 사용한 정렬</h3> + +<p><code>compareFunction</code>은 배열 내의 요소마다 여러 번 호출될 수 있습니다. 이러한 <code>compareFunction</code>의 성질에 따라, 높은 오버헤드가 발생할 수도 있습니다. <code>compareFunction</code>이 복잡해지고, 정렬할 요소가 많아질 경우, <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a>을 사용한 정렬을 고려해보는 것이 좋습니다. 이 방법은 임시 배열을 하나 만들어서 여기에 실제 정렬에 사용할 값만을 뽑아서 넣어서 이를 정렬하고, 그 결과를 이용해서 실제 정렬을 하는 것입니다.</p> + +<pre class="brush: js">// 소트 할 배열 +var list = ['Delta', 'alpha', 'CHARLIE', 'bravo']; + +// 임시 배열은 위치 및 정렬 값이있는 객체를 보유합니다. +var mapped = list.map(function(el, i) { + return { index: i, value: el.toLowerCase() }; +}) + +// 축소 치를 포함한 매핑 된 배열의 소트 +mapped.sort(function(a, b) { + return +(a.value > b.value) || +(a.value === b.value) - 1; +}); + +// 결과 순서를 위한 컨테이너 +var result = mapped.map(function(el){ + return list[el.index]; +}); +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.11', 'Array.prototype.sort')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.sort', 'Array.prototype.sort')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.sort', 'Array.prototype.sort')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.Array.sort")}}</div> + +<div id="compat-mobile"></div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.reverse()")}}</li> + <li>{{jsxref("String.prototype.localeCompare()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/splice/index.html b/files/ko/web/javascript/reference/global_objects/array/splice/index.html new file mode 100644 index 0000000000..eb2a09af12 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/splice/index.html @@ -0,0 +1,153 @@ +--- +title: Array.prototype.splice() +slug: Web/JavaScript/Reference/Global_Objects/Array/splice +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/splice +--- +<div>{{JSRef}}</div> + +<p><code><strong>splice()</strong></code> 메서드는 배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-splice.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">array.splice(<em>start</em>[, <em>deleteCount</em>[, <em>item1</em>[, <em>item2</em>[, <em>...</em>]]]]) +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>start</code></dt> + <dd>배열의 변경을 시작할 인덱스입니다. 배열의 길이보다 큰 값이라면 실제 시작 인덱스는 배열의 길이로 설정됩니다. 음수인 경우 배열의 끝에서부터 요소를 세어나갑니다(원점 -1, 즉 -n이면 요소 끝의 n번째 요소를 가리키며 <code>array.length - n</code>번째 인덱스와 같음). 값의 절대값이 배열의 길이 보다 큰 경우 0으로 설정됩니다.</dd> + <dt><code>deleteCount</code> {{optional_inline}}</dt> + <dd>배열에서 제거할 요소의 수입니다.</dd> + <dd><code>deleteCount</code>를 생략하거나 값이 <code>array.length - start</code>보다 크면 <code>start</code>부터의 모든 요소를 제거합니다.</dd> + <dd><code>deleteCount</code>가 0 이하라면 어떤 요소도 제거하지 않습니다. 이 때는 최소한 하나의 새로운 요소를 지정해야 합니다.</dd> + <dt><code>item1, item2, <em>...</em></code> {{optional_inline}}</dt> + <dd>배열에 추가할 요소입니다. 아무 요소도 지정하지 않으면 <code>splice()</code>는 요소를 제거하기만 합니다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>제거한 요소를 담은 배열. 하나의 요소만 제거한 경우 길이가 1인 배열을 반환합니다. 아무 값도 제거하지 않았으면 빈 배열을 반환합니다.</p> + +<h2 id="설명">설명</h2> + +<p>만약 제거할 요소의 수와 추가할 요소의 수가 다른 경우 배열의 길이는 달라집니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="하나도_제거하지_않고_2번_인덱스에_drum_추가">하나도 제거하지 않고, 2번 인덱스에 "drum" 추가</h3> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; +var removed = myFish.splice(2, 0, 'drum'); + +// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"] +// removed is [], no elements removed</pre> + +<h3 id="하나도_제거하지_않고_2번_인덱스에_drum과_guitar_추가">하나도 제거하지 않고, 2번 인덱스에 "drum"과 "guitar" 추가</h3> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; +var removed = myFish.splice(2, 0, 'drum', 'guitar'); + +// myFish is ["angel", "clown", "drum", "guitar", "mandarin", "sturgeon"] +// removed is [], no elements removed +</pre> + +<h3 id="3번_인덱스에서_한_개_요소_제거">3번 인덱스에서 한 개 요소 제거</h3> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon']; +var removed = myFish.splice(3, 1); + +// removed is ["mandarin"] +// myFish is ["angel", "clown", "drum", "sturgeon"] +</pre> + +<h3 id="2번_인덱스에서_한_개_요소_제거하고_trumpet_추가">2번 인덱스에서 한 개 요소 제거하고 "trumpet" 추가</h3> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'drum', 'sturgeon']; +var removed = myFish.splice(2, 1, 'trumpet'); + +// myFish is ["angel", "clown", "trumpet", "sturgeon"] +// removed is ["drum"]</pre> + +<h3 id="0번_인덱스에서_두_개_요소_제거하고_parrot_anemone_blue_추가">0번 인덱스에서 두 개 요소 제거하고 "parrot", "anemone", "blue" 추가</h3> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'trumpet', 'sturgeon']; +var removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue'); + +// myFish is ["parrot", "anemone", "blue", "trumpet", "sturgeon"] +// removed is ["angel", "clown"]</pre> + +<h3 id="2번_인덱스에서_두_개_요소_제거">2번 인덱스에서 두 개 요소 제거</h3> + +<pre class="brush: js">var myFish = ['parrot', 'anemone', 'blue', 'trumpet', 'sturgeon']; +var removed = myFish.splice(myFish.length - 3, 2); + +// myFish is ["parrot", "anemone", "sturgeon"] +// removed is ["blue", "trumpet"]</pre> + +<h3 id="-2번_인덱스에서_한_개_요소_제거">-2번 인덱스에서 한 개 요소 제거</h3> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; +var removed = myFish.splice(-2, 1); + +// myFish is ["angel", "clown", "sturgeon"] +// removed is ["mandarin"]</pre> + +<h3 id="2번_인덱스를_포함해서_이후의_모든_요소_제거">2번 인덱스를 포함해서 이후의 모든 요소 제거</h3> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; +var removed = myFish.splice(2); + +// myFish is ["angel", "clown"] +// removed is ["mandarin", "sturgeon"]</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.12', 'Array.prototype.splice')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.splice', 'Array.prototype.splice')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Array.splice")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.push()", "push()")}} / {{jsxref("Array.prototype.pop()", "pop()")}} — 배열 끝에 요소를 추가하거나 제거</li> + <li>{{jsxref("Array.prototype.unshift()", "unshift()")}} / {{jsxref("Array.prototype.shift()", "shift()")}} — 배열 처음에 요소를 추가하거나 제거</li> + <li>{{jsxref("Array.prototype.concat()", "concat()")}} — 배열과 배열 또는 값을 합친 새로운 배열 반환</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/tolocalestring/index.html b/files/ko/web/javascript/reference/global_objects/array/tolocalestring/index.html new file mode 100644 index 0000000000..4fc1bd7f1a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/tolocalestring/index.html @@ -0,0 +1,195 @@ +--- +title: Array.prototype.toLocaleString() +slug: Web/JavaScript/Reference/Global_Objects/Array/toLocaleString +tags: + - Array + - Internationalization + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/toLocaleString +--- +<div>{{JSRef}}</div> + +<p><code><strong>toLocaleString()</strong></code> 메서드는 배열의 요소를 나타내는 문자열을 반환합니다. 요소는 <code>toLocaleString</code> 메서드를 사용하여 문자열로 변환되고 이 문자열은 locale 고유 문자열(가령 쉼표 “,”)에 의해 분리됩니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/array-tolocalestring.html")}}</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>arr</var>.toLocaleString([locales[, options]]);</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>locales</code> {{optional_inline}}</dt> + <dd>A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the <code>locales</code> argument, see the {{jsxref("Intl")}} page.</dd> + <dt><code>options</code> {{optional_inline}}</dt> + <dd>An object with configuration properties, for numbers see {{jsxref("Number.prototype.toLocaleString()")}}, and for dates see {{jsxref("Date.prototype.toLocaleString()")}}.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>배열의 요소를 표현하는 문자열.</p> + +<h2 id="설명">설명</h2> + +<p>배열의 요소는 <code>toLocaleString</code> 메서드를 사용하여 문자열로 변환됩니다:</p> + +<ul> + <li><code>Object</code>: {{jsxref("Object.prototype.toLocaleString()")}}</li> + <li><code>Number</code>: {{jsxref("Number.prototype.toLocaleString()")}}</li> + <li><code>Date</code>: {{jsxref("Date.prototype.toLocaleString()")}}</li> +</ul> + +<h2 id="예제">예제</h2> + +<h3 id="toLocaleString_사용"><code>toLocaleString</code> 사용</h3> + +<pre class="brush: js">var number = 1337; +var date = new Date(); +var myArr = [number, date, 'foo']; + +var str = myArr.toLocaleString(); + +console.log(str); +// '1337,6.12.2013 19:37:35,foo' 출력(log) +// Europe/Berlin 시간대로 German (de-DE) locale에서 실행하는 경우 +</pre> + +<h2 id="폴리필">폴리필</h2> + +<pre class="brush: js">// https://tc39.github.io/ecma402/#sup-array.prototype.tolocalestring +if (!Array.prototype.toLocaleString) { + Object.defineProperty(Array.prototype, 'toLocaleString', { + value: function(locales, options) { + // 1. Let O be ? ToObject(this value). + if (this == null) { + throw new TypeError('"this" is null or not defined'); + } + + var a = Object(this); + + // 2. Let len be ? ToLength(? Get(A, "length")). + var len = a.length >>> 0; + + // 3. Let separator be the String value for the + // list-separator String appropriate for the + // host environment's current locale (this is + // derived in an implementation-defined way). + // NOTE: In this case, we will use a comma + var separator = ','; + + // 4. If len is zero, return the empty String. + if (len === 0) { + return ''; + } + + // 5. Let firstElement be ? Get(A, "0"). + var firstElement = a[0]; + // 6. If firstElement is undefined or null, then + // a.Let R be the empty String. + // 7. Else, + // a. Let R be ? + // ToString(? + // Invoke( + // firstElement, + // "toLocaleString", + // « locales, options » + // ) + // ) + var r = firstElement == null ? + '' : firstElement.toLocaleString(locales, options); + + // 8. Let k be 1. + var k = 1; + + // 9. Repeat, while k < len + while (k < len) { + // a. Let S be a String value produced by + // concatenating R and separator. + var s = r + separator; + + // b. Let nextElement be ? Get(A, ToString(k)). + var nextElement = a[k]; + + // c. If nextElement is undefined or null, then + // i. Let R be the empty String. + // d. Else, + // i. Let R be ? + // ToString(? + // Invoke( + // nextElement, + // "toLocaleString", + // « locales, options » + // ) + // ) + r = nextElement == null ? + '' : nextElement.toLocaleString(locales, options); + + // e. Let R be a String value produced by + // concatenating S and R. + r = s + r; + + // f. Increase k by 1. + k++; + } + + // 10. Return R. + return r; + } + }); +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.4.3', 'Array.prototype.toLocaleString')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.tolocalestring', 'Array.prototype.toLocaleString')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.tolocalestring', 'Array.prototype.toLocaleString')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES Int Draft', '#sup-array.prototype.tolocalestring', 'Array.prototype.toLocaleString')}}</td> + <td>{{Spec2('ES Int Draft')}}</td> + <td>This definition supersedes the definition provided in ECMA-262.</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.Array.toLocaleString")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.toString()")}}</li> + <li>{{jsxref("Intl")}}</li> + <li>{{jsxref("Object.prototype.toLocaleString()")}}</li> + <li>{{jsxref("Number.prototype.toLocaleString()")}}</li> + <li>{{jsxref("Date.prototype.toLocaleString()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/tosource/index.html b/files/ko/web/javascript/reference/global_objects/array/tosource/index.html new file mode 100644 index 0000000000..e503b9c617 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/tosource/index.html @@ -0,0 +1,71 @@ +--- +title: Array.prototype.toSource() +slug: Web/JavaScript/Reference/Global_Objects/Array/toSource +tags: + - Array + - JavaScript + - Method + - Non-standard + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/toSource +--- +<div>{{JSRef}} {{non-standard_header}}</div> + +<p><code><strong>toSource()</strong></code> 메서드는 해당 배열의 소스 코드를 문자열로 반환합니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>arr</var>.toSource()</pre> + +<h3 id="반환_값">반환 값</h3> + +<p>배열의 소스 코드를 나타내는 문자열을 반환합니다.</p> + +<h2 id="설명">설명</h2> + +<p><code>toSource</code> 메서드는 다음의 값을 반환합니다.</p> + +<ul> + <li>내장 된 {{jsxref("Array")}} 객체의 경우에는 <code>toSource</code>는 소스 코드를 사용할 수 없음을 나타내며 다음의 문자열을 반환합니다. + + <pre class="brush: js">function Array() { + [native code] +} +</pre> + </li> + <li>{{jsxref("Array")}} 인스턴스의 경우에는<code>toSource</code>는 소스 코드를 나타내는 문자열을 반환합니다.</li> +</ul> + +<p>이 메서드는 보통 코드에 명시되지 않고 자바스크립트 내부적으로 호출됩니다. 디버깅을 위해 <code>toSource</code>를 호출하여 배열의 내용을 검사할 수 있습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="배열의_소스_코드_검사하기">배열의 소스 코드 검사하기</h3> + +<p>다음 코드는 배열의 소스 코드 문자열을 생성합니다.</p> + +<pre class="brush: js">var alpha = new Array('a', 'b', 'c'); + +alpha.toSource(); +//returns ['a', 'b', 'c'] +</pre> + +<h2 id="명세">명세</h2> + +<p>Not part of any standard. Implemented in JavaScript 1.3.</p> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.toSource")}}</p> +</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Object.prototype.toSource()")}}</li> + <li>{{jsxref("Array.prototype.toString()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/tostring/index.html b/files/ko/web/javascript/reference/global_objects/array/tostring/index.html new file mode 100644 index 0000000000..9a1179be14 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/tostring/index.html @@ -0,0 +1,80 @@ +--- +title: Array.prototype.toString() +slug: Web/JavaScript/Reference/Global_Objects/Array/toString +tags: + - Array + - JavaScript + - Method + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Array/toString +--- +<div>{{JSRef}}</div> + +<p><code><strong>toString()</strong></code> 메서드는 지정된 배열 및 그 요소를 나타내는 문자열을 반환합니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/array-tostring.html")}}</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>arr</var>.toString()</code></pre> + +<h3 id="반환_값">반환 값</h3> + +<p>배열을 표현하는 문자열을 반환합니다.</p> + +<h2 id="설명">설명</h2> + +<p>{{jsxref("Array")}} 객체는 {{jsxref("Object")}}의 <code>toString</code> 메서드를 재정의(override)합니다. Array 객체에 대해, <code>toString</code> 메서드는 배열을 합쳐(join) 쉼표로 구분된 각 배열 요소를 포함하는 문자열 하나를 반환합니다. 예를 들어, 다음 코드는 배열을 생성하며 그 배열을 문자열로 변환하기 위해 <code>toString</code>을 사용합니다.</p> + +<pre class="brush: js">var monthNames = ['Jan', 'Feb', 'Mar', 'Apr']; +var myVar = monthNames.toString(); // 'Jan,Feb,Mar,Apr'을 myVar에 할당. +</pre> + +<p>JavaScript는 배열이 텍스트 값으로 표현되거나 배열이 문자열 연결(concatenation)에 참조될 때 자동으로 <code>toString</code> 메서드를 호출합니다.</p> + +<h3 id="ECMAScript_5_의미">ECMAScript 5 의미</h3> + +<p>JavaScript 1.8.5 (Firefox 4)부터, ECMAScript 제5판 의미(semantics)와 일치하는 <code>toString()</code> 메서드는 일반(generic) 메서드이므로 모든 객체에 사용될 수 있습니다. 객체가 <code>join()</code> 메서드가 있는 경우, 호출되어 그 값이 반환됩니다. 그렇지 않으면 {{jsxref("Object.prototype.toString()")}}가 호출되어 그 결과값이 반환됩니다.</p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>초기 정의. JavaScript 1.1에서 구현됨.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.2', 'Array.prototype.toString')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.tostring', 'Array.prototype.toString')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.tostring', 'Array.prototype.toString')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.Array.toString")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.join()")}}</li> + <li>{{jsxref("Object.prototype.toSource()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/unshift/index.html b/files/ko/web/javascript/reference/global_objects/array/unshift/index.html new file mode 100644 index 0000000000..c4a03fd091 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/unshift/index.html @@ -0,0 +1,91 @@ +--- +title: Array.prototype.unshift() +slug: Web/JavaScript/Reference/Global_Objects/Array/unshift +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/unshift +--- +<div>{{JSRef}}</div> + +<p><code><strong>unshift()</strong></code> 메서드는 새로운 요소를 배열의 맨 앞쪽에 추가하고, 새로운 길이를 반환합니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/array-unshift.html")}}</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>arr</var>.unshift([...elementN])</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>element<em>N</em></code></dt> + <dd>배열 맨 앞에 추가할 요소.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>메서드를 호출한 배열의 새로운 {{jsxref("Array.length", "length")}} 속성.</p> + +<h2 id="설명">설명</h2> + +<p><code>unshift</code> 메서드는 배열 형태의 객체 시작점에 주어진 값을 삽입합니다.</p> + +<p><code>unshift</code>는 제네릭하도록 설계되었으며, 배열 형태를 가진 객체가 {{jsxref("Function.call", "호출", "", 1)}}하거나 객체에 {{jsxref("Function.apply", "적용", "", 1)}}할 수 있습니다. <code>length</code> 속성을 가지지 않고, 대신 마지막 요소를 0부터 시작하는 순차적 인덱스로만 나타내는 객체에서는 의도한 것과 다르게 행동할 수 있습니다.</p> + +<h2 id="예제">예제</h2> + +<pre class="brush: js">var arr = [1, 2]; + +arr.unshift(0); // result of call is 3, the new array length +// arr is [0, 1, 2] + +arr.unshift(-2, -1); // = 5 +// arr is [-2, -1, 0, 1, 2] + +arr.unshift([-3]); +// arr is [[-3], -2, -1, 0, 1, 2] +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">비고</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.13', 'Array.prototype.unshift')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.unshift', 'Array.prototype.unshift')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.Array.unshift")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.push()")}}</li> + <li>{{jsxref("Array.prototype.pop()")}}</li> + <li>{{jsxref("Array.prototype.shift()")}}</li> + <li>{{jsxref("Array.prototype.concat()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/array/values/index.html b/files/ko/web/javascript/reference/global_objects/array/values/index.html new file mode 100644 index 0000000000..eb66adb964 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/values/index.html @@ -0,0 +1,87 @@ +--- +title: Array.prototype.values() +slug: Web/JavaScript/Reference/Global_Objects/Array/values +tags: + - Array + - ECMAScript 2015 + - Iterator + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/values +--- +<div>{{JSRef}}</div> + +<p><strong><code>values()</code></strong> 메서드는 배열의 각 인덱스에 대한 값을 가지는 새로운 <strong><code>Array Iterator</code></strong> 객체를 반환합니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/array-values.html")}}</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>arr</var>.values() +</pre> + +<h3 id="반환_값">반환 값</h3> + +<p>새로운 {{jsxref("Array")}} 반복기 객체.</p> + +<h2 id="예제">예제</h2> + +<h3 id="for...of_루프를_통한_반복"><code>for...of</code> 루프를 통한 반복</h3> + +<pre class="brush: js">var arr = ['w', 'y', 'k', 'o', 'p']; +var eArr = arr.values(); +// your browser must support for..of loop +// and let-scoped variables in for loops +for (let letter of eArr) { + console.log(letter); +} +</pre> + +<h3 id="다른_반복법">다른 반복법</h3> + +<pre class="brush: js">var arr = ['w', 'y', 'k', 'o', 'p']; +var eArr = arr.values(); +console.log(eArr.next().value); // w +console.log(eArr.next().value); // y +console.log(eArr.next().value); // k +console.log(eArr.next().value); // o +console.log(eArr.next().value); // p +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">비고</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-array.prototype.values', 'Array.prototype.values')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.values', 'Array.prototype.values')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.Array.values")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.keys()")}}</li> + <li>{{jsxref("Array.prototype.entries()")}}</li> + <li>{{jsxref("Array.prototype.forEach()")}}</li> + <li>{{jsxref("Array.prototype.every()")}}</li> + <li>{{jsxref("Array.prototype.some()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/arraybuffer/arraybuffer/index.html b/files/ko/web/javascript/reference/global_objects/arraybuffer/arraybuffer/index.html new file mode 100644 index 0000000000..4012646fa4 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/arraybuffer/arraybuffer/index.html @@ -0,0 +1,70 @@ +--- +title: ArrayBuffer() 생성자 +slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/ArrayBuffer +tags: + - ArrayBuffer + - Constructor + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/ArrayBuffer +--- +<div>{{JSRef}}</div> + +<p><strong><code>ArrayBuffer()</code></strong> 생성자는 {{jsxref("ArrayBuffer")}} 객체를 생성합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/arraybuffer-constructor.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">new ArrayBuffer(<em>length</em>) +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>length</code></dt> + <dd>생성할 <code>ArrayBuffer</code>의 바이트 크기.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>지정한 크기를 가진 새로운 <code>ArrayBuffer</code> 객체. 내용은 모두 0으로 초기화됩니다.</p> + +<h3 id="예외">예외</h3> + +<p><code>length</code>가 {{jsxref("Number.MAX_SAFE_INTEGER")}}보다 크거나, 음수면 {{jsxref("RangeError")}}.</p> + +<h2 id="예제">예제</h2> + +<p>아래 예제 코드는 8바이트 버퍼를 생성한 후 {{jsxref("Int32Array")}} 뷰로 그 버퍼를 참조합니다.</p> + +<pre class="brush: js">var buffer = new ArrayBuffer(8); +var view = new Int32Array(buffer);</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.ArrayBuffer.ArrayBuffer")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Typed_arrays">JavaScript 형식화 배열</a></li> + <li>{{jsxref("SharedArrayBuffer")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/arraybuffer/bytelength/index.html b/files/ko/web/javascript/reference/global_objects/arraybuffer/bytelength/index.html new file mode 100644 index 0000000000..b17502631a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/arraybuffer/bytelength/index.html @@ -0,0 +1,57 @@ +--- +title: ArrayBuffer.prototype.byteLength +slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/byteLength +tags: + - ArrayBuffer + - JavaScript + - Property + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/byteLength +--- +<div>{{JSRef}}</div> + +<p><code><strong>byteLength</strong></code> 접근자 속성은 {{jsxref("ArrayBuffer")}}의 길이를 바이트 단위로 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/arraybuffer-bytelength.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>arr</var>aybuffer.byteLength</pre> + +<h2 id="설명">설명</h2> + +<p><code>byteLength</code> 속성은 설정자 속성이 <code>undefined</code>인 접근자 속성으로, 오직 읽기만 가능합니다. <code>byteLength</code>는 배열 버퍼를 처음 생성할 때 정해지며 바꿀 수 없습니다. <code>ArrayBuffer</code>가 분리된 경우 0을 반환합니다.</p> + +<h2 id="예제">예제</h2> + +<pre class="brush:js">var buffer = new ArrayBuffer(8); +buffer.byteLength; // 8 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-get-arraybuffer.prototype.bytelength', 'ArrayBuffer.prototype.byteLength')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.ArrayBuffer.byteLength")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("ArrayBuffer")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/arraybuffer/index.html b/files/ko/web/javascript/reference/global_objects/arraybuffer/index.html new file mode 100644 index 0000000000..8b5b0cd361 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/arraybuffer/index.html @@ -0,0 +1,97 @@ +--- +title: ArrayBuffer +slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer +tags: + - ArrayBuffer + - JavaScript + - Reference + - TypedArrays +translation_of: Web/JavaScript/Reference/Global_Objects/ArrayBuffer +--- +<div>{{JSRef}}</div> + +<p><strong><code>ArrayBuffer</code></strong> 객체는 일반적인 고정 길이 원시 이진 데이터 버퍼를 나타냅니다.</p> + +<p>ArrayBuffer는 바이트로 구성된 배열로, 다른 언어에서는 종종 "바이트 배열"이라고 부릅니다. <code>ArrayBuffer</code>에 담긴 정보를 직접 수정하는 것은 불가능하지만, 대신 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/TypedArray">형식화 배열</a>이나 {{jsxref("DataView")}} 객체를 통해 버퍼를 특정 형식으로 나타내고, 이를 통해 버퍼의 내용을 읽거나 쓸 수 있습니다.</p> + +<p>{{jsxref("ArrayBuffer.ArrayBuffer", "ArrayBuffer()")}} 생성자는 주어진 길이를 가진 새로운 <code>ArrayBuffer</code>를 생성합니다. 또한 Base64 문자열이나 <a href="/ko/docs/Web/API/FileReader/readAsArrayBuffer">로컬 파일</a>처럼 기존 데이터에서 배열 버퍼를 생성할 수도 있습니다.</p> + +<h2 id="생성자">생성자</h2> + +<dl> + <dt>{{jsxref("ArrayBuffer.ArrayBuffer", "ArrayBuffer()")}}</dt> + <dd>새로운 <code>ArrayBuffer</code> 객체를 생성합니다.</dd> +</dl> + +<h2 id="속성">속성</h2> + +<dl> + <dt><code>ArrayBuffer.length</code></dt> + <dd><code>ArrayBuffer</code> 생성자의 길이 속성으로, 값은 1입니다.</dd> + <dt>{{jsxref("ArrayBuffer.@@species", "get ArrayBuffer[@@species]")}}</dt> + <dd>파생 객체를 생성할 때 사용할 생성자 함수입니다.</dd> + <dt><code>ArrayBuffer.prototype</code></dt> + <dd>모든 <code>ArrayBuffer</code> 객체에 속성을 추가할 수 있습니다.</dd> +</dl> + +<h2 id="메서드">메서드</h2> + +<dl> + <dt>{{jsxref("ArrayBuffer.isView()")}}</dt> + <dd>주어진 매개변수가 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/TypedArray">형식화 배열</a> 객체 또는 {{jsxref("DataView")}}와 같은 <code>ArrayBuffer</code>의 뷰면 <code>true</code>를, 아니면 <code>false</code>를 반환합니다.</dd> + <dt>{{jsxref("ArrayBuffer.transfer()")}} {{experimental_inline}}</dt> + <dd>주어진 버퍼의 내용으로 새로운 버퍼를 만들고, 그 길이를 지정한 길이만큼 자르거나 확장(0 초기화)한 후 반환합니다.</dd> +</dl> + +<h2 id="인스턴스">인스턴스</h2> + +<p>모든 <code>ArrayBuffer</code> 인스턴스는 <code>ArrayBuffer.prototype</code>을 상속합니다.</p> + +<h3 id="속성_2">속성</h3> + +<dl> + <dt><code>ArrayBuffer.prototype.constructor</code></dt> + <dd>객체의 프로토타입을 생성하는 함수를 지정합니다. 초깃값은 내장 <code>ArrayBuffer</code> 생성자입니다.</dd> + <dt>{{jsxref("ArrayBuffer.prototype.byteLength")}} {{readonlyInline}}</dt> + <dd><code>ArrayBuffer</code>의 바이트 길이입니다. 처음 생성 시 정해지며 변경할 수 없습니다.</dd> +</dl> + +<h3 id="메서드_2">메서드</h3> + +<dl> + <dt>{{jsxref("ArrayBuffer.prototype.slice()")}}</dt> + <dd><code>ArrayBuffer</code>를 지정한 위치에서 잘라낸 새로운 <code>ArrayBuffer</code>를 반환합니다.</dd> +</dl> + +<h2 id="예제">예제</h2> + +<p>다음 코드는 8바이트 버퍼를 생성하고, {{jsxref("Global_Objects/Int32Array", "Int32Array")}} 뷰로 그 버퍼를 참조합니다.</p> + +<pre class="brush: js">const buffer = new ArrayBuffer(8); +const view = new Int32Array(buffer);</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-arraybuffer-objects', 'ArrayBuffer')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.ArrayBuffer")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Typed_arrays" title="en/JavaScript typed arrays">JavaScript 형식화 배열</a></li> + <li>{{jsxref("SharedArrayBuffer")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/arraybuffer/isview/index.html b/files/ko/web/javascript/reference/global_objects/arraybuffer/isview/index.html new file mode 100644 index 0000000000..c68d5e0ef3 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/arraybuffer/isview/index.html @@ -0,0 +1,76 @@ +--- +title: ArrayBuffer.isView() +slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView +tags: + - ArrayBuffer + - JavaScript + - Method + - Reference + - TypedArrays +translation_of: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView +--- +<div>{{JSRef}}</div> + +<p><code><strong>ArrayBuffer.isView()</strong></code> 메서드는 주어진 값이 <code>ArrayBuffer</code> 뷰, 즉 <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray">형식화 배열 객체</a> 또는 {{jsxref("DataView")}}인지 판별합니다..</p> + +<div>{{EmbedInteractiveExample("pages/js/arraybuffer-isview.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">ArrayBuffer.isView(<em>value</em>)</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>value</code></dt> + <dd>판별할 값.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 값이 {{jsxref("ArrayBuffer")}} 뷰라면 <code>true</code>, 아니면 <code>false</code>.</p> + +<h2 id="예제">예제</h2> + +<pre class="brush: js">ArrayBuffer.isView(); // false +ArrayBuffer.isView([]); // false +ArrayBuffer.isView({}); // false +ArrayBuffer.isView(null); // false +ArrayBuffer.isView(undefined); // false +ArrayBuffer.isView(new ArrayBuffer(10)); // false + +ArrayBuffer.isView(new Uint8Array()); // true +ArrayBuffer.isView(new Float32Array()); // true +ArrayBuffer.isView(new Int8Array(10).subarray(0, 3)); // true + +const buffer = new ArrayBuffer(2); +const dv = new DataView(buffer); +ArrayBuffer.isView(dv); // true +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-arraybuffer.isview', 'ArrayBuffer.isView')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.ArrayBuffer.isView")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Typed_arrays" title="en/JavaScript typed arrays">JavaScript 형식화 배열</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/arraybuffer/slice/index.html b/files/ko/web/javascript/reference/global_objects/arraybuffer/slice/index.html new file mode 100644 index 0000000000..6c286be9aa --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/arraybuffer/slice/index.html @@ -0,0 +1,77 @@ +--- +title: ArrayBuffer.prototype.slice() +slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/slice +tags: + - ArrayBuffer + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/slice +--- +<div>{{JSRef}}</div> + +<p><code><strong>slice()</strong></code> 메서드는 현재 <code>ArrayBuffer</code>를 주어진 시작과 끝점에 맞춰 자른 새로운 <code>ArrayBuffer</code>를 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/arraybuffer-slice.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><em>arraybuffer</em>.slice(<em>begin</em>[, <em>end</em>])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>begin</code></dt> + <dd>자르기 시작할 지점을 나타내는 0 기반 인덱스.</dd> +</dl> + +<dl> + <dt><code>end</code> {{optional_inline}}</dt> + <dd>자르기 끝낼 지점을 나타내는 바이트 인덱스. 지정하지 않은 경우 새로운 <code>ArrayBuffer</code>는 지정한 시작점부터 현재 <code>ArrayBuffer</code>의 끝까지 가지게 됩니다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>새로운 {{jsxref("ArrayBuffer")}} 객체.</p> + +<h2 id="설명">설명</h2> + +<p><code>slice()</code> 메서드는 <code>end</code> 매개변수로 지정한 바이트 위치 바로 앞까지 현재 배열 버퍼를 복사합니다. <code>begin</code>과 <code>end</code>는 음의 값인 경우 배열의 시작부터 위치를 세지 않고 끝에서부터 셉니다.</p> + +<p><code>end</code> 값이 유효한 범위를 벗어날 경우 버퍼 길이에 맞춰 잘라냅니다. 또한 새로운 ArrayBuffer의 길이가 음의 값이 나올 경우 0으로 처리합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="ArrayBuffer_복사하기"><code>ArrayBuffer</code> 복사하기</h3> + +<pre class="brush: js">const buf1 = new ArrayBuffer(8); +const buf2 = buf1.slice(0); +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-arraybuffer.prototype.slice', 'ArrayBuffer.prototype.slice')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.ArrayBuffer.slice")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("ArrayBuffer")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/asyncfunction/index.html b/files/ko/web/javascript/reference/global_objects/asyncfunction/index.html new file mode 100644 index 0000000000..9578d2e534 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/asyncfunction/index.html @@ -0,0 +1,125 @@ +--- +title: AsyncFunction +slug: Web/JavaScript/Reference/Global_Objects/AsyncFunction +tags: + - JavaScript +translation_of: Web/JavaScript/Reference/Global_Objects/AsyncFunction +--- +<div>{{JSRef}}</div> + +<p><code><strong>Async</strong></code><strong><code>Function</code> 생성자는</strong> 새로운 {{jsxref("Statements/async_function", "async function")}} 객체를 만든다. 자바스크립트에서 모든 비동기 함수는 사실상 AsyncFunction 객체이다.</p> + +<p><code>AsyncFunction</code>이 전역변수가 아님에 주의한다. 다음코드를 보면 알 수 있다. </p> + +<pre class="brush: js">Object.getPrototypeOf(async function(){}).constructor +</pre> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox">new AsyncFunction([<var>arg1</var>[, <var>arg2</var>[, ...<var>argN</var>]],] <var>functionBody</var>)</pre> + +<h3 id="파라미터">파라미터</h3> + +<dl> + <dt><code>arg1, arg2, ... arg<em>N</em></code></dt> + <dd>인수의 이름들은 함수내에서 사용되는 이름이다. 이름은 자바스크립트 식별자 로 유용한 문자열이거나 컴마로 구분된 문자열 목록이어야 한다. 예를들면 "x","theValue",or"a,b"와 같다.</dd> + <dt><code>functionBody</code></dt> + <dd>함수 정의를 구성하는 자바스크립트 명령문들로 구성된 문자열.</dd> +</dl> + +<h2 id="상세설명">상세설명</h2> + +<p>AsyncFunction 생성자를 통해 만들어진 {{jsxref("Statements/async_function", "async function")}} 객체는 함수가 만들어질때 분석된다. 이방법에서는 코드가 실행되지 않을 때도 작동하기 때문에 {{jsxref("Statements/async_function", "async function expression")}} 으로 비동기함수를 정의하고 해당 코드에서 호출할 때보다 비효율적이다.</p> + +<p>함수에 전달된 모든 인수들은 전달된 순서대로 함수내에서 인수이름으로 식별자가 생성된 것처럼 다루어진다.</p> + +<div class="note"> +<p><strong>주의:</strong> <code>AsyncFunction</code> 생성자로 만들어진 {{jsxref("Statements/async_function", "async functions")}} 객체는 클로저를 생성 컨텍스트에 만들지 않는다; 이 객체들은 항상 전역 범위에서 생성됩니다. </p> + +<p><font><font>이객체들을 실행할 때, </font></font><code>AsyncFunction</code><font><font>생성자가 호출 </font><font>된 범위의 변수가 아니라 자신의 지역 변수와 전역 변수에만 액세스 할 수 있습니다 </font><font>.</font></font></p> + +<p><font><font>이것은 비동기 함수 표현식을위한 코드와 함께 {{jsxref ( "Global_Objects / eval", "eval")}}을 사용하는 것과 다릅니다.</font></font></p> +</div> + +<p><code>AsyncFunction</code> 생성자를 (<code>new</code> 연산자를 사용하지 않고) 함수로 호출하는 것과 생성자로 동작시키는 것은 동일하다.</p> + +<h2 id="속성">속성</h2> + +<dl> + <dt><code><strong>AsyncFunction.length</strong></code></dt> + <dd><code>AsyncFunction</code> 생성자의 <code>length</code> 속성(이 값은 1임).</dd> + <dt><strong><code>AsyncFunction.prototype</code></strong></dt> + <dd>모든 비동기 함수 객체에 속성을 추가할 수 있도록 함.</dd> + <dt><code><strong>AsyncFunction.constructor</strong></code></dt> + <dd>초기값은 {{jsxref("AsyncFunction")}}임.</dd> + <dt><code><strong>AsyncFunction.prototype[@@toStringTag]</strong></code></dt> + <dd>"AsyncFunction"을 반환.</dd> +</dl> + +<h2 id="AsyncFunction_인스턴스"><code>AsyncFunction 인스턴스</code></h2> + +<p><code>AsyncFunction</code> 인스턴스는 <code>AsyncFunction.prototype</code> 에서ㅜ메소드와 속성을 상속받는다.</p> + +<p>여느 생성자에서와 같이 모든 <code>AsyncFunction</code> 인스턴스들을 수정할 수 있도록 생성자의 <code>prototype</code> 객체를 수정할 수 있다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="AsyncFunction_생성자를_통한_비동기_함수_만들기"><code>AsyncFunction</code> 생성자를 통한 비동기 함수 만들기</h3> + +<pre>function resolveAfter2Seconds(x) { + return new Promise(resolve => { + setTimeout(() => { + resolve(x); + }, 2000); + }); +} + +let AsyncFunction = Object.getPrototypeOf(async function(){}).constructor + +let a = new AsyncFunction('a', + 'b', + 'return await resolveAfter2Seconds(a) + await resolveAfter2Seconds(b);'); + +a(10, 20).then(v => { + console.log(v); // 4초 후에 30을 출력 +});</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-async-function-objects', 'AsyncFunction object')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Initial definition in ES2017.</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div class="hidden"> +<p>The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> +</div> + +<p>{{Compat("javascript.builtins.AsyncFunction")}}</p> + + + +<h2 id="참고_문서">참고 문서</h2> + +<ul> + <li>{{jsxref("Statements/async_function", "async function function")}}</li> + <li>{{jsxref("Operators/async_function", "async function expression")}}</li> + <li>{{jsxref("Global_Objects/Function", "Function")}}</li> + <li>{{jsxref("Statements/function", "function statement")}}</li> + <li>{{jsxref("Operators/function", "function expression")}}</li> + <li>{{jsxref("Functions_and_function_scope", "Functions and function scope", "", 1)}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/atomics/index.html b/files/ko/web/javascript/reference/global_objects/atomics/index.html new file mode 100644 index 0000000000..6f155e8272 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/atomics/index.html @@ -0,0 +1,162 @@ +--- +title: Atomics +slug: Web/JavaScript/Reference/Global_Objects/Atomics +translation_of: Web/JavaScript/Reference/Global_Objects/Atomics +--- +<div>{{JSRef}} {{SeeCompatTable}}</div> + +<div><strong>Atomics 오브젝트</strong>는 atomic operations 정적메소드로서 제공됩니다. 다음과 같은 오브젝트와 함께 {{jsxref("SharedArrayBuffer")}} 사용합니다.</div> + +<p>Atomic operations Atomic Module을 인스톨해야합니다. 다른 global objects들과 다르게 Atomic은 constructor가 아닙니다. <strong>new operator</strong>를 사용하면 안되고 invoke Atomics object 함수로 사용하면됩니다. Atomics의 속성과 함수들은 static입니다. (as is the case with the {{jsxref("Math")}} object, for example).</p> + +<h2 id="Methods">Methods</h2> + +<h3 id="Atomic_operations">Atomic operations</h3> + +<p>메모리가 공유되었을때, 멀티쓰레드는 메모리안에 같은 데이터들을 읽거나 쓸 수 있습니다.<br> + Atomic operations은 예측 가능한 값을 쓰고 읽으며 다음 작업이 시작되기 전에 작업이 완료되고,작업이 중단되지 않도록합니다.</p> + +<dl> + <dt>{{jsxref("Atomics.add()")}}</dt> + <dd>Adds a given value at a given position in the array. Returns the old value at that position.</dd> + <dt>{{jsxref("Atomics.and()")}}</dt> + <dd>Computes a bitwise AND at a given position in the array. Returns the old value at that position.</dd> + <dt>{{jsxref("Atomics.compareExchange()")}}</dt> + <dd>Stores a given value at a given position in the array, if it equals a given value. Returns the old value.</dd> + <dt>{{jsxref("Atomics.exchange()")}}</dt> + <dd>Stores a given value at a given position in the array. Returns the old value.</dd> +</dl> + +<dl> + <dt>{{jsxref("Atomics.load()")}}</dt> + <dd>Returns the value at the given position in the array.</dd> + <dt>{{jsxref("Atomics.or()")}}</dt> + <dd>Computes a bitwise OR at a given position in the array. Returns the old value at that position.</dd> + <dt>{{jsxref("Atomics.store()")}}</dt> + <dd>Stores a given value at the given position in the array. Returns the value.</dd> + <dt>{{jsxref("Atomics.sub()")}}</dt> + <dd>Subtracts a given value at a given position in the array. Returns the old value at that position.</dd> + <dt>{{jsxref("Atomics.xor()")}}</dt> + <dd>Computes a bitwise XOR at a given position in the array. Returns the old value at that position.</dd> +</dl> + +<h3 id="Wait_and_wake">Wait and wake</h3> + +<p>The <code>wait()</code> and <code>wake()</code> methods are modeled on Linux futexes ("fast user-space mutex") and provide ways for waiting until a certain condition becomes true and are typically used as blocking constructs.</p> + +<dl> + <dt>{{jsxref("Atomics.wait()")}}</dt> + <dd> + <p>Verifies that a given position in the array still contains a given value and sleeps awaiting or times out. Returns either <code>"ok"</code>, <code>"not-equal"</code>, or <code>"timed-out"</code>. If waiting is not allowed in the calling agent then it throws an Error exception (most browsers will not allow <code>wait()</code> on the browser's main thread).</p> + </dd> + <dt>{{jsxref("Atomics.wake()")}}</dt> + <dd>Wakes up some agents that are sleeping in the wait queue on the given array position. Returns the number of agents that were woken up.</dd> + <dt>{{jsxref("Atomics.isLockFree()", "Atomics.isLockFree(size)")}}</dt> + <dd> + <p>An optimization primitive that can be used to determine whether to use locks or atomic operations. Returns <code>true</code>, if an atomic operation on arrays of the given element size will be implemented using a hardware atomic operation (as opposed to a lock). Experts only.</p> + </dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Shared Memory', '#AtomicsObject', 'Atomics')}}</td> + <td>{{Spec2('Shared Memory')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}} [2]</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop("46")}} [1] [3]</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile("46")}} [1]</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] This feature is disabled by a preference setting. In about:config, set <code>javascript.options.shared_memory</code> to <code>true</code>. </p> + +<p>[2] The implementation is under development and needs these runtime flags: <code>--js-flags=--harmony-sharedarraybuffer --enable-blink-feature=SharedArrayBuffer</code></p> + +<h2 id="Compatibility_notes">Compatibility notes</h2> + +<p>[3] The Shared memory specification is still stabilizing. Prior to SpiderMonkey 48 {{geckoRelease(48)}}, the latest API names and semantics weren't implemented yet. The changes between Firefox version 46 and version 48 are:</p> + +<ul> + <li>The methods <code>Atomics.futexWakeOrRequeue()</code> and <code>Atomics.fence()</code> are now removed entirely ({{bug(1259544)}} and {{bug(1225028)}}).</li> + <li>The methods {{jsxref("Atomics.wait()")}} and {{jsxref("Atomics.wake()")}} were named <code>Atomics.futexWait()</code> and <code>Atomics.futexWake()</code> ({{bug(1260910)}}). Note: The old names have been removed in version 49 and later ({{bug(1262062)}}).</li> + <li>The properties <code>Atomics.OK</code>, <code>Atomics.TIMEDOUT</code>, <code>Atomics.NOTEQUAL</code> have been removed. The {{jsxref("Atomics.wait()")}} method now returns the strings "ok", "timed-out" and "not-equal" ({{bug(1260835)}}).</li> + <li> + <p>The <code>count</code> parameter of the {{jsxref("Atomics.wake()")}} method has been changed: it now defaults to <code>+Infinity</code>, not <code>0</code> ({{bug(1253350)}}).</p> + </li> +</ul> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("ArrayBuffer")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Typed_arrays">JavaScript typed arrays</a></li> + <li><a href="/en-US/docs/Web/API/Web_Workers_API">Web Workers</a></li> + <li><a href="https://github.com/lars-t-hansen/parlib-simple">parlib-simple </a>– a simple library providing synchronization and work distribution abstractions.</li> + <li><a href="https://github.com/tc39/ecmascript_sharedmem/blob/master/TUTORIAL.md">Shared Memory – a brief tutorial</a></li> + <li><a href="https://hacks.mozilla.org/2016/05/a-taste-of-javascripts-new-parallel-primitives/">A Taste of JavaScript’s New Parallel Primitives – Mozilla Hacks</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/bigint/bigint/index.html b/files/ko/web/javascript/reference/global_objects/bigint/bigint/index.html new file mode 100644 index 0000000000..9a7405fac8 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/bigint/bigint/index.html @@ -0,0 +1,62 @@ +--- +title: BigInt() 생성자 +slug: Web/JavaScript/Reference/Global_Objects/BigInt/BigInt +tags: + - BigInt + - Constructor + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/BigInt/BigInt +--- +<div>{{JSRef}}</div> + +<p><strong><code>BigInt()</code></strong> 생성자는 {{jsxref("BigInt")}} 객체를 생성합니다.</p> + +<h2 id="구분">구분</h2> + +<pre class="syntaxbox">BigInt(<em>value</em>); +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>value</code></dt> + <dd>생성하는 객체에 할당할 숫자 값. 문자열 또는 정수를 사용할 수 있습니다.</dd> +</dl> + +<div class="blockIndicator note"> +<p><strong>참고</strong>: <code>BigInt()</code>는 {{jsxref("Operators/new", "new")}} 연산자와 함께 사용하지 않습니다.</p> +</div> + +<h2 id="예제">예제</h2> + +<pre class="brush: js">BigInt(123); +// 123n +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-bigint-constructor', 'BigInt constructor')}}</td> + <td>{{Spec2('ESDraft')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.BigInt.BigInt")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("BigInt")}} 클래스</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/bigint/index.html b/files/ko/web/javascript/reference/global_objects/bigint/index.html new file mode 100644 index 0000000000..dcfc19e799 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/bigint/index.html @@ -0,0 +1,280 @@ +--- +title: BigInt +slug: Web/JavaScript/Reference/Global_Objects/BigInt +tags: + - BigInt + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/BigInt +--- +<div>{{JSRef}}</div> + +<p><strong><code>BigInt</code></strong>는 {{jsxref("Number")}} 원시 값이 안정적으로 나타낼 수 있는 최대치인 2<sup>53</sup> - 1보다 큰 정수를 표현할 수 있는 내장 객체입니다.</p> + +<h2 id="설명">설명</h2> + +<p><code>BigInt</code>는 정수 리터럴의 뒤에 <code>n</code>을 붙이거나(<code>10n</code>) 함수 <code>BigInt()</code>를 호출해 생성할 수 있습니다.</p> + +<pre class="brush: js">const theBiggestInt = 9007199254740991n; + +const alsoHuge = BigInt(9007199254740991); +// ↪ 9007199254740991n + +const hugeString = BigInt("9007199254740991"); +// ↪ 9007199254740991n + +const hugeHex = BigInt("0x1fffffffffffff"); +// ↪ 9007199254740991n + +const hugeBin = BigInt("0b11111111111111111111111111111111111111111111111111111"); +// ↪ 9007199254740991n</pre> + +<p><code>BigInt</code>와 {{jsxref("Number")}}는 어떤 면에서 비슷하지만 중요한 차이점이 있습니다. 예컨대 <code>BigInt</code>는 내장 {{jsxref("Math")}} 객체의 메서드와 함께 사용할 수 없고, 연산에서 <code>Number</code>와 혼합해 사용할 수 없습니다. 따라서 먼저 같은 자료형으로 변환해야 합니다. 그러나, <code>BigInt</code>가 <code>Number</code>로 바뀌면 정확성을 잃을 수 있으니 주의해야 합니다.</p> + +<h3 id="자료형_정보">자료형 정보</h3> + +<p><code>BigInt</code>의 <code>typeof</code> 판별 결과는 <code>"bigint"</code>입니다.</p> + +<pre class="brush: js">typeof 1n === 'bigint'; // true +typeof BigInt('1') === 'bigint'; // true +</pre> + +<p>{{jsxref("Object")}}로 감싼 <code>BigInt</code>는 일반적인 <code>object</code> 자료형으로 취급합니다.</p> + +<pre class="brush: js">typeof Object(1n) === 'object'; // true +</pre> + +<h3 id="연산자">연산자</h3> + +<p><code>+</code>, <code>*</code>, <code>-</code>, <code>**</code>, <code>%</code> 연산자를 <code>BigInt</code>나 객체로 감싼 <code>BigInt</code>에서 사용할 수 있습니다. <a href="/ko/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators">비트 연산자</a>도 사용할 수 있으나, 모든 <code>BigInt</code>는 부호를 가져야 하므로 <code>>>></code> (부호 버림 오른쪽 시프트)는 사용할 수 없습니다. <a href="https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs">asm.js에서 문제를 일으키지 않도록</a>, 단항 <code>+</code> 연산자도 지원하지 않습니다.</p> + +<pre class="brush: js">const previousMaxSafe = BigInt(Number.MAX_SAFE_INTEGER); +// ↪ 9007199254740991 + +const maxPlusOne = previousMaxSafe + 1n; +// ↪ 9007199254740992n + +const theFuture = previousMaxSafe + 2n; +// ↪ 9007199254740993n, this works now! + +const multi = previousMaxSafe * 2n; +// ↪ 18014398509481982n + +const subtr = multi – 10n; +// ↪ 18014398509481972n + +const mod = multi % 10n; +// ↪ 2n + +const bigN = 2n ** 54n; +// ↪ 18014398509481984n + +bigN * -1n +// ↪ –18014398509481984n +</pre> + +<p><code>/</code> 연산자도 정수 연산에서 예상할 수 있는 결과를 동일하게 도출합니다. 그러나 <code>BigInt</code>는 <code>BigDecimal</code>이 아니므로, 연산의 결과는 언제나 소수점 이하를 버립니다. 즉, 정수가 아닌 결과는 나오지 않습니다.</p> + +<div class="blockIndicator warning"> +<p>소수점 결과를 포함하는 연산을 <code>BigInt</code>와 사용하면 소수점 이하는 사라집니다.</p> +</div> + +<pre class="brush: js">const expected = 4n / 2n; +// ↪ 2n + +const rounded = 5n / 2n; +// ↪ 2.5n이 아니라 2n +</pre> + +<h3 id="비교">비교</h3> + +<p><code>BigInt</code>는 {{jsxref("Number")}}와 일치하지 않지만 동등합니다.</p> + +<pre class="brush: js">0n === 0 +// ↪ false + +0n == 0 +// ↪ true</pre> + +<p><code>Number</code>와 <code>BigInt</code>는 일반적인 방법으로 비교할 수 있습니다.</p> + +<pre class="brush: js">1n < 2 +// ↪ true + +2n > 1 +// ↪ true + +2 > 2 +// ↪ false + +2n > 2 +// ↪ false + +2n >= 2 +// ↪ true</pre> + +<p>배열의 요소로 함께 사용했을 땐 정렬도 가능합니다.</p> + +<pre class="brush: js">const mixed = [4n, 6, -12n, 10, 4, 0, 0n]; +// ↪ [4n, 6, -12n, 10, 4, 0, 0n] + +mixed.sort(); +// ↪ [-12n, 0, 0n, 10, 4n, 4, 6] +</pre> + +<p>{{jsxref("Object")}}로 감싼 <code>BigInt</code>의 경우 다른 객체와 마찬가지로 자기 자신과 비교했을 때만 일치합니다.</p> + +<pre class="brush: js">0n === Object(0n); // false +Object(0n) === Object(0n); // false + +const o = Object(0n); +o === o // true +</pre> + +<h3 id="조건">조건</h3> + +<p><code>BigInt</code>는 다음의 상황에서는 {{jsxref("Number")}}처럼 행동합니다.</p> + +<ul> + <li>{{jsxref("Boolean")}} 함수를 사용해 Boolean 객체로 변환</li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Operators/%EB%85%BC%EB%A6%AC_%EC%97%B0%EC%82%B0%EC%9E%90(Logical_Operators)">논리 연산자</a> <code>||</code>, <code>&&</code>, <code>!</code>와 함께 사용</li> + <li>{{jsxref("Statements/if...else", "if")}}문 등 조건 판별 시</li> +</ul> + +<pre class="brush: js">if (0n) { + console.log('if에서 안녕!'); +} else { + console.log('else에서 안녕!'); +} + +// ↪ "else에서 안녕!" + +0n || 12n +// ↪ 12n + +0n && 12n +// ↪ 0n + +Boolean(0n) +// ↪ false + +Boolean(12n) +// ↪ true + +!12n +// ↪ false + +!0n +// ↪ true +</pre> + +<h2 id="생성자">생성자</h2> + +<dl> + <dt>{{jsxref("BigInt.BigInt", "BigInt()")}}</dt> + <dd><code>BigInt</code> 객체를 생성합니다.</dd> +</dl> + +<h2 id="정적_메서드">정적 메서드</h2> + +<dl> + <dt>{{jsxref("BigInt.asIntN()")}}</dt> + <dd>주어진 <code>BigInt</code>를 <code>-2<sup>width-1</sup></code>과 <code>2<sup>width-1</sup> - 1</code>의 범위로 자릅니다.</dd> + <dt>{{jsxref("BigInt.asUintN()")}}</dt> + <dd>주어진 <code>BigInt</code>를 <code>0</code>과 <code>2<sup>width</sup> - 1</code>의 범위로 자릅니다.</dd> +</dl> + +<h2 id="인스턴스_메서드">인스턴스 메서드</h2> + +<dl> + <dt>{{jsxref("BigInt.prototype.toLocaleString()")}}</dt> + <dd>BigInt를 주어진 언어에 적합한 형태를 가진 문자열로 변환해 반환합니다. {{jsxref("Object.prototype.toLocaleString()")}} 메서드를 재정의합니다.</dd> + <dt>{{jsxref("BigInt.prototype.toString()")}}</dt> + <dd><code>BigInt</code>의 값을 주어진 진수로 표현한 문자열을 반환합니다. {{jsxref("Object.prototype.toString()")}} 메서드를 재정의합니다.</dd> + <dt>{{jsxref("BigInt.prototype.valueOf()")}}</dt> + <dd><code>BigInt</code> 객체의 원시 값 표현을 반환합니다. {{jsxref("Object.prototype.valueOf()")}} 메서드를 재정의합니다.</dd> +</dl> + +<h2 id="권장사항">권장사항</h2> + +<h3 id="변환">변환</h3> + +<p><code>BigInt</code>를 {{jsxref("Number")}}로 변환하는 과정에서 정확도를 유실할 수 있으므로, 2<sup>53</sup>보다 큰 값을 예상할 수 있는 경우 <code>BigInt</code>만 사용하는 것이 좋습니다.</p> + +<h3 id="암호화">암호화</h3> + +<p><code>BigInt</code>가 지원하는 연산의 소요시간은 상수 시간이 아니기 때문에 <a href="https://www.chosenplaintext.ca/articles/beginners-guide-constant-time-cryptography.html">암호화에 적합하지 않습니다</a>.</p> + +<h3 id="JSON과_함께_사용하기">JSON과 함께 사용하기</h3> + +<p><code>BigInt</code>는 직렬화할 수 없기 때문에, {{jsxref("JSON.stringify()")}}에 <code>BigInt</code>를 포함한 값을 전달한다면 <code>TypeError</code>가 발생합니다. 대신, 필요한 경우 자신만의 <code>toJSON</code> 메서드를 만들 수 있습니다.</p> + +<pre class="brush: js">BigInt.prototype.toJSON = function() { return this.toString(); }</pre> + +<p>이제 아래 코드가 오류를 던지지 않고 문자열을 반환합니다.</p> + +<pre class="brush: js">JSON.stringify(BigInt(1)); +// '"1"' +</pre> + +<h2 id="예제">예제</h2> + +<h3 id="소수_구하기">소수 구하기</h3> + +<pre class="brush: js">// 주어진 BigInt가 소수이면 true 반환 +function isPrime(p) { + for (let i = 2n; i * i <= p; i++) { + if (p % i === 0n) return false; + } + return true; +} + +// BigInt를 받아, n번째 소수를 BigInt로 반환 +function nthPrime(nth) { + let maybePrime = 2n; + let prime = 0n; + + while (nth >= 0n) { + if (isPrime(maybePrime)) { + nth -= 1n; + prime = maybePrime; + } + maybePrime += 1n; + } + + return prime; +} + +nthPrime(20n) +// ↪ 73n</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName("ESDraft", "#sec-bigint-objects", "<code>BigInt</code> objects")}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.BigInt")}}</p> + +<h3 id="구현_진척도">구현 진척도</h3> + +<p>본 기능은 아직 안정적인 크로스 브라우징에 도달하지 못했으므로, 매일 업데이트되는 아래 표에서 브라우저별 구현 상황을 확인할 수 있습니다. 이 데이터는 각 브라우저 JavaScript 엔진의 나이틀리 빌드 또는 최신 릴리즈판에서, JavaScript 표준 테스트인 <a href="https://github.com/tc39/test262">Test262</a>의 관련 항목을 시험해 생성합니다.</p> + +<p>{{EmbedTest262ReportResultsTable("BigInt")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Number")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/bigint/prototype/index.html b/files/ko/web/javascript/reference/global_objects/bigint/prototype/index.html new file mode 100644 index 0000000000..6ba56eb37e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/bigint/prototype/index.html @@ -0,0 +1,59 @@ +--- +title: BigInt.prototype +slug: Web/JavaScript/Reference/Global_Objects/BigInt/prototype +tags: + - BigInt + - JavaScript + - Property + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/BigInt/prototype +--- +<div>{{JSRef}}</div> + +<p><strong><code>BigInt.prototype</code></strong> 속성은 {{jsxref("BigInt")}} 생성자의 프로토타입을 나타냅니다.</p> + +<p>{{js_property_attributes(0, 0, 0)}}</p> + +<h2 id="설명">설명</h2> + +<p>모든 {{jsxref("BigInt")}} 인스턴스는 <code>BigInt.prototype</code>을 상속합니다. <code>BigInt</code> 생성자의 프로토타입 객체를 변형해 모든 <code>BigInt</code> 인스턴스에 영향을 줄 수 있습니다.</p> + +<h2 id="속성">속성</h2> + +<dl> + <dt><code>BigInt.prototype.constructor</code></dt> + <dd>이 객체의 인스턴스를 만들 때 사용한 함수를 반환합니다. 기본값은 {{jsxref("BigInt")}} 객체입니다.</dd> +</dl> + +<h2 id="메서드">메서드</h2> + +<dl> + <dt><code>BigInt.prototype.toLocaleString()</code></dt> + <dd>BigInt를 주어진 언어에 적합한 형태를 가진 문자열로 변환해 반환합니다. {{jsxref("Object.prototype.toLocaleString()")}} 메서드를 재정의합니다.</dd> + <dt><code>BigInt.prototype.toString()</code></dt> + <dd><code>BigInt</code>의 값을 주어진 진수로 표현한 문자열을 반환합니다. {{jsxref("Object.prototype.toString()")}} 메서드를 재정의합니다.</dd> + <dt><code>BigInt.prototype.valueOf()</code></dt> + <dd><code>BigInt</code> 객체의 원시 값 표현을 반환합니다. {{jsxref("Object.prototype.valueOf()")}} 메서드를 재정의합니다.</dd> +</dl> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + </tr> + <tr> + <td><a href="https://tc39.github.io/proposal-bigint/#sec-bigint.prototype">BigInt.prototype</a></td> + <td>Stage 3</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div class="hidden">To contribute to this compatibility data, please write a pull request against this repository: <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>.</div> + +<p>{{Compat("javascript.builtins.BigInt.prototype")}}</p> diff --git a/files/ko/web/javascript/reference/global_objects/boolean/boolean/index.html b/files/ko/web/javascript/reference/global_objects/boolean/boolean/index.html new file mode 100644 index 0000000000..bbe86a5134 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/boolean/boolean/index.html @@ -0,0 +1,55 @@ +--- +title: Boolean() 생성자 +slug: Web/JavaScript/Reference/Global_Objects/Boolean/Boolean +tags: + - Boolean + - Constructor + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Boolean/Boolean +--- +<div>{{JSRef}}</div> + +<p><strong><code>Boolean()</code></strong> 생성자는 {{jsxref("Boolean")}} 객체를 생성할 때 사용합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/boolean-constructor.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">new Boolean([<var>value</var>])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>value</code> {{optional_inline}}</dt> + <dd><code>Boolean</code> 객체의 초깃값.</dd> +</dl> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-boolean-constructor', 'Boolean constructor')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Boolean.Boolean")}}</p> +</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>용어 사전: {{Glossary("Boolean")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/boolean/index.html b/files/ko/web/javascript/reference/global_objects/boolean/index.html new file mode 100644 index 0000000000..06618f3ffe --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/boolean/index.html @@ -0,0 +1,108 @@ +--- +title: Boolean +slug: Web/JavaScript/Reference/Global_Objects/Boolean +tags: + - Boolean + - Constructor + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Boolean +--- +<div>{{JSRef}}</div> + +<p><strong><code>Boolean</code></strong> 객체는 불리언 값을 감싸고 있는 객체입니다.</p> + +<h2 id="설명">설명</h2> + +<p>첫 번재 매개변수로서 전달한 값은 필요한 경우 불리언 값으로 변환됩니다. 값이 없거나 <code>0</code>, <code>-0</code>, {{jsxref("null")}}, <code>false</code>, {{jsxref("NaN")}}, {{jsxref("undefined")}}, 빈 문자열 (<code>""</code>)이라면 객체의 초기값은 <code>false</code>가 됩니다. 문자열 <code>"false"</code>를 포함한 그 외 모든 다른 값은 초기값을 <code>true</code>로 설정합니다.</p> + +<p><code>Boolean</code> 객체의 <code>true</code>와 <code>false</code> 값을 원시 <code>Boolean</code> 값 <code>true</code>, <code>false</code>와 혼동해선 안됩니다.</p> + +<p>값이 {{jsxref("undefined")}}, {{jsxref("null")}}이 아닌 <strong>모든</strong> 객체는 조건문에서 <code>true</code>로 계산됩니다. 이는 값이 <code>false</code>인 <code>Boolean</code> 객체도 포함합니다. 즉 아래 {{jsxref("Statements/if...else", "if")}} 문의 조건은 참입니다.</p> + +<pre class="brush: js notranslate">var x = new Boolean(false); +if (x) { + // 이 코드는 실행됨 +} +</pre> + +<p>그러나 원시 <code>Boolean</code> 값에는 적용되지 않습니다. 따라서 아래 {{jsxref("Statements/if...else", "if")}} 문의 조건은 거짓입니다.</p> + +<pre class="brush: js notranslate">var x = false; +if (x) { + // 이 코드는 실행되지 않음 +} +</pre> + +<p>불리언이 아닌 값을 변환할 때 <code>Boolean</code> 객체를 사용해선 안됩니다. 대신 <code>Boolean</code> 함수를 사용하세요.</p> + +<pre class="brush: js notranslate">var x = Boolean(expression); // 추천 +var x = new Boolean(expression); // 사용하지 말것</pre> + +<p>값이 <code>false</code>인 <code>Boolean</code> 객체를 포함한 어떠한 객체를 <code>Boolean</code> 객체의 초기값으로 넘겨주더라도 새로운 <code>Boolean</code> 객체는 <code>true</code>를 가집니다.</p> + +<pre class="brush: js notranslate">var myFalse = new Boolean(false); // 초기값 거짓 +var g = Boolean(myFalse); // 초기값 참 +var myString = new String('Hello'); // 문자열 객체 +var s = Boolean(myString); // 초기값 참</pre> + +<p><code>Boolean</code> 원시 값의 자리에서 <code>Boolean</code> 객체를 이용해선 안됩니다.</p> + +<h2 id="생성자">생성자</h2> + +<dl> + <dt>{{jsxref("Boolean.Boolean", "Boolean()")}}</dt> + <dd><code>Boolean</code> 객체를 생성합니다.</dd> +</dl> + +<h2 id="인스턴스_메서드">인스턴스 메서드</h2> + +<dl> + <dt>{{jsxref("Boolean.prototype.toString()")}}</dt> + <dd>객체의 값에 따라 문자열 <code>"true"</code> 또는 <code>"false"</code>를 반환합니다. {{jsxref("Object.prototype.toString()")}} 메서드를 재정의합니다.</dd> + <dt>{{jsxref("Boolean.prototype.valueOf()")}}</dt> + <dd>{{jsxref("Boolean")}} 객체의 원시값을 반환합니다. {{jsxref("Object.prototype.valueOf()")}} 메서드를 재정의합니다.</dd> +</dl> + +<h2 id="예제">예제</h2> + +<h3 id="false_값으로_초기화한_Boolean_객체_만들기"><code>false</code> 값으로 초기화한 <code>Boolean</code> 객체 만들기</h3> + +<pre class="brush: js notranslate">var bNoParam = new Boolean(); +var bZero = new Boolean(0); +var bNull = new Boolean(null); +var bEmptyString = new Boolean(''); +var bfalse = new Boolean(false);</pre> + +<h3 id="true_값으로_초기화한_Boolean_객체_만들기"><code>true</code> 값으로 초기화한 <code>Boolean</code> 객체 만들기</h3> + +<pre class="brush: js notranslate">var btrue = new Boolean(true); +var btrueString = new Boolean('true'); +var bfalseString = new Boolean('false'); +var bSuLin = new Boolean('Su Lin'); +var bArrayProto = new Boolean([]); +var bObjProto = new Boolean({});</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-boolean-objects', 'Boolean')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.Boolean")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{Glossary("Boolean")}}</li> + <li>{{interwiki("wikipedia", "불리언 자료형")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/boolean/prototype/index.html b/files/ko/web/javascript/reference/global_objects/boolean/prototype/index.html new file mode 100644 index 0000000000..7d1ce4f379 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/boolean/prototype/index.html @@ -0,0 +1,81 @@ +--- +title: Boolean.prototype +slug: Web/JavaScript/Reference/Global_Objects/Boolean/prototype +tags: + - Boolean + - JavaScript + - Property + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Boolean +--- +<div>{{JSRef}}</div> + +<p><strong><code>Boolean.prototype</code></strong> 속성은 {{jsxref("Boolean")}} 생성자의 프로토타입을 나타냅니다.</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<div>{{EmbedInteractiveExample("pages/js/boolean-constructor.html")}}</div> + + + +<h2 id="설명">설명</h2> + +<p>{{jsxref("Boolean")}} 인스턴스는 <code>Boolean.prototype</code>을 상속받습니다. 생성자의 프로토타입 객체를 사용해 모든 <code>Boolean</code> 인스턴스에 속성이나 메서드를 추가할 수 있습니다.</p> + +<h2 id="속성">속성</h2> + +<dl> + <dt><code>Boolean.prototype.constructor</code></dt> + <dd>인스턴스의 프로토타입을 생성한 함수를 반환합니다. 기본값은 {{jsxref("Boolean")}} 함수입니다.</dd> +</dl> + +<h2 id="메서드">메서드</h2> + +<dl> + <dt>{{jsxref("Boolean.prototype.toSource()")}} {{non-standard_inline}}</dt> + <dd>{{jsxref("Boolean")}} 객체의 소스를 포함한 문자열을 반환합니다. 반환 문자열을 사용해 동일한 객체를 생성할 수 있습니다. {{jsxref("Object.prototype.toSource()")}} 메서드를 재정의합니다.</dd> + <dt>{{jsxref("Boolean.prototype.toString()")}}</dt> + <dd>객체의 값에 따라 문자열 <code>"true"</code> 또는 <code>"false"</code>를 반환합니다. {{jsxref("Object.prototype.toString()")}} 메서드를 재정의합니다.</dd> + <dt>{{jsxref("Boolean.prototype.valueOf()")}}</dt> + <dd>{{jsxref("Boolean")}} 객체의 원시 값을 반환합니다. {{jsxref("Object.prototype.valueOf()")}} 메서드를 재정의합니다.</dd> +</dl> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.6.3.1', 'Boolean.prototype')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-boolean.prototype', 'Boolean.prototype')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-boolean.prototype', 'Boolean.prototype')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Boolean.prototype")}}</p> diff --git a/files/ko/web/javascript/reference/global_objects/boolean/tostring/index.html b/files/ko/web/javascript/reference/global_objects/boolean/tostring/index.html new file mode 100644 index 0000000000..5cdb2c1f47 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/boolean/tostring/index.html @@ -0,0 +1,69 @@ +--- +title: Boolean.prototype.toString() +slug: Web/JavaScript/Reference/Global_Objects/Boolean/toString +tags: + - Boolean + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Boolean/toString +--- +<div>{{JSRef}}</div> + +<p><code><strong>toString()</strong></code> 메서드는 {{jsxref("Boolean")}} 객체를 나타내는 문자열을 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/boolean-tostring.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox notranslate"><var>bool</var>.toString()</pre> + +<h3 id="반환_값">반환 값</h3> + +<p>{{jsxref("Boolean")}} 객체를 나타내는 문자열.</p> + +<h2 id="설명">설명</h2> + +<p>{{jsxref("Boolean")}} 객체는 {{jsxref("Object.prototype.toString()")}} 메서드를 상속받지 않고 재정의합니다. <code>Boolean</code> 객체에서 <code>toString()</code> 메서드는 객체의 문자열 표현을 반환합니다.</p> + +<p>JavaScript는 {{jsxref("Boolean")}}을 문자열로 표현해야 할 때나 문자열 결합에 사용할 때 <code>toString()</code>을 자동으로 호출합니다.</p> + +<p><code>toString()</code>은 불리언 객체의 값에 따라 문자열 "<code>true</code>" 또는 "<code>false</code>"를 반환합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="toString_사용하기"><code>toString()</code> 사용하기</h3> + +<pre class="brush: js notranslate">var flag = new Boolean(true); +flag.toString(); // false +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-boolean.prototype.tostring', 'Boolean.prototype.toString')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Boolean.toString")}}</p> +</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Object.prototype.toString()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/boolean/valueof/index.html b/files/ko/web/javascript/reference/global_objects/boolean/valueof/index.html new file mode 100644 index 0000000000..50df1d98d2 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/boolean/valueof/index.html @@ -0,0 +1,67 @@ +--- +title: Boolean.prototype.valueOf() +slug: Web/JavaScript/Reference/Global_Objects/Boolean/valueOf +tags: + - Boolean + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Boolean/valueOf +--- +<div>{{JSRef}}</div> + +<p><code><strong>valueOf()</strong></code> 메서드는 {{jsxref("Boolean")}} 객체의 원시 값을 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/boolean-valueof.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox notranslate"><var>bool</var>.valueOf()</pre> + +<h3 id="반환_값">반환 값</h3> + +<p>{{jsxref("Boolean")}} 객체의 원시 값.</p> + +<h2 id="설명">설명</h2> + +<p><code>valueOf()</code> 메서드는 {{jsxref("Boolean")}} 객체나 불리언 리터럴의 원시 값을 Boolean 자료형의 값으로 반환합니다.</p> + +<p><code>valueOf()</code> 메서드는 보통 JavaScript 내부에서 호출하며 코드에서 명시적으로 사용하지는 않습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="valueOf_사용하기"><code>valueOf</code> 사용하기</h3> + +<pre class="brush: js notranslate">var x = new Boolean(); +x.valueOf(); // false +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-boolean.prototype.valueof', 'Boolean.prototype.valueOf')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Boolean.valueOf")}}</p> +</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Object.prototype.valueOf()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/dataview/dataview/index.html b/files/ko/web/javascript/reference/global_objects/dataview/dataview/index.html new file mode 100644 index 0000000000..7c8b3634a1 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/dataview/dataview/index.html @@ -0,0 +1,75 @@ +--- +title: DataView() 생성자 +slug: Web/JavaScript/Reference/Global_Objects/DataView/DataView +tags: + - Constructor + - DataView + - JavaScript + - Reference + - TypedArrays +translation_of: Web/JavaScript/Reference/Global_Objects/DataView/DataView +--- +<div>{{JSRef}}</div> + +<p><strong><code>DataView()</code></strong> 생성자는 새로운 {{jsxref("DataView")}} 객체를 생성합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/dataview-constructor.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">new DataView(<var>buffer</var> [, <var>byteOffset</var> [, <var>byteLength</var>]])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code><var>buffer</var></code></dt> + <dd>새로운 <code>DataView</code> 객체의 저장소로 사용할 {{jsxref("ArrayBuffer")}} 또는 {{jsxref("SharedArrayBuffer")}} {{experimental_inline}}.</dd> + <dt><code><var>byteOffset</var></code> {{optional_inline}}</dt> + <dd>새로운 뷰가 참조할 첫 번째 바이트로의 바이트 단위 오프셋. 지정하지 않을 경우 버퍼 뷰는 첫 번째 바이트부터 시작합니다.</dd> + <dt><code><var>byteLength</var></code> {{optional_inline}}</dt> + <dd>바이트 배열의 요소 수. 지정하지 않을 경우 뷰의 길이는 버퍼의 길이와 같아집니다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>지정한 데이터 버퍼를 나타내는 새로운 <code>DataView</code> 객체.</p> + +<p><code>DataView</code> 객체는 배열 버퍼의 "인터프리터"라고 생각하면 좀 더 쉽습니다. <code>DataView</code>는 읽기와 쓰기 모두에서 버퍼에 잘 맞도록 숫자를 올바르게 변환하는 법, 즉 정수/부동소수점 실수 변환, 엔디언 등 이진 형식으로 나타낸 숫자의 처리법을 알고 있습니다.</p> + +<h3 id="예외">예외</h3> + +<dl> + <dt>{{jsxref("RangeError")}}</dt> + <dd> + <p><code>byteOffset</code> 또는 <code>byteLength</code> 매개변수가 버퍼의 끝을 벗어남.</p> + + <p>예를 들어, 버퍼가 16바이트 길이인데 <code>byteOffset</code>을 8로, <code>byteLength</code>를 10으로 설정할 경우 총 길이 18로서 2바이트를 초과하므로 오류가 발생합니다.</p> + </dd> +</dl> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-dataview-constructor', 'DataView constructor')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.DataView.DataView")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("DataView")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/dataview/index.html b/files/ko/web/javascript/reference/global_objects/dataview/index.html new file mode 100644 index 0000000000..3bde0a032c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/dataview/index.html @@ -0,0 +1,168 @@ +--- +title: DataView +slug: Web/JavaScript/Reference/Global_Objects/DataView +tags: + - DataView + - JavaScript + - Reference + - TypedArrays +translation_of: Web/JavaScript/Reference/Global_Objects/DataView +--- +<div>{{JSRef}}</div> + +<p><strong><code>DataView</code></strong> 뷰는 플랫폼의 자체 {{glossary("endianness", "엔디언")}}(바이트 정렬 방법)에 신경 쓰지 않으면서 {{jsxref("ArrayBuffer")}}에서 다양한 숫자 자료형의 데이터를 읽고 쓰기 위한 저수준 인터페이스를 제공합니다.</p> + +<h2 id="설명">설명</h2> + +<h3 id="엔디언">엔디언</h3> + +<p>다중 바이트 숫자 자료형은 장치의 아키텍처에 따라 메모리에 다르게 표현됩니다. {{glossary("endianness", "엔디언")}} 용어 사전을 참고하세요. <code>DataView</code> 접근자는 코드를 실행하는 컴퓨터의 엔디언에 관계 없이 데이터의 접근법을 명시적으로 통제할 수 있습니다.</p> + +<pre class="brush: js">var littleEndian = (function() { + var buffer = new ArrayBuffer(2); + new DataView(buffer).setInt16(0, 256, true /* littleEndian */); + // Int16Array uses the platform's endianness. + return new Int16Array(buffer)[0] === 256; +})(); +console.log(littleEndian); // true or false</pre> + +<h3 id="64비트_정수_자료형">64비트 정수 자료형</h3> + +<p>JavaScript는 64비트 정수형 값에 대한 표준 지원을 아직 제공하지 않으므로 <code>DataView</code>도 64비트 연산을 지원하지 않습니다. 필요한 경우 최대 정확도 {{jsxref("Number.MAX_SAFE_INTEGER")}}의 값을 가져올 수 있는 <code>getUint64()</code> 함수를 만들 수는 있으며, 어느 정도까지는 충분할 것입니다.</p> + +<pre class="brush: js">function getUint64(dataview, byteOffset, littleEndian) { + // split 64-bit number into two 32-bit (4-byte) parts + const left = dataview.getUint32(byteOffset, littleEndian); + const right = dataview.getUint32(byteOffset+4, littleEndian); + + // combine the two 32-bit values + const combined = littleEndian? left + 2**32*right : 2**32*left + right; + + if (!Number.isSafeInteger(combined)) + console.warn(combined, 'exceeds MAX_SAFE_INTEGER. Precision may be lost'); + + return combined; +}</pre> + +<p>완전한 범위의 64비트를 지원해야 할 경우 {{jsxref("BigInt")}}를 사용하세요. 단, <code>BigInt</code>는 사용자 계층 라이브러리 구현체보다는 훨씬 빠르지만, 가변 크기라는 성질로 인해 JavaScript 32비트 정수보다는 항상 느릴 수밖에 없습니다.</p> + +<pre class="brush: js">const BigInt = window.BigInt, bigThirtyTwo = BigInt(32), bigZero = BigInt(0); +function getUint64BigInt(dataview, byteOffset, littleEndian) { + // split 64-bit number into two 32-bit (4-byte) parts + const left = BigInt(dataview.getUint32(byteOffset|0, !!littleEndian)>>>0); + const right = BigInt(dataview.getUint32((byteOffset|0) + 4|0, !!littleEndian)>>>0); + + // combine the two 32-bit values and return + return littleEndian ? (right<<bigThirtyTwo)|left : (left<<bigThirtyTwo)|right; +}</pre> + +<h2 id="생성자">생성자</h2> + +<dl> + <dt>{{jsxref("DataView.DataView", "DataView()")}}</dt> + <dd>새로운 <code>DataView</code> 객체를 생성합니다.</dd> +</dl> + +<h2 id="속성">속성</h2> + +<dl> + <dt><code>DataView.prototype.constructor</code></dt> + <dd>객체의 프로토타입을 생성한 함수를 나타냅니다. 초깃값은 내장 <code>DataView</code> 생성자입니다.</dd> + <dt>{{jsxref("DataView.prototype.buffer")}} {{readonlyInline}}</dt> + <dd>뷰가 참조하는 {{jsxref("ArrayBuffer")}}입니다.</dd> + <dt>{{jsxref("DataView.prototype.byteLength")}} {{readonlyInline}}</dt> + <dd>뷰의 시작점부터 측정한 {{jsxref("ArrayBuffer")}}의 길이(바이트 단위)입니다.</dd> + <dt>{{jsxref("DataView.prototype.byteOffset")}} {{readonlyInline}}</dt> + <dd>뷰의 시작점 오프셋(바이트 단위)입니다.</dd> +</dl> + +<h2 id="메서드">메서드</h2> + +<h3 id="읽기">읽기</h3> + +<dl> + <dt>{{jsxref("DataView.prototype.getInt8()")}}</dt> + <dd>뷰의 시작점에서부터 주어진 오프셋을 적용한 위치의 8비트 정수(byte)를 가져옵니다.</dd> + <dt>{{jsxref("DataView.prototype.getUint8()")}}</dt> + <dd>뷰의 시작점에서부터 주어진 오프셋을 적용한 위치의 8비트 부호 없는 정수(unsigned byte)를 가져옵니다.</dd> + <dt>{{jsxref("DataView.prototype.getInt16()")}}</dt> + <dd>뷰의 시작점에서부터 주어진 오프셋을 적용한 위치의 16비트 정수(short)를 가져옵니다.</dd> + <dt>{{jsxref("DataView.prototype.getUint16()")}}</dt> + <dd>뷰의 시작점에서부터 주어진 오프셋을 적용한 위치의 16비트 부호 없는 정수(unsigned short)를 가져옵니다.</dd> + <dt>{{jsxref("DataView.prototype.getInt32()")}}</dt> + <dd>뷰의 시작점에서부터 주어진 오프셋을 적용한 위치의 32비트 정수(long)를 가져옵니다.</dd> + <dt>{{jsxref("DataView.prototype.getUint32()")}}</dt> + <dd>뷰의 시작점에서부터 주어진 오프셋을 적용한 위치의 32비트 부호 없는 정수(unsigned short)를 가져옵니다.</dd> + <dt>{{jsxref("DataView.prototype.getFloat32()")}}</dt> + <dd>뷰의 시작점에서부터 주어진 오프셋을 적용한 위치의 32비트 실수(float)를 가져옵니다.</dd> + <dt>{{jsxref("DataView.prototype.getFloat64()")}}</dt> + <dd>뷰의 시작점에서부터 주어진 오프셋을 적용한 위치의 64비트 실수(double)를 가져옵니다.</dd> + <dt>{{jsxref("DataView.prototype.getBigInt64()")}}</dt> + <dd>뷰의 시작점에서부터 주어진 오프셋을 적용한 위치의 64비트 정수(long long)를 가져옵니다.</dd> + <dt>{{jsxref("DataView.prototype.getBigUint64()")}}</dt> + <dd>뷰의 시작점에서부터 주어진 오프셋을 적용한 위치의 64비트 부호 없는 정수(unsigned long long)를 가져옵니다.</dd> +</dl> + +<h3 id="쓰기">쓰기</h3> + +<dl> + <dt>{{jsxref("DataView.prototype.setInt8()")}}</dt> + <dd>뷰의 시작점에서부터 주어진 오프셋을 적용한 위치에 8비트 정수(byte)를 저장합니다.</dd> + <dt>{{jsxref("DataView.prototype.setUint8()")}}</dt> + <dd>뷰의 시작점에서부터 주어진 오프셋을 적용한 위치에 8비트 부호 없는 정수(unsigned byte)를 저장합니다.</dd> + <dt>{{jsxref("DataView.prototype.setInt16()")}}</dt> + <dd>뷰의 시작점에서부터 주어진 오프셋을 적용한 위치에 16비트 정수(short)를 저장합니다.</dd> + <dt>{{jsxref("DataView.prototype.setUint16()")}}</dt> + <dd>뷰의 시작점에서부터 주어진 오프셋을 적용한 위치에 16비트 부호 없는 정수(unsigned short)를 저장합니다.</dd> + <dt>{{jsxref("DataView.prototype.setInt32()")}}</dt> + <dd>뷰의 시작점에서부터 주어진 오프셋을 적용한 위치에 32비트 정수(long)를 저장합니다.</dd> + <dt>{{jsxref("DataView.prototype.setUint32()")}}</dt> + <dd>뷰의 시작점에서부터 주어진 오프셋을 적용한 위치에 32비트 부호 없는 정수(unsigned long)를 저장합니다.</dd> + <dt>{{jsxref("DataView.prototype.setFloat32()")}}</dt> + <dd>뷰의 시작점에서부터 주어진 오프셋을 적용한 위치에 32비트 실수(float)를 저장합니다.</dd> + <dt>{{jsxref("DataView.prototype.setFloat64()")}}</dt> + <dd>뷰의 시작점에서부터 주어진 오프셋을 적용한 위치에 64비트 실수(double)를 저장합니다.</dd> + <dt>{{jsxref("DataView.prototype.setBigInt64()")}}</dt> + <dd>뷰의 시작점에서부터 주어진 오프셋을 적용한 위치에 64비트 정수(long long)를 저장합니다.</dd> + <dt>{{jsxref("DataView.prototype.setBigUint64()")}}</dt> + <dd>뷰의 시작점에서부터 주어진 오프셋을 적용한 위치에 64비트 부호 없는 정수(unsigned long long)를 저장합니다.</dd> +</dl> + +<h2 id="예제">예제</h2> + +<pre class="brush: js">var buffer = new ArrayBuffer(16); +var view = new DataView(buffer, 0); + +view.setInt16(1, 42); +view.getInt16(1); //42 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-dataview-objects', 'DataView')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.DataView")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("ArrayBuffer")}}</li> + <li>{{jsxref("SharedArrayBuffer")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/getdate/index.html b/files/ko/web/javascript/reference/global_objects/date/getdate/index.html new file mode 100644 index 0000000000..1a5d6f2d5a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/getdate/index.html @@ -0,0 +1,84 @@ +--- +title: Date.prototype.getDate() +slug: Web/JavaScript/Reference/Global_Objects/Date/getDate +tags: + - Date + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getDate +--- +<div>{{JSRef}}</div> + +<p><strong><code>getDate()</code></strong> 메서드는 주어진 날짜의 현지 시간 기준 일을 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/date-getdate.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.getDate()</code></pre> + +<h3 id="반환_값">반환 값</h3> + +<p>현지 시간에 따라, 주어진 날짜의 일에 해당하는 1 이상 31 이하의 정수.</p> + +<h2 id="예제">예제</h2> + +<h3 id="getDate()_사용하기"><code>getDate()</code> 사용하기</h3> + +<p>아래 코드의 두 번째 명령문은 <code>Xmas95</code>의 값에 기반하여 <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">day</span></font>에 2를 할당합니다.</p> + +<pre class="brush: js">var Xmas95 = new Date('December 25, 1995 23:15:30'); +var day = Xmas95.getDate(); + +console.log(day); // 25 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.getdate', 'Date.prototype.getDate')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.getdate', 'Date.prototype.getDate')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.14', 'Date.prototype.getDate')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Date.getDate")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Date.prototype.getUTCDate()")}}</li> + <li>{{jsxref("Date.prototype.getUTCDay()")}}</li> + <li>{{jsxref("Date.prototype.setDate()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/getday/index.html b/files/ko/web/javascript/reference/global_objects/date/getday/index.html new file mode 100644 index 0000000000..1c936def69 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/getday/index.html @@ -0,0 +1,95 @@ +--- +title: Date.prototype.getDay() +slug: Web/JavaScript/Reference/Global_Objects/Date/getDay +tags: + - Date + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getDay +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary"><strong><code>getDay()</code></strong> 메서드는 주어진 날짜의 현지 시간 기준 요일을 반환합니다. 0은 일요일을 나타냅니다.</span> 현재의 일을 반환하려면 {{jsxref("Date.prototype.getDate()")}}를 사용하세요.</p> + +<div>{{EmbedInteractiveExample("pages/js/date-getday.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.getDay()</code></pre> + +<h3 id="반환_값">반환 값</h3> + +<p>현지 시간에 따라, 주어진 날짜의 요일에 해당하는 0 이상 6 이하의 정수. (일요일은 0, 월요일은 1, 화요일은 2, ...)</p> + +<h2 id="예제">예제</h2> + +<h3 id="getDay()_사용하기"><code>getDay()</code> 사용하기</h3> + +<p>1995년 12월 25일은 월요일입니다. 따라서 아래 코드의 두 번째 명령문은 <code>Xmas95</code>의 값에 기반하여 <code>weekday</code>에 1을 할당합니다.</p> + +<pre class="brush: js">var Xmas95 = new Date('December 25, 1995 23:15:30'); +var weekday = Xmas95.getDay(); + +console.log(weekday); // 1 +</pre> + +<div class="blockIndicator note"> +<p><strong>참고:</strong> 필요하다면, 요일의 이름(<code>"월요일"</code> 등)을 {{jsxref("DateTimeFormat", "Intl.DateTimeFormat")}}과 <code>options</code> 매개변수를 사용해 얻을 수 있습니다. 이 방법을 사용하면 국제화도 더 쉬워집니다.</p> + +<pre class="brush: js">var options = { weekday: 'long'}; +console.log(new Intl.DateTimeFormat('en-US', options).format(Xmas95)); +// Monday +console.log(new Intl.DateTimeFormat('ko-KR', options).format(Xmas95)); +// 월요일 +</pre> +</div> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.getday', 'Date.prototype.getDay')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.getday', 'Date.prototype.getDay')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.16', 'Date.prototype.getDay')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Date.getDay")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Date.prototype.getUTCDate()")}}</li> + <li>{{jsxref("Date.prototype.getUTCDay()")}}</li> + <li>{{jsxref("Date.prototype.setDate()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/getfullyear/index.html b/files/ko/web/javascript/reference/global_objects/date/getfullyear/index.html new file mode 100644 index 0000000000..c1a90e5340 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/getfullyear/index.html @@ -0,0 +1,88 @@ +--- +title: Date.prototype.getFullYear() +slug: Web/JavaScript/Reference/Global_Objects/Date/getFullYear +tags: + - Date + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getFullYear +--- +<div>{{JSRef}}</div> + +<p><strong><code>getFullYear()</code></strong> 메서드는 주어진 날짜의 현지 시간 기준 연도를 반환합니다.</p> + +<p>{{jsxref("Date.prototype.getYear()", "getYear()")}} 메서드 대신 이 메서드를 사용하세요.</p> + +<div>{{EmbedInteractiveExample("pages/js/date-getfullyear.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.getFullYear()</code></pre> + +<h3 id="반환_값">반환 값</h3> + +<p>현지 시간에 따라, 주어진 날짜의 연도에 해당하는 숫자.</p> + +<h2 id="설명">설명</h2> + +<p><code>getFullYear()</code>가 반환하는 값은 절댓값입니다. <code>getFullYear()</code>는 1000년과 9999년 사이의, 1995년과 같은 날짜에 대해서는 네 자리 숫자를 반환합니다. 이 메서드를 사용해야 2000년 이후의 날짜에 대해서도 호환을 유지할 수 있습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="getFullYear()_사용하기"><code>getFullYear()</code> 사용하기</h3> + +<p>다음 예제에서는 현재 연도의 네 자릿값을 변수 <code>year</code>에 할당합니다.</p> + +<pre class="brush: js">var today = new Date(); +var year = today.getFullYear(); +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.3.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.10', 'Date.prototype.getFullYear')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.getfullyear', 'Date.prototype.getFullYear')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.getfullyear', 'Date.prototype.getFullYear')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Date.getFullYear")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Date.prototype.getUTCFullYear()")}}</li> + <li>{{jsxref("Date.prototype.setFullYear()")}}</li> + <li>{{jsxref("Date.prototype.getYear()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/gethours/index.html b/files/ko/web/javascript/reference/global_objects/date/gethours/index.html new file mode 100644 index 0000000000..8095548633 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/gethours/index.html @@ -0,0 +1,83 @@ +--- +title: Date.prototype.getHours() +slug: Web/JavaScript/Reference/Global_Objects/Date/getHours +tags: + - Date + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getHours +--- +<div>{{JSRef}}</div> + +<p><strong><code>getHours()</code></strong> 메서드는 주어진 날짜의 현지 시간 기준 시를 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/date-gethours.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.getHours()</code></pre> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 날짜의 현지 시간 기준 시를 나타내는 0에서 23 사이의 정수.</p> + +<h2 id="예제">예제</h2> + +<h3 id="getHours()_사용하기"><code>getHours()</code> 사용하기</h3> + +<p>아래의 두 번째 명령문은 {{jsxref("Date")}} 객체 <code>Xmas95</code> 날짜의 시를 <code>hours</code> 변수에 할당합니다.</p> + +<pre class="brush: js">var Xmas95 = new Date('December 25, 1995 23:15:30'); +var hours = Xmas95.getHours(); + +console.log(hours); // 23 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.18', 'Date.prototype.getHours')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.gethours', 'Date.prototype.getHours')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.gethours', 'Date.prototype.getHours')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Date.getHours")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Date.prototype.getUTCHours()")}}</li> + <li>{{jsxref("Date.prototype.setHours()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/getmilliseconds/index.html b/files/ko/web/javascript/reference/global_objects/date/getmilliseconds/index.html new file mode 100644 index 0000000000..49be5d7ff7 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/getmilliseconds/index.html @@ -0,0 +1,81 @@ +--- +title: Date.prototype.getMilliseconds() +slug: Web/JavaScript/Reference/Global_Objects/Date/getMilliseconds +tags: + - Date + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getMilliseconds +--- +<div>{{JSRef}}</div> + +<p><code><strong>getMilliseconds()</strong></code> 메서드는 <code>Date</code> 인스턴스의 밀리초를 현지 시간 기준으로 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/date-getmilliseconds.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>dateObj</var>.getMilliseconds()</pre> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 날짜의 현지 시간 기준 밀리초를 나타내는 0에서 999 사이의 정수.</p> + +<h2 id="예제">예제</h2> + +<h3 id="getMilliseconds()_사용하기"><code>getMilliseconds()</code> 사용하기</h3> + +<p>다음 예제에서는 현재 시간의 밀리초를 변수 <code>milliseconds</code>에 할당합니다.</p> + +<pre class="brush: js">var today = new Date(); +var milliseconds = today.getMilliseconds(); +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.3.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.24', 'Date.prototype.getMilliseconds')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.getmilliseconds', 'Date.prototype.getMilliseconds')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.getmilliseconds', 'Date.prototype.getMilliseconds')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Date.getMilliseconds")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Date.prototype.getUTCMilliseconds()")}}</li> + <li>{{jsxref("Date.prototype.setMilliseconds()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/getminutes/index.html b/files/ko/web/javascript/reference/global_objects/date/getminutes/index.html new file mode 100644 index 0000000000..5cd9c3c99a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/getminutes/index.html @@ -0,0 +1,83 @@ +--- +title: Date.prototype.getMinutes() +slug: Web/JavaScript/Reference/Global_Objects/Date/getMinutes +tags: + - Date + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getMinutes +--- +<div>{{JSRef}}</div> + +<p><code><strong>getMinutes()</strong></code> 메서드는 <code>Date</code> 인스턴스의 분을 현지 시간 기준으로 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/date-getminutes.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>dateObj</var>.getMinutes()</pre> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 날짜의 현지 시간 기준 분을 나타내는 0에서 59 사이의 정수.</p> + +<h2 id="예제">예제</h2> + +<h3 id="getMinutes()_사용하기"><code>getMinutes()</code> 사용하기</h3> + +<p>다음 예제는 {{jsxref("Date")}} 객체 <code>Xmas95</code>의 분을 사용해 변수 <code>minutes</code>에 15를 할당합니다.</p> + +<pre class="brush: js">var Xmas95 = new Date('December 25, 1995 23:15:30'); +var minutes = Xmas95.getMinutes(); + +console.log(minutes); // 15 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.20', 'Date.prototype.getMinutes')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.getminutes', 'Date.prototype.getMinutes')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.getminutes', 'Date.prototype.getMinutes')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Date.getMinutes")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Date.prototype.getUTCMinutes()")}}</li> + <li>{{jsxref("Date.prototype.setMinutes()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/getmonth/index.html b/files/ko/web/javascript/reference/global_objects/date/getmonth/index.html new file mode 100644 index 0000000000..48fe002a99 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/getmonth/index.html @@ -0,0 +1,94 @@ +--- +title: Date.prototype.getMonth() +slug: Web/JavaScript/Reference/Global_Objects/Date/getMonth +tags: + - Date + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getMonth +--- +<div>{{JSRef}}</div> + +<p><strong><code>getMonth()</code> </strong>메서드는 <code>Date</code> 객체의 월 값을 현지 시간에 맞춰 반환합니다. 월은 0부터 시작합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/date-getmonth.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>dateObj</var>.getMonth()</pre> + +<h3 id="반환_값">반환 값</h3> + +<p>현지 시간 기준 월을 나타내는 0에서 11 사이의 정수. 0은 1월, 1은 2월... 을 나타냅니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="getMonth()_사용하기"><code>getMonth()</code> 사용하기</h3> + +<p>다음 예제는 {{jsxref("Date")}} 객체 <code>Xmas95</code>의 값을 사용해 변수 <code>month</code>에 11을 할당합니다.</p> + +<pre class="brush: js">var Xmas95 = new Date('December 25, 1995 23:15:30'); +var month = Xmas95.getMonth(); + +console.log(month); // 11 +</pre> + +<div class="blockIndicator note"> +<p><strong>참고:</strong> 필요한 경우 {{jsxref("DateTimeFormat", "Intl.DateTimeFormat()")}}과 <code>options</code> 매개변수를 사용해 해당하는 달의 이름(<code>"January"</code> 등)을 가져올 수 있습니다. 이 방법을 사용하면 국제화도 보다 편리합니다.</p> + +<pre class="brush: js">var options = { month: 'long'}; +console.log(new Intl.DateTimeFormat('ko-KR', options).format(Xmas95)); +// 12월 +console.log(new Intl.DateTimeFormat('en-US', options).format(Xmas95)); +// December +</pre> +</div> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.12', 'Date.prototype.getMonth')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.getmonth', 'Date.prototype.getMonth')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.getmonth', 'Date.prototype.getMonth')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Date.getMonth")}}</p> + +<h2 id="See_also" name="See_also">같이 보기</h2> + +<ul> + <li>{{jsxref("Date.prototype.getUTCMonth()")}}</li> + <li>{{jsxref("Date.prototype.setMonth()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/getseconds/index.html b/files/ko/web/javascript/reference/global_objects/date/getseconds/index.html new file mode 100644 index 0000000000..c5155d4d4a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/getseconds/index.html @@ -0,0 +1,83 @@ +--- +title: Date.prototype.getSeconds() +slug: Web/JavaScript/Reference/Global_Objects/Date/getSeconds +tags: + - Date + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getSeconds +--- +<div>{{JSRef}}</div> + +<p><strong><code>getSeconds()</code> </strong>메서드는 <code>Date</code> 객체의 초 값을 현지 시간에 맞춰 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/date-getseconds.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>dateObj</var>.getSeconds()</pre> + +<h3 id="반환_값">반환 값</h3> + +<p>현지 시간 기준 초를 나타내는 0에서 59 사이의 정수.</p> + +<h2 id="예제">예제</h2> + +<h3 id="getSeconds()_사용하기"><code>getSeconds()</code> 사용하기</h3> + +<p>다음 예제는 {{jsxref("Date")}} 객체 <code>Xmas95</code>의 값을 사용해 변수 <code>seconds</code>에 30을 할당합니다.</p> + +<pre class="brush: js">var Xmas95 = new Date('December 25, 1995 23:15:30'); +var seconds = Xmas95.getSeconds(); + +console.log(seconds); // 30 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.22', 'Date.prototype.getSeconds')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.getseconds', 'Date.prototype.getSeconds')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.getseconds', 'Date.prototype.getSeconds')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Date.getSeconds")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Date.prototype.getUTCSeconds()")}}</li> + <li>{{jsxref("Date.prototype.setSeconds()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/gettime/index.html b/files/ko/web/javascript/reference/global_objects/date/gettime/index.html new file mode 100644 index 0000000000..20b554b41f --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/gettime/index.html @@ -0,0 +1,139 @@ +--- +title: Date.prototype.getTime() +slug: Web/JavaScript/Reference/Global_Objects/Date/getTime +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getTime +--- +<div>{{JSRef}}</div> + +<p><strong>getTime()</strong> 메서드는 표준시에 따라 지정된 날짜의 시간에 해당하는 숫자 값을 반환합니다.</p> + +<p>이 메서드를 사용하면 다른 {{jsxref ( "Date")}} 객체에 날짜와 시간을 지정할 수 있습니다. 이 메소드는 기능적으로 {{jsxref("Date.valueof", "valueOf()")}} 메소드와 동일합니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.getTime()</code></pre> + +<h3 id="Return_value">Return value</h3> + +<p>1970 년 1 월 1 일 00:00:00 UTC와 주어진 날짜 사이의 경과 시간 (밀리 초)을 나타내는 숫자입니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="날짜_복사에_getTime_()_사용">날짜 복사에 getTime () 사용</h3> + +<p>동일한 시간 값으로 날짜 객체를 생성합니다.</p> + +<pre class="brush: js">// 월은 0부터 시작하여 생일은 1995 년 1 월 10 일이됩니다. +var birthday = new Date(1994, 12, 10); +var copy = new Date(); +copy.setTime(birthday.getTime()); +</pre> + +<p> </p> + +<h3 id="측정_실행_시간">측정 실행 시간</h3> + +<p>새로 생성 된 {{jsxref ( "Date")}} 객체에서 두 개의 연속 getTime () 호출을 뺀 후에이 두 호출 사이의 시간 범위를 지정하십시오. 일부 작업의 실행 시간을 계산하는 데 사용할 수 있습니다. 불필요한 {{jsxref ( "Date")}} 객체를 인스턴스화하지 않으려면 {{jsxref("Date.now()")}}를 참조하십시오.</p> + +<pre class="brush: js">var end, start; + +start = new Date(); +for (var i = 0; i < 1000; i++) { + Math.sqrt(i); +} +end = new Date(); + +console.log('Operation took ' + (end.getTime() - start.getTime()) + ' msec'); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.9', 'Date.prototype.getTime')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.gettime', 'Date.prototype.getTime')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.gettime', 'Date.prototype.getTime')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Date.prototype.setTime()")}}</li> + <li>{{jsxref("Date.prototype.valueOf()")}}</li> + <li>{{jsxref("Date.now()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/gettimezoneoffset/index.html b/files/ko/web/javascript/reference/global_objects/date/gettimezoneoffset/index.html new file mode 100644 index 0000000000..5f1681767f --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/gettimezoneoffset/index.html @@ -0,0 +1,119 @@ +--- +title: Date.prototype.getTimezoneOffset() +slug: Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset +--- +<div>{{JSRef}}</div> + +<p><strong>getTimezoneOffset() </strong>메소드는 현재 로케일 (즉, 호스트 시스템 설정)에 대한 시간대 오프셋 (UTC)을 분 단위로 반환합니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.getTimezoneOffset()</code></pre> + +<h3 id="Return_value">Return value</h3> + +<p>현재 호스트 설정을 기반으로하는 날짜에 대한 시간대 오프셋 (UTC) (분)을 나타내는 숫자입니다.</p> + +<h2 id="Description">Description</h2> + +<p>시간대 오프셋은 UTC와 현지 시간의 차이 (분)입니다. 이것은 로컬 시간대가 UTC보다 뒤떨어져 있으면 오프셋이 양수이고 앞에있을 경우 음수임을 의미합니다. 예를 들어, 시간대 UTC + 10 : 00 (오스트레일리아 동부 표준시, 블라디보스토크 시간, 차모로 표준시)의 경우 -600이 반환됩니다.</p> + +<p>반환 된 표준 시간대 오프셋은 호출 된 날짜에 적용되는 오프셋입니다. 호스트 시스템이 일광 절약 시간으로 구성된 경우 오프셋은 Date가 나타내는 날짜와 시간에 따라 변경되고 일광 절약 시간이 적용됩니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_getTimezoneOffset()">Using <code>getTimezoneOffset()</code></h3> + +<pre class="brush: js">// 호스트 장치의 현재 시간대 오프셋 가져 오기 +var x = new Date(); +var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60; + +// 2016 년 국제 노동절 (5 월 1 일)에 대한 시간대 오프셋 가져 오기 +var labourDay = new Date(2016,4,1) +var labourDayOffset = labourDay.getTimezoneOffset() / 60; +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.26', 'Date.prototype.getTimezoneOffset')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.gettimezoneoffset', 'Date.prototype.getTimezoneOffset')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.gettimezoneoffset', 'Date.prototype.getTimezoneOffset')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatIE("5")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> diff --git a/files/ko/web/javascript/reference/global_objects/date/getutcdate/index.html b/files/ko/web/javascript/reference/global_objects/date/getutcdate/index.html new file mode 100644 index 0000000000..f74fb120db --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/getutcdate/index.html @@ -0,0 +1,118 @@ +--- +title: Date.prototype.getUTCDate() +slug: Web/JavaScript/Reference/Global_Objects/Date/getUTCDate +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getUTCDate +--- +<div>{{JSRef}}</div> + +<p><strong>getUTCDate()</strong> 메서드는 표준시에 따라 지정된 날짜에 해당 월의 요일 (날짜)을 반환합니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.getUTCDate()</code></pre> + +<h3 id="Return_value">Return value</h3> + +<p>보편적 인 시간에 따라 지정된 날짜의 달의 날짜를 나타내는 1에서 31 사이의 정수입니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_getUTCDate()">Using <code>getUTCDate()</code></h3> + +<p>다음 예제에서는 현재 날짜의 일 부분을 day 변수에 할당합니다.</p> + +<pre class="brush: js">var today = new Date(); +var day = today.getUTCDate(); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.3.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.15', 'Date.prototype.getUTCDate')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.getutcdate', 'Date.prototype.getUTCDate')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.getutcdate', 'Date.prototype.getUTCDate')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Date.prototype.getDate()")}}</li> + <li>{{jsxref("Date.prototype.getUTCDay()")}}</li> + <li>{{jsxref("Date.prototype.setUTCDate()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/getutcday/index.html b/files/ko/web/javascript/reference/global_objects/date/getutcday/index.html new file mode 100644 index 0000000000..c451fba612 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/getutcday/index.html @@ -0,0 +1,118 @@ +--- +title: Date.prototype.getUTCDay() +slug: Web/JavaScript/Reference/Global_Objects/Date/getUTCDay +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getUTCDay +--- +<div>{{JSRef}}</div> + +<p><strong>getUTCDay()</strong> 메서드는 지정된 날짜의 요일을 표준시에 따라 반환합니다. 여기서 0은 일요일을 나타냅니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.getUTCDay()</code></pre> + +<h3 id="Return_value">Return value</h3> + +<p>지정된 날짜의 요일에 해당하는 표준시에 따른 정수입니다 (일요일은 0, 월요일은 1, 화요일은 2 등).</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_getUTCDay()">Using <code>getUTCDay()</code></h3> + +<p>다음 예제에서는 현재 날짜의 평일 부분을 weekday 변수에 할당합니다.</p> + +<pre class="brush: js">var today = new Date(); +var weekday = today.getUTCDay(); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.3.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.17', 'Date.prototype.getUTCDay')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.getutcday', 'Date.prototype.getUTCDay')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.getutcday', 'Date.prototype.getUTCDay')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Date.prototype.getUTCDate()")}}</li> + <li>{{jsxref("Date.prototype.getDay()")}}</li> + <li>{{jsxref("Date.prototype.setUTCDate()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/getutcfullyear/index.html b/files/ko/web/javascript/reference/global_objects/date/getutcfullyear/index.html new file mode 100644 index 0000000000..f7097db08a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/getutcfullyear/index.html @@ -0,0 +1,121 @@ +--- +title: Date.prototype.getUTCFullYear() +slug: Web/JavaScript/Reference/Global_Objects/Date/getUTCFullYear +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getUTCFullYear +--- +<div>{{JSRef}}</div> + +<p><strong>getUTCFullYear()</strong> 메서드는 표준시에 따라 지정된 날짜의 연도를 반환합니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.getUTCFullYear()</code></pre> + +<h3 id="Return_value">Return value</h3> + +<p>주어진 날짜의 연도를 표준시에 따라 나타내는 숫자입니다.</p> + +<h2 id="Description">Description</h2> + +<p><strong>getUTCFullYear()</strong>에 의해 반환 된 값은 1995 년과 같이 2000 년과 호환되는 절대 숫자입니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_getUTCFullYear()">Using <code>getUTCFullYear()</code></h3> + +<p>다음 예제에서는 현재 연도의 4 자리 값을 변수 year에 할당합니다.</p> + +<pre class="brush: js">var today = new Date(); +var year = today.getUTCFullYear(); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.3.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.11', 'Date.prototype.getUTCFullYear')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.getutcfullyear', 'Date.prototype.getUTCFullYear')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.getutcfullyear', 'Date.prototype.getUTCFullYear')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Date.prototype.getFullYear()")}}</li> + <li>{{jsxref("Date.prototype.setFullYear()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/getutchours/index.html b/files/ko/web/javascript/reference/global_objects/date/getutchours/index.html new file mode 100644 index 0000000000..11171e568c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/getutchours/index.html @@ -0,0 +1,117 @@ +--- +title: Date.prototype.getUTCHours() +slug: Web/JavaScript/Reference/Global_Objects/Date/getUTCHours +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getUTCHours +--- +<div>{{JSRef}}</div> + +<p>getUTCHours () 메서드는 표준시에 따라 지정된 날짜의 시간을 반환합니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.getUTCHours()</code></pre> + +<h3 id="Return_value">Return value</h3> + +<p>0부터 23까지의 정수로, 표준시에 따라 지정된 날짜의 시간을 나타냅니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_getUTCHours()">Using <code>getUTCHours()</code></h3> + +<p>다음 예제에서는 현재 시간의 시간 부분을 시간 변수로 지정합니다.</p> + +<pre class="brush: js">var today = new Date(); +var hours = today.getUTCHours(); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.3.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.19', 'Date.prototype.getUTCHours')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.getutchours', 'Date.prototype.getUTCHours')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.getutchours', 'Date.prototype.getUTCHours')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Date.prototype.getHours()")}}</li> + <li>{{jsxref("Date.prototype.setUTCHours()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/getutcmilliseconds/index.html b/files/ko/web/javascript/reference/global_objects/date/getutcmilliseconds/index.html new file mode 100644 index 0000000000..8121d3c7c4 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/getutcmilliseconds/index.html @@ -0,0 +1,117 @@ +--- +title: Date.prototype.getUTCMilliseconds() +slug: Web/JavaScript/Reference/Global_Objects/Date/getUTCMilliseconds +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getUTCMilliseconds +--- +<div>{{JSRef}}</div> + +<p><strong>getUTCMilliseconds()</strong> 메서드는 표준시에 따라 지정된 날짜의 밀리 초를 반환합니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.getUTCMilliseconds()</code></pre> + +<h3 id="Return_value">Return value</h3> + +<p>0부터 999까지의 정수로, 표준시에 따라 지정된 날짜의 밀리 초를 나타냅니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_getUTCMilliseconds()">Using <code>getUTCMilliseconds()</code></h3> + +<p>다음 예제에서는 현재 시간의 밀리 초 부분을 밀리 초 변수에 할당합니다.</p> + +<pre class="brush: js">var today = new Date(); +var milliseconds = today.getUTCMilliseconds(); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.3.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.25', 'Date.prototype.getUTCMilliseconds')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.getutcmilliseconds', 'Date.prototype.getUTCMilliseconds')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.getutcmilliseconds', 'Date.prototype.getUTCMilliseconds')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Date.prototype.getMilliseconds()")}}</li> + <li>{{jsxref("Date.prototype.setUTCMilliseconds()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/getutcminutes/index.html b/files/ko/web/javascript/reference/global_objects/date/getutcminutes/index.html new file mode 100644 index 0000000000..45c453dced --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/getutcminutes/index.html @@ -0,0 +1,117 @@ +--- +title: Date.prototype.getUTCMinutes() +slug: Web/JavaScript/Reference/Global_Objects/Date/getUTCMinutes +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getUTCMinutes +--- +<div>{{JSRef}}</div> + +<p><strong>getUTCMinutes()</strong> 메서드는 표준시에 따라 지정된 날짜의 분을 반환합니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.getUTCMinutes()</code></pre> + +<h3 id="Return_value">Return value</h3> + +<p>0부터 59까지의 정수로, 표준시에 따라 지정된 날짜의 분을 나타냅니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_getUTCMinutes()">Using <code>getUTCMinutes()</code></h3> + +<p>다음 예제에서는 현재 시간의 분 부분을 minutes 변수에 할당합니다.</p> + +<pre class="brush: js">var today = new Date(); +var minutes = today.getUTCMinutes(); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.3.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.21', 'Date.prototype.getUTCMinutes')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.getutcminutes', 'Date.prototype.getUTCMinutes')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.getutcminutes', 'Date.prototype.getUTCMinutes')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Date.prototype.getMinutes()")}}</li> + <li>{{jsxref("Date.prototype.setUTCMinutes()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/getutcmonth/index.html b/files/ko/web/javascript/reference/global_objects/date/getutcmonth/index.html new file mode 100644 index 0000000000..b4031536d6 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/getutcmonth/index.html @@ -0,0 +1,117 @@ +--- +title: Date.prototype.getUTCMonth() +slug: Web/JavaScript/Reference/Global_Objects/Date/getUTCMonth +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getUTCMonth +--- +<div>{{JSRef}}</div> + +<p><strong>getUTCMonth()</strong>는 지정된 날짜의 월을 0부터 시작하는 값 (0은 첫 해를 나타냄)으로 표준시에 따라 반환합니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.getUTCMonth()</code></pre> + +<h3 id="Return_value">Return value</h3> + +<p>0부터 11까지의 정수로, 표준시에 따라 주어진 날짜의 달에 해당합니다. 1 월은 0, 2 월은 1, 3 월은 2 등입니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_getUTCMonth()">Using <code>getUTCMonth()</code></h3> + +<p>다음 예제에서는 현재 날짜의 월 부분을 month 변수에 할당합니다.</p> + +<pre class="brush: js">var today = new Date(); +var month = today.getUTCMonth(); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.3.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.13', 'Date.prototype.getUTCMonth')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.getutcmonth', 'Date.prototype.getUTCMonth')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.getutcmonth', 'Date.prototype.getUTCMonth')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Date.prototype.getMonth()")}}</li> + <li>{{jsxref("Date.prototype.setUTCMonth()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/getutcseconds/index.html b/files/ko/web/javascript/reference/global_objects/date/getutcseconds/index.html new file mode 100644 index 0000000000..d643903df7 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/getutcseconds/index.html @@ -0,0 +1,117 @@ +--- +title: Date.prototype.getUTCSeconds() +slug: Web/JavaScript/Reference/Global_Objects/Date/getUTCSeconds +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getUTCSeconds +--- +<div>{{JSRef}}</div> + +<p><strong>getUTCSeconds()</strong> 메서드는 표준시에 따라 지정된 날짜의 초를 반환합니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.getUTCSeconds()</code></pre> + +<h3 id="Return_value">Return value</h3> + +<p>0부터 59까지의 정수로, 표준시에 따라 지정된 날짜의 초를 나타냅니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_getUTCSeconds()">Using <code>getUTCSeconds()</code></h3> + +<p>다음 예제에서는 현재 시간의 초 부분을 초 변수에 지정합니다.</p> + +<pre class="brush: js">var today = new Date(); +var seconds = today.getUTCSeconds(); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.3.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.23', 'Date.prototype.getUTCSeconds')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.getutcseconds', 'Date.prototype.getUTCSeconds')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.getutcseconds', 'Date.prototype.getUTCSeconds')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Date.prototype.getSeconds()")}}</li> + <li>{{jsxref("Date.prototype.setUTCSeconds()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/index.html b/files/ko/web/javascript/reference/global_objects/date/index.html new file mode 100644 index 0000000000..d9cf05bbdb --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/index.html @@ -0,0 +1,239 @@ +--- +title: Date +slug: Web/JavaScript/Reference/Global_Objects/Date +tags: + - Constructor + - Date + - JavaScript + - Reference + - 날짜 + - 시간 +translation_of: Web/JavaScript/Reference/Global_Objects/Date +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary"><strong><code>Date</code></strong> 생성자는 시간의 특정 지점을 나타내는 <code>Date</code> 객체를 생성합니다.</span> <code>Date</code> 객체는 1970년 1월 1일 UTC(국제표준시) 00:00으로부터 지난 시간을 밀리초로 나타내는 <a href="http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_16">유닉스 타임스탬프</a>를 사용합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/date-constructor.html")}}</div> + + + +<h2 id=".EC.83.9D.EC.84.B1" name=".EC.83.9D.EC.84.B1"><code>Date</code> 객체 초기화</h2> + +<p>JavaScript Date 객체를 생성하는 법은 {{jsxref("new")}} 연산자를 사용하는 것이 유일합니다.</p> + +<pre class="brush: js">let now = new Date();</pre> + +<p>단순히 {{jsxref("Date", "Date")}} 객체를 직접 호출했을 때, 반환 값은 <code>Date</code> 객체가 아니라 날짜를 나타낸 문자열입니다. JavaScript는 <code>Date</code> 리터럴 구문이 없습니다.</p> + +<h2 id=".EC.83.9D.EC.84.B1" name=".EC.83.9D.EC.84.B1">구문</h2> + +<pre class="syntaxbox">new Date(); +new Date(<var>value</var>); +new Date(<var>dateString</var>); +new Date(<var>year</var>, <var>monthIndex</var>[, <var>day</var>[, <var>hour</var>[, <var>minutes</var>[, <var>seconds</var>[, <var>milliseconds</var>]]]]]); +</pre> + +<h3 id=".ED.8C.8C.EB.9D.BC.EB.AF.B8.ED.84.B0" name=".ED.8C.8C.EB.9D.BC.EB.AF.B8.ED.84.B0">매개변수</h3> + +<p><code>Date()</code> 생성자는 네 가지 형태로 사용할 수 있습니다.</p> + +<h4 id="매개변수_없음">매개변수 없음</h4> + +<p>매개변수를 제공하지 않으면, 현지 시간으로 생성 순간의 날짜와 시간을 나타내는 <code>Date</code> 객체를 생성합니다.</p> + +<h4 id="유닉스_타임스탬프">유닉스 타임스탬프</h4> + +<dl> + <dt><code>value</code></dt> + <dd><a href="http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_16">유닉스 타임스탬프</a>, 즉 1970년 1월 1일 00:00:00 UTC(유닉스 시간)부터의 시간을 밀리초 단위로 표현하되 윤초는 무시한 정숫값. 대부분의 유닉스 타임스탬프 함수는 초 단위까지만 정확함을 유의하세요.</dd> + <dt> + <h4 id="타임스탬프_문자열">타임스탬프 문자열</h4> + </dt> + <dt><code>dateString</code></dt> + <dd>날짜를 표현하는 문자열값. {{jsxref("Date.parse()")}} 메서드가 인식할 수 있는 형식(<a href="http://tools.ietf.org/html/rfc2822#page-14">IETF 호환 RFC 2822 타임스탬프</a>와 <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15">ISO8601의 한 버전</a>)이어야 합니다 + <div class="note"><strong>참고</strong>: <code>Date</code> 생성자(와 <code>Date.parse</code>)를 사용해 날짜 문자열에서 시간을 알아내는건 하지 않는 것이 좋습니다. 브라우저 간 차이와 여러 비일관성이 존재하며 RFC 2822 규격 문자열의 지원은 관례일 뿐입니다. ISO 8601 규격 문자열은 시간 정보가 없을 때("1970-01-01" 등) 현지 시간이 아닌 UTC 기준으로 처리합니다.</div> + </dd> +</dl> + +<h4 id="개별_날짜_및_시간_구성_요소">개별 날짜 및 시간 구성 요소</h4> + +<p>적어도 연도와 월이 주어지면, 자신의 구성 요소(연, 월, 일, 시, 분, 초, 밀리초)를 모두 매개변수의 값에서 가져오는 <code>Date</code> 객체를 생성합니다. 누락한 요소에는 가장 낮은 값(<code>day</code>는 1, 나머지는 0)을 사용합니다.</p> + +<dl> + <dt><code>year</code></dt> + <dd>연도를 나타내는 정숫값. 0부터 99는 1900부터 1999로 처리합니다. {{anch("두 자리 연도는 1900년대로", "아래 예제")}}를 참고하세요.</dd> + <dt><code>monthIndex</code></dt> + <dd>월을 나타내는 정숫값. 0은 1월을 나타내고 11은 12월을 나타냅니다.</dd> + <dt><code>day</code> {{optional_inline}}</dt> + <dd>일을 나타내는 정숫값. 기본값은 1입니다.</dd> + <dt><code>hours</code> {{optional_inline}}</dt> + <dd>시를 나타내는 정숫값. 기본값은 0(자정)입니다.</dd> +</dl> + +<dl> + <dt><code>minutes</code> {{optional_inline}}</dt> + <dd>분을 나타내는 정숫값. 기본값은 0분입니다.</dd> + <dt><code>seconds</code> {{optional_inline}}</dt> + <dd>초를 나타내는 정숫값. 기본값은 0초입니다.</dd> + <dt><code>milliseconds</code> {{optional_inline}}</dt> + <dd>밀리초를 나타내는 정숫값. 기본값은 0밀리초입니다.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<h3 id="유닉스_시간과_타임스탬프">유닉스 시간과 타임스탬프</h3> + +<p>JavaScript 날짜는 1970년 1월 1일 자정 (UTC)로부터 지난 시간을 밀리초 단위로 나타낸 것입니다. 이 날짜와 시간을 합쳐 <strong>유닉스 시간</strong>이라고 부릅니다. 유닉스 시간은 컴퓨터로 날짜와 시간을 기록할 때 널리 사용하는 기준점입니다.</p> + +<div class="blockIndicator note"> +<p><strong>참고</strong>: 시간과 날짜는 현시 시간으로 저장된다는 점을 기억하는게 중요합니다. 시간, 날짜, 아니면 각각의 구성 요소를 회수하는 기본 메서드도 현지 시간에서 동작합니다.</p> +</div> + +<p>하루는 86,400,000 밀리초입니다. 타임스탬프 기록에 사용하는 수의 크기를 고려했을 때, Date 객체는 유닉스 시간으로부터 약 ±100,000,000일 (1억일)을 기록할 수 있습니다. 따라서 293,742년이 오면 문제가 발생할 여지가 있습니다.</p> + +<h3 id="날짜_형식과_시간대_변환">날짜 형식과 시간대 변환</h3> + +<p>날짜를 얻는 방법과 시간대를 바꾸는 메서드는 여럿 있습니다. 그 중 특히 유용한 함수는 날짜 및 시간을 국제 표준 시간인 협정 표준시(UTC)로 반환하는 함수입니다. UTC는 그리니치 시간대라고도 불리는데, 기준 시간대가 영국의 런던과 인근의 그리니치를 지나는 경선이기 때문입니다. 사용자의 장치는 현지 시간을 제공합니다.</p> + +<p>{{jsxref("Date.getDay", "getDay()")}}와 {{jsxref("Date.setHours", "setHours()")}}처럼 현지 시간을 기준으로 한 구성요소 읽기 및 쓰기 메서드처럼, {{jsxref("Date.getDayUTC", "getUTCDay()")}} 와 {{jsxref("Date.setHoursUTC", "setUTCHours()")}}처럼 UTC를 기준으로 하는 읽기 및 쓰기 메서드도 존재합니다.</p> + +<h2 id="속성">속성</h2> + +<dl> + <dt>{{jsxref("Date.prototype")}}</dt> + <dd><code>Date</code> 객체에 추가 속성을 부여할 수 있습니다.</dd> + <dt><code>Date.length</code></dt> + <dd><code>Date.length</code>의 값은 7로, 생성자가 받을 수 있는 매개변수의 수입니다. 보통 유용하게 쓸 수 있는 값은 아닙니다.</dd> +</dl> + +<h2 id="메서드">메서드</h2> + +<dl> + <dt>{{jsxref("Date.now()")}}</dt> + <dd>1970년 1월 1일 00:00:00 UTC(유닉스 시간)부터 지난 시간을 밀리초 단위의 숫자 값으로 반환합니다. 윤초는 무시합니다.</dd> + <dt>{{jsxref("Date.parse()")}}</dt> + <dd>Parses a string representation of a date and returns the number of milliseconds since 1 January, 1970, 00:00:00, UTC. + <div class="note"><strong>Note:</strong> Parsing of strings with <code>Date.parse</code> is strongly discouraged due to browser differences and inconsistencies.</div> + </dd> + <dt>{{jsxref("Date.UTC()")}}</dt> + <dd>Accepts the same parameters as the longest form of the constructor (i.e. 2 to 7) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC, with leap seconds ignored.</dd> +</dl> + +<h2 id="Date_instances" name="Date_instances">JavaScript <code>Date</code> 인스턴스</h2> + +<p>All <code>Date</code> instances inherit from {{jsxref("Date.prototype")}}. The prototype object of the <code>Date</code> constructor can be modified to affect all <code>Date</code> instances.</p> + +<h3 id="Date.prototype_메서드"><code>Date.prototype</code> 메서드</h3> + +<div>{{page('/ko/docs/Web/JavaScript/Reference/Global_Objects/Date/prototype', 'Methods')}}</div> + +<h2 id=".EC.98.88.EC.A0.9C" name=".EC.98.88.EC.A0.9C">예제</h2> + +<h3 id=".EC.98.88.EC.A0.9C:_.EB.82.A0.EC.A7.9C.EB.A5.BC_.EC.A7.80.EC.A0.95.ED.95.98.EB.8A.94_.EC.97.AC.EB.9F.AC.EA.B0.80.EC.A7.80_.EB.B0.A9.EB.B2.95" name=".EC.98.88.EC.A0.9C:_.EB.82.A0.EC.A7.9C.EB.A5.BC_.EC.A7.80.EC.A0.95.ED.95.98.EB.8A.94_.EC.97.AC.EB.9F.AC.EA.B0.80.EC.A7.80_.EB.B0.A9.EB.B2.95">날짜를 지정하는 여러가지 방법</h3> + +<p>아래 예제는 날짜를 지정하는 몇가지 방법을 보여줍니다:</p> + +<div class="blockIndicator note"> +<p><strong>Note:</strong> parsing of date strings with the <code>Date</code> constructor (and <code>Date.parse</code>, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.</p> +</div> + +<pre class="brush: js">var today = new Date(); +var birthday = new Date("December 17, 1995 03:24:00"); +var birthday = new Date(95,11,17); +var birthday = new Date(95,11,17,3,24,0); +</pre> + +<h3 id="두_자리_연도는_1900년대로">두 자리 연도는 1900년대로</h3> + +<p>In order to create and get dates between the years 0 and 99 the {{jsxref("Date.prototype.setFullYear()")}} and {{jsxref("Date.prototype.getFullYear()")}} methods should be used.</p> + +<pre class="brush: js">var date = new Date(98, 1); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT) + +// Deprecated method, 98 maps to 1998 here as well +date.setYear(98); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT) + +date.setFullYear(98); // Sat Feb 01 0098 00:00:00 GMT+0000 (BST) +</pre> + +<h3 id=".EC.98.88.EC.A0.9C:_.EA.B2.BD.EA.B3.BC.EC.8B.9C.EA.B0.84_.EA.B3.84.EC.82.B0" name=".EC.98.88.EC.A0.9C:_.EA.B2.BD.EA.B3.BC.EC.8B.9C.EA.B0.84_.EA.B3.84.EC.82.B0">경과시간 계산</h3> + +<p>The following examples show how to determine the elapsed time between two JavaScript dates in milliseconds.</p> + +<p>Due to the differing lengths of days (due to daylight saving changeover), months and years, expressing elapsed time in units greater than hours, minutes and seconds requires addressing a number of issues and should be thoroughly researched before being attempted.</p> + +<pre class="brush: js">// Date 객체 사용 +var start = Date.now(); + +// 시간이 오래 걸리는 작업을 여기 배치합니다 +doSomethingForALongTime(); +var end = Date.now(); +var elapsed = end - start; // 경과 시간, 밀리초. +</pre> + +<pre class="brush: js">// 내장 메서드 사용 +var start = new Date(); + +// 시간이 오래 걸리는 작업을 여기 배치합니다. +doSomethingForALongTime(); +var end = new Date(); +var elapsed = end.getTime() - start.getTime(); // 경과 시간, 밀리초. +</pre> + +<pre class="brush: js"><code>// to test a function and get back its return +function printElapsedTime(fTest) { + var nStartTime = Date.now(), + vReturn = fTest(), + nEndTime = Date.now(); + + console.log('Elapsed time: ' + String(nEndTime - nStartTime) + ' milliseconds'); + return vReturn; +} + +var yourFunctionReturn = printElapsedTime(yourFunction);</code></pre> + +<div class="blockIndicator note"><strong>Note:</strong> In browsers that support the {{domxref("window.performance", "Web Performance API", "", 1)}}'s high-resolution time feature, {{domxref("Performance.now()")}} can provide more reliable and precise measurements of elapsed time than {{jsxref("Date.now()")}}.</div> + +<h3 id="Get_the_number_of_seconds_since_Unix_Epoch">Get the number of seconds since Unix Epoch</h3> + +<pre class="brush: js">var seconds = Math.floor(Date.now() / 1000);</pre> + +<p>In this case it's important to return only an integer (so a simple division won't do), and also to only return actually elapsed seconds (that's why this code uses {{jsxref("Math.floor()")}} and not {{jsxref("Math.round()")}}).</p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date-objects', 'Date')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date-objects', 'Date')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9', 'Date')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Date", 3)}}</p> diff --git a/files/ko/web/javascript/reference/global_objects/date/now/index.html b/files/ko/web/javascript/reference/global_objects/date/now/index.html new file mode 100644 index 0000000000..323df8ad45 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/now/index.html @@ -0,0 +1,119 @@ +--- +title: Date.now() +slug: Web/JavaScript/Reference/Global_Objects/Date/now +translation_of: Web/JavaScript/Reference/Global_Objects/Date/now +--- +<div>{{JSRef}}</div> + +<p><strong><code>Date.now()</code></strong> 메소드는 UTC 기준으로 1970년 1월 1일 0시 0분 0초부터 현재까지 경과된 밀리 초를 반환합니다.</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox"><code>var timeInMs = Date.now();</code></pre> + +<h3 id="인자">인자</h3> + +<p>없음</p> + +<h2 id="설명">설명</h2> + +<p>now() 메소드는 1970년 1월 1일 0시 0분 0초부터 현재까지 경과된 밀리 초를 {{jsxref("Number")}} 형으로 반환합니다.</p> + +<p>now()는 {{jsxref("Date")}}의 정적 메소드이기 때문에, 항상 <code>Date.now() 처럼 사용하셔야 합니다.</code></p> + +<h2 id="Polyfill">Polyfill</h2> + +<p>이 메소든는 ECMA-262 5판에서 표준화되었습니다. 아직 이 메소드를 지원하도록 갱신되지 않은 엔진들은 이 메소드의 미지원에 대한 차선책으로 다음 코드를 활용하실 수 있습니다.</p> + +<pre class="brush: js">if (!Date.now) { + Date.now = function now() { + return new Date().getTime(); + }; +} +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.4.4', 'Date.now')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.5.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.now', 'Date.now')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.now', 'Date.now')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("5")}}</td> + <td>{{CompatGeckoDesktop("1.9")}}</td> + <td>{{CompatIE("9")}}</td> + <td>{{CompatOpera("10.50")}}</td> + <td>{{CompatSafari("4")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{domxref("Performance.now()")}} — provides timestamps with sub-millisecond resolution for use in measuring web page performance</li> + <li>{{domxref("console.time()")}} / {{domxref("console.timeEnd()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/parse/index.html b/files/ko/web/javascript/reference/global_objects/date/parse/index.html new file mode 100644 index 0000000000..57e8effa54 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/parse/index.html @@ -0,0 +1,231 @@ +--- +title: Date.parse() +slug: Web/JavaScript/Reference/Global_Objects/Date/parse +translation_of: Web/JavaScript/Reference/Global_Objects/Date/parse +--- +<div>{{JSRef}}</div> + +<p>Date.parse () 메서드는 날짜의 문자열 표현을 구문 분석하고 1970 년 1 월 1 일 00:00:00 UTC 이후의 밀리 초 수를 반환하거나 문자열이 인식되지 않거나 경우에 따라 잘못된 날짜 값을 포함하는 경우 NaN을 반환합니다. (예 : 2015-02-31).</p> + +<p>ES5까지는 Date.parse를 사용하지 않는 것이 좋습니다. 문자열 구문 분석은 전적으로 구현에 따라 다릅니다. 다른 호스트가 날짜 문자열을 구문 분석하는 방법에는 여전히 많은 차이점이 있으므로 날짜 문자열을 수동으로 구문 분석해야합니다 (다양한 형식을 수용하면 라이브러리가 도움이 될 수 있습니다).</p> + +<h2 id="Syntax">Syntax</h2> + +<p>Direct call:</p> + +<pre class="syntaxbox">Date.parse(<var>dateString</var>)</pre> + +<p>Implicit call:</p> + +<pre class="syntaxbox">new Date(<var>dateString</var>)</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>dateString</code></dt> + <dd>RFC2822 또는 ISO 8601 날짜를 나타내는 문자열 (다른 형식도 사용할 수 있지만 예기치 않은 결과 일 수 있음)</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>1970 년 1 월 1 일 00:00:00 UTC 이후 경과 된 밀리 초를 나타내는 숫자 및 주어진 문자열 표현을 파싱하여 얻은 날짜입니다. 인수가 유효한 날짜를 나타내지 않으면 {{jsxref ( "NaN")}}이 반환됩니다.</p> + +<h2 id="Description">Description</h2> + +<p>parse () 메서드는 날짜 문자열 (예 : "Dec 25, 1995")을 사용하고 1970 년 1 월 1 일 00:00:00 UTC 이후의 밀리 초 수를 반환합니다. 이 함수는 예를 들어 {{jsxref("Date.prototype.setTime()", "setTime()")}} 메서드 및 {{jsxref ( "Global_Objects / Date ","Date ")}} 객체를 반환합니다.</p> + +<p>주어진 시간을 나타내는 문자열이 주어지면 parse ()는 시간 값을 반환합니다. RFC2822 / IETF 날짜 구문 (RFC2822 섹션 3.3)을 받아들입니다. "Mon, 25 Dec 1995 13:30:00 GMT". 미국 대륙의 표준 시간대 약어를 이해하지만, 일반적으로 "Mon, 25 Dec 1995 13:30:00 +0430"(그리니치 자오선의 동쪽으로 4 시간 30 분)과 같이 시간대 오프셋을 사용하십시오.</p> + +<p>GMT와 UTC는 동등한 것으로 간주됩니다. 현지 시간대는 시간대 정보가없는 RFC2822 섹션 3.3 형식의 인수를 해석하는 데 사용됩니다.</p> + +<p>날짜 문자열 구문 분석의 차이로 인해 결과가 일관되지 않아 문자열을 수동으로 구문 분석하는 것이 좋습니다. 특히 "2015-10-12 12:00:00"과 같은 문자열을 NaN으로 구문 분석 할 수있는 다른 ECMAScript 구현, UTC 또는 현지 시간대.</p> + +<h3 id="ECMAScript_5_ISO-8601_format_support">ECMAScript 5 ISO-8601 format support</h3> + +<p>날짜 시간 문자열은 ISO 8601 형식 일 수 있습니다. 예를 들어, "2011-10-10"(날짜 만) 또는 "2011-10-10T14 : 48 : 00"(날짜 및 시간)을 전달하고 구문 분석 할 수 있습니다. 문자열이 ISO 8601 날짜 인 경우 UTC 시간대는 인수를 해석하는 데 사용됩니다. 문자열이 ISO 8601 형식의 날짜 및 시간이면 로컬로 처리됩니다.</p> + +<p>날짜 문자열 구문 분석 중에 시간대 지정자를 사용하여 인수를 해석하지만 반환되는 값은 1970 년 1 월 1 일 00:00:00 UTC와 인수 또는 NaN이 나타내는 시점 사이의 밀리 초입니다.</p> + +<p>parse ()는 {{jsxref ( "Date")}}의 정적 메서드이기 때문에 {{jsxref ( "Date")}} 인스턴스의 메서드가 아닌 Date.parse ()로 호출됩니다.</p> + +<h3 id="가정_된_시간대의_차이점">가정 된 시간대의 차이점</h3> + +<p>"March 7, 2014"이라는 날짜 문자열이 주어지면 parse ()는 현지 시간대를 사용하지만 "2014-03-07"과 같은 ISO 형식이 주어지면 UTC (ES5 및 ECMAScript 2015)의 시간대로 가정합니다. 따라서 {{jsxref ( "Date")}} 이러한 문자열을 사용하여 생성 된 객체는 시스템이 현지 표준 시간대 (UTC)로 설정되어 있지 않으면 지원되는 ECMAScript 버전에 따라 다른 순간을 나타낼 수 있습니다. 즉, 변환되는 문자열의 형식에 따라 동등하게 나타나는 두 개의 날짜 문자열이 서로 다른 두 개의 값을 가질 수 있습니다.</p> + +<h3 id="구현_특정_날짜_형식으로_폴백">구현 특정 날짜 형식으로 폴백</h3> + +<p>ECMAScript 사양은 다음과 같이 설명합니다. String이 표준 형식을 준수하지 않으면 함수는 구현 특정 휴리스틱 또는 구현 특정 파싱 알고리즘으로 폴백 할 수 있습니다. 인식 할 수없는 문자열 또는 ISO 형식의 문자열에 잘못된 요소 값이 포함 된 날짜로 인해 Date.parse ()가 {{jsxref ( "NaN")}}을 반환합니다.</p> + +<p>그러나 ECMA-262에 정의 된 ISO 형식으로 인식되지 않는 날짜 문자열의 잘못된 값은 제공된 브라우저 및 값에 따라 {{jsxref ( "NaN")}}이 될 수도 있고 그렇지 않을 수도 있습니다 (예 :</p> + +<pre class="brush: js">// Non-ISO string with invalid date values +new Date('23/25/2014'); +</pre> + +<p>Firefox 30에서는 2015 년 11 월 25 일, Safari 7에서는 유효하지 않은 날짜로 처리됩니다. 그러나 문자열이 ISO 형식 문자열로 인식되고 유효하지 않은 값을 포함하면 {{jsxref ( "NaN ")}} ES5 이상을 준수하는 모든 브라우저에서 :</p> + +<pre class="brush: js">// ISO string with invalid values +new Date('2014-25-23').toISOString(); +// returns "RangeError: invalid date" in all es5 compliant browsers +</pre> + +<p>SpiderMonkey의 구현 관련 추론은 jsdate.cpp에서 찾을 수 있습니다. 문자열 "10 06 2014"는 부적합한 ISO 형식의 예이므로 맞춤 루틴으로 되돌아갑니다. 파싱이 어떻게 작동하는지에 대한 대략적인 개요를 참조하십시오.</p> + +<pre class="brush: js">new Date('10 06 2014'); +</pre> + +<p>2014 년 10 월 6 일과 2014 년 6 월 10 일이 아닌 현지 날짜로 취급됩니다. 다른 예 :</p> + +<pre class="brush: js">new Date('foo-bar 2014').toString(); +// returns: "Invalid Date" + +Date.parse('foo-bar 2014'); +// returns: NaN +</pre> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_Date.parse()">Using <code>Date.parse()</code></h3> + +<p>IPOdate가 기존의 {{jsxref ( "Date")}} 객체 인 경우 다음과 같이 1995 년 8 월 9 일 (현지 시간)으로 설정할 수 있습니다.</p> + +<pre class="brush: js">IPOdate.setTime(Date.parse('Aug 9, 1995'));</pre> + +<p>표준이 아닌 날짜 문자열을 파싱하는 몇 가지 다른 예는 다음과 같습니다.</p> + +<pre class="brush: js">Date.parse('Aug 9, 1995');</pre> + +<p>문자열이 표준 시간대를 지정하지 않고 ISO 형식이 아니므로 표준 시간대 GMT-0300의 807937200000과 다른 표준 시간대의 다른 값을 반환하므로 표준 시간대는 기본적으로 local입니다.</p> + +<pre class="brush: js">Date.parse('Wed, 09 Aug 1995 00:00:00 GMT');</pre> + +<p>GMT (UTC)가 제공되는 현지 시간대와 상관없이 807926400000을 반환합니다.</p> + +<pre class="brush: js">Date.parse('Wed, 09 Aug 1995 00:00:00');</pre> + +<p>인수에 표준 시간대 지정자가 없으므로 ISO 형식이 아니기 때문에 표준 시간대 GMT-0300에서 807937200000과 다른 표준 시간대의 다른 값을 반환하므로 로컬로 처리됩니다.</p> + +<pre class="brush: js">Date.parse('Thu, 01 Jan 1970 00:00:00 GMT');</pre> + +<p>현지 시간대와 상관없이 0을 반환합니다. GMT (UTC)가 제공됩니다.</p> + +<pre class="brush: js">Date.parse('Thu, 01 Jan 1970 00:00:00');</pre> + +<p>표준 시간대가 제공되지 않고 문자열이 ISO 형식이 아니기 때문에 표준 시간대 GMT-0400의 14400000과 다른 표준 시간대의 다른 값을 반환하므로 현지 표준 시간대가 사용됩니다.</p> + +<pre class="brush: js">Date.parse('Thu, 01 Jan 1970 00:00:00 GMT-0400');</pre> + +<p>현지 시간대와 관계없이 14400000을 반환합니다. GMT (UTC)가 제공됩니다.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.4.2', 'Date.parse')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>ISO 8601 format added.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.parse', 'Date.parse')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.parse', 'Date.parse')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>ISO 8601 format</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckodesktop("2.0")}}</td> + <td>{{CompatIE("9")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>ISO 8601 format</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Compatibility_notes">Compatibility notes</h2> + +<ul> + <li>Firefox 49 {{geckoRelease(49)}} changed the parsing of 2-digit years to be aligned with the Google Chrome browser instead of Internet Explorer. Now, 2-digit years that are less than or equal to <code>50</code> are parsed as 21st century years. For example, <code>04/16/17</code>, previously parsed as April 16, 1917, will be April 16, 2017 now. To avoid any interoperability issues or ambiguous years, it is recommended to use the ISO 8601 format like "2017-04-16" ({{bug(1265136)}}).</li> +</ul> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Date.UTC()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/prototype/index.html b/files/ko/web/javascript/reference/global_objects/date/prototype/index.html new file mode 100644 index 0000000000..7fe5dc9617 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/prototype/index.html @@ -0,0 +1,182 @@ +--- +title: Date.prototype +slug: Web/JavaScript/Reference/Global_Objects/Date/prototype +tags: + - Date + - JavaScript + - Property + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Date +--- +<div>{{JSRef}}</div> + +<p><strong><code>Date.prototype</code></strong> 속성은 {{jsxref("Date")}} 생성자의 프로토타입을 나타냅니다.</p> + +<div>{{js_property_attributes(0, 0, 1)}}</div> + +<h2 id="설명">설명</h2> + +<p>JavaScript {{jsxref("Date")}} 인스턴스는 <code>Date.prototype</code>을 상속합니다. 생성자의 프로토타입을 변경해 모든 <code>Date</code> 인스턴스의 속성과 메서드를 수정할 수 있습니다.</p> + +<p>2000년대 달력과의 호환성을 위해 연도는 언제나 완전하게 네 자리 숫자로 작성해야 합니다. 즉 98 대신 1998이 올바른 작성법입니다. <code>Date</code>는 완전한 연도 설정에 도움이 될 {{jsxref("Date.prototype.getFullYear()", "getFullYear()")}}, {{jsxref("Date.prototype.setFullYear()", "setFullYear()")}}, {{jsxref("Date.prototype.getUTCFullYear()", "getUTCFullYear()")}}, {{jsxref("Date.prototype.setUTCFullYear()", "setUTCFullYear()")}} 메서드를 가지고 있습니다.</p> + +<p>ECMAScript 6부터 <code>Date.prototype</code>은 {{jsxref("Date")}} 인스턴스가 아닌 평범한 객체입니다.</p> + +<h2 id="속성">속성</h2> + +<dl> + <dt><code>Date.prototype.constructor</code></dt> + <dd>인스턴스 생성에 사용한 생성자를 반환합니다. 기본값은 {{jsxref("Date")}}입니다.</dd> +</dl> + +<h2 id="메서드">메서드</h2> + +<h3 id="접근자">접근자</h3> + +<dl> + <dt>{{jsxref("Date.prototype.getDate()")}}</dt> + <dd>주어진 날짜의 일(1-31)을 현지 시간에 맞춰 반환합니다.</dd> + <dt>{{jsxref("Date.prototype.getDay()")}}</dt> + <dd>주어진 날짜의 요일(0-6)을 현지 시간에 맞춰 반환합니다.</dd> + <dt>{{jsxref("Date.prototype.getFullYear()")}}</dt> + <dd>주어진 날짜의 연도(4자리 수)를 현지 시간에 맞춰 반환합니다.</dd> + <dt>{{jsxref("Date.prototype.getHours()")}}</dt> + <dd>주어진 날짜의 시(0-23)를 현지 시간에 맞춰 반환합니다.</dd> + <dt>{{jsxref("Date.prototype.getMilliseconds()")}}</dt> + <dd>주어진 날짜의 밀리초(0-999)를 현지 시간에 맞춰 반환합니다.</dd> + <dt>{{jsxref("Date.prototype.getMinutes()")}}</dt> + <dd>주어진 날짜의 분(0-59)을 현지 시간에 맞춰 반환합니다.</dd> + <dt>{{jsxref("Date.prototype.getMonth()")}}</dt> + <dd>주어진 날짜의 월(0-11)을 현지 시간에 맞춰 반환합니다.</dd> + <dt>{{jsxref("Date.prototype.getSeconds()")}}</dt> + <dd>주어진 날짜의 초(0-59)를 현지 시간에 맞춰 반환합니다.</dd> + <dt>{{jsxref("Date.prototype.getTime()")}}</dt> + <dd>주어진 날짜와 1970년 1월 1일 0시 0분(UTC)의 차이를 밀리초로 반환합니다.</dd> + <dt>{{jsxref("Date.prototype.getTimezoneOffset()")}}</dt> + <dd>현재 로케일의 시간대 차이를 분으로 환산해 반환합니다.</dd> + <dt>{{jsxref("Date.prototype.getUTCDate()")}}</dt> + <dd>주어진 날짜의 일(1-31)을 UTC에 맞춰 반환합니다.</dd> + <dt>{{jsxref("Date.prototype.getUTCDay()")}}</dt> + <dd>주어진 날짜의 요일(0-6)을 UTC에 맞춰 반환합니다.</dd> + <dt>{{jsxref("Date.prototype.getUTCFullYear()")}}</dt> + <dd>주어진 날짜의 연도(4자리 수)를 UTC에 맞춰 반환합니다.</dd> + <dt>{{jsxref("Date.prototype.getUTCHours()")}}</dt> + <dd>주어진 날짜의 시(0-23)를 UTC에 맞춰 반환합니다.</dd> + <dt>{{jsxref("Date.prototype.getUTCMilliseconds()")}}</dt> + <dd>주어진 날짜의 밀리초(0-999)를 UTC에 맞춰 반환합니다.</dd> + <dt>{{jsxref("Date.prototype.getUTCMinutes()")}}</dt> + <dd>주어진 날짜의 분(0-59)을 UTC에 맞춰 반환합니다.</dd> + <dt>{{jsxref("Date.prototype.getUTCMonth()")}}</dt> + <dd>주어진 날짜의 월(0-11)을 UTC에 맞춰 반환합니다.</dd> + <dt>{{jsxref("Date.prototype.getUTCSeconds()")}}</dt> + <dd>주어진 날짜의 초(0-59)를 UTC에 맞춰 반환합니다.</dd> + <dt>{{jsxref("Date.prototype.getYear()")}} {{deprecated_inline}}</dt> + <dd>주어진 날짜의 연도(주로 두세자리 숫자)를 현지 시간에 맞춰 반환합니다. {{jsxref("Date.prototype.getFullYear()", "getFullYear()")}}를 사용하세요.</dd> +</dl> + +<h3 id="설정자">설정자</h3> + +<dl> + <dt>{{jsxref("Date.prototype.setDate()")}}</dt> + <dd>Sets the day of the month for a specified date according to local time.</dd> + <dt>{{jsxref("Date.prototype.setFullYear()")}}</dt> + <dd>Sets the full year (e.g. 4 digits for 4-digit years) for a specified date according to local time.</dd> + <dt>{{jsxref("Date.prototype.setHours()")}}</dt> + <dd>Sets the hours for a specified date according to local time.</dd> + <dt>{{jsxref("Date.prototype.setMilliseconds()")}}</dt> + <dd>Sets the milliseconds for a specified date according to local time.</dd> + <dt>{{jsxref("Date.prototype.setMinutes()")}}</dt> + <dd>Sets the minutes for a specified date according to local time.</dd> + <dt>{{jsxref("Date.prototype.setMonth()")}}</dt> + <dd>Sets the month for a specified date according to local time.</dd> + <dt>{{jsxref("Date.prototype.setSeconds()")}}</dt> + <dd>Sets the seconds for a specified date according to local time.</dd> + <dt>{{jsxref("Date.prototype.setTime()")}}</dt> + <dd>Sets the {{jsxref("Date")}} object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC, allowing for negative numbers for times prior.</dd> + <dt>{{jsxref("Date.prototype.setUTCDate()")}}</dt> + <dd>Sets the day of the month for a specified date according to universal time.</dd> + <dt>{{jsxref("Date.prototype.setUTCFullYear()")}}</dt> + <dd>Sets the full year (e.g. 4 digits for 4-digit years) for a specified date according to universal time.</dd> + <dt>{{jsxref("Date.prototype.setUTCHours()")}}</dt> + <dd>Sets the hour for a specified date according to universal time.</dd> + <dt>{{jsxref("Date.prototype.setUTCMilliseconds()")}}</dt> + <dd>Sets the milliseconds for a specified date according to universal time.</dd> + <dt>{{jsxref("Date.prototype.setUTCMinutes()")}}</dt> + <dd>Sets the minutes for a specified date according to universal time.</dd> + <dt>{{jsxref("Date.prototype.setUTCMonth()")}}</dt> + <dd>Sets the month for a specified date according to universal time.</dd> + <dt>{{jsxref("Date.prototype.setUTCSeconds()")}}</dt> + <dd>Sets the seconds for a specified date according to universal time.</dd> + <dt>{{jsxref("Date.prototype.setYear()")}} {{deprecated_inline}}</dt> + <dd>Sets the year (usually 2-3 digits) for a specified date according to local time. Use {{jsxref("Date.prototype.setFullYear()", "setFullYear()")}} instead.</dd> +</dl> + +<h3 id="변환_접근자">변환 접근자</h3> + +<dl> + <dt>{{jsxref("Date.prototype.toDateString()")}}</dt> + <dd>Returns the "date" portion of the {{jsxref("Date")}} as a human-readable string like 'Thu Apr 12 2018'</dd> + <dt>{{jsxref("Date.prototype.toISOString()")}}</dt> + <dd>Converts a date to a string following the ISO 8601 Extended Format.</dd> + <dt>{{jsxref("Date.prototype.toJSON()")}}</dt> + <dd>Returns a string representing the {{jsxref("Date")}} using {{jsxref("Date.prototype.toISOString()", "toISOString()")}}. Intended for use by {{jsxref("JSON.stringify()")}}.</dd> + <dt>{{jsxref("Date.prototype.toGMTString()")}} {{deprecated_inline}}</dt> + <dd>Returns a string representing the {{jsxref("Date")}} based on the GMT (UT) time zone. Use {{jsxref("Date.prototype.toUTCString()", "toUTCString()")}} instead.</dd> + <dt>{{jsxref("Date.prototype.toLocaleDateString()")}}</dt> + <dd>Returns a string with a locality sensitive representation of the date portion of this date based on system settings.</dd> + <dt>{{jsxref("Date.prototype.toLocaleFormat()")}} {{non-standard_inline}}</dt> + <dd>Converts a date to a string, using a format string.</dd> + <dt>{{jsxref("Date.prototype.toLocaleString()")}}</dt> + <dd>Returns a string with a locality sensitive representation of this date. Overrides the {{jsxref("Object.prototype.toLocaleString()")}} method.</dd> + <dt>{{jsxref("Date.prototype.toLocaleTimeString()")}}</dt> + <dd>Returns a string with a locality sensitive representation of the time portion of this date based on system settings.</dd> + <dt>{{jsxref("Date.prototype.toSource()")}} {{non-standard_inline}}</dt> + <dd>Returns a string representing the source for an equivalent {{jsxref("Date")}} object; you can use this value to create a new object. Overrides the {{jsxref("Object.prototype.toSource()")}} method.</dd> + <dt>{{jsxref("Date.prototype.toString()")}}</dt> + <dd>Returns a string representing the specified {{jsxref("Date")}} object. Overrides the {{jsxref("Object.prototype.toString()")}} method.</dd> + <dt>{{jsxref("Date.prototype.toTimeString()")}}</dt> + <dd>Returns the "time" portion of the {{jsxref("Date")}} as a human-readable string.</dd> + <dt>{{jsxref("Date.prototype.toUTCString()")}}</dt> + <dd>Converts a date to a string using the UTC timezone.</dd> + <dt>{{jsxref("Date.prototype.valueOf()")}}</dt> + <dd>Returns the primitive value of a {{jsxref("Date")}} object. Overrides the {{jsxref("Object.prototype.valueOf()")}} method.</dd> +</dl> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5', 'Date.prototype')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-properties-of-the-date-prototype-object', 'Date.prototype')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-properties-of-the-date-prototype-object', 'Date.prototype')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Date.prototype")}}</p> diff --git a/files/ko/web/javascript/reference/global_objects/date/setdate/index.html b/files/ko/web/javascript/reference/global_objects/date/setdate/index.html new file mode 100644 index 0000000000..17f2b8aa02 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/setdate/index.html @@ -0,0 +1,127 @@ +--- +title: Date.prototype.setDate() +slug: Web/JavaScript/Reference/Global_Objects/Date/setDate +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setDate +--- +<div>{{JSRef}}</div> + +<p><strong>setDate()</strong> 메서드는 현재 설정된 월의 시작 부분을 기준으로 {{jsxref ( "Date")}} 객체의 날짜를 설정합니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.setDate(<var>dayValue</var>)</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>dayValue</code></dt> + <dd>월의 일을 나타내는 정수입니다.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>1970 년 1 월 1 일 00:00:00 UTC와 주어진 날짜 사이의 밀리 초 ({{jsxref ( "Date")}} 개체도 변경됩니다).</p> + +<h2 id="Description">Description</h2> + +<p>dayValue가 해당 월의 날짜 값 범위를 벗어나면 setDate ()는 그에 따라 {{jsxref ( "Date")}} 객체를 업데이트합니다. 예를 들어, dayValue에 0이 제공되면 날짜는 이전 달의 마지막 날로 설정됩니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_setDate()">Using <code>setDate()</code></h3> + +<pre class="brush: js">var theBigDay = new Date(1962, 6, 7); // 1962-07-07 +theBigDay.setDate(24); // 1962-07-24 +theBigDay.setDate(32); // 1962-08-01 +theBigDay.setDate(22); // 1962-08-22</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.36', 'Date.prototype.setDate')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.setdate', 'Date.prototype.setDate')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.setdate', 'Date.prototype.setDate')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Date.prototype.getDate()")}}</li> + <li>{{jsxref("Date.prototype.setUTCDate()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/setfullyear/index.html b/files/ko/web/javascript/reference/global_objects/date/setfullyear/index.html new file mode 100644 index 0000000000..f9faaca856 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/setfullyear/index.html @@ -0,0 +1,133 @@ +--- +title: Date.prototype.setFullYear() +slug: Web/JavaScript/Reference/Global_Objects/Date/setFullYear +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setFullYear +--- +<div>{{JSRef}}</div> + +<p><strong>setFullYear()</strong> 메서드는 현지 시간에 따라 지정된 날짜의 전체 연도를 설정합니다. 새로운 타임 스탬프를 반환합니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.setFullYear(<var>yearValue</var>[, <var>monthValue</var>[, <var>dayValue</var>]])</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>yearValue</code></dt> + <dd>연도의 숫자 값을 지정하는 정수입니다 (예 : 1995).</dd> + <dt><code>monthValue</code></dt> + <dd>선택 과목. 1 월에서 12 월까지의 월을 나타내는 0에서 11 사이의 정수입니다.</dd> + <dt><code>dayValue</code></dt> + <dd>선택 과목. 한 달의 날짜를 나타내는 1 - 31 사이의 정수입니다. dayValue 매개 변수를 지정하는 경우 monthValue도 지정해야합니다.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>1970 년 1 월 1 일 00:00:00 UTC와 업데이트 된 날짜 사이의 밀리 초 숫자입니다.</p> + +<h2 id="Description">Description</h2> + +<p>monthValue 및 dayValue 매개 변수를 지정하지 않으면 {{jsxref ("Date.prototype.getMonth()", "getMonth()")}} 및 {{jsxref("Date.prototype.getDate)","getDate()")}} 메소드가 사용됩니다.</p> + +<p>지정한 매개 변수가 예상 범위를 벗어나면 setFullYear ()가 다른 매개 변수와 {{jsxref ( "Date")}} 객체의 날짜 정보를 그에 따라 업데이트하려고 시도합니다. 예를 들어, monthValue에 15를 지정하면 연도가 1 (yearValue + 1)만큼 증가하고 3은 해당 월에 사용됩니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_setFullYear()">Using <code>setFullYear()</code></h3> + +<pre class="brush: js">var theBigDay = new Date(); +theBigDay.setFullYear(1997); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.3.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.40', 'Date.prototype.setFullYear')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.setfullyear', 'Date.prototype.setFullYear')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.setfullyear', 'Date.prototype.setFullYear')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Date.prototype.getUTCFullYear()")}}</li> + <li>{{jsxref("Date.prototype.setUTCFullYear()")}}</li> + <li>{{jsxref("Date.prototype.setYear()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/sethours/index.html b/files/ko/web/javascript/reference/global_objects/date/sethours/index.html new file mode 100644 index 0000000000..cbc1d4ff32 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/sethours/index.html @@ -0,0 +1,138 @@ +--- +title: Date.prototype.setHours() +slug: Web/JavaScript/Reference/Global_Objects/Date/setHours +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setHours +--- +<div>{{JSRef}}</div> + +<p>setHours () 메서드는 현지 시간에 따라 지정된 날짜의 시간을 설정하고 1970 년 1 월 1 일 00:00:00 UTC 이후 업데이트 된 {{jsxref ( "Date")}}에 의해 표시되는 시간 (밀리 초)을 반환합니다. 예.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.setHours(<var>hoursValue</var>[, <var>minutesValue</var>[, <var>secondsValue</var>[, <var>msValue</var>]]])</code></pre> + +<h3 id="Versions_prior_to_JavaScript_1.3">Versions prior to JavaScript 1.3</h3> + +<pre class="syntaxbox"><code><var>dateObj</var>.setHours(<var>hoursValue</var>)</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>hoursValue</code></dt> + <dd>시를 나타내는 0에서 23 사이의 정수입니다.</dd> + <dt><code>minutesValue</code></dt> + <dd>선택 과목. 분을 나타내는 0에서 59 사이의 정수입니다.</dd> + <dt><code>secondsValue</code></dt> + <dd>선택 과목. 초를 나타내는 0에서 59 사이의 정수입니다. secondsValue 매개 변수를 지정하면 minutesValue도 지정해야합니다.</dd> + <dt><code>msValue</code></dt> + <dd>선택 과목. 밀리 초를 나타내는 0에서 999 사이의 숫자입니다. msValue 매개 변수를 지정하는 경우 minutesValue 및 secondsValue도 지정해야합니다.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>1970 년 1 월 1 일 00:00:00 UTC와 업데이트 된 날짜 사이의 밀리 초 숫자입니다.</p> + +<h2 id="Description">Description</h2> + +<p>minutesValue, secondsValue 및 msValue 매개 변수를 지정하지 않으면 {{jsxref("Date.prototype.getMinutes()", "getMinutes()")}}에서 반환 된 값, {{jsxref("Date.prototype.getSeconds()","getSeconds()")}} 및 {{jsxref("Date.prototype.getMilliseconds()","getMilliseconds()")}} 메서드가 사용됩니다.</p> + +<p>지정한 매개 변수가 예상 범위를 벗어나면 setHours ()는 그에 따라 {{jsxref ("Date")}} 객체의 날짜 정보를 업데이트하려고 시도합니다. 예를 들어 secondsValue에 100을 사용하면 분은 1 (minutesValue + 1)만큼 증가하고 40은 초 단위로 사용됩니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_setHours()">Using <code>setHours()</code></h3> + +<pre class="brush:js">var theBigDay = new Date(); +theBigDay.setHours(7); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.34', 'Date.prototype.setHours')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.sethours', 'Date.prototype.setHours')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.sethours', 'Date.prototype.setHours')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Date.prototype.getHours()")}}</li> + <li>{{jsxref("Date.prototype.setUTCHours()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/setmilliseconds/index.html b/files/ko/web/javascript/reference/global_objects/date/setmilliseconds/index.html new file mode 100644 index 0000000000..d0904ae69e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/setmilliseconds/index.html @@ -0,0 +1,126 @@ +--- +title: Date.prototype.setMilliseconds() +slug: Web/JavaScript/Reference/Global_Objects/Date/setMilliseconds +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setMilliseconds +--- +<div>{{JSRef}}</div> + +<p>setMilliseconds () 메서드는 현지 시간에 따라 지정된 날짜의 밀리 초를 설정합니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.setMilliseconds(<var>millisecondsValue</var>)</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>millisecondsValue</code></dt> + <dd>밀리 초를 나타내는 0에서 999 사이의 숫자입니다.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>1970 년 1 월 1 일 00:00:00 UTC와 업데이트 된 날짜 사이의 밀리 초 숫자입니다.</p> + +<h2 id="Description">Description</h2> + +<p>예상되는 범위를 벗어난 숫자를 지정하면 {{jsxref ( "Date")}} 객체의 날짜 정보가 그에 따라 업데이트됩니다. 예를 들어, 1005를 지정하면 초 수가 1 씩 증가하고 5는 밀리 초 단위로 사용됩니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_setMilliseconds()">Using <code>setMilliseconds()</code></h3> + +<pre class="brush: js">var theBigDay = new Date(); +theBigDay.setMilliseconds(100); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.3.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.28', 'Date.prototype.setMilliseconds')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.setmilliseconds', 'Date.prototype.setMilliseconds')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.setmilliseconds', 'Date.prototype.setMilliseconds')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Date.prototype.getMilliseconds()")}}</li> + <li>{{jsxref("Date.prototype.setUTCMilliseconds()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/setminutes/index.html b/files/ko/web/javascript/reference/global_objects/date/setminutes/index.html new file mode 100644 index 0000000000..296923aa47 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/setminutes/index.html @@ -0,0 +1,136 @@ +--- +title: Date.prototype.setMinutes() +slug: Web/JavaScript/Reference/Global_Objects/Date/setMinutes +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setMinutes +--- +<div>{{JSRef}}</div> + +<p>setMinutes () 메서드는 현지 시간에 따라 지정된 날짜의 분을 설정합니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.setMinutes(<var>minutesValue</var>[, <var>secondsValue</var>[, <var>msValue</var>]])</code></pre> + +<h3 id="Versions_prior_to_JavaScript_1.3">Versions prior to JavaScript 1.3</h3> + +<pre class="syntaxbox"><code><var>dateObj</var>.setMinutes(<var>minutesValue</var>)</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>minutesValue</code></dt> + <dd>분을 나타내는 0에서 59 사이의 정수입니다.</dd> + <dt><code>secondsValue</code></dt> + <dd>선택 과목. 초를 나타내는 0에서 59 사이의 정수입니다. secondsValue 매개 변수를 지정하면 minutesValue도 지정해야합니다.</dd> + <dt><code>msValue</code></dt> + <dd>선택 과목. 밀리 초를 나타내는 0에서 999 사이의 숫자입니다. msValue 매개 변수를 지정하는 경우 minutesValue 및 secondsValue도 지정해야합니다.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>1970 년 1 월 1 일 00:00:00 UTC와 업데이트 된 날짜 사이의 밀리 초 숫자입니다.</p> + +<h2 id="Description">Description</h2> + +<p>secondsValue 및 msValue 매개 변수를 지정하지 않으면 {{jsxref("Date.prototype.getSeconds()", "getSeconds()")}} 및 {{jsxref ("Date.prototype.getMilliseconds ","getMilliseconds() ")}} 메소드가 사용됩니다.</p> + +<p>지정한 매개 변수가 예상 범위를 벗어나면 setMinutes ()는 그에 따라 {{jsxref("Date")}} 객체의 날짜 정보를 업데이트하려고 시도합니다. 예를 들어 secondsValue에 100을 사용하면 분은 1 (minutesValue + 1)만큼 증가하고 40은 초 단위로 사용됩니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_setMinutes()">Using <code>setMinutes()</code></h3> + +<pre class="brush: js">var theBigDay = new Date(); +theBigDay.setMinutes(45); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.32', 'Date.prototype.setMinutes')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.setminutes', 'Date.prototype.setMinutes')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.setminutes', 'Date.prototype.setMinutes')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Date.prototype.getMinutes()")}}</li> + <li>{{jsxref("Date.prototype.setUTCMinutes()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/setmonth/index.html b/files/ko/web/javascript/reference/global_objects/date/setmonth/index.html new file mode 100644 index 0000000000..bd954f83e9 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/setmonth/index.html @@ -0,0 +1,147 @@ +--- +title: Date.prototype.setMonth() +slug: Web/JavaScript/Reference/Global_Objects/Date/setMonth +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setMonth +--- +<div>{{JSRef}}</div> + +<p>setMonth () 메서드는 현재 설정된 연도에 따라 지정된 날짜의 월을 설정합니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.setMonth(<var>monthValue</var>[, <var>dayValue</var>])</code></pre> + +<h3 id="Versions_prior_to_JavaScript_1.3">Versions prior to JavaScript 1.3</h3> + +<pre class="syntaxbox"><code><var>dateObj</var>.setMonth(<var>monthValue</var>)</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>monthValue</code></dt> + <dd>1 월에서 12 월까지의 월을 나타내는 0에서 11 사이의 정수입니다.</dd> + <dt><code>dayValue</code></dt> + <dd>선택 과목. 한 달의 날짜를 나타내는 1에서 31 사이의 정수입니다.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>1970 년 1 월 1 일 00:00:00 UTC와 업데이트 된 날짜 사이의 밀리 초 숫자입니다.</p> + +<h2 id="Description">Description</h2> + +<p>dayValue 매개 변수를 지정하지 않으면 {{jsxref("Date.prototype.getDate()", "getDate()")}} 메서드에서 반환 된 값이 사용됩니다.</p> + +<p>지정한 매개 변수가 예상 범위를 벗어나면 setMonth ()는 그에 따라 {{jsxref("Date")}} 객체의 날짜 정보를 업데이트하려고 시도합니다. 예를 들어 monthValue에 15를 사용하면 연도가 1 씩 증가하고 3은 월에 사용됩니다.</p> + +<p>현재 날짜가이 메서드의 동작에 영향을 미칩니다. 개념적으로 새로운 날짜를 반환하기 위해 매개 변수로 지정된 새 달의 첫 번째 날에 해당 월의 현재 날짜로 지정된 일 수를 추가합니다. 예를 들어 현재 값이 2016 년 8 월 31 일인 경우 setMonth를 1로 설정하면 2016 년 3 월 2 일에 반환됩니다. 이는 2016 년 2 월에 29 일이 있었기 때문입니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_setMonth()">Using <code>setMonth()</code></h3> + +<pre class="brush: js">var theBigDay = new Date(); +theBigDay.setMonth(6); + +//Watch out for end of month transitions +var endOfMonth = new Date(2016, 7, 31); +endOfMonth.setMonth(1); +console.log(endOfMonth); //Wed Mar 02 2016 00:00:00 + + +</pre> + +<p> </p> + +<p> </p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.38', 'Date.prototype.setMonth')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.setmonth', 'Date.prototype.setMonth')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.setmonth', 'Date.prototype.setMonth')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Date.prototype.getMonth()")}}</li> + <li>{{jsxref("Date.prototype.setUTCMonth()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/setseconds/index.html b/files/ko/web/javascript/reference/global_objects/date/setseconds/index.html new file mode 100644 index 0000000000..3b3ea09ead --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/setseconds/index.html @@ -0,0 +1,134 @@ +--- +title: Date.prototype.setSeconds() +slug: Web/JavaScript/Reference/Global_Objects/Date/setSeconds +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setSeconds +--- +<div>{{JSRef}}</div> + +<p>setSeconds () 메서드는 현지 시간에 따라 지정된 날짜의 초를 설정합니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.setSeconds(<var>secondsValue</var>[, <var>msValue</var>])</code></pre> + +<h3 id="Versions_prior_to_JavaScript_1.3">Versions prior to JavaScript 1.3</h3> + +<pre class="syntaxbox"><code><var>dateObj</var>.setSeconds(<var>secondsValue</var>)</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>secondsValue</code></dt> + <dd>초를 나타내는 0에서 59 사이의 정수입니다.</dd> + <dt><code>msValue</code></dt> + <dd>선택 과목. 밀리 초를 나타내는 0에서 999 사이의 숫자입니다.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>1970 년 1 월 1 일 00:00:00 UTC와 업데이트 된 날짜 사이의 밀리 초 숫자입니다.</p> + +<h2 id="Description">Description</h2> + +<p>msValue 매개 변수를 지정하지 않으면 {{jsxref("Date.prototype.getMilliseconds()", "getMilliseconds()")}} 메서드에서 반환 된 값이 사용됩니다.</p> + +<p>지정한 매개 변수가 예상 범위를 벗어나면 setSeconds ()는 {{jsxref("Date")}} 객체의 날짜 정보를 그에 따라 업데이트하려고 시도합니다. 예를 들어, secondsValue에 100을 사용하면 {{jsxref("Date")}} 객체에 저장된 분이 1 씩 증가하고 40 초 동안 사용됩니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_setSeconds()">Using <code>setSeconds()</code></h3> + +<pre class="brush: js">var theBigDay = new Date(); +theBigDay.setSeconds(30); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.30', 'Date.prototype.setSeconds')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.setseconds', 'Date.prototype.setSeconds')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.setseconds', 'Date.prototype.setSeconds')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Date.prototype.getSeconds()")}}</li> + <li>{{jsxref("Date.prototype.setUTCSeconds()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/settime/index.html b/files/ko/web/javascript/reference/global_objects/date/settime/index.html new file mode 100644 index 0000000000..e47d43720a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/settime/index.html @@ -0,0 +1,127 @@ +--- +title: Date.prototype.setTime() +slug: Web/JavaScript/Reference/Global_Objects/Date/setTime +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setTime +--- +<div>{{JSRef}}</div> + +<p>setTime () 메서드는 {{jsxref ( "Date")}} 객체를 1970 년 1 월 1 일 00:00:00 UTC부터 밀리 초 단위로 나타내는 시간으로 설정합니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.setTime(<var>timeValue</var>)</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>timeValue</code></dt> + <dd>1970 년 1 월 1 일 00:00:00 UTC 이후의 밀리 초 수를 나타내는 정수입니다.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>1970 년 1 월 1 일 00:00:00 UTC와 업데이트 된 날짜 (사실상 인수의 값) 사이의 밀리 초 수입니다.</p> + +<h2 id="Description">Description</h2> + +<p>setTime () 메서드를 사용하면 다른 {{jsxref ( "Date")}} 객체에 날짜와 시간을 지정할 수 있습니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_setTime()">Using <code>setTime()</code></h3> + +<pre class="brush: js">var theBigDay = new Date('July 1, 1999'); +var sameAsBigDay = new Date(); +sameAsBigDay.setTime(theBigDay.getTime()); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.27', 'Date.prototype.setTime')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.settime', 'Date.prototype.setTime')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.settime', 'Date.prototype.setTime')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Date.prototype.getTime()")}}</li> + <li>{{jsxref("Date.prototype.setUTCHours()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/setutcdate/index.html b/files/ko/web/javascript/reference/global_objects/date/setutcdate/index.html new file mode 100644 index 0000000000..28c1ef3835 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/setutcdate/index.html @@ -0,0 +1,126 @@ +--- +title: Date.prototype.setUTCDate() +slug: Web/JavaScript/Reference/Global_Objects/Date/setUTCDate +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setUTCDate +--- +<div>{{JSRef}}</div> + +<p><strong>setUTCDate()</strong> 메서드는 표준시에 따라 지정된 날짜의 날짜를 설정합니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.setUTCDate(<var>dayValue</var>)</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>dayValue</code></dt> + <dd>한 달의 날짜를 나타내는 1에서 31 사이의 정수입니다.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>1970 년 1 월 1 일 00:00:00 UTC와 업데이트 된 날짜 사이의 밀리 초 숫자입니다.</p> + +<h2 id="Description">Description</h2> + +<p>지정한 매개 변수가 예상 범위를 벗어난 경우 setUTCDate ()는 그에 따라 {{jsxref ( "Date")}} 객체의 날짜 정보를 업데이트하려고 시도합니다. 예를 들어, dayValue에 40을 사용하고 {{jsxref ( "Date")}} 객체에 저장된 달이 6 월이면 일이 10으로 변경되고 월이 7 월로 증가합니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_setUTCDate()">Using <code>setUTCDate()</code></h3> + +<pre class="brush: js">var theBigDay = new Date(); +theBigDay.setUTCDate(20); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.3.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.37', 'Date.prototype.setUTCDate')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.setutcdate', 'Date.prototype.setUTCDate')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.setutcdate', 'Date.prototype.setUTCDate')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Date.prototype.getUTCDate()")}}</li> + <li>{{jsxref("Date.prototype.setDate()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/setutcfullyear/index.html b/files/ko/web/javascript/reference/global_objects/date/setutcfullyear/index.html new file mode 100644 index 0000000000..8410c68faa --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/setutcfullyear/index.html @@ -0,0 +1,132 @@ +--- +title: Date.prototype.setUTCFullYear() +slug: Web/JavaScript/Reference/Global_Objects/Date/setUTCFullYear +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setUTCFullYear +--- +<div>{{JSRef}}</div> + +<p><strong>setUTCFullYear()</strong> 메서드는 지정된 날짜의 전체 연도를 표준시에 따라 설정합니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.setUTCFullYear(<var>yearValue</var>[, <var>monthValue</var>[, <var>dayValue</var>]])</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>yearValue</code></dt> + <dd>연도의 숫자 값을 지정하는 정수입니다 (예 : 1995).</dd> + <dt><code>monthValue</code></dt> + <dd>선택 과목. 1 월에서 12 월까지의 월을 나타내는 0에서 11 사이의 정수입니다.</dd> + <dt><code>dayValue</code></dt> + <dd>선택 과목. 한 달의 날짜를 나타내는 1 - 31 사이의 정수입니다. dayValue 매개 변수를 지정하는 경우 monthValue도 지정해야합니다.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>1970 년 1 월 1 일 00:00:00 UTC와 업데이트 된 날짜 사이의 밀리 초 숫자입니다.</p> + +<h2 id="Description">Description</h2> + +<p>monthValue 및 dayValue 매개 변수를 지정하지 않으면 {{jsxref ( "Date.prototype.getUTCMonth ()", "getUTCMonth()")}} 및 {{jsxref("Date.prototype.getUTCDate)","getUTCDate()")}} 메소드가 사용됩니다.</p> + +<p>지정한 매개 변수가 예상 범위를 벗어난 경우 setUTCFullYear ()는 다른 매개 변수와 {{jsxref("Date")}} 객체의 날짜 정보를 그에 따라 업데이트하려고 시도합니다. 예를 들어, monthValue에 15를 지정하면 연도가 1 (yearValue + 1)만큼 증가하고 3은 해당 월에 사용됩니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_setUTCFullYear()">Using <code>setUTCFullYear()</code></h3> + +<pre class="brush: js">var theBigDay = new Date(); +theBigDay.setUTCFullYear(1997); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.3.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.41', 'Date.prototype.setUTCFullYear')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.setutcfullyear', 'Date.prototype.setUTCFullYear')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.setutcfullyear', 'Date.prototype.setUTCFullYear')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Date.prototype.getUTCFullYear()")}}</li> + <li>{{jsxref("Date.prototype.setFullYear()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/setutchours/index.html b/files/ko/web/javascript/reference/global_objects/date/setutchours/index.html new file mode 100644 index 0000000000..dae2e10373 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/setutchours/index.html @@ -0,0 +1,134 @@ +--- +title: Date.prototype.setUTCHours() +slug: Web/JavaScript/Reference/Global_Objects/Date/setUTCHours +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setUTCHours +--- +<div>{{JSRef}}</div> + +<p>setUTCHours () 메서드는 표준시에 따라 지정된 날짜의 시간을 설정하고 1970 년 1 월 1 일 00:00:00 UTC 이후 업데이트 된 {{jsxref ( "Date")}}에 의해 표시되는 시간 (밀리 초)을 반환합니다. 예.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.setUTCHours(<var>hoursValue</var>[, <var>minutesValue</var>[, <var>secondsValue</var>[, <var>msValue</var>]]])</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>hoursValue</code></dt> + <dd>시를 나타내는 0에서 23 사이의 정수입니다.</dd> + <dt><code>minutesValue</code></dt> + <dd>선택 과목. 분을 나타내는 0에서 59 사이의 정수입니다.</dd> + <dt><code>secondsValue</code></dt> + <dd>선택 과목. 초를 나타내는 0에서 59 사이의 정수입니다. secondsValue 매개 변수를 지정하면 minutesValue도 지정해야합니다.</dd> + <dt><code>msValue</code></dt> + <dd>선택 과목. 밀리 초를 나타내는 0에서 999 사이의 숫자입니다. msValue 매개 변수를 지정하는 경우 minutesValue 및 secondsValue도 지정해야합니다.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>1970 년 1 월 1 일 00:00:00 UTC와 업데이트 된 날짜 사이의 밀리 초 숫자입니다.</p> + +<h2 id="Description">Description</h2> + +<p>minutesValue, secondsValue 및 msValue 매개 변수를 지정하지 않으면 {{jsxref ( "Date.prototype.getUTCMinutes()", "getUTCMinutes()")}}, {{jsxref("Date.prototype .getUTCSeconds() ","getUTCSeconds()")}} 및 {{jsxref("Date.prototype.getUTCMilliseconds() ","getUTCMilliseconds()")}} 메소드가 사용됩니다.</p> + +<p>지정한 매개 변수가 예상 범위를 벗어나면 setUTCHours ()는 그에 따라 {{jsxref("Date")}} 객체의 날짜 정보를 업데이트하려고 시도합니다. 예를 들어 secondsValue에 100을 사용하면 분은 1 (minutesValue + 1)만큼 증가하고 40은 초 단위로 사용됩니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_setUTCHours()">Using <code>setUTCHours()</code></h3> + +<pre class="brush: js">var theBigDay = new Date(); +theBigDay.setUTCHours(8); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.3.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.35', 'Date.prototype.setUTCHours')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.setutchours', 'Date.prototype.setUTCHours')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.setutchours', 'Date.prototype.setUTCHours')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Date.prototype.getUTCHours()")}}</li> + <li>{{jsxref("Date.prototype.setHours()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/setutcmilliseconds/index.html b/files/ko/web/javascript/reference/global_objects/date/setutcmilliseconds/index.html new file mode 100644 index 0000000000..8f93cc7875 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/setutcmilliseconds/index.html @@ -0,0 +1,126 @@ +--- +title: Date.prototype.setUTCMilliseconds() +slug: Web/JavaScript/Reference/Global_Objects/Date/setUTCMilliseconds +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setUTCMilliseconds +--- +<div>{{JSRef}}</div> + +<p><strong>setUTCMilliseconds()</strong> 메서드는 표준시에 따라 지정된 날짜의 밀리 초를 설정합니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.setUTCMilliseconds(<var>millisecondsValue</var>)</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>millisecondsValue</code></dt> + <dd>밀리 초를 나타내는 0에서 999 사이의 숫자입니다.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>1970 년 1 월 1 일 00:00:00 UTC와 업데이트 된 날짜 사이의 밀리 초 숫자입니다.</p> + +<h2 id="Description">Description</h2> + +<p>지정한 매개 변수가 예상 범위를 벗어난 경우 setUTCMilliseconds ()는 그에 따라 {{jsxref ( "Date")}} 객체의 날짜 정보를 업데이트하려고 시도합니다. 예를 들어 millisecondsValue에 1100을 사용하면 {{jsxref ( "Date")}} 객체에 저장된 초가 1 씩 증가하고 100은 밀리 초 단위로 사용됩니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_setUTCMilliseconds()">Using <code>setUTCMilliseconds()</code></h3> + +<pre class="brush: js">var theBigDay = new Date(); +theBigDay.setUTCMilliseconds(500); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.3.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.29', 'Date.prototype.setUTCMilliseconds')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.setutcmilliseconds', 'Date.prototype.setUTCMilliseconds')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.setutcmilliseconds', 'Date.prototype.setUTCMilliseconds')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Date.prototype.getUTCMilliseconds()")}}</li> + <li>{{jsxref("Date.prototype.setMilliseconds()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/setutcminutes/index.html b/files/ko/web/javascript/reference/global_objects/date/setutcminutes/index.html new file mode 100644 index 0000000000..c39b343935 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/setutcminutes/index.html @@ -0,0 +1,132 @@ +--- +title: Date.prototype.setUTCMinutes() +slug: Web/JavaScript/Reference/Global_Objects/Date/setUTCMinutes +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setUTCMinutes +--- +<div>{{JSRef}}</div> + +<p><strong>setUTCMinutes()</strong> 메서드는 표준시에 따라 지정된 날짜의 분을 설정합니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.setUTCMinutes(<var>minutesValue</var>[, <var>secondsValue</var>[, <var>msValue</var>]])</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>minutesValue</code></dt> + <dd>분을 나타내는 0에서 59 사이의 정수입니다.</dd> + <dt><code>secondsValue</code></dt> + <dd>선택 과목. 초를 나타내는 0에서 59 사이의 정수입니다. secondsValue 매개 변수를 지정하면 minutesValue도 지정해야합니다.</dd> + <dt><code>msValue</code></dt> + <dd>선택 과목. 밀리 초를 나타내는 0에서 999 사이의 숫자입니다. msValue 매개 변수를 지정하는 경우 minutesValue 및 secondsValue도 지정해야합니다.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>1970 년 1 월 1 일 00:00:00 UTC와 업데이트 된 날짜 사이의 밀리 초 숫자입니다.</p> + +<h2 id="Description">Description</h2> + +<p>secondsValue 및 msValue 매개 변수를 지정하지 않으면 {{jsxref ( "Date.prototype.getUTCSeconds()", "getUTCSeconds()")}} 및 {{jsxref ("Date.prototype.getUTCMilliseconds","getUTCMilliseconds()")}} 메소드가 사용됩니다.</p> + +<p>지정한 매개 변수가 예상 범위를 벗어나면 setUTCMinutes ()는 그에 따라 {{jsxref("Date")}} 객체의 날짜 정보를 업데이트하려고 시도합니다. 예를 들어 secondsValue에 100을 사용하면 분은 1 (minutesValue + 1)만큼 증가하고 40은 초 단위로 사용됩니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_setUTCMinutes()">Using <code>setUTCMinutes()</code></h3> + +<pre class="brush: js">var theBigDay = new Date(); +theBigDay.setUTCMinutes(43); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.3.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.33', 'Date.prototype.setUTCMinutes')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.setutcminutes', 'Date.prototype.setUTCMinutes')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.setutcminutes', 'Date.prototype.setUTCMinutes')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Date.prototype.getUTCMinutes()")}}</li> + <li>{{jsxref("Date.prototype.setMinutes()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/setutcmonth/index.html b/files/ko/web/javascript/reference/global_objects/date/setutcmonth/index.html new file mode 100644 index 0000000000..266112be92 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/setutcmonth/index.html @@ -0,0 +1,130 @@ +--- +title: Date.prototype.setUTCMonth() +slug: Web/JavaScript/Reference/Global_Objects/Date/setUTCMonth +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setUTCMonth +--- +<div>{{JSRef}}</div> + +<p>setUTCMonth () 메서드는 표준시에 따라 지정된 날짜의 월을 설정합니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.setUTCMonth(<var>monthValue</var>[, <var>dayValue</var>])</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>monthValue</code></dt> + <dd>1 월에서 12 월까지의 월을 나타내는 0에서 11 사이의 정수입니다.</dd> + <dt><code>dayValue</code></dt> + <dd>선택 과목. 한 달의 날짜를 나타내는 1에서 31 사이의 정수입니다.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>1970 년 1 월 1 일 00:00:00 UTC와 업데이트 된 날짜 사이의 밀리 초 숫자입니다.</p> + +<h2 id="Description">Description</h2> + +<p>dayValue 매개 변수를 지정하지 않으면 {{jsxref("Date.prototype.getUTCDate()", "getUTCDate()")}} 메서드에서 반환 된 값이 사용됩니다.</p> + +<p>지정한 매개 변수가 예상 범위를 벗어난 경우 setUTCMonth()는 그에 따라 {{jsxref("Date")}} 객체의 날짜 정보를 업데이트하려고 시도합니다. 예를 들어 monthValue에 15를 사용하면 연도가 1 씩 증가하고 3은 월에 사용됩니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_setUTCMonth()">Using <code>setUTCMonth()</code></h3> + +<pre class="brush: js">var theBigDay = new Date(); +theBigDay.setUTCMonth(11); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.3.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.39', 'Date.prototype.setUTCMonth')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.setutcmonth', 'Date.prototype.setUTCMonth')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.setutcmonth', 'Date.prototype.setUTCMonth')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Date.prototype.getUTCMonth()")}}</li> + <li>{{jsxref("Date.prototype.setMonth()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/setutcseconds/index.html b/files/ko/web/javascript/reference/global_objects/date/setutcseconds/index.html new file mode 100644 index 0000000000..f4d5609444 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/setutcseconds/index.html @@ -0,0 +1,130 @@ +--- +title: Date.prototype.setUTCSeconds() +slug: Web/JavaScript/Reference/Global_Objects/Date/setUTCSeconds +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setUTCSeconds +--- +<div>{{JSRef}}</div> + +<p><strong>setUTCSeconds()</strong> 메서드는 표준시에 따라 지정된 날짜의 초를 설정합니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.setUTCSeconds(<var>secondsValue</var>[, <var>msValue</var>])</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>secondsValue</code></dt> + <dd>초를 나타내는 0에서 59 사이의 정수입니다.</dd> + <dt><code>msValue</code></dt> + <dd>선택 과목. 밀리 초를 나타내는 0에서 999 사이의 숫자입니다.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>1970 년 1 월 1 일 00:00:00 UTC와 업데이트 된 날짜 사이의 밀리 초 숫자입니다.</p> + +<h2 id="Description">Description</h2> + +<p>msValue 매개 변수를 지정하지 않으면 {{jsxref("Date.prototype.getUTCMilliseconds()", "getUTCMilliseconds()")}} 메서드에서 반환 된 값이 사용됩니다.</p> + +<p>지정한 매개 변수가 예상 범위를 벗어나면 setUTCSeconds()가 그에 따라 {{jsxref("Date")}} 객체의 날짜 정보를 업데이트하려고 시도합니다. 예를 들어, secondsValue에 100을 사용하면 {{jsxref("Date")}} 객체에 저장된 분이 1 씩 증가하고 40 초 동안 사용됩니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_setUTCSeconds()">Using <code>setUTCSeconds()</code></h3> + +<pre class="brush: js">var theBigDay = new Date(); +theBigDay.setUTCSeconds(20); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.3.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.31', 'Date.prototype.setUTCSeconds')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.setutcseconds', 'Date.prototype.setUTCSeconds')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.setutcseconds', 'Date.prototype.setUTCSeconds')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Date.prototype.getUTCSeconds()")}}</li> + <li>{{jsxref("Date.prototype.setSeconds()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/todatestring/index.html b/files/ko/web/javascript/reference/global_objects/date/todatestring/index.html new file mode 100644 index 0000000000..1ded363e99 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/todatestring/index.html @@ -0,0 +1,82 @@ +--- +title: Date.prototype.toDateString() +slug: Web/JavaScript/Reference/Global_Objects/Date/toDateString +translation_of: Web/JavaScript/Reference/Global_Objects/Date/toDateString +--- +<div>{{JSRef}}</div> + +<p><code><strong>toDateString()</strong></code> 메서드는 미국 영어로 사람이 읽을 수있는 형태로 {{jsxref("Date")}} 객체의 날짜 부분을 반환합니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/date-todatestring.html")}}</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.toDateString()</code></pre> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 {{jsxref ( "Date")}} 객체의 날짜 부분을 사람이 읽을 수있는 형태로 미국 영어로 나타내는 문자열입니다.</p> + +<h2 id="설명">설명</h2> + +<p>{{jsxref ( "Date")}} 인스턴스는 특정 시점을 참조합니다. {{jsxref ( "Date.prototype.toString ()", "toString ()")}}을 호출하면 사람이 읽을 수있는 형식의 미국식 영어로 된 날짜가 반환됩니다. SpiderMonkey에서는 날짜 부분 (일, 월, 연도)과 시간 부분 (시, 분, 초 및 시간대)으로 구성됩니다. 때로는 날짜 부분의 문자열을 얻는 것이 바람직합니다. 이러한 일은 toDateString () 메서드를 사용하여 수행 할 수 있습니다.</p> + +<p>toDateString () 메서드는 ECMA-262를 구현하는 호환 엔진이 {{jsxref ( "Date.prototype.toString ()", "toString ()")}} 날짜 ")}} 객체를 사용할 수 있습니다. 형식은 구현에 따라 다르며 간단한 문자열 분할 방법은 여러 엔진에서 일관된 결과를 생성하지 않을 수 있습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="A_basic_usage_of_toDateString()">A basic usage of <code>toDateString()</code></h3> + +<pre class="brush: js">var d = new Date(1993, 6, 28, 14, 39, 7); + +console.log(d.toString()); // logs Wed Jul 28 1993 14:39:07 GMT-0600 (PDT) +console.log(d.toDateString()); // logs Wed Jul 28 1993 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.3', 'Date.prototype.toDateString')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.todatestring', 'Date.prototype.toDateString')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.todatestring', 'Date.prototype.toDateString')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.Date.toDateString")}}</p> + +<div> </div> + +<div id="compat-mobile"> </div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Date.prototype.toLocaleDateString()")}}</li> + <li>{{jsxref("Date.prototype.toTimeString()")}}</li> + <li>{{jsxref("Date.prototype.toString()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/toisostring/index.html b/files/ko/web/javascript/reference/global_objects/date/toisostring/index.html new file mode 100644 index 0000000000..a9743f04d6 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/toisostring/index.html @@ -0,0 +1,107 @@ +--- +title: Date.prototype.toISOString() +slug: Web/JavaScript/Reference/Global_Objects/Date/toISOString +tags: + - Date + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Date/toISOString +--- +<div>{{JSRef}}</div> + +<p><strong><code>toISOString()</code></strong> 메서드는 단순화한 확장 ISO 형식(<a href="http://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a>)의 문자열을 반환합니다. 반환값은 언제나 24글자 또는 27글자(각각 <strong><code>YYYY-MM-DDTHH:mm:ss.sssZ</code></strong> 또는 <strong><code>±YYYYYY-MM-DDTHH:mm:ss.sssZ</code></strong>)입니다. 시간대는 언제나 UTC이며 접미어 "<code>Z</code>"로 표현합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/date-toisostring.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.toISOString()</code></pre> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 날짜를 국제표준시 기준 <a href="http://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a> 형식으로 표현한 문자열.</p> + +<h2 id="예제">예제</h2> + +<h3 id="toISOString()_사용하기"><code>toISOString()</code> 사용하기</h3> + +<p>아래 예제는 비표준 문자열의 분석을 포함하고 있어 비 Mozilla 브라우저에서는 올바르게 작동하지 않을 수 있습니다.</p> + +<pre class="brush: js">const today = new Date('05 October 2011 14:48 UTC'); + +console.log(today.toISOString()); // Returns 2011-10-05T14:48:00.000Z</pre> + +<h2 id="폴리필">폴리필</h2> + +<p><code>toISOString</code>은 ECMA-262 제5판에 표준으로 자리잡았습니다. 아직 지원하지 않는 환경에서는 다음 코드를 추가해 대체할 수 있습니다.</p> + +<pre class="brush: js">if (!Date.prototype.toISOString) { + (function() { + + function pad(number) { + if (number < 10) { + return '0' + number; + } + return number; + } + + Date.prototype.toISOString = function() { + return this.getUTCFullYear() + + '-' + pad(this.getUTCMonth() + 1) + + '-' + pad(this.getUTCDate()) + + 'T' + pad(this.getUTCHours()) + + ':' + pad(this.getUTCMinutes()) + + ':' + pad(this.getUTCSeconds()) + + '.' + (this.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) + + 'Z'; + }; + + }()); +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.43', 'Date.prototype.toISOString')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.8.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.toisostring', 'Date.prototype.toISOString')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.toisostring', 'Date.prototype.toISOString')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Date.toISOString")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Date.prototype.toLocaleDateString()")}}</li> + <li>{{jsxref("Date.prototype.toTimeString()")}}</li> + <li>{{jsxref("Date.prototype.toUTCString()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/tojson/index.html b/files/ko/web/javascript/reference/global_objects/date/tojson/index.html new file mode 100644 index 0000000000..5f069e3417 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/tojson/index.html @@ -0,0 +1,81 @@ +--- +title: Date.prototype.toJSON() +slug: Web/JavaScript/Reference/Global_Objects/Date/toJSON +tags: + - Date + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Date/toJSON +--- +<div>{{JSRef}}</div> + +<p><strong><code>toJSON()</code></strong> 메서드는 {{jsxref("Date")}} 객체의 문자열 표현을 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/date-tojson.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.toJSON()</code></pre> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 날짜의 문자열 표현.</p> + +<h2 id="설명">설명</h2> + +<p>{{jsxref("Date")}} 인스턴스는 시간의 특정 지점을 가리킵니다. <code>toJSON()</code>을 호출하면 {{jsxref("Date.prototype.toISOString()", "toISOString()")}} 사용해 그 인스턴스가 가리키는 시간의 문자열 표현을 반환합니다. <code>toJSON()</code>은 <code>Date</code> 값을 {{Glossary("JSON")}}으로 직렬화할 때 유용하게 사용할 수 있도록 만들어졌습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="toJSON()_사용하기"><code>toJSON()</code> 사용하기</h3> + +<pre class="brush:js">const jsonDate = (new Date()).toJSON(); +const backToDate = new Date(jsonDate); + +console.log(jsonDate); //2015-10-26T07:46:36.611Z +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.44', 'Date.prototype.toJSON')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.8.5.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.tojson', 'Date.prototype.toJSON')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.tojson', 'Date.prototype.toJSON')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Date.toJSON")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Date.prototype.toLocaleDateString()")}}</li> + <li>{{jsxref("Date.prototype.toTimeString()")}}</li> + <li>{{jsxref("Date.prototype.toUTCString()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/tostring/index.html b/files/ko/web/javascript/reference/global_objects/date/tostring/index.html new file mode 100644 index 0000000000..5adaaf4f84 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/tostring/index.html @@ -0,0 +1,125 @@ +--- +title: Date.prototype.toString() +slug: Web/JavaScript/Reference/Global_Objects/Date/toString +tags: + - Date + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Date/toString +--- +<div>{{JSRef}}</div> + +<p> <strong><code>toString()</code></strong> 메서드는 {{jsxref("Date")}} 객체의 시간을 문자열로 반환합니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/date-tostring.html")}}</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>dateObj</var>.toString()</pre> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 날짜를 나타내는 문자열.</p> + +<h2 id="설명">설명</h2> + +<p>{{jsxref("Date")}} 객체는 <code>toString()</code> 메서드를 {{jsxref("Object.prototype")}}이 아닌 {{jsxref("Date.prototype")}}에서 상속받습니다. <code>Date.prototype.toString()</code>의 반환값은 ECMA-262에 명시되어있으며 다음과 같이 요약할 수 있습니다.</p> + +<ul> + <li>요일: 세 글자 영어 요일명. 예: "Sat"</li> + <li>공백</li> + <li>월: 세 글자 영어 월 이름. 예: "Sep"</li> + <li>공백</li> + <li>일: 두 글자 숫자. 예: "01"</li> + <li>공백</li> + <li>연: 네 글자 숫자. 예: "2018"</li> + <li>공백</li> + <li>시: 두 글자 숫자. 예: "14"</li> + <li>콜론</li> + <li>분: 두 글자 숫자. 예: "53"</li> + <li>콜론</li> + <li>초: 두 글자 숫자. 예: "26"</li> + <li>공백</li> + <li>문자열 "GMT"</li> + <li>시간대 차이의 부호. + <ul> + <li>0 이상일 경우 "+"</li> + <li>0 미만일 경우 "-"</li> + </ul> + </li> + <li>두 글자 숫자로 표현한 시 차이. 예: "14"</li> + <li>두 글자 숫자로 표현한 분 차이. 예: "00"</li> + <li>선택사항: 다음으로 구성한 시간대의 이름. + <ul> + <li>공백</li> + <li>여는 소괄호</li> + <li>구현마다 다를 수 있는 시간대 이름. 약어와 전체 이름 둘 다 가능. 예: "Korea Standard Time", "한국 표준시" 또는 "KST"</li> + <li>닫는 소괄호</li> + </ul> + </li> +</ul> + +<p>예: "Sat Sep 01 2018 14:53:26 GMT+0900 (KST)"</p> + +<p>ECMAScript 2018(제9판) 전까지 <code>toString()</code>의 반환 형식은 구현에 따라 다를 수 있었습니다. 따라서 특정 형식에 의존하지 않아야 합니다.</p> + +<p><code>toString()</code> 메서드는 날짜를 문자열로 표현해야 할 때 자동으로 쓰입니다. <code>console.log(new Date())</code>와 <code>const today = 'Today is ' + new Date()</code> 등의 경우를 예로 들 수 있습니다.</p> + +<p><code>toString()</code>은 제네릭 메서드로 <code>this</code>의 값이 {{jsxref("Date")}}일 필요는 없습니다. 그러나 내부적으로 <code>[[TimeValue]]</code> 속성이 필요한데, 이는 JavaScript로는 설정할 수 없어 결국 사용이 <code>Date</code> 인스턴스로 제한됩니다. <code>Date</code> 외의 다른 객체에서 호출하면 {{jsxref("TypeError")}}가 발생합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="toString()_사용"><code>toString()</code> 사용</h3> + +<pre class="brush: js"><code>var x = new Date(); +var myVar = x.toString(); // assigns a string value to myVar in the same format as: + // Mon Sep 08 1998 14:36:22 GMT+0900 (KST)</code></pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.2', 'Date.prototype.toLocaleTimeString')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.tostring', 'Date.prototype.toString')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.tostring', 'Date.prototype.toString')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Date.toString")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Object.prototype.toString()")}}</li> + <li>{{jsxref("Date.prototype.toDateString()")}}</li> + <li>{{jsxref("Date.prototype.toLocaleString()")}}</li> + <li>{{jsxref("Date.prototype.toTimeString()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/utc/index.html b/files/ko/web/javascript/reference/global_objects/date/utc/index.html new file mode 100644 index 0000000000..f340c4d44a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/utc/index.html @@ -0,0 +1,139 @@ +--- +title: Date.UTC() +slug: Web/JavaScript/Reference/Global_Objects/Date/UTC +tags: + - Date + - JavaScript + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Date/UTC +--- +<div>{{JSRef}}</div> + +<p><strong><code>Date.UTC()</code></strong> 메서드는 {{jsxref("Date")}} 생성자와 비슷한 매개변수를 받지만, 모두 UTC로 취급합니다. 반환 값은 1970년 1월 1일 00:00:00 UTC부터 매개변수가 나타내는 시간의 차이를 밀리초로 나타낸 수입니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/date-utc.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<p><strong>ECMAScript 2017 이상:</strong></p> + +<pre class="syntaxbox">Date.UTC(<var>year[</var>, <var>month</var>[, <var>day</var>[, <var>hour</var>[, <var>minute</var>[, <var>second</var>[, <var>millisecond</var>]]]]])</pre> + +<p><strong>ECMAScript 2016 이하:</strong> (<code>month</code> 필수)</p> + +<pre class="syntaxbox">Date.UTC(<var>year</var>, <var>month</var>[, <var>day</var>[, <var>hour</var>[, <var>minute</var>[, <var>second</var>[, <var>millisecond</var>]]]]])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>year</code></dt> + <dd>네 자리 연도.</dd> + <dt><code>month</code></dt> + <dd>월을 나타내는 0(1월)에서 11(12월) 사이의 정수. ECMAScript 2016까지는 필수 매개변수였으나, ECMA2017부터는 선택사항입니다.</dd> + <dt><code>day</code> {{optional_inline}}</dt> + <dd>일을 나타내는 1에서 31 사이의 정수. 기본값은 1입니다.</dd> + <dt><code>hour</code> {{optional_inline}}</dt> + <dd>시를 나타내는 0에서 23 사이의 정수. 기본값은 0입니다.</dd> + <dt><code>minute</code> {{optional_inline}}</dt> + <dd>분을 나타내는 0에서 59 사이의 정수. 기본값은 0입니다.</dd> + <dt><code>second</code> {{optional_inline}}</dt> + <dd>초를 나타내는 0에서 59 사이의 정수. 기본값은 0입니다.</dd> + <dt><code>millisecond</code> {{optional_inline}}</dt> + <dd>밀리초를 나타내는 0에서 999 사이의 정수. 기본값은 0입니다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 날짜와 1970년 1월 1일 00:00:00 UTC의 차이를 밀리초로 나타낸 숫자.</p> + +<h2 id="설명">설명</h2> + +<p><code>Date.UTC()</code>는 날짜 및 시간을 받고, 1970년 1월 1일 00:00:00 UTC와의 차이를 밀리초 수로 나타내 반환합니다.</p> + +<p>0에서 99 사이의 연도는 20세기<code>(1900 + year)</code>로 취급합니다. 즉 95를 입력할 경우 1995로 취급합니다.</p> + +<p><code>Date.UTC()</code> 메서드는 {{jsxref("Date")}} 생성자와 다른 점이 두 가지 있습니다.</p> + +<ul> + <li><code>Date.UTC()</code>는 현지 시간 대신 국제 표준시(UTC)를 사용합니다.</li> + <li><code>Date.UTC()</code>는 {{jsxref("Date")}} 객체를 만드는 대신 시간 값을 숫자로 반환합니다.</li> +</ul> + +<p>주어진 매개변수가 통상적인 범위를 벗어나면 <code>Date.UTC()</code> 메서드는 다른 매개변수 값을 조절해 계산합니다. 예를 들어, 월 값으로 15를 사용하면 연도가 1 증가(<code>year + 1</code>)하고, 월 계산에는 3을 대신 사용합니다.</p> + +<p><code>Date.UTC()</code>는 {{jsxref("Date")}}의 정적 메서드이므로, 사용자가 생성한 {{jsxref("Date")}} 인스턴스에서 호출하지 않고 <code>Date.UTC()</code> 형태로 사용합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="Date.UTC()_사용하기"><code>Date.UTC()</code> 사용하기</h3> + +<p>다음 예제는 현지 시간 대신 UTC를 사용하여 {{jsxref("Date")}} 객체를 생성합니다.</p> + +<pre class="brush:js">var utcDate = new Date(Date.UTC(96, 11, 1, 0, 0, 0)); +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.utc', 'Date.UTC')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.utc', 'Date.UTC')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.4.3', 'Date.UTC')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Date.UTC")}}</p> + +<h2 id="호환성_참고사항">호환성 참고사항</h2> + +<h3 id="매개변수를_두_개_미만_제공하는_경우">매개변수를 두 개 미만 제공하는 경우</h3> + +<p>Date.UTC()가 두 개 미만의 매개변수를 받은 경우, ECMAScript 2017은 {{jsxref("NaN")}}을 반환할 것을 요구합니다. 이를 지원하지 않던 엔진은 업데이트됐습니다. ({{bug(1050755)}}, <a href="https://github.com/tc39/ecma262/pull/642">ecma-262 #642</a>를 참고하세요)</p> + +<pre class="brush: js">Date.UTC(); +Date.UTC(1); + +// Safari: NaN +// Chrome/Opera/V8: NaN + +// Firefox <54: non-NaN +// Firefox 54+: NaN + +// IE: non-NaN +// Edge: NaN</pre> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Date.parse()")}}</li> + <li>{{jsxref("Date")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/date/valueof/index.html b/files/ko/web/javascript/reference/global_objects/date/valueof/index.html new file mode 100644 index 0000000000..778321f74e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/valueof/index.html @@ -0,0 +1,79 @@ +--- +title: Date.prototype.valueOf() +slug: Web/JavaScript/Reference/Global_Objects/Date/valueOf +translation_of: Web/JavaScript/Reference/Global_Objects/Date/valueOf +--- +<div>{{JSRef}}</div> + +<p><strong><code>valueOf()</code></strong> 함수는 {{jsxref("Date")}} 객체의 원시값을 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/date-valueof.html")}}</div> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>dateObj</var>.valueOf()</code></pre> + +<h3 id="Return_value">Return value</h3> + +<p>반환되는 milliseconds 값은 1 January 1970 00:00:00 UTC 와 주어진 일시 사이의 값입니다.</p> + +<h2 id="Description">Description</h2> + +<p><code>valueOf()</code> 함수는 01 January, 1970 UTC 이후의 milliseconds 단위의 자연수 타입인 {{jsxref("Date")}} 객체의 원시값을 반환합니다.</p> + +<p>이 함수는 {{jsxref("Date.prototype.getTime()")}} 함수와 동일한 결과값을 반환합니다.</p> + +<p>이 함수는 사용자 코드에 명시된 것이 아닌, JavaScript 자체에 포함되어 있습니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_valueOf()">Using <code>valueOf()</code></h3> + +<pre class="brush: js">var x = new Date(56, 6, 17); +var myVar = x.valueOf(); // myVar에 -424713600000를 할당합니다. +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>최초 정의. JavaScript 1.1에서 구현</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.9.5.8', 'Date.prototype.valueOf')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-date.prototype.valueof', 'Date.prototype.valueOf')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-date.prototype.valueof', 'Date.prototype.valueOf')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Date.valueOf")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Object.prototype.valueOf()")}}</li> + <li>{{jsxref("Date.prototype.getTime()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/decodeuri/index.html b/files/ko/web/javascript/reference/global_objects/decodeuri/index.html new file mode 100644 index 0000000000..bb29400506 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/decodeuri/index.html @@ -0,0 +1,101 @@ +--- +title: decodeURI() +slug: Web/JavaScript/Reference/Global_Objects/decodeURI +tags: + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Global_Objects/decodeURI +--- +<div>{{jsSidebar("Objects")}}</div> + +<p><code><strong>decodeURI()</strong></code> 함수는 {{jsxref("encodeURI")}}이나 비슷한 루틴으로 사전에 만들어진 URI(Uniform Resource Identifier, 인터넷식별자) 를 해독합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/globalprops-decodeuri.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code>decodeURI(<em>encodedURI</em>)</code></pre> + +<h3 id="파라미터">파라미터</h3> + +<dl> + <dt><code>encodedURI</code></dt> + <dd>완전하고 암호화된 인터넷식별자(URI)</dd> +</dl> + +<h3 id="리턴_값">리턴 값</h3> + +<p>주어진 암호화된 URI의 암호화되지 않은 버전을 나타내는 새 문자열을 반환합니다.</p> + +<h3 id="예외">예외</h3> + +<p><code><em>encodedURI</em></code>에 유효하지 않은 문자열이 포함된 경우 {{jsxref("URIError")}} ("malformed URI sequence") 예외를 던집니다.</p> + +<h2 id="설명">설명</h2> + +<p><span id="result_box" lang="ko"><span>암호화된 URI의 각 이스케이프 시퀀스(확장문자열)를 자신을 나타내는 문자로 바꾸지만 {{jsxref ( "encodeURI")}}에서 도입할 수 없었던 이스케이프 시퀀스는 해독하지 않습니다.</span> <span>"#"문자는 이스케이프 시퀀스에서 해독되지 않습니다.</span></span></p> + +<h2 id="예제">예제</h2> + +<h3 id="Decoding_a_Cyrillic_URL">Decoding a Cyrillic URL</h3> + +<pre class="brush: js">decodeURI('https://developer.mozilla.org/ru/docs/JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B'); +// "https://developer.mozilla.org/ru/docs/JavaScript_шеллы" +</pre> + +<h3 id="Catching_errors">Catching errors</h3> + +<pre>try { + var a = decodeURI('%E0%A4%A'); +} catch(e) { + console.error(e); +} + +// URIError: malformed URI sequence</pre> + +<h2 id="사양">사양</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.1.3.1', 'decodeURI')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-decodeuri-encodeduri', 'decodeURI')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-decodeuri-encodeduri', 'decodeURI')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.decodeURI")}}</p> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("decodeURIComponent")}}</li> + <li>{{jsxref("encodeURI")}}</li> + <li>{{jsxref("encodeURIComponent")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/decodeuricomponent/index.html b/files/ko/web/javascript/reference/global_objects/decodeuricomponent/index.html new file mode 100644 index 0000000000..d263252cbf --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/decodeuricomponent/index.html @@ -0,0 +1,92 @@ +--- +title: decodeURIComponent() +slug: Web/JavaScript/Reference/Global_Objects/decodeURIComponent +tags: + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/decodeURIComponent +--- +<div>{{jsSidebar("Objects")}}</div> + +<p><code><strong>decodeURIComponent()</strong></code> 함수는 {{jsxref("encodeURIComponent")}} 나 비슷한 방법으로 생성된 Uniform Resource Identifier(URI) 컴포넌트를 해독합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/globalprops-decodeuricomponent.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code>decodeURIComponent(<em>encodedURI</em>)</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>encodedURI</code></dt> + <dd>암호화된 Uniform Resource Identifier(URI) 컴포넌트.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>이스케이프되지 않은 특정 글자들 중 새로운 문자열.</p> + +<h3 id="예외">예외</h3> + +<p><span id="result_box" lang="ko"><span>잘못 사용되었을 경우 {{jsxref ( "URIError")}} ( "</span></span> malformed URI sequence <span lang="ko"><span>") 예외를 발생시킵니다.</span></span></p> + +<h2 id="설명">설명</h2> + +<p>암호화된 URI 컴포넌트에서 각각의 이스케이프 시퀀스(확장 문자열)를 자신을 나타내는 문자로 바꿉니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="키릴문자_URL_컴포넌트의_복호화">키릴문자 URL 컴포넌트의 복호화</h3> + +<pre class="brush: js">decodeURIComponent("JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B"); +// "JavaScript_шеллы" +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.1.3.2', 'decodeURIComponent')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-decodeuricomponent-encodeduricomponent', 'decodeURIComponent')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-decodeuricomponent-encodeduricomponent', 'decodeURIComponent')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.decodeURIComponent")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("decodeURI")}}</li> + <li>{{jsxref("encodeURI")}}</li> + <li>{{jsxref("encodeURIComponent")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/encodeuri/index.html b/files/ko/web/javascript/reference/global_objects/encodeuri/index.html new file mode 100644 index 0000000000..c5dff2ed37 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/encodeuri/index.html @@ -0,0 +1,111 @@ +--- +title: encodeURI() +slug: Web/JavaScript/Reference/Global_Objects/encodeURI +tags: + - JavaScript + - Reference + - URI + - URL +translation_of: Web/JavaScript/Reference/Global_Objects/encodeURI +--- +<div>{{jsSidebar("Objects")}}</div> + +<p><span class="seoSummary"><code><strong>encodeURI()</strong></code> 함수는 {{glossary("URI")}}의 특정한 문자를 UTF-8로 인코딩해 하나, 둘, 셋, 혹은 네 개의 연속된 이스케이프 문자로 나타냅니다.</span> (두 개의 대리 문자로 이루어진 문자만 이스케이프 문자 네 개로 변환됩니다.)</p> + +<div>{{EmbedInteractiveExample("pages/js/globalprops-encodeuri.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code>encodeURI(<em>URI</em>)</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>URI</code></dt> + <dd>완전한 URI.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 문자열을 URI로서 인코딩한 새로운 문자열.</p> + +<h2 id="설명">설명</h2> + +<p><span id="result_box" lang="ko"><span><code>encodeURI()</code> 함수는 URI에서 특별한 뜻을 가진 문자(예약 문자)는 인코딩 하지 않습니다. 아래 예제는 "URI 도식"이 포함할 수 있는 모든 부분을 담고 있습니다. 일부 문자가 어떤 방식으로 특별한 의미를 주입하고 있는지 잘 살펴보세요.</span></span></p> + +<pre>http://username:password@www.example.com:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor</pre> + +<p><span id="result_box" lang="ko"><span>따라서 <code>encodeURI()</code>는 완전한 URI를 형성하는데 필요한 문자는 인코딩 <strong>하지 않습니다</strong>.</span> <span>또한, 예약된 목적을 가지지는 않지만 URI가 그대로 포함할 수 있는 몇 가지 문자("비예약 표식")도 인코딩 <strong>하지 않습니다</strong>. (<a href="https://www.ietf.org/rfc/rfc2396.txt">RFC 2396</a>을 참고하세요)</span></span></p> + +<p><code>encodeURI()</code> 는 다음 문자를 <strong>제외</strong>한 문자를 이스케이프 합니다.</p> + +<pre><strong><code>이스케이프 하지 않는 문자</code></strong>: + + A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) #<code> +</code> +</pre> + +<p><code>encodeURI()</code>와 {{jsxref("encodeURIComponent", "encodeURIComponent()")}}의 차이는 다음과 같습니다.</p> + +<pre class="brush: js">var set1 = ";,/?:@&=+$#"; // 예약 문자 +var set2 = "-_.!~*'()"; // 비예약 표식 +var set3 = "ABC abc 123"; // 알파벳 및 숫자, 공백 + +console.log(encodeURI(set1)); // ;,/?:@&=+$# +console.log(encodeURI(set2)); // -_.!~*'() +console.log(encodeURI(set3)); // ABC%20abc%20123 (공백은 %20으로 인코딩) + +console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24%23 +console.log(encodeURIComponent(set2)); // -_.!~*'() +console.log(encodeURIComponent(set3)); // ABC%20abc%20123 (공백은 %20으로 인코딩) + +</pre> + +<p><code>encodeURI()</code> 혼자서는 {{domxref("XMLHttpRequest")}} 등이 사용할, 적합한 HTTP {{httpmethod("GET")}}과 {{httpmethod("POST")}} 요청을 구성할 수 없습니다. <code>GET</code>과 <code>POST</code>에서 특별한 문자로 취급하는 <code>"&"</code>, <code>"+"</code>, <code>"="</code>를 인코딩 하지 않기 때문입니다. 그러나 <code>encodeURIComponent()</code>는 저 세 문자도 인코딩 대상에 포함합니다.</p> + +<p><span id="result_box" lang="ko"><span>상위-하위 쌍을 이루지 않은 단일 대리 문자를 인코딩 시도하면 {{jsxref("URIError")}}가 발생합니다.</span></span></p> + +<pre class="brush: js">// high-low pair ok +console.log(encodeURIComponent('\uD800\uDFFF')); + +// lone high surrogate throws "URIError: malformed URI sequence" +console.log(encodeURIComponent('\uD800')); + +// lone low surrogate throws "URIError: malformed URI sequence" +console.log(encodeURIComponent('\uDFFF')); +</pre> + +<p>또한, URL의 보다 최신 RFC인 <a href="http://tools.ietf.org/html/rfc3986">RFC3986</a>을 따르고자 한다면, 대괄호가 {{glossary("IPv6")}} 지원을 위해 추가로 예약됨에 따라 <code>encodeURI()</code>가 인코딩하지 않으므로 URL을 생성할 때 주의해야 합니다. 다음 예시 코드가 도움이 될 수도 있습니다.</p> + +<pre class="brush: js">function fixedEncodeURI(str) { + return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']'); +}</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-encodeuri-uri', 'encodeURI')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.encodeURI")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("decodeURI")}}</li> + <li>{{jsxref("encodeURIComponent")}}</li> + <li>{{jsxref("decodeURIComponent")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/encodeuricomponent/index.html b/files/ko/web/javascript/reference/global_objects/encodeuricomponent/index.html new file mode 100644 index 0000000000..191f66b198 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/encodeuricomponent/index.html @@ -0,0 +1,148 @@ +--- +title: encodeURIComponent() +slug: Web/JavaScript/Reference/Global_Objects/encodeURIComponent +tags: + - JavaScript + - Reference + - URI +translation_of: Web/JavaScript/Reference/Global_Objects/encodeURIComponent +--- +<div>{{jsSidebar("Objects")}}</div> + +<p><span class="seoSummary"><code><strong>encodeURIComponent()</strong></code> 함수는 {{glossary("URI")}}의 특정한 문자를 UTF-8로 인코딩해 하나, 둘, 셋, 혹은 네 개의 연속된 이스케이프 문자로 나타냅니다.</span> (두 개의 대리 문자로 이루어진 문자만 이스케이프 문자 네 개로 변환됩니다.)</p> + +<div>{{EmbedInteractiveExample("pages/js/globalprops-encodeuricomponent.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">encodeURIComponent(<em>str</em>);</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>str</code></dt> + <dd>URI 구성요소.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 문자열을 URI 구성요소로서 인코딩한 새로운 문자열.</p> + +<h2 id="설명">설명</h2> + +<p><code>encodeURIComponent()</code>는 다음 문자를 <strong>제외</strong>한 문자를 이스케이프 합니다.</p> + +<pre><strong><code>N</code>ot Escaped</strong>: + + A-Z a-z 0-9 <code>-</code> <code>_</code> <code>.</code> <code>!</code> <code>~</code> <code>*</code> <code>'</code> <code>(</code> <code>) +</code> +</pre> + +<p><code>encodeURIComponent()</code>와 {{jsxref("encodeURI", "encodeURI()")}}의 차이는 다음과 같습니다.</p> + +<pre class="brush: js">var set1 = ";,/?:@&=+$"; // Reserved Characters +var set2 = "-_.!~*'()"; // Unescaped Characters +var set3 = "#"; // Number Sign +var set4 = "ABC abc 123"; // Alphanumeric Characters + Space + +console.log(encodeURI(set1)); // ;,/?:@&=+$ +console.log(encodeURI(set2)); // -_.!~*'() +console.log(encodeURI(set3)); // # +console.log(encodeURI(set4)); // ABC%20abc%20123 (the space gets encoded as %20) + +console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24 +console.log(encodeURIComponent(set2)); // -_.!~*'() +console.log(encodeURIComponent(set3)); // %23 +console.log(encodeURIComponent(set4)); // ABC%20abc%20123 (the space gets encoded as %20) +</pre> + +<p><span id="result_box" lang="ko"><span>상위-하위 쌍을 이루지 않은 단일 대리 문자를 인코딩 시도하면 {{jsxref("URIError")}}가 발생합니다.</span></span></p> + +<pre class="brush: js">// high-low pair ok +console.log(encodeURIComponent('\uD800\uDFFF')); + +// lone high surrogate throws "URIError: malformed URI sequence" +console.log(encodeURIComponent('\uD800')); + +// lone low surrogate throws "URIError: malformed URI sequence" +console.log(encodeURIComponent('\uDFFF')); +</pre> + +<p><code>encodeURIComponent()</code>를 사용해, 서버에 {{HTTPMethod("POST")}}로 요청할 양식 필드를 인코딩 하세요. 입력 중 의도치 않게 생성될 수 있는 HTML 특수 개체 등의 <code>"&"</code> 문자를 처리할 수 있습니다.</p> + +<p>예를 들어 사용자가 입력한 <code>"Jack & Jill"</code>은 <code>"Jack &amp; Jill"</code>로 인코딩 됩니다. <code>encodeURIComponent()</code>를 사용하지 않았다면 서버가 앰퍼샌드를 새로운 필드의 시작으로 인식할 수 있으므로 데이터의 무결성을 해칠 수 있습니다.</p> + +<p><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#application/x-www-form-urlencoded-encoding-algorithm"><code>application/x-www-form-urlencoded</code></a>의 스페이스는 <code>"+"</code>로 치환되어야 하므로, <code>encodeURIComponent()</code>의 결과에 추가로 <code>"%20"</code>을 <code>"+"</code>로 바꾸세요.</p> + +<p>비록 URI의 구분자로서 형식화된 사용처는 없지만, 그럼에도 <code>!</code>, <code>'</code>, <code>(</code>, <code>)</code>, <code>*</code>을 추가로 예약하는 <a class="external" href="http://tools.ietf.org/html/rfc3986">RFC 3986</a>을 엄격하게 따르려면 아래의 코드를 사용해보세요.</p> + +<pre class="brush: js">function fixedEncodeURIComponent(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { + return '%' + c.charCodeAt(0).toString(16); + }); +} +</pre> + +<h2 id="예제">예제</h2> + +<p>다음 예제는 UTF-8 {{HTTPHeader("Content-Disposition")}} 과{{HTTPHeader("Link")}} 서버 응답 헤더에서 (UTF-8 파일 이름 등의 이유로) 필요한 문자 인코딩 방법을 보입니다.</p> + +<pre class="brush: js">var fileName = 'my file(2).txt'; +var header = "Content-Disposition: attachment; filename*=UTF-8''" + + encodeRFC5987ValueChars(fileName); + +console.log(header); +// logs "Content-Disposition: attachment; filename*=UTF-8''my%20file%282%29.txt" + + +function encodeRFC5987ValueChars(str) { + return encodeURIComponent(str). + // Note that although RFC3986 reserves "!", RFC5987 does not, + // so we do not need to escape it + replace(/['()]/g, escape). // i.e., %27 %28 %29 + replace(/\*/g, '%2A'). + // The following are not required for percent-encoding per RFC5987, + // so we can allow for a little better readability over the wire: |`^ + replace(/%(?:7C|60|5E)/g, unescape); +} + +// here is an alternative to the above function +function encodeRFC5987ValueChars2(str) { + return encodeURIComponent(str). + // Note that although RFC3986 reserves "!", RFC5987 does not, + // so we do not need to escape it + replace(/['()*]/g, c => "%" + c.charCodeAt(0).toString(16)). // i.e., %27 %28 %29 %2a (Note that valid encoding of "*" is %2A + // which necessitates calling toUpperCase() to properly encode) + // The following are not required for percent-encoding per RFC5987, + // so we can allow for a little better readability over the wire: |`^ + replace(/%(7C|60|5E)/g, (str, hex) => String.fromCharCode(parseInt(hex, 16))); +}</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-encodeuricomponent-uricomponent', 'encodeURIComponent')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.encodeURIComponent")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("decodeURI")}}</li> + <li>{{jsxref("encodeURI")}}</li> + <li>{{jsxref("decodeURIComponent")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/error/index.html b/files/ko/web/javascript/reference/global_objects/error/index.html new file mode 100644 index 0000000000..986cb5afa0 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/error/index.html @@ -0,0 +1,240 @@ +--- +title: Error +slug: Web/JavaScript/Reference/Global_Objects/Error +tags: + - Error + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Error +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary"><strong><code>Error</code></strong> 생성자는 오류 객체를 생성합니다.</span> <code>Error</code> 객체의 인스턴스는 런타임 오류가 발생했을 때 던져집니다. <code>Error</code> 객체를 사용자 지정 예외의 기반 객체로 사용할 수도 있습니다.</p> + +<h2 id="Syntax" name="Syntax">구문</h2> + +<pre class="syntaxbox">new Error([<em>message</em>[, <em>fileName</em>[, <em>lineNumber</em>]]])</pre> + +<h3 id="Parameters" name="Parameters">매개변수</h3> + +<dl> + <dt><code>message</code> {{optional_inline}}</dt> + <dd>사람이 읽을 수 있는, 오류에 대한 설명.</dd> + <dt><code>fileName</code> {{optional_inline}} {{non-standard_inline}}</dt> + <dd>생성할 <code>Error</code> 객체의 <code>fileName</code> 속성 값. 기본값은 <code>Error</code> 생성자를 호출한 코드를 포함하고 있는 파일의 이름입니다.</dd> + <dt><code>lineNumber</code> {{optional_inline}} {{non-standard_inline}}</dt> + <dd>생성할 <code>Error</code> 객체의 <code>lineNumber</code> 속성 값. 기본값은 <code>Error</code> 생성자 호출을 포함한 줄 번호입니다.</dd> +</dl> + +<h2 id="Description" name="Description">설명</h2> + +<p>런타임 오류는 새로운 <code>Error</code> 객체를 생성하고 던집니다.</p> + +<p>이 페이지는 <code>Error</code> 오브젝트 자체와, 생성자 함수로서의 사용처를 다룹니다. <code>Error</code> 인스턴스가 상속하는 속성과 메서드는 {{jsxref("Error.prototype")}}을 참고하세요.</p> + +<h3 id="함수로_사용">함수로 사용</h3> + +<p><code>Error</code>를 {{jsxref("Operators/new", "new")}} 없이 함수로 사용하면 <code>Error</code> 객체를 반환합니다. 즉 <code>Error</code>를 직접 호출해도 인스턴스를 만드는 것과 동일한 결과를 얻을 수 있습니다.</p> + +<pre class="brush: js">// 이렇게 호출하는 것과 +const x = Error('I was created using a function call!'); +// 이렇게 사용하는게 동일 +const y = new Error('I was constructed via the "new" keyword!'); +</pre> + +<h3 id="Error_types" name="Error_types">오류 유형</h3> + +<p>JavaScript에는 일반적인 <code>Error</code> 생성자 외에도 7개의 중요 오류 생성자가 존재합니다. 클라이언트측 예외에 대해서는 <a href="/ko/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#예외처리문">제어 흐름과 에러 처리</a>를 참고하세요.</p> + +<dl> + <dt>{{jsxref("EvalError")}}</dt> + <dd>전역 함수 {{jsxref("eval", "eval()")}}에서 발생하는 오류의 인스턴스를 생성합니다.</dd> + <dt>{{jsxref("InternalError")}} {{non-standard_inline}}</dt> + <dd>JavaScript 엔진의 내부에서 오류가 발생했음을 나타내는 오류 인스턴스를 생성합니다.</dd> + <dt>{{jsxref("RangeError")}}</dt> + <dd>숫자 변수나 매개변수가 유효한 범위를 벗어났음을 나타내는 오류 인스턴스를 생성합니다.</dd> + <dt>{{jsxref("ReferenceError")}}</dt> + <dd>잘못된 참조를 했음을 나타내는 오류 인스턴스를 생성합니다.</dd> + <dt>{{jsxref("SyntaxError")}}</dt> + <dd>{{jsxref("eval", "eval()")}}이 코드를 분석하는 중 잘못된 구문을 만났음을 나타내는 오류 인스턴스를 생성합니다.</dd> + <dt>{{jsxref("TypeError")}}</dt> + <dd>변수나 매개변수가 유효한 자료형이 아님을 나타내는 오류 인스턴스를 생성합니다.</dd> + <dt>{{jsxref("URIError")}}</dt> + <dd>{{jsxref("encodeURI", "encodeURI()")}}나 {{jsxref("decodeURI", "decodeURl()")}} 함수에 부적절한 매개변수를 제공했을 때 발생하는 오류의 인스턴스를 생성합니다.</dd> +</dl> + +<h2 id="Properties" name="Properties">속성</h2> + +<dl> + <dt>{{jsxref("Error.prototype")}}</dt> + <dd><code>Error</code> 인스턴스에 속성을 추가할 수 있습니다.</dd> +</dl> + +<h2 id="Methods" name="Methods">메서드</h2> + +<p>전역 <code>Error</code> 객체는 자신의 메서드를 가지지 않습니다. 그러나 프로토타입 체인을 통해 일부 메서드를 상속받습니다.</p> + +<h2 id="Error_instances" name="Error_instances"><code>Error</code> 인스턴스</h2> + +<div>{{page('ko/docs/Web/JavaScript/Reference/Global_Objects/Error/prototype', '설명')}}</div> + +<h3 id="속성">속성</h3> + +<div>{{page('ko/docs/Web/JavaScript/Reference/Global_Objects/Error/prototype', '속성')}}</div> + +<h3 id="메서드">메서드</h3> + +<div>{{page('ko/docs/Web/JavaScript/Reference/Global_Objects/Error/prototype', '메서드')}}</div> + +<h2 id="Examples" name="Examples">예제</h2> + +<h3 id="Example:_Throwing_a_generic_error" name="Example:_Throwing_a_generic_error">일반적인 오류 던지기</h3> + +<p><code>Error</code> 객체를 생성한 후엔 대개 {{jsxref("Statements/throw", "throw")}} 키워드를 이용해 던집니다. {{jsxref("Statements/try...catch", "try...catch")}} 구문을 이용하여 오류를 처리할 수 있습니다.</p> + +<pre class="brush: js">try { + throw new Error("이런!"); +} catch (e) { + alert(e.name + ": " + e.message); +} +</pre> + +<h3 id="Example:_Handling_a_specific_error" name="Example:_Handling_a_specific_error">특정 오류 처리하기</h3> + +<p><span class="comment">this should probably be removed</span>오류의 {{jsxref("Object.prototype.constructor", "constructor")}} 속성을 판별해 특정 오류에 대해서만 처리를 할 수 있습니다. 현대적인 JavaScript 엔진의 코드를 작성한다면 {{jsxref("Operators/instanceof", "instanceof")}} 키워드를 이용할 수도 있습니다.</p> + +<pre class="brush: js">try { + foo.bar(); +} catch (e) { + if (e instanceof EvalError) { + alert(e.name + ": " + e.message); + } else if (e instanceof RangeError) { + alert(e.name + ": " + e.message); + } + // ... etc +} +</pre> + +<h3 id="사용자_정의_에러_타입">사용자 정의 에러 타입</h3> + +<p><code>throw new MyError()</code> 이후 <code>instanceof MyError</code>로 직접 만든 오류를 판별할 수 있도록 <code>Error</code>의 파생 오류 정의를 고려해보세요. 더 깔끔하고 일관적인 오류 처리 코드를 작성할 수 있습니다. StackOverflow의 <a href="http://stackoverflow.com/questions/1382107/whats-a-good-way-to-extend-error-in-javascript">"What's a good way to extend Error in JavaScript?"</a>를 방문해 심도 있는 논의를 읽어보세요.</p> + +<h4 id="ES6_사용자_정의_오류_클래스">ES6 사용자 정의 오류 클래스</h4> + +<div class="warning"> +<p>Babel 버전 7 미만으로 사용자 정의 오류 클래스를 처리하려면 {{jsxref("Object.defineProperty()")}} 메서드를 사용해 정의해야만 합니다. 그렇지 않으면 오래된 Babel 및 다른 트랜스파일러가 <a href="https://github.com/loganfsmyth/babel-plugin-transform-builtin-extend">추가 설정</a> 없이 코드를 처리할 수 없습니다.</p> +</div> + +<div class="note"> +<p>ES2015 클래스를 사용할 때, 일부 브라우저는 <code>CustomError</code> 생성자를 스택 트레이스에 포함합니다.</p> +</div> + +<pre class="brush: js">class CustomError extends Error { + constructor(foo = 'bar', ...params) { + // Pass remaining arguments (including vendor specific ones) to parent constructor + super(...params); + + // Maintains proper stack trace for where our error was thrown (only available on V8) + if (Error.captureStackTrace) { + Error.captureStackTrace(this, CustomError); + } + + // Custom debugging information + this.foo = foo; + this.date = new Date(); + } +} + +try { + throw new CustomError('baz', 'bazMessage'); +} catch(e){ + console.log(e.foo); //baz + console.log(e.message); //bazMessage + console.log(e.stack); //stacktrace +}</pre> + +<h4 id="ES5_사용자_정의_오류_객체">ES5 사용자 정의 오류 객체</h4> + +<div class="warning"> +<p>프로토타입 선언을 사용하면 모든 브라우저가 <code>CustomError</code> 생성자를 스택 트레이스에 포함합니다.</p> +</div> + +<pre class="brush: js">function CustomError(foo, message, fileName, lineNumber) { + var instance = new Error(message, fileName, lineNumber); + instance.foo = foo; + Object.setPrototypeOf(instance, Object.getPrototypeOf(this)); + if (Error.captureStackTrace) { + Error.captureStackTrace(instance, CustomError); + } + return instance; +} + +CustomError.prototype = Object.create(Error.prototype, { + constructor: { + value: Error, + enumerable: false, + writable: true, + configurable: true + } +}); + +if (Object.setPrototypeOf){ + Object.setPrototypeOf(CustomError, Error); +} else { + CustomError.__proto__ = Error; +} + + +try { + throw new CustomError('baz', 'bazMessage'); +} catch(e){ + console.log(e.foo); //baz + console.log(e.message) ;//bazMessage +} +</pre> + +<h2 id="See_also" name="See_also">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.11', 'Error')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-error-objects', 'Error')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-error-objects', 'Error')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Error")}}</p> + +<h2 id="See_also" name="See_also">같이 보기</h2> + +<ul> + <li>{{jsxref("Error.prototype")}}</li> + <li>{{jsxref("Statements/throw", "throw")}}</li> + <li>{{jsxref("Statements/try...catch", "try...catch")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/error/name/index.html b/files/ko/web/javascript/reference/global_objects/error/name/index.html new file mode 100644 index 0000000000..bca8a4937f --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/error/name/index.html @@ -0,0 +1,72 @@ +--- +title: Error.prototype.name +slug: Web/JavaScript/Reference/Global_Objects/Error/name +translation_of: Web/JavaScript/Reference/Global_Objects/Error/name +--- +<div>{{JSRef}}</div> + +<div><strong><code>name</code> </strong>프로퍼티는 에러 타입을 설명하기 위한 이름을 나타냅니다. 초기값은 "Error"입니다.</div> + +<h2 id="설명">설명</h2> + +<p>{{jsxref("Error")}} 인스턴스는 주어진 이름인 "Error"를 기본 값으로 갖습니다. name 프로퍼티는 {{jsxref("Error.prototype.message", "message")}}와 함께 {{jsxref("Error.prototype.toString()")}}에서 사용되며 해당 에러를 문자열로 표현합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="사용자_정의_에러_발생시키기">사용자 정의 에러 발생시키기</h3> + +<pre class="brush: js">var e = new Error('Malformed input'); // e.name은 'Error' + +e.name = 'ParseError'; +throw e; +// e.toString()은 'ParseError: Malformed input'을 반환합니다 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.11.4.2', 'Error.prototype.name')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-error.prototype.name', 'Error.prototype.name')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-error.prototype.name', 'Error.prototype.name')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div> +<div> +<div class="hidden">이 페이지의 호환성 테이블은 구조화된 데이터로부터 생성됩니다. 해당 데이터를 개선하고 싶다면 <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>을 체크아웃하고 저희에게 풀 리퀘스트를 보내주십시오.</div> + +<p>{{Compat("javascript.builtins.Error.name")}}</p> +</div> +</div> + +<h2 id="참고">참고</h2> + +<ul> + <li>{{jsxref("Error.prototype.message")}}</li> + <li>{{jsxref("Error.prototype.toString()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/eval/index.html b/files/ko/web/javascript/reference/global_objects/eval/index.html new file mode 100644 index 0000000000..000c8b2228 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/eval/index.html @@ -0,0 +1,285 @@ +--- +title: eval() +slug: Web/JavaScript/Reference/Global_Objects/eval +tags: + - JavaScript + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/eval +--- +<div>{{jsSidebar("Objects")}}</div> + +<div class="blockIndicator warning"> +<p><strong>주의:</strong> 문자열로부터 <code><strong>eval()</strong></code>을 실행하는 것은 엄청나게 위험합니다. <code><strong>eval()</strong></code>을 사용하면 해커가 위험한 코드를 사용할 수 있습니다. 아래에 <a href="#eval을 절대 사용하지 말 것!">eval을 절대 사용하지 말 것!</a>을 확인하세요.</p> +</div> + +<p><code><strong>eval()</strong></code>은 문자로 표현된 JavaScript 코드를 실행하는 함수입니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/globalprops-eval.html")}}</div> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox notranslate"><code>eval(<em>string</em>)</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>string</code></dt> + <dd>자바스크립트 표현식, 명령문, 또는 연속되는 다수의 명령문을 나타내는 문자열. 표현식은 이미 존재하는 객체의 변수나 속성을 포함할 수 있습니다.</dd> +</dl> + +<h3 id="반환값">반환값</h3> + +<p>주어진 코드를 평가하여 얻은 값. 값이 없다면 {{jsxref("undefined")}}를 반환합니다.</p> + +<h2 id="설명">설명</h2> + +<p><code>eval()</code>은 전역 객체의 함수 속성입니다.</p> + +<p><code>eval()</code>의 인자는 문자열입니다. 인자가 표현식을 나타낸다면 <code>eval()</code>은 표현식을 평가합니다. 인자가 하나 이상의 JavaScript 명령문을 나타낸다면 모두 실행합니다. 연산식을 계산하기 위해 <code>eval()</code>을 호출하지 마세요. 자바스크립트는 연산식을 알아서 계산합니다.</p> + +<p>문자열로 연산식을 구성하면 나중에 <code>eval()</code>로 계산할 수 있습니다. <code>x</code> 라는 변수가 있다고 가정하면 <code>x</code>가 포함된 연산식을 문자열로, 예를 들어 "<code>3 * x + 2</code>"로 나타내고 나중에 <code>eval()</code>을 호출해서 계산을 연기할 수 있습니다.</p> + +<p><code>eval()</code>의 인자가 문자열이 아니면 <code>eval()</code>은 인자를 그대로 반환합니다. 다음 예시에서, <code>String</code> 생성자가 명시된 경우 문자열을 계산하는 대신 <code>String</code> 객체를 반환합니다.</p> + +<pre class="brush:js notranslate">eval(new String("2 + 2")); // "2 + 2"를 포함한 String 객체를 반환 +eval("2 + 2"); // 4를 반환 +</pre> + +<p><code>toString()</code>을 사용하는 일반적인 방식으로 제약을 피할 수 있습니다.</p> + +<pre class="brush:js notranslate">var expression = new String("2 + 2"); +eval(expression.toString()); // 4를 반환 +</pre> + +<p><code>eval</code>을 직접 호출하지 않고 참조를 통해 <em>간접적으로</em> 사용한다면 <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-10.4.2">ECMAScript 5부터는</a> 지역 범위가 아니라 전역 범위에서 동작합니다. 예를 들어 <code>eval()</code>로 함수를 선언하면 전역 함수가 되고, 실행되는 코드는 실행되는 위치의 지역 범위에 접근할 수 없습니다.</p> + +<pre class="notranslate"><code>function test() { + var x = 2, y = 4; + console.log(eval('x + y')); // 직접 호출, 지역 범위 사용, 결과값은 6 + var geval = eval; // eval을 전역 범위로 호출하는 것과 같음 + console.log(geval('x + y')); // 간접 호출, 전역 범위 사용, `x`가 정의되지 않았으므로 ReferenceError 발생 + (0, eval)('x + y'); // 다른 방식으로 간접 호출 +}</code></pre> + +<h2 id="eval을_절대_사용하지_말_것!"><a name="dont-use-it"><code>eval</code>을 절대 사용하지 말 것!</a></h2> + +<p><code>eval()</code>은 인자로 받은 코드를 caller의 권한으로 수행하는 위험한 함수입니다. 악의적인 영향을 받았을 수 있는 문자열을 <code>eval()</code>로 실행한다면, 당신의 웹페이지나 확장 프로그램의 권한으로 사용자의 기기에서 악의적인 코드를 수행하는 결과를 초래할 수 있습니다. 또한, 제3자 코드가 <code>eval()</code>이 호출된 위치의 스코프를 볼 수 있으며, 이를 이용해 비슷한 함수인 {{jsxref("Global_Objects/Function", "Function")}}으로는 실현할 수 없는 공격이 가능합니다.</p> + +<p>또한 최신 JS 엔진에서 여러 코드 구조를 최적화하는 것과 달리 <code>eval()</code>은 JS 인터프리터를 사용해야 하기 때문에 다른 대안들보다 느립니다.</p> + +<p>추가로, 최신 JavaScript 인터프리터는 자바스크립트를 기계 코드로 변환합니다. 즉, 변수명의 개념이 완전히 없어집니다. 그러나 <code>eval</code>을 사용하면 브라우저는 기계 코드에 해당 변수가 있는지 확인하고 값을 대입하기 위해 길고 무거운 변수명 검색을 수행해야 합니다. 또한 <code>eval()</code>을 통해 자료형 변경 등 변수에 변화가 일어날 수 있으며, 브라우저는 이에 대응하기 위해 기계 코드를 재작성해야 합니다. 그러나, (다행히) <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Function">window.Function</a>이라는 <code> eval</code>보다 훨씬 나은 대안이 있습니다. <code>eval()</code>을 사용하는 코드를 <code>Function()</code>으로 바꾸는 방법에 대해서는 아래를 참조하세요.</p> + +<p><code>eval</code>을 사용하는 나쁜 코드:</p> + +<pre class="brush:js notranslate">function looseJsonParse(obj){ + return eval(obj); +} +console.log(looseJsonParse( + "{a:(4-1), b:function(){}, c:new Date()}" +)) +</pre> + +<p><code>eval</code>이 없는 코드:</p> + +<pre class="brush:js notranslate">function looseJsonParse(obj){ + return Function('"use strict";return (' + obj + ')')(); +} +console.log(looseJsonParse( + "{a:(4-1), b:function(){}, c:new Date()}" +)) +</pre> + +<p>위의 두 코드는 얼핏 보면 같은 방식으로 실행되는 것처럼 보이지만, <code>eval</code>이 있는 코드가 훨씬 느립니다. 평가되는 객체의 <code>c: new Date()</code>를 주목하세요. <code>eval</code>이 없는 함수의 경우 이 객체는 전역 범위에서 평가되기 때문에 브라우저에서는 <code>Date</code>를 같은 이름의 지역 변수가 아니라 <code>window.Date</code>로 취급할 수 있습니다. 그러나 <code>eval()</code>을 사용하는 코드에서는 아래와 같은 경우도 존재할 수 있기 때문에 <code>Date</code>를 이렇게 취급할 수 없습니다.</p> + +<pre class="brush:js notranslate">function Date(n){ + return ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"][n%7 || 0]; +} +function looseJsonParse(obj){ + return eval(obj); +} +console.log(looseJsonParse( + "{a:(4-1), b:function(){}, c:new Date()}" +)) +</pre> + +<p>그러므로 <code>eval()</code>이 있는 코드의 경우 브라우저는 <code>Date()</code>라는 지역 변수의 존재를 확인하기 위해 무거운 변수명 탐색을 수행해야 하며, 이는 <code>Function()</code>과 비교하면 매우 느립니다.</p> + +<p>만약 위의 상황에서 실제로 새로 선언한 <code>Date</code> 함수를 <code>Function()</code>에서 실행해야 하는 상황을 생각해 봅시다. 이렇게 되면 <code>eval()</code>로 돌아가야 할까요? 물론 아닙니다. 아래의 접근을 시도해 보세요.</p> + +<pre class="brush:js notranslate">function Date(n){ + return ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"][n%7 || 0]; +} +function runCodeWithDateFunction(obj){ + return Function('"use strict";return (' + obj + ')')()( + Date + ); +} +console.log(runCodeWithDateFunction( + "function(Date){ return Date(5) }" +)) +</pre> + +<p>위 코드는 삼중 중첩 함수를 사용하기 때문에 매우 비효율적으로 보일 수 있지만, 이 방법의 이점을 우선 살펴봅시다.</p> + +<p>1. <code>runCodeWithDateFunction</code>에 문자열로 전달된 코드를 최소화<sup>minify</sup>할 수 있다.</p> + +<p>2. Function call overhead is minimal, making the far smaller code size well worth the benefit</p> + +<p>3. <code>Function()</code>은 <code>"use strict";</code>를 사용함으로써 코드의 성능을 최적화할 수 있다.</p> + +<p>4. <code>eval()</code>을 사용하지 않으므로 실행 속도가 훨씬 빠르다.</p> + +<p>마지막으로 코드 최소화의 측면에서 살펴보면, 위와 같이 <code>Function()</code>을 사용했을 때는 아래의 최소화된 코드와 같이 함수의 인자 이름 역시 짧게 줄일 수 있으므로 runCodeWithDateFunction에 전달하는 코드 문자열을 더욱 효율적으로 줄일 수 있습니다.</p> + +<pre class="brush:js notranslate">console.log(Function('"use strict";return(function(a){return a(5)})')()(function(a){ +return"Monday Tuesday Wednesday Thursday Friday Saturday Sunday".split(" ")[a%7||0]}));</pre> + +<p>자주 쓰이는 용례에 대해서는 <code>eval()</code>이나 <code>Function()</code>보다 안전하고 빠른 대안도 존재합니다.</p> + +<h3 id="객체의_속성에_접근하기">객체의 속성에 접근하기</h3> + +<p>속성명으로 속성을 찾는 데 <code>eval()</code>을 사용해서는 안 됩니다. 다음 예제와 같이 코드를 실행하기 전까지는 접근할 속성을 알 수 없는 상황을 생각해 봅시다. 이 상황은 <code>eval</code>로 처리할 수 있습니다.</p> + +<pre class="brush:js notranslate">var obj = { a: 20, b: 30 }; +var propname = getPropName(); // "a" 또는 "b"를 반환 + +eval( "var result = obj." + propname ); +</pre> + +<p>그러나 여기에서 <code>eval()</code>을 쓸 필요가 없고, 지양되어야 합니다. 그 대신 훨씬 빠르고 안전한 <a href="/ko/docs/Web/JavaScript/Reference/Operators/Property_Accessors" title="JavaScript/Reference/Operators/Member_Operators">속성 접근자</a>를 사용하여야 합니다.</p> + +<pre class="brush:js notranslate">var obj = { a: 20, b: 30 }; +var propname = getPropName(); // "a" 또는 "b"를 반환 +var result = obj[ propname ]; // obj[ "a" ]는 obj.a와 동일함 +</pre> + +<p>이 방법으로 더 깊은 속성에도 접근할 수 있습니다. <code>eval()</code>을 사용한다면 다음과 같을 것입니다.</p> + +<pre class="notranslate"><code>var obj = {a: {b: {c: 0}}}; +var propPath = getPropPath(); // "a.b.c"를 반환한다고 가정 + +eval( 'var result = obj.' + propPath );</code></pre> + +<p>여기서 <code>eval()</code>의 사용을 피하려면 속성 경로를 <code><a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/String/split">split</a></code>한 다음 순서대로 접근할 수도 있습니다.</p> + +<pre class="notranslate"><code>function getDescendantProp(obj, desc) { + var arr = desc.split('.'); + while (arr.length) { + obj = obj[arr.shift()]; + } + return obj; +} + +var obj = {a: {b: {c: 0}}}; +var propPath = getPropPath(); // "a.b.c"를 반환한다고 가정 +var result = getDescendantProp(obj, propPath);</code></pre> + +<p>속성에 값을 대입하는 것도 비슷하게 할 수 있습니다.</p> + +<pre class="notranslate"><code>function setDescendantProp(obj, desc, value) { + var arr = desc.split('.'); + while (arr.length > 1) { + obj = obj[arr.shift()]; + } + return obj[arr[0]] = value; +} + +var obj = {a: {b: {c: 0}}}; +var propPath = getPropPath(); // "a.b.c"를 반환한다고 가정 +var result = setDescendantProp(obj, propPath, 1); // test.a.b.c의 값은 1로 지정됨</code> +</pre> + +<h3 id="단편적인_코드_수행_대신_함수_사용하기">단편적인 코드 수행 대신 함수 사용하기</h3> + +<p>JavaScript의 <a href="http://en.wikipedia.org/wiki/First-class_function">함수는 1급 객체</a>이므로 다른 API에 함수를 인자로 전달할 수도 있고, 변수나 객체의 속성으로 대입할 수도 있습니다. 다수의 DOM API는 이 점을 염두에 두고 설계되므로, 다음과 같이 코드를 짜야 합니다.</p> + +<pre class="brush: js notranslate">// setTimeout(" ... ", 1000) 대신에 +setTimeout(function() { ... }, 1000); + +// elt.setAttribute("onclick", "...") 대신에 +elt.addEventListener("click", function() { ... } , false); </pre> + +<p>또한 <a href="/en-US/docs/Web/JavaScript/Closures" title="JavaScript/Guide/Closures">클로저</a>를 이용해 문자열을 합치는 등의 연산 없이 매개변수화된 함수를 생성할 수 있습니다.</p> + +<h3 id="JSON_파싱_문자열을_JavaScript_객체로_변환">JSON 파싱 (문자열을 JavaScript 객체로 변환)</h3> + +<p><code>eval()</code>을 호출하려는 문자열에 코드가 아니라 데이터가 포함되어 있다면(예를 들어 <code>"[1, 2, 3]"</code>과 같은 배열), 대신 JavaScript의 문법 일부를 이용해 문자열로 데이터를 표현할 수 있는 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/JSON" title="JSON">JSON</a>을 사용하는 것을 고려해 보세요. <a href="/en-US/docs/Downloading_JSON_and_JavaScript_in_extensions" title="Downloading_JSON_and_JavaScript_in_extensions">Downloading JSON and JavaScript in extensions</a>도 참고해 보세요.</p> + +<p>JSON 문법은 JavaScript 문법에 비해 제약이 있기 때문에, 유효한 JavaScript 리터럴이 JSON으로 변환되지 않는 경우도 있습니다. 예를 들어, JSON에서는 배열이나 객체를 콤마로 끝낼 수 없고, 객체 리터럴에서 속성명(키)은 반드시 따옴표로 감싸야 합니다. 나중에 JSON으로 파싱할 문자열을 생성할 때는 JSON 직렬 변환기<sup>JSON serializer</sup>를 사용하여야 합니다.</p> + +<h3 id="코드_대신_데이터_전달하기">코드 대신 데이터 전달하기</h3> + +<p>예를 들어, 웹 페이지의 내용을 추출하는 확장 프로그램은 JavaScript 코드 대신 <a href="/ko/docs/XPath" title="XPath">XPath</a>에 스크랩 규칙을 정의할 수 있습니다.</p> + +<h3 id="제한된_권한으로_코드_실행하기">제한된 권한으로 코드 실행하기</h3> + +<p>제3자 코드를 실행해야 할 때는 제한된 권한으로 실행하는 것을 고려해야 합니다. 이는 주로 확장 프로그램이나 XUL 어플리케이션에 적용되며, 이때 <a href="/en-US/docs/Components.utils.evalInSandbox" title="Components.utils.evalInSandbox">Components.utils.evalInSandbox</a>를 사용할 수 있습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="eval_사용하기"><code>eval</code> 사용하기</h3> + +<p>아래 코드에서 <code>eval()</code>를 포함하는 문장은 모두 42를 반환합니다. 전자는 문자열 "<code>x + y + 1</code>"을, 후자는 문자열 "<code>42</code>"를 평가합니다.</p> + +<pre class="brush:js notranslate">var x = 2; +var y = 39; +var z = "42"; +eval("x + y + 1"); // 42를 반환 +eval(z); // 42를 반환 +</pre> + +<h3 id="eval을_사용해서_JavaScript_코드_문자열_평가하기"><code>eval</code>을 사용해서 JavaScript 코드 문자열 평가하기</h3> + +<p>다음 예제에서는 <code>eval()</code>을 사용하여 <code>str</code> 문자열을 평가합니다. 이 문자열은 <code>x</code>가 5이면 로그를 출력한 다음 <code>z</code>에 42를 할당하고, 그렇지 않으면 <code>z</code>에 0 을 할당하는 JavaScript 코드입니다. 두 번째 문장이 실행되면, <code>eval()</code>은 이 문장의 집합을 수행하고, <code>z</code>에 할당된 값을 반환합니다.</p> + +<pre class="brush:js notranslate">var x = 5; +var str = "if (x == 5) {console.log('z is 42'); z = 42;} else z = 0; "; + +console.log("z is ", eval(str));</pre> + +<p>여러 값을 정의할 경우 마지막 값을 반환합니다.</p> + +<pre class="notranslate"><code>var x = 5; +var str = "if (x == 5) {console.log('z is 42'); z = 42; x = 420; } else z = 0;"; + +console.log('x is ', eval(str)); // z는 42, x는 420</code></pre> + +<h3 id="마지막_표현식이_수행된다">마지막 표현식이 수행된다</h3> + +<p><code>eval()</code> 은 마지막 표현식의 평가값을 반환합니다.</p> + +<pre class="brush:js notranslate">var str = "if ( a ) { 1+1; } else { 1+2; }"; +var a = true; +var b = eval(str); // 2를 반환 + +console.log("b is : " + b); + +a = false; +b = eval(str); // 3을 반환 + +console.log("b is : " + b);</pre> + +<h3 id="함수_정의_문자열로서의_eval_은_앞뒤를_와_로_감싸야_한다">함수 정의 문자열로서의 <code>eval</code> 은 앞뒤를 "("와 ")"로 감싸야 한다</h3> + +<pre class="brush:js notranslate">var fctStr1 = "function a() {}" +var fctStr2 = "(function a() {})" +var fct1 = eval(fctStr1) // undefined를 반환 +var fct2 = eval(fctStr2) // 함수를 반환 +</pre> + +<h2 id="sect1"></h2> + +<h2 id="브라우저_호환성"><span style="">브라우저 호환성</span></h2> + +<div class="hidden">The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</div> + +<p>{{Compat("javascript.builtins.eval")}}</p> + +<h2 id="참고">참고</h2> + +<ul> + <li>{{jsxref("Global_Objects/uneval", "uneval()")}}</li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Operators/Property_Accessors">속성 접근자</a></li> + <li><a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Content_scripts#Using_eval()_in_content_scripts">WebExtensions: Using eval in content scripts</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/evalerror/index.html b/files/ko/web/javascript/reference/global_objects/evalerror/index.html new file mode 100644 index 0000000000..4c8fcf38dd --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/evalerror/index.html @@ -0,0 +1,112 @@ +--- +title: EvalError +slug: Web/JavaScript/Reference/Global_Objects/EvalError +tags: + - Error + - EvalError + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/EvalError +--- +<div>{{JSRef}}</div> + +<p><strong><code>EvalError</code></strong> 객체는 전역 {{jsxref("Global_Objects/eval", "eval()")}} 함수에 관한 오류를 나타냅니다. 이 예외는 JavaScript에 의해 더 이상 발생하지 않지만 <code>EvalError</code> 객체는 하위 호환성을 위해 남아있습니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code>new EvalError([<var>message</var>[, <var>fileName</var>[, <var>lineNumber</var>]]])</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>message</code> {{optional_inline}}</dt> + <dd>인간이 읽을 수 있는 오류 설명.</dd> + <dt><code>fileName</code> {{optional_inline}} {{non-standard_inline}}</dt> + <dd>예외의 원인이 된 코드를 포함하는 파일의 이름.</dd> + <dt><code>lineNumber</code> {{optional_inline}} {{non-standard_inline}}</dt> + <dd>예외를 발생시킨 코드의 행 번호.</dd> +</dl> + +<h2 id="속성">속성</h2> + +<dl> + <dt>{{jsxref("EvalError.prototype")}}</dt> + <dd>EvalError 객체에 속성을 추가할 수 있습니다.</dd> +</dl> + +<h2 id="메서드">메서드</h2> + +<p>전역 EvalError에는 자체 메서드가 없지만 프로토 타입 체인을 통해 일부 메서드를 상속받습니다.</p> + +<h2 id="EvalError_인스턴스"><code>EvalError</code> 인스턴스</h2> + +<h3 id="Properties">Properties</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/EvalError/prototype', 'Properties')}}</div> + +<h3 id="Methods">Methods</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/EvalError/prototype', 'Methods')}}</div> + +<h2 id="예제">예제</h2> + +<p><code>EvalError</code>는 현재 ECMAScript 사양에서 사용되지 않으므로 런타임에 의해 throw되지 않습니다. 그러나 개체 자체는 이전 버전의 사양과의 하위 호환성을 유지합니다.</p> + +<h3 id="Creating_an_EvalError">Creating an <code>EvalError</code></h3> + +<pre class="brush: js">try { + throw new EvalError('Hello', 'someFile.js', 10); +} catch (e) { + console.log(e instanceof EvalError); // true + console.log(e.message); // "Hello" + console.log(e.name); // "EvalError" + console.log(e.fileName); // "someFile.js" + console.log(e.lineNumber); // 10 + console.log(e.columnNumber); // 0 + console.log(e.stack); // "@Scratchpad/2:2:9\n" +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.11.6.1', 'EvalError')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Not used in this specification. Present for backward compatibility.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-native-error-types-used-in-this-standard-evalerror', 'EvalError')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Not used in this specification. Present for backward compatibility.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-native-error-types-used-in-this-standard-evalerror', 'EvalError')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.EvalError")}}</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Error")}}</li> + <li>{{jsxref("EvalError.prototype")}}</li> + <li>{{jsxref("Global_Objects/eval", "eval()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/function/apply/index.html b/files/ko/web/javascript/reference/global_objects/function/apply/index.html new file mode 100644 index 0000000000..1e59ed07f7 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/function/apply/index.html @@ -0,0 +1,236 @@ +--- +title: Function.prototype.apply() +slug: Web/JavaScript/Reference/Global_Objects/Function/apply +tags: + - Function + - JavaScript + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Function/apply +--- +<div>{{JSRef}}</div> + +<p><strong><code>apply()</code></strong> 메서드는 주어진 <code>this</code> 값과 배열 (또는 <a href="/en-US/docs/Web/JavaScript/Guide/Predefined_Core_Objects#Working_with_Array-like_objects">유사 배열 객체</a>) 로 제공되는 <code>arguments</code> 로 함수를 호출합니다.</p> + +<div class="note"> +<p><strong>참고:</strong> 이 함수의 구문은 거의 {{jsxref("Function.call", "call()")}} 구문과 유사합니다. 근본적인 차이점은 <code>call()</code> 은 함수에 전달될 <strong>인수 리스트</strong>를 받는데 비해, <code>apply()</code> 는 <strong>인수들의 단일 배열</strong>을 받는다는 점입니다.</p> +</div> + +<p>{{EmbedInteractiveExample("pages/js/function-apply.html")}}</p> + +<div class="hidden"> +<p>The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p> +</div> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>func</var>.apply(<var>thisArg, </var>[<var>argsArray</var>])</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>thisArg</code></dt> + <dd>옵션. <code>func</code> 를 호출하는데 제공될 <code>this</code> 의 값. <code>this</code> 는 메소드에 의해 실제로 보여지는 값이 아닐 수 있음을 유의합니다. 메소드가 {{jsxref("Strict_mode", "non-strict mode", "", 1)}} 코드의 함수일 경우, {{jsxref("null")}} 과 {{jsxref("undefined")}} 가 전역 객체로 대체되며, 기본 값은 제한됩니다.</dd> + <dt><code>argsArray</code></dt> + <dd>옵션. <em><code>func</code></em> 이 호출되어야 하는 인수를 지정하는 유사 배열 객체, 함수에 제공된 인수가 없을 경우 {{jsxref("null")}} 또는 {{jsxref("undefined")}}. ECMAScript 5 의 시작으로 이러한 인수들은 배열 대신 제네릭 유사 배열 객체로 사용될 수 있습니다. 아래의 {{anch("Browser_compatibility", "브라우저 호환성")}} 정보를 보세요.</dd> +</dl> + +<h3 id="반환값">반환값</h3> + +<p>지정한 <strong><code>this</code></strong> 값과 인수들로 호출한 함수의 결과.</p> + +<h2 id="Description" name="Description">설명</h2> + +<p>이미 존재하는 함수를 호출할 때 다른 <code>this</code> 객체를 할당할 수 있습니다. <code>this</code> 는 현재 객체, 호출하는 객체를 참조합니다. <code>apply</code> 를 사용해, 새로운 객체마다 메소드를 재작성할 필요없이 한 번만 작성해 다른 객체에 상속시킬 수 있습니다.</p> + +<p><code>apply</code> 는 지원되는 인수의 타입만 제외하면 {{jsxref("Function.call", "call()")}} 과 매우 유사합니다. 인수(파라미터)의 리스트 대신 인수들의 배열을 사용할 수 있습니다. 또한 <code>apply</code> 를 사용해, 배열 리터럴이나 (예, <em>func</em>.apply(this, ['eat', 'bananas']), {{jsxref("Array")}} 객체 (예, <em>func</em>.apply(this, new Array('eat', 'bananas'))) 를 사용할 수 있습니다.</p> + + + +<p><code>argsArray</code> 파라미터를 위한 {{jsxref("Functions/arguments", "arguments")}} 를 사용할 수도 있습니다. <code>arguments</code> 는 함수의 지역 변수입니다. 이는 호출된 객체의 지정되지 않은 모든 인수에 대해 사용할 수 있습니다. 따라서, <code>apply</code> 메소드를 사용할 때 호출된 객체의 인수를 알 필요가 없습니다. <code>arguments</code> 를 사용해 모든 인수들을 호출된 객체로 전달할 수 있습니다. 그럼 호출된 객체는 그 인수들을 처리할 수 있게 됩니다.</p> + + + +<p>ECMAScript 5번 째 판의 시작으로, 모든 유사 배열 객체 타입을 사용할 수 있으며, 실제로 이는 프로퍼티 <code>length</code> 와 범위 <code>(0..length-1)</code> 내의 정수 프로퍼티를 갖는 다는 것을 의미합니다. 예를 들면, 이제 {{domxref("NodeList")}} 또는 <code>{ 'length': 2, '0': 'eat', '1': 'bananas' }</code> 와 같은 커스텀 객체를 사용할 수 있습니다.</p> + +<div class="blockIndicator note">Chrome 14와 Internet Explorer 9를 포함한 대부분의 브라우저는 아직 유사배열객체를 apply에 사용할 수 없으며 오류가 출력됩니다.</div> + +<h2 id="Examples" name="Examples">예제</h2> + +<h3 id="Example_Using_apply_to_chain_constructors" name="Example:_Using_apply_to_chain_constructors">배열에 배열을 붙이기 위해 <code>apply</code> 사용하기</h3> + +<p><code>push</code> 를 사용하여 요소를 배열에 추가 할 수 있습니다. <code>push</code> 는 가변 인수를 허용하기 때문에 여러 요소를 동시에 추가 할 수 있습니다. 그러나 <code>push</code> 에 배열을 전달하면 요소를 개별적으로 추가하는 대신 실제로 해당 배열을 단일 요소로 추가하므로 결국 배열 내부에 배열로 끝납니다. 그것이 우리가 원하는 것이 아니라면? 이 경우 <code>concat</code> 은 우리가 원하는 동작을 하지만 실제로는 기존 배열에 추가되지 않고 새 배열을 만들어 반환 합니다. 그러나 우리는 기존 배열에 추가하고 싶었습니다 ... 그럼 이제 어쩌죠? 루프를 작성 할까요? 분명히 아니죠?</p> + +<p>방법은 <code>apply</code> !</p> + +<pre class="brush: js">var array = ['a', 'b']; +var elements = [0, 1, 2]; +array.push.apply(array, elements); +console.info(array); // ["a", "b", 0, 1, 2] +</pre> + +<h3 id="apply_와_내장함수_사용"><code>apply</code> 와 내장함수 사용</h3> + +<p><code>apply</code> 를 보다 효과적으로 이용하면 일부 내장 함수는 어떤 작업에 대해서는 배열과 루프없이 쉽게 처리됩니다. 다음 예제에서는 배열에서 최대값과 최소값을 구하기 위해 <code>Math.max</code>/<code>Math.min</code> 함수를 이용하고 있습니다.</p> + +<pre class="brush: js">// min/max number in an array +var numbers = [5, 6, 2, 3, 7]; + +// using Math.min/Math.max apply +var max = Math.max.apply(null, numbers); +// 이는 Math.max(numbers[0], ...) 또는 Math.max(5, 6, ...) +// 와 거의 같음 + +var min = Math.min.apply(null, numbers); + +// vs. simple loop based algorithm +max = -Infinity, min = +Infinity; + +for (var i = 0; i < numbers.length; i++) { + if (numbers[i] > max) { + max = numbers[i]; + } + if (numbers[i] < min) { + min = numbers[i]; + } +} +</pre> + +<p>하지만 이러한 방식으로 <code>apply</code> 를 사용하는 경우 주의해야 합니다. JavaScript 엔진의 인수 길이 제한을 초과하는 위험성에 대해 이해할 필요가 있습니다. 함수에 너무 많은(대략 몇 만개 이상) 인수를 줄 때의 상황은 엔진마다 다른데(예를 들어 JavaScriptCore의 경우 <a href="https://bugs.webkit.org/show_bug.cgi?id=80797">인수의 개수 제한은 65536</a>), 상한이 특별히 정해져 있지 않기 때문입니다. 어떤 엔진은 예외를 던집니다. 더 심한 경우는 실제 함수에 인수를 전달했음에도 불구하고 참조할 수 있는 인수의 수를 제한하고 있는 경우도 있습니다(이러한 엔진에 대해 더 자세히 설명하면, 그 엔진이 arguments의 상한을 4개로 했다고 하면[실제 상한은 물론 더 위일 것입니다], 위 예제 코드의 전체 배열이 아니라 <code>5, 6, 2, 3</code> 만 <code>apply</code> 에 전달되어 온 것처럼 작동합니다).</p> + +<p>만약 사용하는 배열 변수의 수가 수만을 초과하는 경우에는 복합적인 전략을 강구해야할 것입니다:한 번에 전달할 배열을 분할하여 사용하기:</p> + +<pre class="brush: js">function minOfArray(arr) { + var min = Infinity; + var QUANTUM = 32768; + + for (var i = 0, len = arr.length; i < len; i += QUANTUM) { + var submin = Math.min.apply(null, + arr.slice(i, Math.min(i + QUANTUM, len))); + min = Math.min(submin, min); + } + + return min; +} + +var min = minOfArray([5, 6, 2, 3, 7]); + +</pre> + + + +<h3 id="생성자_체이닝을_위한_apply_사용">생성자 체이닝을 위한 <code>apply</code> 사용</h3> + +<p>Java 와 유사하게, 객체를 위한 {{jsxref("Operators/new", "constructors", "", 1)}} 체이닝을 위해 <code>apply</code> 를 사용할 수 있습니다. 다음 예제에서 인수 리스트 대신 생성자로 유사 배열 객체를 사용할 수 있게 해주는 <code>construct</code> 라는 전역 {{jsxref("Function")}} 메소드를 생성할 것입니다. </p> + +<pre><code>Function.prototype.construct = function(aArgs) { + var oNew = Object.create(this.prototype); + this.apply(oNew, aArgs); + return oNew; +};</code></pre> + +<div class="blockIndicator note"> +<p><strong>알림:</strong> 위에서 사용된 <code>Object.create()</code> 메소드는 상대적으로 새로운 것입니다. 대안으로, 다음 접근법 중 하나를 고려하세요.</p> + +<p>{{jsxref("Object/__proto__", "Object.__proto__")}} 사용</p> + +<pre><code>Function.prototype.construct = function (aArgs) { + var oNew = {}; + oNew.__proto__ = this.prototype; + this.apply(oNew, aArgs); + return oNew; +};</code></pre> + +<p><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/Closures">클로져</a> 사용:</p> + +<pre><code>Function.prototype.construct = function(aArgs) { + var fConstructor = this, fNewConstr = function() { + fConstructor.apply(this, aArgs); + }; + fNewConstr.prototype = fConstructor.prototype; + return new fNewConstr(); +};</code></pre> + +<p>{{jsxref("Function")}} 생성자 사용</p> + +<pre><code>Function.prototype.construct = function (aArgs) { + var fNewConstr = new Function(""); + fNewConstr.prototype = this.prototype; + var oNew = new fNewConstr(); + this.apply(oNew, aArgs); + return oNew; +};</code></pre> +</div> + +<p>사용 예제</p> + +<pre><code>function MyConstructor() { + for (var nProp = 0; nProp < arguments.length; nProp++) { + this['property' + nProp] = arguments[nProp]; + } +} + +var myArray = [4, 'Hello world!', false]; +var myInstance = MyConstructor.construct(myArray); + +console.log(myInstance.property1); // logs 'Hello world!' +console.log(myInstance instanceof MyConstructor); // logs 'true' +console.log(myInstance.constructor); // logs 'MyConstructor'</code></pre> + +<p><strong>알림:</strong> 네이티브가 아닌 <code>Function.construct</code> 메소드는 {{jsxref("Date")}} 와 같은 일부 네이티브 생성자와 동작하지 않을 것입니다. 그런 경우, {{jsxref("Function.prototype.bind")}} 메소드를 사용해야 합니다. 예를 들어, 다음과 같은 배열이 있다고 할 때, {{jsxref("Global_Objects/Date", "Date")}} 생성자: <code>[2012, 11, 4]</code> 와 함께 사용되려면 다음과 같이 작성해야 합니다: <code>new (Function.prototype.bind.apply(Date, [null].concat([2012, 11, 4])))()</code>. 이는 가장 좋은 방법이 아니며, 어떤 상용 환경에서도 사용되지 않을 수 있습니다.</p> + + + +<h2 id="명세">명세</h2> + +<table> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">코멘트</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>초기 정의. JavaScript 1.3 에 구현됨.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.3.4.3', 'Function.prototype.apply')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-function.prototype.apply', 'Function.prototype.apply')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-function.prototype.apply', 'Function.prototype.apply')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<div class="hidden"> +<p>The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> +</div> + +<p>{{Compat("javascript.builtins.Function.apply")}}</p> + + + +<h2 id="함께_보기">함께 보기</h2> + +<ul> + <li>{{jsxref("Functions/arguments", "arguments")}} 객체</li> + <li>{{jsxref("Function.prototype.bind()")}}</li> + <li>{{jsxref("Function.prototype.call()")}}</li> + <li>{{jsxref("Functions", "Functions and function scope", "", 1)}}</li> + <li>{{jsxref("Reflect.apply()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/function/arguments/index.html b/files/ko/web/javascript/reference/global_objects/function/arguments/index.html new file mode 100644 index 0000000000..9a498f2468 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/function/arguments/index.html @@ -0,0 +1,60 @@ +--- +title: Function.arguments +slug: Web/JavaScript/Reference/Global_Objects/Function/arguments +translation_of: Web/JavaScript/Reference/Global_Objects/Function/arguments +--- +<div>{{JSRef}} {{deprecated_header}}</div> + +<p><code><strong><em>function</em>.arguments</strong></code> 속성은 함수로 부터 넘겨 받은 arguments에 해당하는 배열과 같은 객체이다. 간단하게 {{jsxref("Functions/arguments", "arguments")}}를 대신 사용하자. 이 속성은 strict mode에서 <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-addrestrictedfunctionproperties">꼬리 호출 최적화</a> 때문에 금지 된다.</p> + +<h2 id="설명">설명</h2> + +<p><code><em>function</em>.arguments</code> 문법은 deprecated 되었다. 함수 내 에서 사용 가능한 객체{{jsxref("Functions/arguments", "arguments")}}에 접근하는 추천되는 방법은 단순히 {{jsxref("Functions/arguments", "arguments")}}변수로 참조하는 것이다.</p> + +<p>반복문의 경우, 함수 <code>f</code> 가 여러번 호출 스택에 나타나면, <code>f.arguments</code>의 값은 함수의 가장 최근 호출 arguments를 나타낸다.</p> + +<p>arguments의 값은 함수 실행 과정에서 특별한 호출이 없다면 일반적으로 null 이다 (즉, 함수가 호출은 되었으나 반환되지 않음).</p> + +<h2 id="예제">예제</h2> + +<h3 id="arguments_object를_사용한_예시">arguments object를 사용한 예시</h3> + +<pre class="brush: js">function f(n) { g(n - 1); } + +function g(n) { + console.log('before: ' + g.arguments[0]); + if (n > 0) { f(n); } + console.log('after: ' + g.arguments[0]); +} + +f(2); + +console.log('returned: ' + g.arguments); + +// Output + +// before: 1 +// before: 0 +// after: 0 +// after: 1 +// returned: null +</pre> + +<h2 id="Specifications">Specifications</h2> + +<p><code><em>function</em>.arguments</code>는 표준이 아니다. ECMAScript 3에서 {{jsxref("Functions/arguments", "arguments")}}를 참조하기 때문에 deprecated 되었다.</p> + +<h2 id="Browser_호환성">Browser 호환성</h2> + +<div> +<div class="hidden">이 페이지에 있는 호환성 테이블은 구조화된 데이터로 생성 되었습니다. 이 데이터에 기여를 하기 원하시면, 이 <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> 페이지를 확인 하시고 Pull Request를 보내주시기 바랍니다.</div> + +<p>{{Compat("javascript.builtins.Function.arguments")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Functions/arguments", "arguments")}} 객체</li> + <li>{{jsxref("Functions", "Functions and function scope", "", 1)}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/function/bind/index.html b/files/ko/web/javascript/reference/global_objects/function/bind/index.html new file mode 100644 index 0000000000..6a39852239 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/function/bind/index.html @@ -0,0 +1,296 @@ +--- +title: Function.prototype.bind() +slug: Web/JavaScript/Reference/Global_Objects/Function/bind +tags: + - ECMAScript 2015 + - Function + - JavaScript + - Method + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Function/bind +--- +<div>{{JSRef}}</div> + +<p><code><strong>bind()</strong></code> 메소드가 호출되면 새로운 함수를 생성합니다. 받게되는 첫 인자의 value로는 <code>this</code> 키워드를 설정하고, 이어지는 인자들은 바인드된 함수의 인수에 제공됩니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/function-bind.html", "taller")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>func</var>.bind(<var>thisArg</var>[, <var>arg1</var>[, <var>arg2</var>[, ...]]])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>thisArg</code></dt> + <dd>바인딩<span style="font-size: 13.3333px;"> </span>함수가 대상 함수(target function)의 <code>this</code>에 전달하는 값입니다. 바인딩 함수를 {{jsxref("Operators/new", "new")}} 연산자로 생성한 경우 무시됩니다. <code>bind</code>를 사용하여 <code>setTimeout</code> 내에 콜백 함수를 만들 때, <code>thisArg</code>로 전달된 원시 값은 객체로 변환됩니다. <code>bind</code>할 인수(argument)가 제공되지 않으면 실행 스코프 내의 <code>this</code>는 새로운 함수의 <code>thisArg</code>로 처리됩니다.</dd> + <dt><code>arg1, arg2, ...</code></dt> + <dd>대상 함수의 인수 앞에 사용될 인수.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>지정한 <code>this</code> 값 및 초기 인수를 사용하여 변경한 원본 함수의 복제본.</p> + +<h2 id="설명">설명</h2> + +<p><code>bind()</code> 함수는 새로운 바인딩한 함수를 만듭니다. 바인딩한 함수는 원본 함수 객체를 감싸는 함수로, ECMAScript 2015에서 말하는 특이 함수 객체<sup>exotic function object</sup>입니다. 바인딩한 함수를 호출하면 일반적으로 래핑된 함수가 호출 됩니다.</p> + +<p>바인딩한 함수는 다음과 같은 내부 속성을 가지고 있습니다.</p> + +<ul> + <li><code><strong>[[BoundTargetFunction]]</strong></code> - 바인딩으로 감싼(wrapped) 원본 함수 객체.</li> + <li><code><strong>[[BoundThis]]</strong></code> - 감싸진 함수를 호출했을 때 항상 전달되는 값.</li> + <li><code><strong>[[BoundArguments]]</strong></code> - 감싸진 함수가 호출될 때 첫 번째 인수로 사용되는 값들의 목록.</li> + <li><code><strong>[[Call]]</strong></code> - 이 객체와 관련된 코드 실행. 함수 호출 식을 통해 호출됨. 내부 메소드의 인수는 this 값 및 호출 식으로 함수에 전달되는 인수를 포함하는 목록입니다.</li> +</ul> + +<p>바인딩된 함수가 호출될 때 <code>[[BoundTargetFunction]]</code>의 내부 메소드 <code>[[Call]]</code>을 호출합니다. <code>[[Call]]</code> 은 <code>Call(<em>boundThis</em>, <em>args</em>)</code>와 같은 인자를 가집니다. 이 때, <code><em>boundThis</em></code>는 <code>[[BoundThis]]</code>이고, <code><em>args</em></code>는 함수가 호출될 때 전달되어 따라오는 <code>[[BoundArguments]]</code> 입니다.</p> + +<p>바인딩된 함수는 {{jsxref("Operators/new", "new")}} 연산자를 사용하여 생성될 수도 있습니다: 그렇게 하면 대상 함수가 마치 대신 생성된 것처럼 행동합니다. 제공된 <code>this</code> 값은 무시됩니다, 앞에 붙인(prepend) 인수는 에뮬레이트된 함수에 제공되지만.</p> + +<h2 id="예제">예제</h2> + +<h3 id="바인딩된_함수_생성">바인딩된 함수 생성</h3> + +<p><code>bind()</code>의 가장 간단한 사용법은 호출 방법과 관계없이 특정 <code>this</code> 값으로 호출되는 함수를 만드는 겁니다. 초보 JavaScript 프로그래머로서 흔한 실수는 객체로부터 메소드를 추출한 뒤 그 함수를 호출할때, 원본 객체가 그 함수의 <code>this</code>로 사용될 것이라 기대하는 겁니다(예시 : 콜백 기반 코드에서 해당 메소드 사용). 그러나 특별한 조치가 없으면, 대부분의 경우 원본 객체는 손실됩니다. 원본 객체가 바인딩 되는 함수를 생성하면, 이러한 문제를 깔끔하게 해결할 수 있습니다.</p> + +<pre class="brush: js">this.x = 9; +var module = { + x: 81, + getX: function() { return this.x; } +}; + +module.getX(); // 81 + +var retrieveX = module.getX; +retrieveX(); +// 9 반환 - 함수가 전역 스코프에서 호출됐음 + +// module과 바인딩된 'this'가 있는 새로운 함수 생성 +// 신입 프로그래머는 전역 변수 x와 +// module의 속성 x를 혼동할 수 있음 +var boundGetX = retrieveX.bind(module); +boundGetX(); // 81 +</pre> + +<h3 id="부분_적용_함수">부분 적용 함수</h3> + +<p><code>bind()</code>의 다음으로 간단한 사용법은 미리 지정된 초기 인수가 있는 함수를 만드는 겁니다. 지정될 초기 인수가 있다면 제공된 <code>this</code> 값을 따르고, 바인딩 된 함수에 전달되어 바인딩 된 함수가 호출될 때마다 대상 함수의 인수 앞에 삽입됩니다.</p> + +<pre><code>function list() { + return Array.prototype.slice.call(arguments); +} + +var list1 = list(1, 2, 3); // [1, 2, 3] + +// 선행될 인수를 설정하여 함수를 생성합니다. +var leadingThirtysevenList = list.bind(null, 37); + +var list2 = leadingThirtysevenList(); // [37] + +var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3] + + +function addArguments(arg1, arg2) { + return arg1 + arg2 +} + +var result1 = addArguments(1, 2); // 3 + +// 첫 번째 인수를 지정하여 함수를 생성합니다. +var addThirtySeven = addArguments.bind(null, 37); + +var result2 = addThirtySeven(5); // 37 + 5 = 42 + +// 두 번째 인수는 무시됩니다. +var result3 = addThirtySeven(5, 10); // 37 + 5 = 42</code> +</pre> + +<h3 id="setTimeout과_함께_사용"><code>setTimeout</code>과 함께 사용</h3> + +<p>{{domxref("window.setTimeout()")}} 내에서 기본으로, <code>this</code> 키워드는 {{ domxref("window") }} (또는 <code>global</code>) 객체로 설정됩니다. 클래스 인스턴스를 참조하는 <code>this</code>를 필요로 하는 클래스 메소드로 작업하는 경우, 명시해서 <code>this</code>를 콜백 함수에 바인딩할 수 있습니다, 인스턴스를 유지하기 위해.</p> + +<pre class="brush: js">function LateBloomer() { + this.petalCount = Math.ceil(Math.random() * 12) + 1; +} + +// 1초 지체 후 bloom 선언 +LateBloomer.prototype.bloom = function() { + window.setTimeout(this.declare.bind(this), 1000); +}; + +LateBloomer.prototype.declare = function() { + console.log('I am a beautiful flower with ' + + this.petalCount + ' petals!'); +}; + +var flower = new LateBloomer(); +flower.bloom(); +// 1초 뒤, 'declare' 메소드 유발</pre> + +<h3 id="생성자로_쓰이는_바인딩된_함수">생성자로 쓰이는 바인딩된 함수</h3> + +<div class="warning"> +<p><strong>경고:</strong> 이 부분은 JavaScript 능력을 보이고 <code>bind()</code> 메소드의 일부 극단 상황(edge case)을 기록합니다. 아래 보이는 메소드는 일을 하는 가장 좋은 방법은 아니며 아마도 상용 환경에서 전혀 사용되지 않을 겁니다.</p> +</div> + +<p>바인딩된 함수는 자동으로 대상 함수에 의해 생성되는 새로운 인스턴스를 생성하는 {{jsxref("Operators/new", "new")}} 연산자와 함께 쓰기에 적합합니다. 바인딩된 함수가 값을 생성하는 데 쓰이는 경우, 제공된 <code>this</code>는 무시됩니다. 그러나, 제공된 인수는 여전히 생성자 호출에 (인수부) 앞에 붙습니다:</p> + +<pre class="brush: js">function Point(x, y) { + this.x = x; + this.y = y; +} + +Point.prototype.toString = function() { + return this.x + ',' + this.y; +}; + +var p = new Point(1, 2); +p.toString(); // '1,2' + +// 아래 폴리필에서는 지원되지 않음, + +// 원 bind와는 잘 작동: + +var YAxisPoint = Point.bind(null, 0/*x*/); + + +var emptyObj = {}; +var YAxisPoint = Point.bind(emptyObj, 0/*x*/); + +var axisPoint = new YAxisPoint(5); +axisPoint.toString(); // '0,5' + +axisPoint instanceof Point; // true +axisPoint instanceof YAxisPoint; // true +new Point(17, 42) instanceof YAxisPoint; // true +</pre> + +<p>{{jsxref("Operators/new", "new")}}와 함께 쓰기 위한 바인딩된 함수를 만들기 위해 특별한 일을 할 필요가 없음을 주의하세요. 그 결과 분명히 호출되는 바인딩된 함수를 만들기 위해 특별히 아무것도 할 필요가 없습니다, 오히려 {{jsxref("Operators/new", "new")}}를 사용해서만 호출되는 바인딩된 함수를 요구하는 경우에도.</p> + +<pre class="brush: js">// 예는 JavaScript 콘솔에서 직접 실행될 수 있음 +// ...위에서부터 이어짐 + +// 여전히 일반 함수로서 호출될 수 있음 +// (보통 이를 원하지 않더라도) +YAxisPoint(13); + +emptyObj.x + ',' + emptyObj.y; +// > '0,13' +</pre> + +<p>오로지 {{jsxref("Operators/new", "new")}}를 사용하거나 호출해서만 바인딩된 함수의 사용을 지원하고 싶은 경우, 대상 함수는 그 제한을 강제해야 합니다.</p> + +<h3 id="바로_가기_생성">바로 가기 생성</h3> + +<p><code>bind()</code>는 특정 <code>this</code> 값을 필요로 하는 함수의 바로 가기(shortcut)를 만들고 싶은 경우에도 도움이 됩니다.</p> + +<p>가령, 배열 같은 객체를 실제 배열로 변환하는 데 사용하고 싶은 {{jsxref("Array.prototype.slice")}}를 취하세요. 이와 같은 바로 가기를 만들 수 있습니다:</p> + +<pre class="brush: js">var slice = Array.prototype.slice; + +// ... + +slice.apply(arguments); +</pre> + +<p><code>bind()</code>로, 이는 단순화될 수 있습니다. 다음 조각 코드에서, <code>slice</code>는 {{jsxref("Function.prototype")}}의 {{jsxref("Function.prototype.apply()", "apply()")}} 함수에 바인딩된 함수입니다, <code>this</code> 값을 {{jsxref("Array.prototype")}}의 {{jsxref("Array.prototype.slice()", "slice()")}} 함수로 설정한 채. 이는 추가 <code>apply()</code> 호출은 삭제될 수 있음을 뜻합니다:</p> + +<pre class="brush: js">// 이전 예에서 "slice"와 같음 +var unboundSlice = Array.prototype.slice; +var slice = Function.prototype.apply.bind(unboundSlice); + +// ... + +slice(arguments); +</pre> + +<h2 id="폴리필">폴리필</h2> + +<p><code>bind</code> 함수는 ECMA-262 제5판에 추가되었습니다; 그러하기에 모든 브라우저에 없을 수 있습니다. 스크립트 시작 부분에 다음 코드를 삽입함으로써 이 문제를 부분적으로 해결할수 있으며, bind() 지원하지 않는 구현에서도 대부분의 기능을 사용할 수 있습니다.</p> + +<pre class="brush: js">if (!Function.prototype.bind) { + Function.prototype.bind = function(oThis) { + if (typeof this !== 'function') { + // ECMAScript 5 내부 IsCallable 함수와 + // 가능한 가장 가까운 것 + throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable'); + } + + var aArgs = Array.prototype.slice.call(arguments, 1), + fToBind = this, + fNOP = function() {}, + fBound = function() { + return fToBind.apply(this instanceof fNOP + ? this + : oThis, + aArgs.concat(Array.prototype.slice.call(arguments))); + }; + + if (this.prototype) { + // Function.prototype은 prototype 속성이 없음 + fNOP.prototype = this.prototype; + } + fBound.prototype = new fNOP(); + + return fBound; + }; +} +</pre> + +<p>이 알고리즘과 스펙화된 알고리즘 간 많은 차이(충분히 다른 차이가 있을 수 있습니다, 이 목록은 정말 철저히 하지 않았기에) 중 일부는 다음입니다:</p> + +<ul> + <li>부분 구현은 {{jsxref("Array.prototype.slice()")}}, {{jsxref("Array.prototype.concat()")}}, {{jsxref("Function.prototype.call()")}} 및 {{jsxref("Function.prototype.apply()")}}, 원래 값을 갖는 내장 메소드에 의존합니다.</li> + <li>부분 구현은 불변(immutable) "poison pill" {{jsxref("Function.caller", "caller")}} 및 get, set 또는 삭제 시 {{jsxref("Global_Objects/TypeError", "TypeError")}}가 발생하는 <code>arguments</code> 속성이 없는 함수를 만듭니다. (이는 구현이 {{jsxref("Object.defineProperty")}}를 지원하는 경우 추가 또는 구현이 {{jsxref("Object.defineGetter", "__defineGetter__")}} 및 {{jsxref("Object.defineSetter", "__defineSetter__")}} 메소드를 지원하는 경우 [삭제 시 오류 발생(throw-on-delete) 동작(behavior) 없이] 부분 구현될 수 있습니다.)</li> + <li>부분 구현은 <code>prototype</code> 속성이 있는 함수를 만듭니다. (고유 바인딩된 함수는 없습니다.)</li> + <li>부분 구현은 {{jsxref("Function.length", "length")}} 속성이 ECMA-262에 의해 부여된(mandated) 그것과 일치하지 않는 바인딩된 함수를 만듭니다: 길이 0인 함수를 만듭니다, 반면에 전체 구현은 대상 함수의 길이 및 미리 지정된 인수의 수에 따라 0이 아닌 길이를 반환할 수 있습니다.</li> +</ul> + +<p>이 부분 구현을 쓰기로 고른 경우, <strong>동작이 ECMA-262 제5판을 벗어난 경우에 의존하지 않아야 합니다!</strong> 그러나 주의 약간(과 아마도 특정 요구에 맞추기 위한 추가 수정)으로, 이 부분 구현은 <code>bind()</code>가 스펙에 따라 널리 구현될 때까지 적당한 다리가 될 수 있습니다.</p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.3.4.5', 'Function.prototype.bind')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>초기 정의. JavaScript 1.8.5에서 구현됨.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-function.prototype.bind', 'Function.prototype.bind')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-function.prototype.bind', 'Function.prototype.bind')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div class="hidden"> +<p>The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> +</div> + +<p>{{Compat("javascript.builtins.Function.bind")}}</p> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("Function.prototype.apply()")}}</li> + <li>{{jsxref("Function.prototype.call()")}}</li> + <li>{{jsxref("Functions", "함수", "", 1)}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/function/call/index.html b/files/ko/web/javascript/reference/global_objects/function/call/index.html new file mode 100644 index 0000000000..a92a7ab931 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/function/call/index.html @@ -0,0 +1,197 @@ +--- +title: Function.prototype.call() +slug: Web/JavaScript/Reference/Global_Objects/Function/call +tags: + - Function + - JavaScript + - Method +translation_of: Web/JavaScript/Reference/Global_Objects/Function/call +--- +<div>{{JSRef}}</div> + +<p><code><strong>call()</strong></code> 메소드는 주어진 <code>this</code> 값 및 각각 전달된 인수와 함께 함수를 호출합니다.</p> + +<div class="blockIndicator note"> +<p><strong>주의:</strong> 이 함수 구문은 {{jsxref("Function.prototype.apply", "apply()")}}와 거의 동일하지만, <code>call()</code>은 <strong>인수 목록</strong>을, 반면에 <code>apply()</code>는 <strong>인수 배열 하나</strong>를 받는다는 점이 중요한 차이점입니다.</p> +</div> + +<p>{{EmbedInteractiveExample("pages/js/function-call.html")}}</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>func</var>.call(<var>thisArg</var>[, <var>arg1</var>[, <var>arg2</var>[, ...]]])</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>thisArg</code></dt> + <dd><em><code>func</code></em> 호출에 제공되는 <code>this</code>의 값.</dd> +</dl> + +<div class="blockIndicator note"> +<dl> + <dd></dd> + <dd> + <p><code>this</code>는 메소드에 의해 보이는 실제값이 아닐 수 있음을 주의하세요: 메소드가 {{jsxref("Functions_and_function_scope/Strict_mode", "비엄격 모드", "", 1)}} 코드 내 함수인 경우, {{jsxref("Global_Objects/null", "null")}} 및 {{jsxref("Global_Objects/undefined", "undefined")}}는 전역 객체로 대체되고 원시값은 객체로 변환됩니다.</p> + </dd> +</dl> +</div> + +<p><code>arg1, arg2, ...</code></p> + +<dl> + <dd>객체를 위한 인수.</dd> +</dl> + +<h3 id="반환값Return_Value">반환값(Return Value)</h3> + +<p><code>this</code> 와 arguments 를 매개로 호출된 함수의 반환값</p> + +<h2 id="설명">설명</h2> + +<p><code>call()</code>은 이미 할당되어있는 다른 객체의 함수/메소드를 호출하는 해당 객체에 재할당할때 사용됩니다. <code>this</code>는 현재 객체(호출하는 객체)를 참조합니다. 메소드를 한번 작성하면 새 객체를 위한 메소드를 재작성할 필요 없이 <code>call()</code>을 이용해 다른 객체에 상속할 수 있습니다.</p> + +<h2 id="예">예</h2> + +<h3 id="객체의_생성자_연결에_call_사용">객체의 생성자 연결에 <code>call</code> 사용</h3> + +<p>Java와 비슷하게, 객체의 생성자 연결(chain)에 <code>call</code>을 사용할 수 있습니다. 다음 예에서, <code>Product</code> 객체의 생성자는 <code>name</code> 및 <code>price</code> 를 매개변수로 정의됩니다. 다른 두 함수 <code>Food</code> 및 <code>Toy</code>는 <code>this</code> 및 <code>name</code>과 <code>price</code>를 전달하는 <code>Product</code>를 호출합니다. <code>Product</code>는 <code>name</code> 및 <code>price</code> 속성을 초기화하고, 특수한 두 함수(Food 및 Toy)는 <code>category</code>를 정의합니다.</p> + +<pre class="brush: js">function Product(name, price) { + this.name = name; + this.price = price; + + if (price < 0) { + throw RangeError('Cannot create product ' + + this.name + ' with a negative price'); + } +} + +function Food(name, price) { + Product.call(this, name, price); + this.category = 'food'; +} + +function Toy(name, price) { + Product.call(this, name, price); + this.category = 'toy'; +} + +var cheese = new Food('feta', 5); +var fun = new Toy('robot', 40); +</pre> + +<h3 id="익명_함수_호출에_call_사용">익명 함수 호출에 <code>call</code> 사용</h3> + +<p>이 예제에서는 익명 함수를 만들고 배열 내 모든 객체에서 이를 호출하기 위해 <code>call</code>을 사용합니다. 여기서 익명 함수의 주목적은 배열 내 객체의 정확한 인덱스를 출력할 수 있는 모든 객체에 print 함수를 추가하는 것 입니다.</p> + +<div class="blockIndicator note"> +<p><code>this</code> 값으로 객체 전달이 반드시 필요하지는 않지만, 해당 예제에서는 설명의 목적으로 사용했습니다. </p> +</div> + +<pre class="brush: js">var animals = [ + { species: 'Lion', name: 'King' }, + { species: 'Whale', name: 'Fail' } +]; + +for (var i = 0; i < animals.length; i++) { + (function(i) { + this.print = function() { + console.log('#' + i + ' ' + this.species + + ': ' + this.name); + } + this.print(); + }).call(animals[i], i); +} +</pre> + +<h3 id="함수_호출_및_this를_위한_문맥_지정에_call_사용">함수 호출 및 '<code>this</code>'를 위한 문맥 지정에 <code>call</code> 사용</h3> + +<p>아래 예제에서, <code>greet</code>을 호출하면 <code>this</code> 값은 객체 <code>obj</code>에 바인딩됩니다.</p> + +<pre class="brush: js">function greet() { + var reply = [this.animal, 'typically sleep between', this.sleepDuration].join(' '); + console.log(reply); +} + +var obj = { + animal: 'cats', sleepDuration: '12 and 16 hours' +}; + +greet.call(obj); // cats typically sleep between 12 and 16 hours +</pre> + +<h3 id="첫번째_인수_지정_없이_함수_호출에_call_사용">첫번째 인수 지정 없이 함수 호출에 <code>call</code> 사용</h3> + +<p>아래 예제에서, <code>display</code> 함수에 첫번째 인수를 전달하지 않고 호출합니다. 첫번째 인수를 전달하지 않으면, <code>this</code>의 값은 전역 객체에 바인딩됩니다.</p> + +<pre class="brush: js">var sData = 'Wisen'; +function display(){ + console.log('sData value is %s ', this.sData); +} + +display.call(); // sData value is Wisen +</pre> + +<div class="blockIndicator note"> +<p><strong> 주의:</strong> 엄격 모드(strict mode)에서, <code>this</code> 는 <code>undefined</code>값을 가집니다. See below.</p> +</div> + +<pre>'use strict'; + +var sData = 'Wisen'; + +function display() { + console.log('sData value is %s ', this.sData); +} + +display.call(); // Cannot read the property of 'sData' of undefined +</pre> + +<h2 id="스펙">스펙</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>초기 정의. JavaScript 1.3에서 구현됨.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.3.4.4', 'Function.prototype.call')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-function.prototype.call', 'Function.prototype.call')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-function.prototype.call', 'Function.prototype.call')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.Function.call")}}</p> + +<h2 id="참조">참조</h2> + +<ul> + <li> + <h2 id="jsxrefFunction.prototype.bind">{{jsxref("Function.prototype.bind()")}}</h2> + </li> + <li>{{jsxref("Function.prototype.apply()")}}</li> + <li> + <p><a href="/ko/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript">객체 지향 JavaScript 소개</a></p> + </li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/function/index.html b/files/ko/web/javascript/reference/global_objects/function/index.html new file mode 100644 index 0000000000..5d7dde941a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/function/index.html @@ -0,0 +1,167 @@ +--- +title: Function +slug: Web/JavaScript/Reference/Global_Objects/Function +tags: + - Constructor + - Function + - JavaScript +translation_of: Web/JavaScript/Reference/Global_Objects/Function +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary"><strong><code>Function</code> 생성자</strong>는 새 <code>Function</code> 객체를 만듭니다.</span> 이 생성자를 직접 호출하여 동적으로 함수를 생성할 수도 있으나, 보안 문제 및 {{jsxref("eval")}}과 유사한(그러나 훨씬 덜 심각한) 성능 문제가 발생할 수 있습니다. 하지만 <code>eval</code>과 달리, <code>Function</code> 생성자는 전역 범위로 한정된 함수만 생성합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/function-constructor.html")}}</div> + + + +<p>모든 JavaScript 함수는 사실 <code>Function</code> 객체입니다. 이는 <code>(function(){}).constructor === Function</code>이 참을 반환하는 것에서 알 수 있습니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code>new Function ([<var>arg1</var>[, <var>arg2</var>[, ...<var>argN</var>]],] <var>functionBody</var>)</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>arg1, arg2, ... arg<em>N</em></code></dt> + <dd>형식 인수 이름으로 사용할 이름. 각 이름은 유효한 JavaScript {{glossary("identifier", "식별자")}}거나, 쉼표로 구분한 유효한 식별자 목록이어야 합니다. 즉, "<code>x</code>", "<code>theValue</code>", "<code>x,theValue</code>"등의 값을 사용할 수 있습니다.</dd> + <dt><code>functionBody</code></dt> + <dd>함수 정의를 구성하는 JavaScript 문을 담은 문자열.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p><code>Function</code> 생성자로 생성한 <code>Function</code> 객체는 함수를 생성할 때 구문 분석을 수행합니다. 반면, {{jsxref("Operators/function", "함수 표현식", "", 1)}}이나 {{jsxref("Statements/function", "함수 선언문", "", 1)}}으로 함수를 정의하고 코드 내에서 호출한 경우 나머지 코드와 함께 구문 분석되므로, <code>Function</code> 생성자가 더 비효율적입니다.</p> + +<p>함수로 전달되는 모든 인수는 생성될 함수의 매개 변수 식별자 이름으로 전달되는 순서대로 처리됩니다.</p> + +<p>(<code>new</code> 연산자를 사용하지 않고) 함수로써 <code>Function</code> 생성자를 호출하는 것은 생성자로 호출하는 것과 같습니다. 하지만, new 연산자가 제거됨으로써 코드의 크기를 약간(4 바이트 더 작게) 줄일 수 있으므로 <code>Function</code>에 대해서는 <code>new</code> 연산자를 사용하지 않는 것이 좋습니다.</p> + +<h2 id="Function의_속성과_메서드"><code>Function</code>의 속성과 메서드</h2> + +<p>전역 <code>Function</code> 객체는 자신만의 메서드 또는 속성이 없습니다. 그러나, 그 자체로 함수이기에 {{jsxref("Function.prototype")}}에서 프로토타입 체인을 통해 일부 메서드 및 속성을 상속받습니다.</p> + +<h2 id="Function_프로토타입_객체"><code>Function</code> 프로토타입 객체</h2> + +<h3 id="속성">속성</h3> + +<div> +<dl> + <dt>{{jsxref("Function.arguments")}} {{deprecated_inline}}</dt> + <dd>함수에 전달되는 인수(argument)에 해당하는 배열. 이는 {{jsxref("Function")}}의 속성으로 사라지므로(deprecated), 대신 함수 내에서 이용 가능한 {{jsxref("Functions/arguments", "arguments")}} 객체를 사용하세요.</dd> + <dt><s class="obsoleteElement">{{jsxref("Function.arity")}} {{obsolete_inline}}</s></dt> + <dd><s class="obsoleteElement">함수에 의해 기대되는 인수의 수를 지정하기 위해 사용됐으나 제거되었습니다. 대신 {{jsxref("Function.length", "length")}} 속성을 사용하세요.</s></dd> + <dt>{{jsxref("Function.caller")}} {{non-standard_inline}}</dt> + <dd>현재 실행 중인 함수를 호출한 함수를 지정합니다.</dd> + <dt>{{jsxref("Function.length")}}</dt> + <dd>함수에 의해 기대되는 인수의 수를 지정합니다.</dd> + <dt>{{jsxref("Function.name")}}</dt> + <dd>함수명.</dd> + <dt>{{jsxref("Function.displayName")}} {{non-standard_inline}}</dt> + <dd>함수의 표시명.</dd> + <dt><code>Function.prototype.constructor</code></dt> + <dd>객체의 프로토타입을 만드는 함수를 지정합니다. 자세한 사항은 {{jsxref("Object.prototype.constructor")}} 참조.</dd> +</dl> +</div> + +<h3 id="메서드">메서드</h3> + +<div> +<dl> + <dt>{{jsxref("Function.prototype.apply()")}}</dt> + <dd>함수를 호출하고 <em>this</em>를 제공된 값으로 설정합니다, 인수는 {{jsxref("Array")}} 객체로 전달될 수 있습니다.</dd> + <dt>{{jsxref("Function.prototype.bind()")}}</dt> + <dd>호출될 때 <em>this</em>를 제공된 값으로 설정하는 새로운 함수를 만듭니다, 새로운 함수가 호출됐을 때 주어진 순서로 모두 제공되는 선행 인수와 함께.</dd> + <dt>{{jsxref("Function.prototype.call()")}}</dt> + <dd>함수를 호출(실행)하고 <em>this</em>를 제공된 값으로 설정합니다, 인수는 그대로 전달될 수 있습니다.</dd> + <dt>{{jsxref("Function.prototype.isGenerator()")}} {{non-standard_inline}}</dt> + <dd>함수가 <a href="/ko/docs/Web/JavaScript/Guide/Iterators_and_Generators" title="generator">생성기</a>인 경우 <code>true</code>를 반환합니다; 그렇지 않으면 <code>false</code>를 반환합니다.</dd> + <dt>{{jsxref("Function.prototype.toSource()")}} {{non-standard_inline}}</dt> + <dd>함수의 소스 코드를 나타내는 문자열을 반환합니다. {{jsxref("Object.prototype.toSource")}} 메서드를 재정의(override)합니다.</dd> + <dt>{{jsxref("Function.prototype.toString()")}}</dt> + <dd>함수의 소스 코드를 나타내는 문자열을 반환합니다. {{jsxref("Object.prototype.toString")}} 메서드를 재정의합니다.</dd> +</dl> +</div> + +<h2 id="Function_인스턴스"><code>Function</code> 인스턴스</h2> + +<p><code>Function</code> 인스턴스는 {{jsxref("Function.prototype")}}에서 메서드 및 속성을 상속받습니다. 모든 생성자와 마찬가지로, 생성자의 프로토타입 객체를 바꿈으로써 모든 <code>Function</code> 인스턴스에 변화를 줄 수 있습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="Function_생성자에_인수_지정하기"><code>Function</code> 생성자에 인수 지정하기</h3> + +<p>다음 코드는 인수 두 개를 갖는 <code>Function</code> 객체를 생성합니다.</p> + +<pre class="brush: js">// 예제는 JavaScript 콘솔에서 직접 실행하실 수 있습니다 + +// 두 개의 인수를 가지고 그 둘의 합을 반환하는 함수 생성 +var adder = new Function('a', 'b', 'return a + b'); + +// 함수 호출 +adder(2, 6); +// > 8 +</pre> + +<p>인수 "<code>a</code>" 및 "<code>b</code>"는 함수 몸통(body)의 "<code>return a + b</code>"에 사용되는 형식 인수명입니다.</p> + +<h3 id="Function_생성자와_함수_선언의_차이">Function 생성자와 함수 선언의 차이</h3> + +<p><code>Function</code> 생성자로 만들어지는 함수는 생성 컨텍스트에 대한 클로저(closure)를 생성하지 않습니다; 이들 함수는 항상 전역 범위에서 생성됩니다. 함수가 실행될 때, 자신의 지역 변수와 전역 변수에만 접근할 수 있으며 <code>Function</code> 생성자가 호출된 그 범위의 변수에는 접근할 수 없습니다. 이 점이 함수 표현식 코드에서 {{jsxref("eval")}}을 사용하는 것과 다른 점입니다.</p> + +<pre class="brush: js">var x = 10; + +function createFunction1() { + var x = 20; + return new Function('return x;'); // 여기서 |x|는 전역 범위에 있는 |x|를 참조함. +} + +function createFunction2() { + var x = 20; + function f() { + return x; // 여기서 |x|는 위의 지역에 있는 |x|를 참조함. + } + return f; +} + +var f1 = createFunction1(); +console.log(f1()); // 10 +var f2 = createFunction2(); +console.log(f2()); // 20 +</pre> + +<p>위 코드는 브라우저에서는 정상 동작하지만, {{glossary("Node.js")}}에서는 <code>x</code>를 찾을 수 없어, <code>f1()</code>이 <code>ReferenceError</code>를 생성합니다. 이는 Node.js의 최상위 스크립트 범위가 전역이 아닌 모듈이므로, <code>x</code>도 모듈 범위에 종속되기 때문입니다.</p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-function-objects', 'Function')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Function")}}</p> +</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Functions", "Functions and function scope")}}</li> + <li>{{jsxref("Statements/function", "function statement")}}</li> + <li>{{jsxref("Operators/function", "function expression")}}</li> + <li>{{jsxref("Statements/function*", "function* statement")}}</li> + <li>{{jsxref("Operators/function*", "function* expression")}}</li> + <li>{{jsxref("AsyncFunction")}}</li> + <li>{{jsxref("GeneratorFunction")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/function/length/index.html b/files/ko/web/javascript/reference/global_objects/function/length/index.html new file mode 100644 index 0000000000..f9e6b30adf --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/function/length/index.html @@ -0,0 +1,80 @@ +--- +title: Function.length +slug: Web/JavaScript/Reference/Global_Objects/Function/length +tags: + - Function + - JavaScript + - Property +translation_of: Web/JavaScript/Reference/Global_Objects/Function/length +--- +<div>{{JSRef}}</div> + +<p><code><strong>length</strong></code> 속성은 함수가 기대하는 인수의 수를 나타냅니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/function-length.html")}}</p> + +<div>{{js_property_attributes(0,0,1)}}</div> + +<h2 id="설명">설명</h2> + +<p><code>length</code>는 함수 객체의 속성으로, 함수가 얼마나 많은 인수를 기대하는지 나타냅니다, 즉 형식 매개변수의 수. 이 수는 {{jsxref("rest_parameters", "나머지 매개변수", "", 1)}}를 포함하지 않습니다. 그에 반해, {{jsxref("Functions/arguments/length", "arguments.length")}}는 함수에 지역(local)이고 실제로 함수에 전달된 인수의 수를 제공합니다.</p> + +<h3 id="Function_생성자의_데이터_속성"><code>Function</code> 생성자의 데이터 속성</h3> + +<p>{{jsxref("Function")}} 생성자는 그 자체로 {{jsxref("Function")}} 객체입니다. 그 <code>length</code> 데이터 속성은 값이 1입니다. 속성의 attribute: 쓰기가능(Writable): <code>false</code>, 열거가능(Enumerable): <code>false</code>, 설정가능(Configurable): <code>true</code>.</p> + +<h3 id="Function_프로토타입_객체의_속성"><code>Function</code> 프로토타입 객체의 속성</h3> + +<p>{{jsxref("Function")}} 프로토타입 객체의 length 속성은 값이 0입니다.</p> + +<h2 id="예제">예제</h2> + +<pre class="brush: js">console.log(Function.length); /* 1 */ + +console.log((function() {}).length); /* 0 */ +console.log((function(a) {}).length); /* 1 */ +console.log((function(a, b) {}).length); /* 2 등. */ +console.log((function(...args) {}).length); /* 0, 나머지 매개변수는 계산되지 않음 */ +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>초기 정의. JavaScript 1.1에서 구현됨.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.3.5.1', 'Function.length')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-function-instances-length', 'Function.length')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>이 속성의 설정가능(<code>configurable</code>) attribute은 이제 <code>true</code>임.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-function-instances-length', 'Function.length')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.Function.length")}}</p> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("Function")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/function/name/index.html b/files/ko/web/javascript/reference/global_objects/function/name/index.html new file mode 100644 index 0000000000..ce2d665b73 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/function/name/index.html @@ -0,0 +1,191 @@ +--- +title: Function.name +slug: Web/JavaScript/Reference/Global_Objects/Function/name +tags: + - ECMAScript6 + - Function + - JavaScript + - Property +translation_of: Web/JavaScript/Reference/Global_Objects/Function/name +--- +<div>{{JSRef}}</div> + +<p><code><strong><em>function</em>.name</strong></code> 속성(property)은 함수 이름을 반환합니다.</p> + +<div>{{js_property_attributes(0,0,1)}}</div> + +<p>비표준, ES6 이전 구현에서는 설정가능(<code>configurable</code>) attribute도 <code>false</code>였음을 주의하세요.</p> + +<h2 id="설명">설명</h2> + +<p><code>name</code> 속성은 함수 이름 또는 (ES6 구현 이전) 익명(anonymous) 함수에 대해서는 빈 문자열을 반환합니다:</p> + +<pre class="brush: js">function doSomething() {} + +console.log(doSomething.name); // logs "doSomething" +</pre> + +<p><code>new Function(...)</code> 또는 그냥 <code>Function(...)</code> 구문으로 생성된 함수는 <code>name</code> 속성을 빈 문자열로 설정합니다. 다음 예에서는 익명 함수가 생성되므로 <code>name</code>은 빈 문자열을 반환합니다:</p> + +<pre class="brush: js">var f = function() {}; +var object = { + someMethod: function() {} +}; + +console.log(f.name == ''); // true +console.log(object.someMethod.name == ''); // 역시 true +</pre> + +<p>ES6 함수를 구현한 브라우저는 익명 함수 이름을 그 구문상 위치로부터 추측할 수 있습니다. 예를 들어:</p> + +<pre class="brush: js">var f = function() {}; +console.log(f.name); // "f"</pre> + +<p>{{jsxref("Operators/Function", "function 식", "", 1)}}에서 이름으로 함수를 정의할 수 있습니다:</p> + +<pre class="brush: js">var object = { + someMethod: function object_someMethod() {} +}; +console.log(object.someMethod.name); // logs "object_someMethod" + +try { object_someMethod } catch(e) { console.log(e); } +// ReferenceError: object_someMethod가 정의되지 않음 +</pre> + +<p>함수 이름은 바꿀 수 없습니다, 이 속성은 읽기 전용입니다:</p> + +<pre class="brush: js">var object = { + // 익명 + someMethod: function() {} +}; + +object.someMethod.name = 'someMethod'; +console.log(object.someMethod.name); // 빈 문자열, someMethod는 익명 +</pre> + +<p>그러나 바꾸려면, {{jsxref("Object.defineProperty()")}}를 사용할 수 있습니다.</p> + +<h2 id="예">예</h2> + +<p>객체의 'class'를 확인하기 위해 <code>obj.constructor.name</code>을 사용할 수 있습니다:</p> + +<pre class="brush: js">function a() {} + +var b = new a(); + +console.log(b.constructor.name); // logs "a" +</pre> + +<h2 id="스펙">스펙</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-name', 'name')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-name', 'name')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(33.0)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Configurable: true</td> + <td>{{CompatChrome(43.0)}}</td> + <td>{{CompatGeckoDesktop(38)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Inferred names on anonymous functions</td> + <td>{{CompatChrome(51.0)}}</td> + <td>{{CompatNo}} [1]</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Configurable: true</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(38)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Inferred names on anonymous functions</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(51.0)}}</td> + <td>{{CompatNo}} [1]</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatChrome(51.0)}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] {{bug(883377)}} 참조.</p> diff --git a/files/ko/web/javascript/reference/global_objects/function/tosource/index.html b/files/ko/web/javascript/reference/global_objects/function/tosource/index.html new file mode 100644 index 0000000000..dcfbdf49e6 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/function/tosource/index.html @@ -0,0 +1,71 @@ +--- +title: Function.prototype.toSource() +slug: Web/JavaScript/Reference/Global_Objects/Function/toSource +tags: + - JavaScript + - 메소드 + - 함수 +translation_of: Web/JavaScript/Reference/Global_Objects/Function/toSource +--- +<div>{{JSRef}} {{non-standard_header}}</div> + +<p><code><strong>toSource()</strong></code> 메소드는 객체의 소스 코드를 나타내는 스트링을 반환합니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>function</var>.toSource(); +</pre> + +<h3 id="반환_값">반환 값</h3> + +<p>객체의 소스 코드를 나타내는 스트링.</p> + +<h2 id="설명">설명</h2> + +<p><code>toSource</code> 메소드는 다음 값들을 반환합니다.</p> + +<ul> + <li>내장 {{jsxref("Function")}} 객체에 대한 <code>toSource()</code> 는 소스 코드 사용이 불가함을 나타내는 다음 스트링을 반환합니다. + + <pre class="brush: js">function Function() { + [native code] +} +</pre> + </li> + <li>커스텀 함수에 대한 <code>toSource()</code> 는 객체를 정의하는 JavaScript 코드를 스트링으로 반환합니다.</li> + <li> + <pre class="brush: js">// 예시: +function hello() { + console.log("Hello, World!"); +} + +hello.toSource(); +</pre> + </li> + <li> + <pre class="brush: js">// 결과: +"function hello() { + console.log(\"Hello, World!\"); +}"</pre> + </li> +</ul> + +<p>이 메소드는 보통 JavaScript 에 의해 내부적으로 호출되며 코드에서 명시적으로 사용되지 않습니다. 디버깅할 때 객체의 컨텐츠를 검사하기 위해 <code>toSource</code> 를 호출해보실 수 있습니다.</p> + +<h2 id="명세">명세</h2> + +<p>어떠한 표준의 일부도 아닙니다. JavaScript 1.3 에서 구현되었습니다.</p> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Function.toSource")}}</p> +</div> + +<h2 id="함께_보기">함께 보기</h2> + +<ul> + <li>{{jsxref("Object.prototype.toSource()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/generator/index.html b/files/ko/web/javascript/reference/global_objects/generator/index.html new file mode 100644 index 0000000000..d29b282355 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/generator/index.html @@ -0,0 +1,186 @@ +--- +title: Generator +slug: Web/JavaScript/Reference/Global_Objects/Generator +tags: + - ECMAScript 2015 + - Generator + - JavaScript + - Legacy Generator + - Legacy Iterator + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Generator +--- +<div>{{JSRef}}</div> + +<p><code><strong>Generator</strong></code> 객체는 {{jsxref("Statements/function*", "generator function", "", 1)}} 으로부터 반환된 값이며 <a href="/en-US/docs/Web/JavaScript/Guide/The_Iterator_protocol">반복자와 반복자 프로토콜</a>을 준수합니다.</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox">function* gen() { + yield 1; + yield 2; + yield 3; +} + +var g = gen(); // "Generator { }"</pre> + +<h2 id="메서드">메서드</h2> + +<dl> + <dt>{{jsxref("Generator.prototype.next()")}}</dt> + <dd>{{jsxref("Operators/yield", "yield")}} 표현을 통해 yield된 값을 반환합니다.</dd> + <dt>{{jsxref("Generator.prototype.return()")}}</dt> + <dd>주어진 값을 반환하고 생성기를 종료합니다.</dd> + <dt>{{jsxref("Generator.prototype.throw()")}}</dt> + <dd>생성기로 에러를 throw합니다.</dd> +</dl> + +<h2 id="예시">예시</h2> + +<h3 id="무한_반복자">무한 반복자</h3> + +<pre class="brush: js">function* idMaker(){ + var index = 0; + while(true) + yield index++; +} + +var gen = idMaker(); // "Generator { }" + +console.log(gen.next().value); // 0 +console.log(gen.next().value); // 1 +console.log(gen.next().value); // 2 +// ...</pre> + +<h2 id="오래된_Generator_객체">오래된 Generator 객체</h2> + +<p>Firefox (SpiderMonkey)는 <a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/1.7">JavaScript 1.7</a>에서 이전 버전의 생성기도 구현 했습니다.이 버전에서는 함수 선언에서 별표 (*)가 필요하지 않습니다 (함수 본문에서 <code>yield</code> 키워드 만 사용). 그러나 오래된 생성기는 더 이상 사용되지 않습니다. 사용하지 마십시오. 곧 제거 될 것입니다 ({{bug(1083482)}}).</p> + +<h3 id="오래된_Generator_메서드들">오래된 Generator 메서드들</h3> + +<dl> + <dt><code>Generator.prototype.next() </code>{{non-standard_inline}}</dt> + <dd>{{jsxref("Operators/yield", "yield")}} 표현을 통해 yield된 값을 반환합니다. ES2015 Generator 객체의 <code>next()</code> 에 해당합니다.</dd> + <dt><code>Generator.prototype.close()</code> {{non-standard_inline}}</dt> + <dd>Generator를 닫고, <code>next()가 호출되면 </code>{{jsxref("StopIteration")}} 에러를 던집니다. ES2015 Generator 객체의 <code>return()</code> 에 해당합니다.</dd> + <dt><code>Generator.prototype.send()</code> {{non-standard_inline}}</dt> + <dd>Generator에 값을 전달하기 위해 사용 합니다. 이 값은 {{jsxref("Operators/yield", "yield")}} 표현식에서 반환되고, 다음 {{jsxref("Operators/yield", "yield")}} 표현식으로 부터 yield된 값을 반환합니다. <code>send(x)</code>는 ES2015 Generator 객체의 <code>next(x)에 해당합니다</code>.</dd> + <dt><strong><code>Generator.</code></strong><code>prototype.</code><strong><code>throw()</code> </strong> {{non-standard_inline}}</dt> + <dd>Generator 로 에러를 throw합니다. ES2015 Generator 객체의 <code>throw()</code> 에 해당합니다.</dd> +</dl> + +<h3 id="오래된_Generator_예제">오래된 Generator 예제</h3> + +<pre class="brush: js">function* fibonacci() { + var a = yield 1; + yield a * 2; +} + +var it = fibonacci(); +console.log(it); // "Generator { }" +console.log(it.next()); // 1 +console.log(it.send(10)); // 20 +console.log(it.close()); // undefined +console.log(it.next()); // throws StopIteration (as the generator is now closed)</pre> + +<h2 id="명세">명세</h2> + +<table class=" standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-generator-objects', 'Generator objects')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-generator-objects', 'Generator objects')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(39.0)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(39.0)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(39.0)}}</td> + </tr> + </tbody> +</table> +</div> + +<p> </p> + +<h2 id="같이_보기">같이 보기</h2> + +<h3 id="오래된_Generator">오래된 Generator</h3> + +<ul> + <li>{{jsxref("Statements/Legacy_generator_function", "The legacy generator function", "", 1)}}</li> + <li>{{jsxref("Operators/Legacy_generator_function", "The legacy generator function expression", "", 1)}}</li> + <li>{{jsxref("StopIteration")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features/The_legacy_Iterator_protocol">The legacy Iterator protocol</a></li> +</ul> + +<h3 id="ES2015_Generator">ES2015 Generator</h3> + +<ul> + <li>{{jsxref("Functions", "Functions", "", 1)}}</li> + <li>{{jsxref("Statements/function", "function")}}</li> + <li>{{jsxref("Operators/function", "function expression")}}</li> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("Statements/function*", "function*")}}</li> + <li>{{jsxref("Operators/function*", "function* expression")}}</li> + <li>{{jsxref("GeneratorFunction")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/The_Iterator_protocol">The Iterator protocol</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/generator/next/index.html b/files/ko/web/javascript/reference/global_objects/generator/next/index.html new file mode 100644 index 0000000000..7f041f9d9b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/generator/next/index.html @@ -0,0 +1,153 @@ +--- +title: Generator.prototype.next() +slug: Web/JavaScript/Reference/Global_Objects/Generator/next +translation_of: Web/JavaScript/Reference/Global_Objects/Generator/next +--- +<div>{{JSRef}}</div> + +<p> <code><strong>next</strong></code><strong><code>()</code></strong> 메소드는 <code>done</code>과 <code>value</code> <code>프로퍼티를 가진 객체를 반환한다</code>. 또한 <code><strong>next</strong></code><strong><code>()</code> </strong><code>메소드를 호출할 때 매개변수를 제공하여 그 값을 generator에 전달할 수 있다.</code></p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox"><code><var>gen</var>.next(value)</code></pre> + +<h3 id="매개_변수">매개 변수</h3> + +<dl> + <dt><code>value</code></dt> + <dd>Generator에 전달할 값</dd> +</dl> + +<h3 id="반환값">반환값</h3> + +<p>두 개의 프로퍼티를 가진 <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object">객체</a></code>:</p> + +<ul> + <li><code>done</code> (boolean) + + <ul> + <li>Iterator(반복자)가 마지막 반복 작업을 마쳤을 경우 <code>true</code>. 만약 iterator(반복자)에 <em>return 값</em>이 있다면 <code>value</code>의 값으로 지정된다.</li> + <li>Iterator(반복자)의 작업이 남아있을 경우 <code>false</code>. Iterator(반복자)에 <code>done</code> 프로퍼티 자체를 특정짓지 않은 것과 동일하다.</li> + </ul> + </li> + <li><code>value</code> - Iterator(반복자)으로부터 반환되는 모든 자바스크립트 값이며 <code>done</code>이 <code>true</code>일 경우 생략될 수 있다.</li> +</ul> + +<h2 id="예제">예제</h2> + +<h3 id="next()_사용하기"><code>next()</code> 사용하기</h3> + +<p>아래의 예시는 간단한 generator와 <code>next</code> 메소드를 통해서 반환되는 객체이다:</p> + +<pre class="brush: js">function* gen() { + yield 1; + yield 2; + yield 3; +} + +var g = gen(); // "Generator { }" +g.next(); // "Object { value: 1, done: false }" +g.next(); // "Object { value: 2, done: false }" +g.next(); // "Object { value: 3, done: false }" +g.next(); // "Object { value: undefined, done: true }" +</pre> + +<h3 id="Generator에_값_전달하기">Generator에 값 전달하기</h3> + +<p>이 예시에서는 <code>next</code>가 값과 함께 호출되었다. 첫 번째 호출이 아무것도 출력하지 않은 것은 Generator가 아직 아무런 값도 <code>yield</code> 하지않았기 때문이다. (두 번째 호출과 함께 전달된 정수 2는 Generator 내부의 <code>yield</code> 키워드에 전달되어 <code>value</code>로 할당되었고 <code>console.log</code>로 출력되었다)</p> + +<pre class="brush: js">function* gen() { + while(true) { + var value = yield null; + console.log(value); + } +} + +var g = gen(); +g.next(1); +// "{ value: null, done: false }" +g.next(2); +// "{ value: null, done: false }" +// 2 +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-generator.prototype.next', 'Generator.prototype.next')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-generator.prototype.next', 'Generator.prototype.next')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop(26)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(26)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/function*">function*</a></code></li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators">Iterators and generators</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/generator/return/index.html b/files/ko/web/javascript/reference/global_objects/generator/return/index.html new file mode 100644 index 0000000000..0c2f9b929d --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/generator/return/index.html @@ -0,0 +1,132 @@ +--- +title: Generator.prototype.return() +slug: Web/JavaScript/Reference/Global_Objects/Generator/return +translation_of: Web/JavaScript/Reference/Global_Objects/Generator/return +--- +<div>{{JSRef}}</div> + +<p><code><strong>return()</strong></code> 메소드는 제공된 값을 반환하고 Generator를 종료시킨다.</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox"><code><var>gen</var>.return(value)</code></pre> + +<h3 id="매개_변수">매개 변수</h3> + +<dl> + <dt><code>value</code></dt> + <dd>반환될 값.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>이 함수의 호출과 함께 주어진 인수 값을 반환한다.</p> + +<h2 id="예시">예시</h2> + +<h3 id="return()_사용"><code>return()</code> 사용</h3> + +<p>아래의 예시는 간단한 Generator와 <code>return</code> 메소드를 보여준다.</p> + +<pre class="brush: js">function* gen() { + yield 1; + yield 2; + yield 3; +} + +var g = gen(); + +g.next(); // { value: 1, done: false } +g.return("foo"); // { value: "foo", done: true } +g.next(); // { value: undefined, done: true } +</pre> + +<h2 id="참고사항">참고사항:</h2> + +<p>만약 <code>done</code>이 <code>true</code>이면 반환되는 객체의 <code>value</code> 프로퍼티의 값은 <code>undefined</code>이다. (<code>return</code>(값)은 <code>next</code>()와 동일)</p> + +<pre>function* gen() {yield 1;} +var g = gen(); +console.log(g.next());//{ value: 1, done: false } +console.log(g.next());//{ value: undefined, done: true } +console.log(g.return(1)); //{ value: undefined, done: true }</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-generator.prototype.return', 'Generator.prototype.return')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-generator.prototype.return', 'Generator.prototype.return')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop(38)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(38)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/function*">function*</a></code></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/generator/throw/index.html b/files/ko/web/javascript/reference/global_objects/generator/throw/index.html new file mode 100644 index 0000000000..534eefe0f6 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/generator/throw/index.html @@ -0,0 +1,99 @@ +--- +title: Generator.prototype.throw() +slug: Web/JavaScript/Reference/Global_Objects/Generator/throw +tags: + - ECMAScript 2015 + - Generator + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Generator/throw +--- +<div>{{JSRef}}</div> + +<p><code><strong>throw()</strong></code> 메서드는 Generator의 실행을 재개시키고 Generator 함수의 실행 문맥 속으로 error를 주입한다. <code>done</code>과 <code>value</code> 프로퍼티를 가진 객체를 반환한다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>gen</var>.throw(exception)</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>exception</code></dt> + <dd>Generator 함수의 실행 문맥 속으로 주입할 예외. 디버깅의 목적이라면 <code>instanceof</code> {{jsxref("Error")}} 인 것이 유용하다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>두 개의 프로퍼티를 가진 <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object">객체</a></code></p> + +<ul> + <li><code>done</code> (boolean) + + <ul> + <li>Iterator(반복자)가 마지막 반복 작업을 마쳤을 경우 <code>true</code>. 만약 iterator(반복자)에 <em>return 값</em>이 있다면 <code>value</code>의 값으로 지정된다.</li> + <li>Iterator(반복자)의 작업이 남아있을 경우 <code>false</code>. Iterator(반복자)에 <code>done</code> 프로퍼티 자체를 특정짓지 않은 것과 동일하다.</li> + </ul> + </li> + <li><code>value</code> - Iterator(반복자)으로부터 반환되는 모든 자바스크립트 값이며 <code>done</code>이 <code>true</code>일 경우 생략될 수 있다.</li> +</ul> + +<h2 id="예제">예제</h2> + +<h3 id="throw()_사용하기"><code>throw()</code> 사용하기</h3> + +<p>다음의 예시는 간단한 Generator 함수와 throw 메소드를 통해서 주입된 에러를 보여준다. 에러는 <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/try...catch">try...catch</a></code>블록을 통해서 핸들링 할 수 있다.</p> + +<pre class="brush: js">function* gen() { + while(true) { + try { + yield 42; + } catch(e) { + console.log("Error caught!"); + } + } +} + +var g = gen(); +g.next(); +// { value: 42, done: false } +g.throw(new Error("Something went wrong")); +// "Error caught!" +// { value: 42, done: false } +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-generator.prototype.throw', 'Generator.prototype.throw')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-generator.prototype.throw', 'Generator.prototype.throw')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Generator.throw")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><code><a href="/ko/docs/Web/JavaScript/Reference/Statements/function*">function*</a></code></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/generatorfunction/index.html b/files/ko/web/javascript/reference/global_objects/generatorfunction/index.html new file mode 100644 index 0000000000..73ee12769d --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/generatorfunction/index.html @@ -0,0 +1,112 @@ +--- +title: GeneratorFunction +slug: Web/JavaScript/Reference/Global_Objects/GeneratorFunction +tags: + - Constructor + - ECMAScript 2015 + - Iterator + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/GeneratorFunction +--- +<div>{{JSRef}}</div> + +<p><strong><code>GeneratorFunction</code> 생성자</strong>는 새로운 {{jsxref("Statements/function*", "generator function")}} 객체를 생성한다. JavaScript 에서 모든 generator function 은 실제로 <code>GeneratorFunction</code> object 이다.</p> + +<p>주의할 점은, <code>GeneratorFunction</code> 이 전역 객체(global object)가 아니란 점이다. GeneratorFunction은 다음의 코드를 실행해서 얻을 수 있다.</p> + +<pre class="brush: js">Object.getPrototypeOf(function*(){}).constructor +</pre> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code>new GeneratorFunction ([<var>arg1</var>[, <var>arg2</var>[, ...<var>argN</var>]],] <var>functionBody</var>)</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>arg1, arg2, ... arg<em>N</em></code></dt> + <dd>이 함수에서 공식적인 argument 이름들로 사용되는 이름들이다. 각각은 유효한 Javascript 식별자이거나 쉼표로 구분된 문자열 리스트에 해당되는 문자열이어야 한다; for example "<code>x</code>", "<code>theValue</code>", or "<code>a,b</code>".</dd> + <dt><code>functionBody</code></dt> + <dd>함수 정의를 구성하는 JavaScript 문이 포함된 문자열.</dd> +</dl> + +<h2 id="Description">Description</h2> + +<p><code>GeneratorFunction</code> 생성자로 생성된 {{jsxref("Statements/function*", "generator function")}} 객체는 그 함수가 생성될 때 분석한다. 이러한 함수들이 나머지 코드들과 함께 분석되기 때문에, {{jsxref("Statements/function*", "function* expression")}}으로 generator function을 선언하고 코드 내에서 호출하는 것보다 덜 효율적입니다.</p> + +<p>그 함수로 전달된 모든 arguments는 생성될 함수 안에서 파라미터의 식별자 이름으로 그것들이 전달된 순서대로 처리된다.</p> + +<div class="note"> +<p><strong>Note:</strong> {{jsxref("Statements/function*", "generator function")}} created with the <code>GeneratorFunction</code> constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the <code>GeneratorFunction</code> constructor was called. This is different from using {{jsxref("Global_Objects/eval", "eval")}} with code for a generator function expression.</p> +</div> + +<p>new 없이 <code>GeneratorFunction</code> 생성자를 함수처럼 사용하는 것은 생성자처럼 사용하는 것과 동일한 효과를 갖는다.</p> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt><code><strong>GeneratorFunction.length</strong></code></dt> + <dd><code>GeneratorFunction</code> 생성자의 length 속성으로 1 값을 갖는다.</dd> + <dt>{{jsxref("GeneratorFunction.prototype")}}</dt> + <dd>모든 generator function objects 에 속성의 추가를 허용한다.</dd> +</dl> + +<h2 id="GeneratorFunction_prototype_object"><code>GeneratorFunction</code> prototype object</h2> + +<h3 id="Properties_2">Properties</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/GeneratorFunction/prototype', 'Properties')}}</div> + +<h2 id="GeneratorFunction_instances"><code>GeneratorFunction</code> instances</h2> + +<p><code>GeneratorFunction</code> 인스턴스는 {{jsxref("GeneratorFunction.prototype")}} 으로부터 속성과 메서드를 상속한다. 다른 모든 생성자들처럼, 생성자의 prototype object 를 변경함으로써 모든 <code>GeneratorFunction</code> instance 에 변화를 줄 수 있다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="GeneratorFunction_생성자로_generator_function_생성하기">GeneratorFunction 생성자로 generator function 생성하기</h3> + +<pre class="brush: js">var GeneratorFunction = Object.getPrototypeOf(function*(){}).constructor +var g = new GeneratorFunction("a", "yield a * 2"); +var iterator = g(10); +console.log(iterator.next().value); // 20 +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-generatorfunction-objects', 'GeneratorFunction')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-generatorfunction-objects', 'GeneratorFunction')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.builtins.GeneratorFunction")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Statements/function*", "function* function")}}</li> + <li>{{jsxref("Operators/function*", "function* expression")}}</li> + <li>{{jsxref("Global_Objects/Function", "Function")}}</li> + <li>{{jsxref("Statements/function", "function statement")}}</li> + <li>{{jsxref("Operators/function", "function expression")}}</li> + <li>{{jsxref("Functions_and_function_scope", "Functions and function scope", "", 1)}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/globalthis/index.html b/files/ko/web/javascript/reference/global_objects/globalthis/index.html new file mode 100644 index 0000000000..df3323a00b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/globalthis/index.html @@ -0,0 +1,89 @@ +--- +title: globalThis +slug: Web/JavaScript/Reference/Global_Objects/globalThis +tags: + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/globalThis +--- +<div>{{jsSidebar("Objects")}}</div> + +<p>전역 <code><strong>globalThis</strong></code> 속성은 전역 <code>this</code> 값을 가진 전역 객체를 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/globalprops-globalthis.html")}}</div> + + + +<p>{{JS_Property_Attributes(1, 0, 1)}}</p> + +<h2 id="설명">설명</h2> + +<p>역사적으로, 서로 다른 JavaScript 환경의 전역 범위에 접근하는건 서로 다른 구문을 필요로 했습니다. 웹에서는 {{domxref("Window.window", "window")}}, {{domxref("Window.self", "self")}}, {{domxref("Window.frames", "frames")}}를 사용할 수 있지만, <a href="/ko/docs/Web/API/Worker">Web Workers</a>에서는 <code>self</code>만 동작합니다. Node.js에서는 아무것도 쓸 수 없고, 대신 <code>global</code>을 사용해야 합니다.<br> + 비엄격 모드에서의 함수 내부에서 <code>this</code>를 사용할 수도 있겠지만, 모듈이나 엄격 모드의 함수에서는 {{jsxref("undefined")}}를 가리키는 문제가 있습니다.<code> Function('return this')()</code>를 사용하는 방법도 존재하지만, 브라우저의 {{glossary("CSP")}} 등으로 {{jsxref("eval", "eval()")}}을 사용할 수 없는 환경에선 {{jsxref("Function")}}도 이렇게 사용할 수 없습니다.</p> + +<p><code>globalThis</code> 속성은 환경에 무관하게 전역 <code>this</code> 값, 즉 전역 객체에 접근하는 표준 방법을 제공합니다. <code>window</code>, <code>self</code> 등 비슷한 속성과는 다르게 브라우저/비 브라우저 맥락 모두에서의 동작을 보장합니다. 따라서 코드를 구동하는 환경을 모르더라도 전역 객체에 일관적으로 접근할 수 있습니다.</p> + +<h3 id="HTML과_WindowProxy">HTML과 WindowProxy</h3> + +<p>많은 JavaScript 엔진에서 <code>globalThis</code>는 실제 전역 객체를 가리킬 것이나, 웹 브라우저는 {{htmlelement("iframe")}}과 교차 창 보안 문제로 인하여 전역 객체를 감싼 {{jsxref("Proxy")}}를 대신 가리키고, 실제 객체에는 직접 접근할 수 없습니다. 일반적인 사용에는 차이가 없다고 봐도 무방하지만, 알아두는 것이 중요합니다.</p> + +<h3 id="이름">이름</h3> + +<p><code>self</code>와 <code>global</code>처럼, 다른 인기있던 제안은 기존 코드와의 호환성 문제를 우려해 제외됐습니다. <a href="https://github.com/tc39/proposal-global/blob/master/NAMING.md">언어 제안서의 "NAMING" 문서</a>를 방문해 더 자세한 정보를 읽어보세요.</p> + +<h2 id="예제">예제</h2> + +<h3 id="환경별_전역_접근">환경별 전역 접근</h3> + +<p><code>globalThis</code> 없이 현재 환경의 전역 객체를 가져오는 방법 중 유일하게 믿을만한 방법은 <code>Function('return this')()</code> 입니다. 그러나 일부 환경에서는 <a href="/ko/docs/Web/HTTP/CSP">CSP</a> 위반에 걸리는 코드이므로, <a href="https://github.com/paulmillr/es6-shim">es6-shim</a>은 대신 다음 검사를 수행합니다.</p> + +<pre class="brush: js notranslate">var getGlobal = function () { + if (typeof self !== 'undefined') { return self; } + if (typeof window !== 'undefined') { return window; } + if (typeof global !== 'undefined') { return global; } + throw new Error('unable to locate global object'); +}; + +var globals = getGlobal(); + +if (typeof globals.setTimeout !== 'function') { + // no setTimeout in this environment! +} +</pre> + +<p><code>globalThis</code>를 사용할 수 있으면 환경별 전역 객체 검사는 더 이상 필요하지 않습니다.</p> + +<pre class="brush: js notranslate">if (typeof globalThis.setTimeout !== 'function') { + // no setTimeout in this environment! +}</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName("ESDraft", "#sec-globalthis", "globalThis")}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.globalThis")}}</p> + +<h3 id="구현_진척도">구현 진척도</h3> + +<p>본 기능은 아직 안정적인 크로스 브라우징에 도달하지 못했으므로, 매일 업데이트되는 아래 표에서 브라우저별 구현 상황을 확인할 수 있습니다. 이 데이터는 각 브라우저 JavaScript 엔진의 나이틀리 빌드 또는 최신 릴리즈판에서, JavaScript 표준 테스트인 <a href="https://github.com/tc39/test262">Test262</a>의 관련 항목을 시험해 생성합니다.</p> + +<p>{{EmbedTest262ReportResultsTable("globalThis")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Operators/this", "this")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/index.html b/files/ko/web/javascript/reference/global_objects/index.html new file mode 100644 index 0000000000..b0741e8fe2 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/index.html @@ -0,0 +1,204 @@ +--- +title: 표준 내장 객체 +slug: Web/JavaScript/Reference/Global_Objects +tags: + - JavaScript + - Overview + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects +--- +<div>{{jsSidebar("Objects")}}</div> + +<p>이 장은 JavaScript의 모든 표준 내장 객체와 그 메서드 및 속성을 나열합니다.</p> + +<p>표준 내장 객체와 전역 객체를 헷갈리지 않도록 주의하세요. 표준 내장 객체는 <strong>전역 범위의 여러 객체</strong>를 일컫습니다. 전역 객체는 엄격 모드를 사용하지 않을 땐 전역 범위에서 {{jsxref("Operators/this", "this")}}, 지원하는 환경에선 {{jsxref("globalThis")}}를 사용해 접근할 수 있는 객체입니다. 사실 전역 범위는 <strong>전역 객체와 전역 객체가 상속한 속성</strong>으로 이루어집니다.</p> + +<p>전역 범위의 나머지 객체는 <a href="/ko/docs/Web/JavaScript/Guide/Working_with_Objects#Creating_new_objects">사용자 스크립트가 생성</a>하거나, 호스트 응용 프로그램이 제공합니다. 브라우저 맥락에서 사용 가능한 호스트 객체는 <a href="/ko/docs/Web/API">API 참고서</a>에서 읽을 수 있습니다. <a href="/ko/docs/DOM/DOM_Reference">DOM</a> 및 코어 <a href="/ko/docs/Web/JavaScript">JavaScript</a>의 차이에 관한 자세한 정보는 <a href="/ko/docs/Web/JavaScript/JavaScript_technologies_overview">JavaScript 기술 개요</a>를 참고하세요.</p> + +<h2 id="항목별_표준_객체">항목별 표준 객체</h2> + +<h3 id="값_속성">값 속성</h3> + +<p>아래 전역 속성은 간단한 값을 반환하며 속성이나 메서드를 가지고 있지 않습니다.</p> + +<ul> + <li>{{jsxref("Infinity")}}</li> + <li>{{jsxref("NaN")}}</li> + <li>{{jsxref("undefined")}}</li> + <li>{{jsxref("null")}} 리터럴</li> + <li>{{jsxref("globalThis")}}</li> +</ul> + +<h3 id="함수_속성">함수 속성</h3> + +<p>객체에 붙지 않고 전역으로 호출하는 함수로, 반환 값을 호출자에게 바로 반환합니다.</p> + +<div class="twocolumns"> +<ul> + <li>{{JSxRef("Global_Objects/eval", "eval()")}}</li> + <li>{{Non-Standard_Inline}} {{JSxRef("Global_Objects/uneval", "uneval()")}} </li> + <li>{{JSxRef("Global_Objects/isFinite", "isFinite()")}}</li> + <li>{{JSxRef("Global_Objects/isNaN", "isNaN()")}}</li> + <li>{{JSxRef("Global_Objects/parseFloat", "parseFloat()")}}</li> + <li>{{JSxRef("Global_Objects/parseInt", "parseInt()")}}</li> + <li>{{JSxRef("Global_Objects/encodeURI", "encodeURI()")}}</li> + <li>{{JSxRef("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}</li> + <li>{{JSxRef("Global_Objects/decodeURI", "decodeURI()")}}</li> + <li>{{JSxRef("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}</li> + <li><strong>Deprecated</strong> + <ul> + <li>{{deprecated_inline}} {{JSxRef("Global_Objects/escape", "escape()")}} </li> + <li>{{deprecated_inline}} {{JSxRef("Global_Objects/unescape", "unescape()")}} </li> + </ul> + </li> +</ul> +</div> + +<h3 id="기초_객체">기초 객체</h3> + +<p>다른 모든 객체의 기반이 되는 기초이자 기본 객체입니다. 일반 객체, 함수, 오류를 나타내는 객체를 포함합니다.</p> + +<ul> + <li>{{jsxref("Object")}}</li> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("Boolean")}}</li> + <li>{{jsxref("Symbol")}}</li> +</ul> + +<h4 id="오류_객체">오류 객체</h4> + +<p>오류 객체는 기초 객체의 특별한 유형으로, 기본적인 {{jsxref("Error")}} 객체와 함께 특정 용도에 최적화된 오류 형태도 포함합니다.</p> + +<div class="twocolumns"> +<ul> + <li>{{JSxRef("Error")}}</li> + <li>{{Experimental_Inline}} {{JSxRef("AggregateError")}} </li> + <li>{{JSxRef("EvalError")}}</li> + <li>{{JSxRef("InternalError")}} </li> + <li>{{JSxRef("RangeError")}}</li> + <li>{{JSxRef("ReferenceError")}}</li> + <li>{{JSxRef("SyntaxError")}}</li> + <li>{{JSxRef("TypeError")}}</li> + <li>{{JSxRef("URIError")}}</li> +</ul> +</div> + +<h3 id="숫자_및_날짜">숫자 및 날짜</h3> + +<p>숫자, 날짜, 수학 계산을 나타내는 기본 객체입니다.</p> + +<ul> + <li>{{jsxref("Number")}}</li> + <li>{{jsxref("BigInt")}}</li> + <li>{{jsxref("Math")}}</li> + <li>{{jsxref("Date")}}</li> +</ul> + +<h3 id="텍스트_처리">텍스트 처리</h3> + +<p>문자열을 나타내는 객체로 문자열을 조작할 방법도 제공합니다.</p> + +<ul> + <li>{{jsxref("String")}}</li> + <li>{{jsxref("RegExp")}}</li> +</ul> + +<h3 id="인덱스_콜렉션">인덱스 콜렉션</h3> + +<p>인덱스 값으로 정렬된 데이터의 콜렉션을 나타냅니다. 배열(형식배열 포함)과 배열형 객체를 포함합니다.</p> + +<div class="twocolumns"> +<ul> + <li>{{JSxRef("Array")}}</li> + <li>{{JSxRef("Int8Array")}}</li> + <li>{{JSxRef("Uint8Array")}}</li> + <li>{{JSxRef("Uint8ClampedArray")}}</li> + <li>{{JSxRef("Int16Array")}}</li> + <li>{{JSxRef("Uint16Array")}}</li> + <li>{{JSxRef("Int32Array")}}</li> + <li>{{JSxRef("Uint32Array")}}</li> + <li>{{JSxRef("Float32Array")}}</li> + <li>{{JSxRef("Float64Array")}}</li> + <li>{{JSxRef("BigInt64Array")}}</li> + <li>{{JSxRef("BigUint64Array")}}</li> +</ul> +</div> + +<h3 id="키_콜렉션">키 콜렉션</h3> + +<p>키를 사용하는 콜렉션을 나타냅니다. {{jsxref("Map")}}, {{jsxref("Set")}} 등 순회 가능한 콜렉션은 요소를 삽입 순서대로 순회할 수 있습니다.</p> + +<ul> + <li>{{jsxref("Map")}}</li> + <li>{{jsxref("Set")}}</li> + <li>{{jsxref("WeakMap")}}</li> + <li>{{jsxref("WeakSet")}}</li> +</ul> + +<h3 id="구조화된_데이터">구조화된 데이터</h3> + +<p>구조화된 데이터 버퍼 및 JavaScript Object Notation(JSON)을 사용하여 작성한 데이터를 나타내고 상호작용합니다.</p> + +<ul> + <li>{{jsxref("ArrayBuffer")}}</li> + <li>{{jsxref("SharedArrayBuffer")}}</li> + <li>{{jsxref("Atomics")}}</li> + <li>{{jsxref("DataView")}}</li> + <li>{{jsxref("JSON")}}</li> +</ul> + +<h3 id="제어_추상화_객체">제어 추상화 객체</h3> + +<p>제어 추상화는 코드 구조화에 도움을 줍니다. 특히, 비동기 코드를 (예를 들어) 깊게 중첩된 콜백 함수 없이 작성할 수 있습니다.</p> + +<ul> + <li>{{jsxref("Promise")}}</li> + <li>{{jsxref("Generator")}}</li> + <li>{{jsxref("GeneratorFunction")}}</li> + <li>{{jsxref("AsyncFunction")}}</li> +</ul> + +<h3 id="리플렉션">리플렉션</h3> + +<ul> + <li>{{jsxref("Reflect")}}</li> + <li>{{jsxref("Proxy")}}</li> +</ul> + +<h3 id="국제화">국제화</h3> + +<p>ECMAScript 코어에 추가된 언어 구분 기능입니다.</p> + +<div class="twocolumns"> +<ul> + <li>{{JSxRef("Intl")}}</li> + <li>{{JSxRef("Global_Objects/Collator", "Intl.Collator")}}</li> + <li>{{JSxRef("Global_Objects/DateTimeFormat", "Intl.DateTimeFormat")}}</li> + <li>{{JSxRef("Global_Objects/ListFormat", "Intl.ListFormat")}}</li> + <li>{{JSxRef("Global_Objects/NumberFormat", "Intl.NumberFormat")}}</li> + <li>{{JSxRef("Global_Objects/PluralRules", "Intl.PluralRules")}}</li> + <li>{{JSxRef("Global_Objects/RelativeTimeFormat", "Intl.RelativeTimeFormat")}}</li> + <li>{{JSxRef("Global_Objects/Locale", "Intl.Locale")}}</li> +</ul> +</div> + +<h3 id="WebAssembly">WebAssembly</h3> + +<div class="twocolumns"> +<ul> + <li>{{JSxRef("WebAssembly")}}</li> + <li>{{JSxRef("WebAssembly.Module")}}</li> + <li>{{JSxRef("WebAssembly.Instance")}}</li> + <li>{{JSxRef("WebAssembly.Memory")}}</li> + <li>{{JSxRef("WebAssembly.Table")}}</li> + <li>{{JSxRef("WebAssembly.CompileError")}}</li> + <li>{{JSxRef("WebAssembly.LinkError")}}</li> + <li>{{JSxRef("WebAssembly.RuntimeError")}}</li> +</ul> +</div> + +<h3 id="기타">기타</h3> + +<ul> + <li>{{JSxRef("Functions/arguments", "arguments")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/infinity/index.html b/files/ko/web/javascript/reference/global_objects/infinity/index.html new file mode 100644 index 0000000000..6305621f65 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/infinity/index.html @@ -0,0 +1,65 @@ +--- +title: Infinity +slug: Web/JavaScript/Reference/Global_Objects/Infinity +tags: + - JavaScript + - Property + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Infinity +--- +<div>{{jsSidebar("Objects")}}</div> + +<p><code><strong>Infinity</strong></code> 전역 속성은 무한대를 나타내는 숫자값입니다.</p> + +<p>{{js_property_attributes(0,0,0)}}</p> + +<div>{{EmbedInteractiveExample("pages/js/globalprops-infinity.html")}}</div> + +<div class="hidden">The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</div> + +<h2 id="설명">설명</h2> + +<p><code>Infinity</code>는 전역 객체의 속성입니다. 즉, 전역 스코프의 변수입니다.</p> + +<p><code>Infinity</code>의 초기값은 {{jsxref("Number.POSITIVE_INFINITY")}}입니다. <code>Infinity</code>(양의 무한대)는 다른 어떤 수보다 더 큽니다.</p> + +<p>수학적인 무한대와는 일부 차이점이 있습니다. {{jsxref("Number.POSITIVE_INFINITY")}} 문서에서 더 알아보세요.</p> + +<p><code>Infinity</code>는 ECMAScript 5 명세에 따라 읽기 전용입니다.</p> + +<h2 id="예제">예제</h2> + +<pre class="brush: js notranslate">console.log(Infinity); /* Infinity */ +console.log(Infinity + 1); /* Infinity */ +console.log(Math.pow(10,1000)); /* Infinity */ +console.log(Math.log(0)); /* -Infinity */ +console.log(1 / Infinity); /* 0 */ +console.log(1 / 0); /* Infinity */ +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-value-properties-of-the-global-object-infinity', 'Infinity')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Infinity")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Number.NEGATIVE_INFINITY")}}</li> + <li>{{jsxref("Number.POSITIVE_INFINITY")}}</li> + <li>{{jsxref("Number.isFinite")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/internalerror/index.html b/files/ko/web/javascript/reference/global_objects/internalerror/index.html new file mode 100644 index 0000000000..e6e5769902 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/internalerror/index.html @@ -0,0 +1,120 @@ +--- +title: InternalError +slug: Web/JavaScript/Reference/Global_Objects/InternalError +translation_of: Web/JavaScript/Reference/Global_Objects/InternalError +--- +<div>{{JSRef}} {{non-standard_header}}</div> + +<p><strong><code>InternalError </code></strong>객체는 JavaScript 엔진 내부에서 발생한 에러를 나타냅니다. 예를 들면, <strong>"InternalError</strong>: too much recursion"라는 에러가 있으며, 이것은 "내부 에러: 너무 많은 재귀 호출" 상황이 발생했을 때 나타납니다. </p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">new InternalError([<var>message</var>[, <var>fileName</var>[, <var>lineNumber</var>]]])</pre> + +<h3 id="파라메터">파라메터</h3> + +<dl> + <dt><code>message</code></dt> + <dd>선택적 파라메터. 에러에 대한 설명.</dd> + <dt><code>fileName</code> {{non-standard_inline}}</dt> + <dd>선택적 파라메터. 예외(Exception)가 발생한 코드를 포함하고 있는 파일 명.</dd> + <dt><code>lineNumber</code> {{non-standard_inline}}</dt> + <dd>선택적 파라메터. 예외(Exception)이 발생한 코드의 라인 넘버.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p><code>InternalError</code> 는 JavaScript 엔진에서 내부 에러가 발생할 때마다 던져집니다.</p> + +<p>다음의 에러 예시 들의 경우는 일반적으로 어떤 값이 너무 큰 경우 입니다.</p> + +<ul> + <li>"too many switch cases", (swich case의 수가 너무 많음.)</li> + <li>"too many parentheses in regular expression", (정규표현식에 너무 많은 괄호가 있음.)</li> + <li>"array initializer too large", (배열 초기화 값이 너무 큼.)</li> + <li>"too much recursion". (너무 많은 재귀 호출.)</li> +</ul> + +<h2 id="속성">속성</h2> + +<dl> + <dt>{{jsxref("InternalError.prototype")}}</dt> + <dd><code>InternalError</code> 객체에 속성을 추가하도록 해줍니다.</dd> +</dl> + +<h2 id="메소드">메소드</h2> + +<p>전역(global)의 <code>InternalError</code> 는 고유의 함수를 가지고 있지 않지만, 몇 가지의 메소드를 프로토타입 체인으로부터 상속받습니다.</p> + +<h2 id="InternalError_인스턴스"><code>InternalError</code> 인스턴스</h2> + +<h3 id="속성_2">속성</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/InternalError/prototype', 'Properties')}}</div> + +<h3 id="메소드_2">메소드</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/InternalError/prototype', 'Methods')}}</div> + +<h2 id="스펙">스펙</h2> + +<p>Not part of any specifications.</p> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("Error")}}</li> + <li>{{jsxref("InternalError.prototype")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/internalerror/prototype/index.html b/files/ko/web/javascript/reference/global_objects/internalerror/prototype/index.html new file mode 100644 index 0000000000..e854c2073a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/internalerror/prototype/index.html @@ -0,0 +1,100 @@ +--- +title: InternalError.prototype +slug: Web/JavaScript/Reference/Global_Objects/InternalError/prototype +translation_of: Web/JavaScript/Reference/Global_Objects/InternalError +--- +<div>{{JSRef}} {{non-standard_header}}</div> + +<p><code><strong>InternalError.prototype </strong></code>속성은 {{jsxref("InternalError")}} 생성자의 프로토타입을 나타냅니다.</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="설명">설명</h2> + +<p>모든 {{jsxref("InternalError")}} 인스턴스는 <code>InternalError.prototype</code> 으로부터 상속받습니다. 프로토타입은 모든 인스턴스에 속성이나 메소드를 추가하거나 하는 데에 사용할 수 있습니다.</p> + +<h2 id="속성">속성</h2> + +<dl> + <dt><code>InternalError.prototype.constructor</code></dt> + <dd>인스턴스의 프로토타입을 생성하는 함수를 명시합니다. </dd> + <dt>{{jsxref("Error.prototype.message", "InternalError.prototype.message")}}</dt> + <dd>에러 메시지. {{jsxref("Error")}} 로부터 상속받습니다. </dd> + <dt>{{jsxref("Error.prototype.name", "InternalError.prototype.name")}}</dt> + <dd>에러명. {{jsxref("Error")}} 로부터 상속받습니다.</dd> + <dt>{{jsxref("Error.prototype.fileName", "InternalError.prototype.fileName")}}</dt> + <dd>에러를 발생시킨 파일의 경로. {{jsxref("Error")}} 로부터 상속받습니다.</dd> + <dt>{{jsxref("Error.prototype.lineNumber", "InternalError.prototype.lineNumber")}}</dt> + <dd>에러를 발생시킨 파일의 라인 넘버. {{jsxref("Error")}} 로부터 상속받습니다.</dd> + <dt>{{jsxref("Error.prototype.columnNumber", "InternalError.prototype.columnNumber")}}</dt> + <dd>에러를 발생 시킨 라인의 컬럼 넘버. {{jsxref("Error")}} 로부터 상속받습니다.</dd> + <dt>{{jsxref("Error.prototype.stack", "InternalError.prototype.stack")}}</dt> + <dd>스택 트레이스. {{jsxref("Error")}} 로부터 상속받습니다. </dd> +</dl> + +<h2 id="메소드">메소드</h2> + +<p>비록 {{jsxref("InternalError")}}의 프로토타입 객체는 고유의 메소드를 가지고 있지는 않습니다. 하지만, {{jsxref("InternalError")}} 인스턴스는 프로토타입 체인을 통해 몇 가지의 메소드를 상속 받습니다.</p> + +<h2 id="스펙">스펙</h2> + +<p>Not part of any specifications.</p> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("Error.prototype")}}</li> + <li>{{jsxref("Function.prototype")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/intl/datetimeformat/index.html b/files/ko/web/javascript/reference/global_objects/intl/datetimeformat/index.html new file mode 100644 index 0000000000..0758e1332b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/intl/datetimeformat/index.html @@ -0,0 +1,303 @@ +--- +title: Intl.DateTimeFormat +slug: Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat +tags: + - DateTimeFormat + - Internationalization + - Intl + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary"><strong><code>Intl.DateTimeFormat</code></strong>은 언어에 맞는 날짜 및 시간 서식을 지원하는 객체의 생성자입니다.</span> <code>dateStyle</code>과 <code>timeStyle</code> 옵션을 통해 날짜와 시간 형식을 빠르게 맞출 수 있고, 더 자세한 조정을 위한 다른 옵션도 존재합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/intl-datetimeformat.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">new Intl.DateTimeFormat([<var>locales</var>[, <var>options</var>]]) +Intl.DateTimeFormat.call(<var>this</var>[, <var>locales</var>[, <var>options</var>]])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>locales</code> {{optional_inline}}</dt> + <dd> + <p><a href="https://ko.wikipedia.org/wiki/IETF_%EC%96%B8%EC%96%B4_%ED%83%9C%EA%B7%B8">BCP 47</a> 언어 태그를 포함하는 문자열이나 문자열의 배열. 로케일 매개변수의 일반적인 형식 및 해석은 {{jsxref("Intl", "<code>Intl</code> 문서", "#Locale_identification_and_negotiation", 1)}}를 참고하세요. 다음의 유니코드 확장 키를 사용할 수 있습니다.</p> + + <dl> + <dt><code>nu</code></dt> + <dd>사용할 기수법. <code>"arab"</code>, <code>"arabext"</code>, <code>"bali"</code>, <code>"beng"</code>, <code>"deva"</code>, <code>"fullwide"</code>, <code>"gujr"</code>, <code>"guru"</code>, <code>"hanidec"</code>, <code>"khmr"</code>, <code>"knda"</code>, <code>"laoo"</code>, <code>"latn"</code>, <code>"limb"</code>, <code>"mlym"</code>, <code>"mong"</code>, <code>"mymr"</code>, <code>"orya"</code>, <code>"tamldec"</code>, <code>"telu"</code>, <code>"thai"</code>, <code>"tibt"</code> 등을 사용할 수 있습니다.</dd> + <dt><code>ca</code></dt> + <dd>역법. <code>"buddhist"</code>, <code>"chinese"</code>, <code>"coptic"</code>, <code>"ethioaa"</code>, <code>"ethiopic"</code>, <code>"gregory"</code>, <code>"hebrew"</code>, <code>"indian"</code>, <code>"islamic"</code>, <code>"islamicc"</code>, <code>"iso8601"</code>, <code>"japanese"</code>, <code>"persian"</code>, <code>"roc"</code> 등을 사용할 수 있습니다.</dd> + <dt><code>hc</code></dt> + <dd>시간 사이클. <code>"h11"</code>, <code>"h12"</code>, <code>"h23"</code>, <code>"h24"</code> 등을 사용할 수 있습니다.</dd> + </dl> + </dd> + <dt><code>options</code> {{optional_inline}}</dt> + <dd> + <p>다음 속성을 포함하는 객체.</p> + + <dl> + <dt><code>dateStyle</code></dt> + <dd><code>format()</code>을 호출했을 때 사용할 날짜 서식. 가능한 값은 다음을 포함합니다. + <ul> + <li><code>"full"</code></li> + <li><code>"long"</code></li> + <li><code>"medium"</code></li> + <li><code>"short"</code></li> + </ul> + </dd> + <dt><code>timeStyle</code></dt> + <dd><code>format()</code>을 호출했을 때 사용할 시간 서식. 가능한 값은 다음을 포함합니다. + <ul> + <li><code>"full"</code></li> + <li><code>"long"</code></li> + <li><code>"medium"</code></li> + <li><code>"short"</code></li> + </ul> + </dd> + <dt><code>localeMatcher</code></dt> + <dd>사용할 로케일 매칭 알고리즘. 가능한 값은 <code>"lookup"</code>과 <code>"best fit"</code>이고, 기본값은 <code>"best fit"</code>입니다. 자세한 정보는 {{jsxref("Intl", "<code>Intl</code> 문서", "#로케일_조정", 1)}}를 참고하세요.</dd> + <dt><code>timeZone</code></dt> + <dd>사용할 시간대. 구현체가 반드시 인식해야 하는 유일한 값은 <code>"UTC"</code>입니다. 기본값은 런타임의 기본 시간대입니다. 구현체에 따라 "<code>Asia/Shanghai</code>", "<code>Asia/Kolkata</code>", "<code>America/New_York</code>" 등 <a href="https://www.iana.org/time-zones">IANA 시간대 데이터베이스</a>의 시간대 이름을 인식할 수도 있습니다.</dd> + <dt><code>hour12</code></dt> + <dd>24시간제 대신 12시간제를 사용할지 여부. 가능한 값은 <code>true</code> 와 <code>false</code>이고, 기본값은 로케일에 따라 다릅니다. 이 옵션을 지정하면 <code>hc</code> 언어 태그와 <code>hourCycle</code> 옵션을 모두 무시합니다.</dd> + <dt><code>hourCycle</code></dt> + <dd>사용할 시간제. 가능한 값은 <code>"h11"</code>, <code>"h12"</code>, <code>"h23"</code>, <code>"h24"</code>입니다. 이 옵션을 지정하면 <code>hc</code> 언어 태그를 무시합니다. <code>hour12</code> 옵션을 지정한 경우 그 값이 우선순위를 가집니다.</dd> + <dt><code>formatMatcher</code></dt> + <dd>사용할 서식 매칭 알고리즘. 가능한 값은 <code>"basic"</code>과 <code>"best fit"</code>이고, 기본값은 <code>"best fit"</code>입니다. 아래의 단락에서 이 속성의 자세한 정보를 확인하세요.</dd> + </dl> + + <p>이후의 속성은 서식을 적용한 출력 결과가 사용할 날짜 및 시간 구성요소를 나타냅니다. 구현체는 적어도 아래의 부분집합을 지원해야 합니다.</p> + + <ul> + <li><code>weekday</code>, <code>year</code>, <code>month</code>, <code>day</code>, <code>hour</code>, <code>minute</code>, <code>second</code></li> + <li><code>weekday</code>, <code>year</code>, <code>month</code>, <code>day</code></li> + <li><code>year</code>, <code>month</code>, <code>day</code></li> + <li><code>year</code>, <code>month</code></li> + <li><code>month</code>, <code>day</code></li> + <li><code>hour</code>, <code>minute</code>, <code>second</code></li> + <li><code>hour</code>, <code>minute</code></li> + </ul> + + <p>구현체에 따라 다른 집합을 지원할 수도 있습니다. 서식 요청은 가능한 모든 부분집합 조합 중 최적으로 일치하는 집합으로 조정됩니다. 조정 알고리즘에는 <a href="http://www.ecma-international.org/ecma-402/1.0/#BasicFormatMatcher">명세에 완벽히 정의된 <code>basic</code> 알고리즘</a>과, 구현체에 따라 다른 <code>best-fit</code> 알고리즘 두 종류가 있으며 <code>formatMatcher</code> 속성의 값이 어느 쪽을 사용할지 결정합니다.</p> + + <dl> + <dt><code>weekday</code></dt> + <dd>요일. 가능한 값은 다음과 같습니다. + <ul> + <li>"<code>long</code>" (<code>금요일</code>, <code>Thursday</code> 등)</li> + <li>"<code>short</code>" (<code>(금)</code>, <code>Thu</code> 등)</li> + <li>"<code>narrow</code>" (<code>(금)</code>, <code>T</code> 등). 일부 로케일에서는 두 개의 요일이 같은 값을 스타일을 가질 수 있습니다. (예: <code>Thursday</code>와 <code>Tuesday</code> 둘 다 <code>T</code>)</li> + </ul> + </dd> + <dt><code>era</code></dt> + <dd>시대. 가능한 값은 다음과 같습니다. + <ul> + <li>"<code>long</code>" (<code>서기</code>, <code>Anno Domini</code> 등)</li> + <li>"<code>short</code>" (<code>AD</code> 등)</li> + <li>"<code>narrow</code>" (<code>A</code>, <code>AD</code> 등)</li> + </ul> + </dd> + <dt><code>year</code></dt> + <dd>연도. 가능한 값은 다음과 같습니다. + <ul> + <li>"<code>numeric</code>" (<code>2019년</code>, <code>2019</code> 등)</li> + <li>"<code>2-digit</code>" (<code>19년</code>, <code>19</code> 등)</li> + </ul> + </dd> + <dt><code>month</code></dt> + <dd>월. 가능한 값은 다음과 같습니다. + <ul> + <li>"<code>numeric</code>" (<code>3</code> 등)</li> + <li>"<code>2-digit</code>" (<code>03</code> 등)</li> + <li>"<code>long</code>" (<code>3월</code>, <code>March</code> 등)</li> + <li>"<code>short</code>" (<code>Mar</code> 등)</li> + <li>"<code>narrow</code>" (<code>M</code> 등). 일부 로케일에서는 두 개의 요일이 같은 값을 스타일을 가질 수 있습니다. (예: <code>March</code>와 <code>May</code> 둘 다 <code>M</code>)</li> + </ul> + </dd> + <dt><code>day</code></dt> + <dd>일. 가능한 값은 다음과 같습니다. + <ul> + <li>"<code>numeric</code>" (<code>1</code> 등)</li> + <li>"<code>2-digit</code>" (<code>01</code> 등)</li> + </ul> + </dd> + <dt><code>hour</code></dt> + <dd>시. 가능한 값은 <code>"numeric"</code>, <code>"2-digit"</code>입니다.</dd> + <dt><code>minute</code></dt> + <dd>분. 가능한 값은 <code>"numeric"</code>, <code>"2-digit"</code>입니다.</dd> + <dt><code>second</code></dt> + <dd>초. 가능한 값은 <code>"numeric"</code>, <code>"2-digit"</code>입니다.</dd> + <dt><code>timeZoneName</code></dt> + <dd>시간대 이름. 가능한 값은 다음과 같습니다. + <ul> + <li>"<code>long</code>" (<code>한국 표준시</code>, <code>British Summer Time</code>등)</li> + <li>"<code>short</code>" (<code>GMT+9</code> 등)</li> + </ul> + </dd> + </dl> + + <p class="noinclude">각 구성요소 속성의 기본값은 {{jsxref("undefined")}}입니다. 그러나 모든 속성이 {{jsxref("undefined")}}일 경우, <code>year</code>, <code>month</code>, <code>day</code>는 <code>"numeric"</code>으로 취급합니다.</p> + </dd> +</dl> + +<h2 id="설명">설명</h2> + +<h3 id="속성">속성</h3> + +<dl> + <dt>{{jsxref("DateTimeFormat.prototype", "Intl.DateTimeFormat.prototype")}}</dt> + <dd>모든 인스턴스에 속성을 추가할 수 있습니다.</dd> +</dl> + +<h3 id="메서드">메서드</h3> + +<dl> + <dt>{{jsxref("DateTimeFormat.supportedLocalesOf", "Intl.DateTimeFormat.supportedLocalesOf()")}}</dt> + <dd>주어진 로케일 목록 중, 런타임이 지원하는 항목을 배열로 반환합니다.</dd> +</dl> + +<h2 id="DateTimeFormat_인스턴스"><code>DateTimeFormat</code> 인스턴스</h2> + +<h3 id="속성_2">속성</h3> + +<p><code>DateTimeFormat</code> 인스턴스는 프로토타입의 다음 속성을 상속합니다.</p> + +<div>{{page('/ko/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/prototype', '속성')}}</div> + +<h3 id="메서드_2">메서드</h3> + +<p><code>DateTimeFormat</code> 인스턴스는 프로토타입의 다음 메서드를 상속합니다.</p> + +<div>{{page('/ko/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/prototype', '메서드')}}</div> + +<h2 id="예제">예제</h2> + +<h3 id="DateTimeFormat_사용하기"><code>DateTimeFormat</code> 사용하기</h3> + +<p>로케일을 지정하지 않고 사용하면 기본 로케일 및 기본 옵션 서식을 적용한 문자열을 반환합니다.</p> + +<pre class="brush: js">var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0)); + +// 매개변수 없이 toLocaleString() 호출한 결과는 +// 구현체, 기본 로케일, 기본 시간대에 다라 달라짐 +console.log(new Intl.DateTimeFormat().format(date)); +// → ko-KR 로케일(언어)와 Asia/Seoul 시간대(UTC+0900)에서 "2012. 12. 20." +</pre> + +<h3 id="locales_사용하기"><code>locales</code> 사용하기</h3> + +<p>다음 예제는 지역화된 숫자 서식의 예시를 보입니다. 어플리케이션의 사용자 인터페이스 언어에 맞는 서식을 적용하려면 <code>locales</code> 매개변수로 적절한 언어(와, 필요한 경우 대체 언어)를 제공하는걸 잊지 마세요.</p> + +<pre class="brush: js">var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0)); + +// 아래 결과는 모두 Asia/Seoul 시간대를 사용한 결과 (UTC+0900, 한국 표준시) + +// 한국어에서 날짜 표기는 연월일 순서 +console.log(new Intl.DateTimeFormat('ko-KR').format(date)); +// → "2012. 12. 20." + +// 미국 영어에서 날짜 표기는 월일년 순서 +console.log(new Intl.DateTimeFormat('en-US').format(date)); +// → "12/20/2012" + +// 영국 영어에서 날짜 표기는 일월년 순서 +console.log(new Intl.DateTimeFormat('en-GB').format(date)); +// → "20/12/2012" + +// 대부분의 아랍어 국가에서는 진짜 아라비아 숫자 사용 +console.log(new Intl.DateTimeFormat('ar-EG').format(date)); +// → "٢٠/١٢/٢٠١٢" + +// 일본어의 경우 어플리케이션에 연호를 사용해야 할 수도 있음 +// 2012년은 헤이세이 24년 +console.log(new Intl.DateTimeFormat('ja-JP-u-ca-japanese').format(date)); +// → "24/12/20" + +// 발리어와 같이 지원되지 않을 수도 있는 언어를 지정할 때는 +// 다음과 같이 대체 언어를 지정할 수 있음. 아래의 경우 대체 언어는 인도어 +console.log(new Intl.DateTimeFormat(['ban', 'id']).format(date)); +// → "20/12/2012" +</pre> + +<h3 id="options_사용하기"><code>options</code> 사용하기</h3> + +<p><code>options</code> 매개변수를 지정해 날짜와 시간 서식 결과를 원하는 형태로 바꿀 수 있습니다.</p> + +<pre class="brush: js">var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0)); + +// 긴 날짜 서식에 더해 요일 요청 +var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; +console.log(new Intl.DateTimeFormat('de-DE', options).format(date)); +// → "Donnerstag, 20. Dezember 2012" + +// 어플리케이션이 GMT를 사용해야 하고, 그 점을 명시해야 할 때 +options.timeZone = 'UTC'; +options.timeZoneName = 'short'; +console.log(new Intl.DateTimeFormat('en-US', options).format(date)); +// → "Thursday, December 20, 2012, GMT" + +// 좀 더 자세한 설정이 필요하면 +options = { + hour: 'numeric', minute: 'numeric', second: 'numeric', + timeZone: 'Australia/Sydney', + timeZoneName: 'short' +}; +console.log(new Intl.DateTimeFormat('en-AU', options).format(date)); +// → "2:00:00 pm AEDT" + +// 미국에서도 24시간제가 필요할 때 +options = { + year: 'numeric', month: 'numeric', day: 'numeric', + hour: 'numeric', minute: 'numeric', second: 'numeric', + hour12: false, + timeZone: 'America/Los_Angeles' +}; +console.log(new Intl.DateTimeFormat('en-US', options).format(date)); +// → "12/19/2012, 19:00:00" +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES Int 1.0', '#sec-12.1', 'Intl.DateTimeFormat')}}</td> + <td>{{Spec2('ES Int 1.0')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES Int 2.0', '#sec-12.1', 'Intl.DateTimeFormat')}}</td> + <td>{{Spec2('ES Int 2.0')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES Int Draft', '#datetimeformat-objects', 'Intl.DateTimeFormat')}}</td> + <td>{{Spec2('ES Int Draft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Intl.DateTimeFormat")}}</p> +</div> + +<h2 id="같이_보기">같이 보기</h2> + +<div>{{page('/ko/docs/Web/JavaScript/Reference/Global_Objects/Intl', '같이_보기')}}</div> diff --git a/files/ko/web/javascript/reference/global_objects/intl/datetimeformat/prototype/index.html b/files/ko/web/javascript/reference/global_objects/intl/datetimeformat/prototype/index.html new file mode 100644 index 0000000000..1990621642 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/intl/datetimeformat/prototype/index.html @@ -0,0 +1,86 @@ +--- +title: Intl.DateTimeFormat.prototype +slug: Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/prototype +tags: + - DateTimeFormat + - Internationalization + - Intl + - JavaScript + - Property + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat +--- +<div>{{JSRef}}</div> + +<p><strong><code>Intl.DateTimeFormat.prototype</code></strong> 속성은 {{jsxref("DateTimeFormat", "Intl.DateTimeFormat")}} 생성자의 프로토타입을 나타냅니다.</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="설명">설명</h2> + +<p><code>Intl.DateTimeFormat</code> 인스턴스에 대한 설명은 {{jsxref("DateTimeFormat")}} 문서를 참고하세요.</p> + +<p>{{jsxref("DateTimeFormat", "Intl.DateTimeFormat")}} 인스턴스는 <code>Intl.DateTimeFormat.prototype</code>을 상속합니다. 프로토타입 객체를 변경하면 모든 {{jsxref("DateTimeFormat", "Intl.DateTimeFormat")}} 인스턴스가 영향을 받습니다.</p> + +<h2 id="속성">속성</h2> + +<dl> + <dt><code>Intl.DateTimeFormat.prototype.constructor</code></dt> + <dd>{{jsxref("DateTimeFormat", "Intl.DateTimeFormat")}}에 대한 참조입니다.</dd> +</dl> + +<h2 id="메서드">메서드</h2> + +<dl> + <dt>{{jsxref("DateTimeFormat.format", "Intl.DateTimeFormat.prototype.format()")}}</dt> + <dd>주어진 날짜에 {{jsxref("DateTimeFormat")}} 객체의 로케일과 서식 설정을 적용해 반환합니다.</dd> +</dl> + +<dl> + <dt>{{jsxref("DateTimeFormat.formatToParts", "Intl.DateTimeFormat.prototype.formatToParts()")}}</dt> + <dd>서식을 적용한 날짜 문자열의 각 부분을 객체로 표현해서 {{jsxref("Array")}}로 반환합니다. 반환 값은 로케일별 커스텀 서식에 사용할 수 있습니다.</dd> + <dt>{{jsxref("DateTimeFormat.resolvedOptions", "Intl.DateTimeFormat.prototype.resolvedOptions()")}}</dt> + <dd>객체 인스턴스 생성 때 주어진 로케일과 서식 설정이 어떻게 반영되었나 나타내는 새로운 객체를 반환합니다.</dd> +</dl> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES Int 1.0', '#sec-12.2.1', 'Intl.DateTimeFormat.prototype')}}</td> + <td>{{Spec2('ES Int 1.0')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES Int 2.0', '#sec-12.2.1', 'Intl.DateTimeFormat.prototype')}}</td> + <td>{{Spec2('ES Int 2.0')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES Int Draft', '#sec-Intl.DateTimeFormat.prototype', 'Intl.DateTimeFormat.prototype')}}</td> + <td>{{Spec2('ES Int Draft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Intl.DateTimeFormat.prototype")}}</p> +</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("DateTimeFormat", "Intl.DateTimeFormat")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/intl/index.html b/files/ko/web/javascript/reference/global_objects/intl/index.html new file mode 100644 index 0000000000..569fb94b80 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/intl/index.html @@ -0,0 +1,134 @@ +--- +title: Intl +slug: Web/JavaScript/Reference/Global_Objects/Intl +tags: + - Internationalization + - Intl + - JavaScript + - Reference + - 국제화 +translation_of: Web/JavaScript/Reference/Global_Objects/Intl +--- +<div>{{JSRef}}</div> + +<p><strong><code>Intl</code></strong> 객체는 각 언어에 맞는 문자비교, 숫자, 시간, 날짜비교를 제공하는, ECMAScript 국제화 API를 위한 이름공간입니다. {{jsxref("Collator")}}, {{jsxref("NumberFormat")}}, {{jsxref("DateTimeFormat")}}는 <code>Intl</code> 객체의 속성을 위한 생성자입니다. 이 페이지는 일반적인 국제화의 기능을 수행하는 객체의 생성자들과 언어를 구분하는 함수들 뿐만 아니라 이러한 속성들에 대해서도 다루고 있습니다.</p> + +<h2 id="속성">속성</h2> + +<dl> + <dt>{{jsxref("Collator", "Intl.Collator")}}</dt> + <dd>콜레이터 생성자입니다. 콜레이터 객체는 각 언어에 맞는 문자열 비교를 가능하게 해줍니다.</dd> + <dt>{{jsxref("DateTimeFormat", "Intl.DateTimeFormat")}}</dt> + <dd>각 언어에 맞는 시간과 날짜 서식을 적용할 수 있는 객체의 생성자입니다.</dd> + <dt>{{jsxref("ListFormat", "Intl.ListFormat")}}</dt> + <dd>각 언어에 맞는 목록 서식을 적용할 수 있는 객체의 생성자입니다.</dd> + <dt>{{jsxref("NumberFormat", "Intl.NumberFormat")}}</dt> + <dd>각 언어에 맞는 숫자 서식을 적용할 수 있는 객체의 생성자입니다.</dd> + <dt>{{jsxref("PluralRules", "Intl.PluralRules")}}</dt> + <dd>각 언어에 맞는 복수형 규칙 및 단수 복수 구분 서식을 적용할 수 있는 객체의 생성자입니다.</dd> + <dt>{{jsxref("RelativeTimeFormat", "Intl.RelativeTimeFormat")}}</dt> + <dd>각 언어에 맞는 상대 시간 서식을 적용할 수 있는 객체의 생성자입니다.</dd> +</dl> + +<h2 id="메서드">메서드</h2> + +<dl> + <dt>{{jsxref("Intl.getCanonicalLocales()")}}</dt> + <dd>표준 로케일 이름 목록을 반환합니다.</dd> +</dl> + +<h2 id="로케일_식별과_조정">로케일 식별과 조정</h2> + +<p>The internationalization constructors as well as several language sensitive methods of other constructors (listed under {{anch("See_also", "See also")}}) use a common pattern for identifying locales and determing the one they will actually use: they all accept <code>locales</code> and <code>options</code> arguments, and negotiate the requested locale(s) against the locales they support using an algorithm specified in the <code>options.localeMatcher</code> property.</p> + +<h3 id="locales_매개변수"><code>locales</code> 매개변수</h3> + +<p>The <code>locales</code> argument must be either a string holding a <a href="http://tools.ietf.org/html/rfc5646">BCP 47 language tag</a>, or an array of such language tags. If the <code>locales</code> argument is not provided or is undefined, the runtime's default locale is used.</p> + +<p>A BCP 47 language tag identifies a language or locale (the difference between the two is fuzzy). In their most common form it can contain, in this order: a language code, a script code, and a country code, all separated by hyphens. Examples:</p> + +<ul> + <li><code>"hi"</code>: Hindi.</li> + <li><code>"de-AT"</code>: German as used in Austria.</li> + <li><code>"zh-Hans-CN"</code>: Chinese written in simplified characters as used in China.</li> +</ul> + +<p>The subtags identifying languages, scripts, countries (regions), and (rarely used) variants in BCP 47 language tags can be found in the <a href="http://www.iana.org/assignments/language-subtag-registry">IANA Language Subtag Registry</a>.</p> + +<p>BCP 47 also allows for extensions, and one of them matters to the JavaScript internationalization functions: the <code>"u"</code> (Unicode) extension. It can be used to request a customization of the locale-specific behavior of a {{jsxref("Collator")}}, {{jsxref("NumberFormat")}}, or {{jsxref("DateTimeFormat")}} object. Examples:</p> + +<ul> + <li><code>"de-DE-u-co-phonebk"</code>: Use the phonebook variant of the German sort order, which expands umlauted vowels to character pairs: ä → ae, ö → oe, ü → ue.</li> + <li><code>"th-TH-u-nu-thai"</code>: Use Thai digits (๐, ๑, ๒, ๓, ๔, ๕, ๖, ๗, ๘, ๙) in number formatting.</li> + <li><code>"ja-JP-u-ca-japanese"</code>: Use the Japanese calendar in date and time formatting, so that 2013 is expressed as the year 25 of the Heisei period, or 平成25.</li> +</ul> + +<h3 id="로케일_조정">로케일 조정</h3> + +<p>The <code>locales</code> argument, after stripping off all Unicode extensions, is interpreted as a prioritized request from the application. The runtime compares it against the locales it has available and picks the best one available. Two matching algorithms exist: the <code>"lookup"</code> matcher follows the Lookup algorithm specified in <a href="http://tools.ietf.org/html/rfc4647#section-3.4">BCP 47</a>; the <code>"best fit"</code> matcher lets the runtime provide a locale that's at least, but possibly more, suited for the request than the result of the Lookup algorithm. If the application doesn't provide a <code>locales</code> argument, or the runtime doesn't have a locale that matches the request, then the runtime's default locale is used. The matcher can be selected using a property of the <code>options</code> argument (see below).</p> + +<p>If the selected language tag had a Unicode extension substring, that extension is now used to customize the constructed object or the behavior of the function. Each constructor or function supports only a subset of the keys defined for the Unicode extension, and the supported values often depend on the language tag. For example, the <code>"co"</code> key (collation) is only supported by {{jsxref("Collator")}}, and its <code>"phonebk"</code> value is only supported for German.</p> + +<h3 id="options_매개변수"><code>options</code> 매개변수</h3> + +<p>The <code>options</code> argument must be an object with properties that vary between constructors and functions. If the <code>options</code> argument is not provided or is undefined, default values are used for all properties.</p> + +<p>One property is supported by all language sensitive constructors and functions: The <code>localeMatcher</code> property, whose value must be a string <code>"lookup"</code> or <code>"best fit"</code> and which selects one of the locale matching algorithms described above.</p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES Int 1.0', '#sec-8', 'Intl')}}</td> + <td>{{Spec2('ES Int 1.0')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES Int 2.0', '#sec-8', 'Intl')}}</td> + <td>{{Spec2('ES Int 2.0')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES Int Draft', '#intl-object', 'Intl')}}</td> + <td>{{Spec2('ES Int Draft')}}</td> + <td>Added Intl.getCanonicalLocales in the 4th edition.</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Intl")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>소개글: <a href="http://norbertlindenberg.com/2012/12/ecmascript-internationalization-api/index.html">The ECMAScript Internationalization API</a></li> + <li>생성자 + <ul> + <li>{{jsxref("Collator", "Intl.Collator")}}</li> + <li>{{jsxref("DateTimeFormat", "Intl.DateTimeFormat")}}</li> + <li>{{jsxref("ListFormat", "Intl.ListFormat")}}</li> + <li>{{jsxref("NumberFormat", "Intl.NumberFormat")}}</li> + <li>{{jsxref("PluralRules", "Intl.PluralRules")}}</li> + <li>{{jsxref("RelativeTimeFormat", "Intl.RelativeTimeFormat")}}</li> + </ul> + </li> + <li>메서드 + <ul> + <li>{{jsxref("String.prototype.localeCompare()")}}</li> + <li>{{jsxref("Number.prototype.toLocaleString()")}}</li> + <li>{{jsxref("Date.prototype.toLocaleString()")}}</li> + <li>{{jsxref("Date.prototype.toLocaleDateString()")}}</li> + <li>{{jsxref("Date.prototype.toLocaleTimeString()")}}</li> + </ul> + </li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/intl/locale/index.html b/files/ko/web/javascript/reference/global_objects/intl/locale/index.html new file mode 100644 index 0000000000..a768a8bb5d --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/intl/locale/index.html @@ -0,0 +1,77 @@ +--- +title: Intl.Locale +slug: Web/JavaScript/Reference/Global_Objects/Intl/Locale +tags: + - Internationalization + - Intl + - JavaScript + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Intl/Locale +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary">The <strong><code>Intl.Locale</code></strong> constructor is a standard built-in property of the Intl object that represents a Unicode locale identifier.</span></p> + +<p>{{EmbedInteractiveExample("pages/js/intl-locale.html")}}</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">new Intl.Locale(<var>tag</var> [, <var>options</var>])</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>tag</code></dt> + <dd>The Unicode locale identifier string.</dd> + <dt><code>options</code></dt> + <dd>An object that contains configuration for the Locale. Keys are Unicode locale tags, values are valid Unicode tag values.</dd> +</dl> + +<h2 id="Description">Description</h2> + +<p>The <code><strong>Intl.Locale</strong></code> object was created to allow for easier manipulation of Unicode locales. Unicode represents locales with a string, called a <em>locale identifier</em>. The locale identifier consists of a <em>language identifier</em> and <em>extension tags</em>. Language identifiers are the core of the locale, consisting of <em>language</em>, <em>script</em>, and <em>region subtags</em>. Additional information about the locale is stored in the optional <em>extension tags</em>. Extension tags hold information about locale aspects such as calendar type, clock type, and numbering system type.</p> + +<p>Traditionally, the Intl API used strings to represent locales, just as Unicode does. This is a simple and lightweight solution that works well. Adding a Locale class, however, adds ease of parsing and manipulating the language, script, and region, as well as extension tags.</p> + +<p><span style="">The Intl.Locale object has the following properties and methods:</span></p> + +<h3 id="Properties">Properties</h3> + +<dl> + <dt>{{jsxref("Locale.prototype", "Intl.Locale.prototype")}}</dt> + <dd>The prototype object for the <code>Locale</code> constructor.</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td><a href="https://tc39.github.io/proposal-intl-locale/#locale-objects">Intl.Locale proposal</a></td> + <td>Stage 3</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Intl.Locale")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li> <a href="https://github.com/zbraniecki/Intl.js/tree/intllocale">The Intl.Locale Polyfill</a></li> + <li><a href="https://www.unicode.org/reports/tr35/#Canonical_Unicode_Locale_Identifiers">Unicode locale identifiers spec</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/intl/locale/language/index.html b/files/ko/web/javascript/reference/global_objects/intl/locale/language/index.html new file mode 100644 index 0000000000..195b2a06a0 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/intl/locale/language/index.html @@ -0,0 +1,62 @@ +--- +title: Intl.Locale.prototype.language +slug: Web/JavaScript/Reference/Global_Objects/Intl/Locale/language +translation_of: Web/JavaScript/Reference/Global_Objects/Intl/Locale/language +--- +<div>{{JSRef}}</div> + +<div></div> + +<p><span class="seoSummary"><strong><code>Intl.Locale.prototype.language</code></strong> 속성은 locale과 관련된 언어를 반환하는 접근자 속성입니다.</span></p> + +<h2 id="Description">Description</h2> + +<p>언어는 locale의 핵심 기능 중 하나입니다. 유니 코드 사양은 locale의 언어 식별자를 언어와 지역으로 함께 취급합니다 (예를 들어 영국 영어와 미국 영어 등의 방언과 변형을 구별하기 위해). {{jsxref("Locale", "Locale")}}의 language 속성은 로캘의 언어 하위 태그를 엄격하게 반환합니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="locale_식별자_문자열_인수에서_언어_설정">locale 식별자 문자열 인수에서 언어 설정</h3> + +<p>유효한 유니 코드 locale 식별자가 되려면 문자열이 언어 하위 태그로 시작해야합니다. {{jsxref("Locale", "Locale")}} 생성자에 대한 주요 인수는 유효한 유니 코드 locale 식별자여야하므로 생성자가 사용될 때마다 언어 하위 태그가있는 식별자를 전달해야합니다.</p> + +<pre class="brush: js">let langStr = new Intl.Locale("en-Latn-US"); + +console.log(langStr.language); // Prints "en"</pre> + +<h3 id="configuration_객체로_언어_오버라이딩_하기">configuration 객체로 언어 오버라이딩 하기</h3> + +<p>언어 하위 태그를 지정해야하지만 {{jsxref("Locale", "Locale")}} 생성자는 언어 하위 태그를 재정의 할 수있는 구성 개체를 사용합니다.</p> + +<pre class="brush: js">let langObj = new Intl.Locale("en-Latn-US", {language: "es"}); + +console.log(langObj.language); // Prints "es"</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td><a href="https://tc39.github.io/proposal-intl-locale/#sec-Intl.Locale.prototype.language">Intl.Locale.prototype.language proposal</a></td> + <td>Stage 3</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + +{{Compat("javascript.builtins.Intl.Locale.language")}}</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Locale", "Locale")}}</li> + <li><a href="https://www.unicode.org/reports/tr35/#unicode_language_subtag_validity">Unicode language subtag specification</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/intl/numberformat/index.html b/files/ko/web/javascript/reference/global_objects/intl/numberformat/index.html new file mode 100644 index 0000000000..6d306a0c77 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/intl/numberformat/index.html @@ -0,0 +1,198 @@ +--- +title: Intl.NumberFormat +slug: Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat +tags: + - Internationalization + - Intl + - JavaScript + - NumberFormat + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat +--- +<div>{{JSRef}}</div> + +<p><strong><code>Intl.NumberFormat</code></strong>은 언어에 맞는 숫자 서식을 지원하는 객체의 생성자입니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/intl-numberformat.html")}}</div> + +<p class="hidden">상호작용 가능한 예제의 소스는 GitHub 리포지토리에 보관되어 있습니다. 상호작용 예제 프로젝트에 기여하고 싶으시다면, <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a>를 클론한 후 풀 리퀘스트를 보내주세요.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">new Intl.NumberFormat([<var>locales</var>[, <var>options</var>]]) +Intl.NumberFormat.call(<var>this</var>[, <var>locales</var>[, <var>options</var>]]) +</pre> + +<h3 id="매개_변수">매개 변수</h3> + +<dl> + <dt><code>locales</code> {{optional_inline}}</dt> + <dd> + <p><a href="https://ko.wikipedia.org/wiki/IETF_%EC%96%B8%EC%96%B4_%ED%83%9C%EA%B7%B8">BCP 47</a> 언어 태그를 포함하는 문자열이나 문자열의 배열. 로케일 매개변수의 일반적인 형식 및 해석은 {{jsxref("Intl", "<code>Intl</code> 문서", "#Locale_identification_and_negotiation", 1)}}를 참고하세요. 다음의 Unicode 확장 키를 사용할 수 있습니다.</p> + + <dl> + <dt><code>nu</code></dt> + <dd>사용할 기수법. <code>"arab"</code>, <code>"arabext"</code>, <code>"bali"</code>, <code>"beng"</code>, <code>"deva"</code>, <code>"fullwide"</code>, <code>"gujr"</code>, <code>"guru"</code>, <code>"hanidec"</code>, <code>"khmr"</code>, <code>"knda"</code>, <code>"laoo"</code>, <code>"latn"</code>, <code>"limb"</code>, <code>"mlym"</code>, <code>"mong"</code>, <code>"mymr"</code>, <code>"orya"</code>, <code>"tamldec"</code>, <code>"telu"</code>, <code>"thai"</code>, <code>"tibt"</code> 등을 사용할 수 있습니다.</dd> + </dl> + </dd> + <dt><code>options</code> {{optional_inline}}</dt> + <dd> + <p>다음 속성을 포함하는 객체.</p> + + <dl> + <dt><code>localeMatcher</code></dt> + <dd>사용할 로케일 매칭 알고리즘. 가능한 값은 <code>"lookup"</code>과 <code>"best fit"</code>이고, 기본값은 <code>"best fit"</code>입니다. 자세한 정보는 {{jsxref("Intl", "<code>Intl</code> 문서", "#로케일_조정", 1)}}를 참고하세요.</dd> + <dt><code>style</code></dt> + <dd>사용할 서식 스타일. 가능한 값은 평문 숫자 <code>"decimal"</code>, 통화 서식 <code>"currency"</code>, 백분율 서식 <code>"percent"</code>입니다. 기본값은 <code>"decimal"</code>입니다.</dd> + <dt><code>currency</code></dt> + <dd>통화 서식에 사용할 통화입니다. 가능한 값은 <a href="https://ko.wikipedia.org/wiki/ISO_4217">ISO 4217 통화 코드</a>로 대한민국 원화 <code>"KRW"</code>, 미국 달러화 <code>"USD"</code>, 유럽 유로화 <code>"EUR"</code> 등을 포함합니다. <a href="http://www.currency-iso.org/en/home/tables/table-a1.html">현재 통화 및 펀드 코드 목록</a>을 참고하세요. 기본값은 없습니다. <code>style</code> 값을 <code>"currency"</code>로 지정했다면, <code>currency</code> 값도 반드시 지정해야 합니다.</dd> + <dt><code>currencyDisplay</code></dt> + <dd>통화 서식에서 통화를 표시하는 방법. 가능한 값은 €와 같이 현지 통화 기호를 사용하는 <code>"symbol"</code>, ISO 통화 코드를 사용하는 <code>"code"</code>, <code>"dollar"</code> 등 현지 통화 이름을 사용하는 <code>"name"</code>이 있습니다. 기본 값은 <code>"symbol"</code>입니다.</dd> + <dt><code>useGrouping</code></dt> + <dd>천 단위 구분자 혹은 천/라크/크로르 단위 구분자의 삽입 여부. 가능한 값은 <code>true</code>와 <code>false</code>입니다. 기본 값은 <code>true</code>입니다.</dd> + </dl> + + <p>아래 속성은 두 가지 그룹으로 나뉩니다. <code>minimumIntegerDigits</code>, <code>minimumFractionDigits</code>, <code>maximumFractionDigits</code>가 첫 번째 그룹이고, <code>minimumSignificantDigits</code>와 <code>maximumSignificantDigits</code>가 두 번째 그룹으로, 두 번째 그룹 중 하나라도 지정하면 첫 번째 그룹은 모두 무시합니다.</p> + + <dl> + <dt><code>minimumIntegerDigits</code></dt> + <dd>정수부의 최소 자릿수. 가능한 값은 1부터 21까지의 수로, 기본값은 1입니다.</dd> + <dt><code>minimumFractionDigits</code></dt> + <dd>소수부의 최소 자릿수. 가능한 값은 0부터 20까지의 수로, 평문 숫자와 백분율 서식의 기본값은 0입니다. 통화 서식의 기본값은 <a href="http://www.currency-iso.org/en/home/tables/table-a1.html">ISO 4217 통화 코드 목록</a>이 제공하는 보조 단위의 자릿수에 따라 다릅니다. (목록에 정보가 없을 경우 2)</dd> + <dt><code>maximumFractionDigits</code></dt> + <dd>소수부의 최대 자릿수. 가능한 값은 0부터 20까지의 수로, 평문 숫자 서식의 기본값은 <code>minimumFractionDigits</code>와 3 중 더 큰 값입니다. 통화 서식의 기본값은 <code>minimumFractionDigits</code>와, <a href="http://www.currency-iso.org/en/home/tables/table-a1.html">ISO 4217 통화 코드 목록</a>이 제공하는 보조 단위의 자릿수(목록에 정보가 없을 경우 2) 중 더 큰 값입니다. 백분율 서식의 기본값은 <code>minimumFractionDigits</code>와 0 중 더 큰 값입니다.</dd> + <dt><code>minimumSignificantDigits</code></dt> + <dd>유효숫자의 최소 수. 가능한 값은 1부터 21까지의 수로, 기본값은 1입니다.</dd> + <dt><code>maximumSignificantDigits</code></dt> + <dd>유효숫자의 최대 수. 가능한 값은 1부터 21까지의 수로, 기본값은 21입니다.</dd> + </dl> + </dd> +</dl> + +<h2 id="설명">설명</h2> + +<h3 id="속성">속성</h3> + +<dl> + <dt>{{jsxref("NumberFormat.prototype", "Intl.NumberFormat.prototype")}}</dt> + <dd>모든 인스턴스에 속성을 추가할 수 있습니다.</dd> +</dl> + +<h3 id="메서드">메서드</h3> + +<dl> + <dt>{{jsxref("NumberFormat.supportedLocalesOf", "Intl.NumberFormat.supportedLocalesOf()")}}</dt> + <dd>주어진 로케일 목록 중, 런타임이 지원하는 항목을 배열로 반환합니다.</dd> +</dl> + +<h2 id="NumberFormat_인스턴스"><code>NumberFormat</code> 인스턴스</h2> + +<h3 id="속성_2">속성</h3> + +<p><code>NumberFormat</code> 인스턴스는 프로토타입의 다음 속성을 상속합니다.</p> + +<div>{{page('/ko/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat/prototype', '속성')}}</div> + +<h3 id="메서드_2">메서드</h3> + +<p><code>NumberFormat</code> 인스턴스는 프로토타입의 다음 메서드를 상속합니다.</p> + +<div>{{page('/ko/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat/prototype', '메서드')}}</div> + +<h2 id="예제">예제</h2> + +<h3 id="기본적인_사용_방법">기본적인 사용 방법</h3> + +<p>로케일을 지정하지 않고 사용하면 기본 로케일 및 기본 옵션 서식을 적용한 문자열을 반환합니다.</p> + +<pre class="brush: js">var number = 3500; + +console.log(new Intl.NumberFormat().format(number)); +// → 한국 로케일의 경우 '3,500' 표시 +</pre> + +<h3 id="locales_사용하기"><code>locales</code> 사용하기</h3> + +<p>다음 예제는 지역화된 숫자 서식의 예시를 보입니다. 어플리케이션의 사용자 인터페이스 언어에 맞는 서식을 적용하려면 <code>locales</code> 매개변수로 적절한 언어(와, 필요한 경우 대체 언어)를 제공하는걸 잊지 마세요.</p> + +<pre class="brush: js">var number = 123456.789; + +// 독일은 소수점 구분자로 쉼표를 사용하고 천 단위 구분자로 마침표를 사용 +console.log(new Intl.NumberFormat('de-DE').format(number)); +// → 123.456,789 + +// 대부분의 아랍어 사용 국가에서는 실제 아라비아 숫자를 사용 +console.log(new Intl.NumberFormat('ar-EG').format(number)); +// → ١٢٣٤٥٦٫٧٨٩ + +// 인도는 천, 라크(십만), 크로르(천만) 단위에 구분자 사용 +console.log(new Intl.NumberFormat('en-IN').format(number)); +// → 1,23,456.789 + +// nu 확장 키로 기수법 지정 (아래 예시는 중국식 숫자 표기) +console.log(new Intl.NumberFormat('zh-Hans-CN-u-nu-hanidec').format(number)); +// → 一二三,四五六.七八九 + +// 발리어와 같이 지원되지 않을 수도 있는 언어를 지정할 때는 +// 다음과 같이 대체 언어를 지정할 수 있음. 아래의 경우 대체 언어는 인도어 +console.log(new Intl.NumberFormat(['ban', 'id']).format(number)); +// → 123.456,789 +</pre> + +<h3 id="options_사용"><code>options</code> 사용</h3> + +<p><code>options</code> 매개변수를 지정해 결과를 원하는 형태로 바꿀 수 있습니다.</p> + +<pre class="brush: js">var number = 123456.789; + +// 통화 서식 +console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(number)); +// → 123.456,79 € + +// 한국 원화는 보조 통화 단위를 사용하지 않음 +console.log(new Intl.NumberFormat('ko-KR', { style: 'currency', currency: 'KRW' }).format(number)); +// → ₩123,457 + +// 유효숫자를 세 개로 제한 +console.log(new Intl.NumberFormat('en-IN', { maximumSignificantDigits: 3 }).format(number)); +// → 1,23,000 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES Int 1.0', '#sec-11.1', 'Intl.NumberFormat')}}</td> + <td>{{Spec2('ES Int 1.0')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ES Int 2.0', '#sec-11.1', 'Intl.NumberFormat')}}</td> + <td>{{Spec2('ES Int 2.0')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES Int Draft', '#numberformat-objects', 'Intl.NumberFormat')}}</td> + <td>{{Spec2('ES Int Draft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Intl.NumberFormat")}}</p> +</div> + +<h2 id="같이_보기">같이 보기</h2> + +<div>{{page('/ko/docs/Web/JavaScript/Reference/Global_Objects/Intl', '같이_보기')}}</div> diff --git a/files/ko/web/javascript/reference/global_objects/intl/numberformat/prototype/index.html b/files/ko/web/javascript/reference/global_objects/intl/numberformat/prototype/index.html new file mode 100644 index 0000000000..19b0b8e0e6 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/intl/numberformat/prototype/index.html @@ -0,0 +1,85 @@ +--- +title: Intl.NumberFormat.prototype +slug: Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/prototype +tags: + - Internationalization + - Intl + - JavaScript + - NumberFormat + - Property + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat +--- +<div>{{JSRef}}</div> + +<p><strong><code>Intl.NumberFormat.prototype</code></strong> 속성은 {{jsxref("NumberFormat", "Intl.NumberFormat")}} 생성자의 프로토타입을 나타냅니다.</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="설명">설명</h2> + +<p><code>Intl.NumberFormat</code> 인스턴스에 대한 설명은 {{jsxref("NumberFormat")}} 문서를 참고하세요.</p> + +<p>{{jsxref("NumberFormat", "Intl.NumberFormat")}} 인스턴스는 <code>Intl.NumberFormat.prototype</code>을 상속합니다. 프로토타입 객체를 변형하면 모든 {{jsxref("NumberFormat", "Intl.NumberFormat")}} 인스턴스가 영향을 받습니다.</p> + +<h2 id="속성">속성</h2> + +<dl> + <dt><code>Intl.NumberFormat.prototype.constructor</code></dt> + <dd><code>Intl.NumberFormat</code>에 대한 참조입니다.</dd> +</dl> + +<h2 id="메서드">메서드</h2> + +<dl> + <dt>{{jsxref("NumberFormat.format", "Intl.NumberFormat.prototype.format()")}}</dt> + <dd>주어진 숫자에 {{jsxref("NumberFormat")}} 객체의 로케일과 서식 설정을 적용해 반환합니다.</dd> +</dl> + +<dl> + <dt>{{jsxref("NumberFormat.formatToParts", "Intl.NumberFormat.prototype.formatToParts()")}}</dt> + <dd>서식을 적용한 숫자의 각 부분을 객체로 표현해서 {{jsxref("Array")}}로 반환합니다. 반환 값은 로케일별 커스텀 서식에 사용할 수 있습니다.</dd> + <dt>{{jsxref("NumberFormat.resolvedOptions", "Intl.NumberFormat.prototype.resolvedOptions()")}}</dt> + <dd>객체 인스턴스 생성 때 주어진 로케일과 콜레이션 설정이 어떻게 반영되었나 나타내는 새로운 객체를 반환합니다.</dd> +</dl> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES Int 1.0', '#sec-11.2.1', 'Intl.NumberFormat.prototype')}}</td> + <td>{{Spec2('ES Int 1.0')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES Int 2.0', '#sec-11.2.1', 'Intl.NumberFormat.prototype')}}</td> + <td>{{Spec2('ES Int 2.0')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES Int Draft', '#sec-Intl.NumberFormat.prototype', 'Intl.NumberFormat.prototype')}}</td> + <td>{{Spec2('ES Int Draft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Intl.NumberFormat.prototype")}}</p> +</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("NumberFormat", "Intl.NumberFormat")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/isfinite/index.html b/files/ko/web/javascript/reference/global_objects/isfinite/index.html new file mode 100644 index 0000000000..834389e2f7 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/isfinite/index.html @@ -0,0 +1,84 @@ +--- +title: isFinite() +slug: Web/JavaScript/Reference/Global_Objects/isFinite +tags: + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/isFinite +--- +<div>{{jsSidebar("Objects")}}</div> + +<p><code><strong>isFinite()</strong></code> 전역 함수는 주어진 값이 유한수인지 판별합니다. 필요한 경우 매개변수를 먼저 숫자로 변환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/globalprops-isfinite.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox notranslate">isFinite(<em>testValue</em>)</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>testValue</code></dt> + <dd>유한한지 판별할 값.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p><code>testValue</code>가 양 또는 음의 {{jsxref("Infinity")}}, {{jsxref("NaN")}}, 또는 {{jsxref("undefined")}}면 <code>false</code>, 아니면 <code>true</code>.</p> + +<h2 id="설명">설명</h2> + +<p><code>isFinite()</code>은 최상위 함수로 어떤 객체와도 연결되지 않았습니다.</p> + +<p>숫자가 유한수인지 판별하기 위해 <code>isFinite()</code>을 사용할 수 있습니다. <code>isFinite()</code>은 주어진 수를 검사해 그 값이 <code>NaN</code>, 양의 무한대, 또는 음의 무한대이면 <code>false</code>를 반환합니다. 그렇지 않으면 <code>true</code>를 반환합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="isFinite_사용하기"><code>isFinite()</code> 사용하기</h3> + +<pre class="brush: js notranslate">isFinite(Infinity); // false +isFinite(NaN); // false +isFinite(-Infinity); // false + +isFinite(0); // true +isFinite(2e64); // true +isFinite(910); // true + +isFinite(null); // true, would've been false with the + // more robust Number.isFinite(null) + +isFinite('0'); // true, would've been false with the + // more robust Number.isFinite("0")</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-isfinite-number', 'isFinite')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.isFinite")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Number.isFinite()")}}</li> + <li>{{jsxref("Number.NaN()")}}</li> + <li>{{jsxref("Number.POSITIVE_INFINITY")}}</li> + <li>{{jsxref("Number.NEGATIVE_INFINITY")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/isnan/index.html b/files/ko/web/javascript/reference/global_objects/isnan/index.html new file mode 100644 index 0000000000..f0b2f12a31 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/isnan/index.html @@ -0,0 +1,190 @@ +--- +title: isNaN() +slug: Web/JavaScript/Reference/Global_Objects/isNaN +tags: + - JavaScript + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/isNaN +--- +<div>{{jsSidebar("Objects")}}</div> + +<p><code><strong>isNaN()</strong></code> 함수는 어떤 값이 {{jsxref("NaN")}}인지 판별합니다. <code>isNaN</code> 함수는 몇몇 {{anch("일반적이지 않은 규칙")}}을 가지고 있으므로, ECMAScript 2015에서 추가한 {{jsxref("Number.isNaN()")}}으로 바꾸는 편이 좋을 수도 있습니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/globalprops-isnan.html")}}</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code>isNaN(<em>value</em>)</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>value</code></dt> + <dd>테스트되는 값.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 값이 {{jsxref("NaN")}}이면 <code>true</code>, 아니면 <code>false</code>.</p> + +<h2 id="설명">설명</h2> + +<h3 id="isNaN_함수의_필요성"><code>isNaN</code> 함수의 필요성</h3> + +<p>JavaScript의 다른 모든 값과 달리, {{jsxref("NaN")}}은 같음 연산(<code>==</code>, <code>===</code>)을 사용해 판별할 수 없습니다. <code>NaN == NaN</code>, <code>NaN === NaN</code>이기 때문입니다. 그래서 <code>NaN</code>을 판별하는 함수가 필요합니다.</p> + +<h3 id="NaN_값의_기원"><code>NaN</code> 값의 기원</h3> + +<p><code>NaN</code> 값은 산술 연산이 <strong>정의되지 않은</strong> 결과 또는 <strong>표현할 수 없는</strong> 결과를 도출하면 생성되며, 반드시 오버플로 조건을 나타내는 것은 아닙니다. 숫자가 아닌 값의 변환을 시도했으나 알맞은 원시 숫자 값이 없는 경우의 결과도 <code>NaN</code>입니다.</p> + +<p>예를 들어 0을 0으로 나누면 <code>NaN</code>이지만, 다른 수를 0으로 나누면 그렇지 않습니다.</p> + +<h3 id="혼란스러운_특별_케이스_행동"><a id="special-behavior" name="special-behavior"></a>혼란스러운 특별 케이스 행동</h3> + +<p><code>isNaN</code> 함수 스펙의 아주 초기 버전 이후로, 숫자 아닌 인수를 위한 행동이 혼란스럽습니다. <code>isNaN</code> 함수의 인수가 <a href="http://es5.github.com/#x8.5" title="http://es5.github.com/#x8.5">Number</a> 형이 아닌 경우, 그 값은 먼저 숫자로 강제됩니다. 결과값은 그 뒤에 {{jsxref("NaN")}}인지 결정하기 위해 테스트됩니다. 따라서 숫자 형으로 강제된 결과 유효한 비 NaN 숫자값(특히 강제될 때 숫자값이 0 또는 1을 주는 빈 문자열 및 불린 원시형)이 되는 비 숫자의 경우, "false" 반환값은 예기치 않을 수 있습니다; 예를 들어 빈 문자열은 분명히 "not a number"입니다. 혼란(confusion)은 용어 "not a number"가 IEEE-754 부동 소수점 값으로 표현된 숫자에 특정 의미가 있다는 사실에서 생깁니다. 함수는 "이 값이, 숫자값으로 강제되는 경우, IEEE-754 'Not A Number' 값인가?"라는 질문에 답하는 것으로 해석되어야 합니다.</p> + +<p>ECMAScript (ES2015) 최근 버전은 {{jsxref("Number.isNaN()")}} 함수를 포함합니다. <code>Number.isNaN(x)</code>는 <code>x</code>가 <code>NaN</code>인지 아닌지 테스트하는 믿을 수 있는 방법이 됩니다. 그러나 <code>Number.isNaN</code>으로도, <code>NaN</code>의 의미는 정확한 숫자 의미로 남아있고 단순히 "not a number"는 아닙니다. 그 대신에, <code>Number.isNaN</code>이 없을 경우에, 식 <code>(x != x)</code>은 변수 <code>x</code>가 <code>NaN</code>인지 아닌지 테스트하는 더 믿을 수 있는 방법입니다, 그 결과는 <code>isNaN</code>을 믿을 수 없게 하는 오탐(false positive)의 대상이 아니기에.</p> + +<p>당신은 isNaN을 다음과 같이 생각할 수 있습니다:</p> + +<pre class="brush: js">isNaN = function(value) { + Number.isNaN(Number(value)); +}</pre> + +<h2 id="예제">예제</h2> + +<pre class="brush: js">isNaN(NaN); // 참 +isNaN(undefined); // 참 +isNaN({}); // 참 + +isNaN(true); // 거짓 +isNaN(null); // 거짓 +isNaN(37); // 거짓 + +// 문자열 +isNaN("37"); // 거짓: "37"은 NaN이 아닌 숫자 37로 변환됩니다 +isNaN("37.37"); // 거짓: "37.37"은 NaN이 아닌 숫자 37.37로 변환됩니다 +isNaN("123ABC"); // 참: parseInt("123ABC")는 123이지만 Number("123ABC")는 NaN입니다 +isNaN(""); // 거짓: 빈 문자열은 NaN이 아닌 0으로 변환됩니다 +isNaN(" "); // 거짓: 공백이 있는 문자열은 NaN이 아닌 0으로 변환됩니다 + +// dates +isNaN(new Date()); // 거짓 +isNaN(new Date().toString()); // 참 + +// 이것이 허위 양성이고 isNaN이 완전히 신뢰할 수 없는 이유이다. +isNaN("blabla") // 참: "blabla"는 숫자로 변환됩니다. + // 이것을 숫자롯 parsing 하는 것을 실패하고 NaN을 반환한다. +</pre> + +<h3 id="유용한_특별_케이스_행동">유용한 특별 케이스 행동</h3> + +<p><code>isNaN()</code>을 고려한 더 용도 중심 방법이 있습니다: <code>isNaN(x)</code>가 <code>false</code>를 반환하면, 그 식이 <code>NaN</code>을 반환하게 하지 않고 산술 식에 <code>x</code>를 쓸 수 있습니다. <code>true</code>를 반환하는 경우, <code>x</code>는 모든 산술 식이 <code>NaN</code>을 반환하게 합니다. 이는 JavaScript에서, <code>isNaN(x) == true</code>가 <code>NaN</code>을 반환하는 <code>x - 0</code>과 동일함(JavaScript에서 <code>x - 0 == NaN</code>가 항상 거짓을 반환하여 그것을 테스트할 수 없지만)을 뜻합니다. 실제로, <code>isNaN(x)</code>, <code>isNaN(x - 0)</code>, <code>isNaN(Number(x))</code>, <code>Number.isNaN(x - 0)</code> 및 <code>Number.isNaN(Number(x))</code>는 항상 같은 값을 반환하며 JavaScript에서 <code>isNaN(x)</code>는 그저 이러한 각각의 조건(terms)을 표현하는 가장 짧은 형태입니다.</p> + +<p>예를 들어 함수에 인수가 산술 처리 가능한(숫자 "처럼" 쓸 수 있는)지를 테스트하기 위해 사용할 수 있습니다, 그렇지 않은 경우 기본 값 또는 다른 무언가를 제공해야 합니다. 이런 식으로 문맥에 따라 암시적인 값 변환을 제공하는 JavaScript의 다양성(versatility) 전체를 이용케 하는 함수를 가질 수 있습니다.</p> + +<h2 id="예시">예시</h2> + +<pre class="brush: js">function increment(x) { + if (isNaN(x)) x = 0; + return x + 1; +}; + +// Number.isNaN()과 같은 효과: +function increment(x) { + if (Number.isNaN(Number(x))) x = 0; + return x + 1; +}; + +// 함수의 인수 x에 대해 다음 경우에, +// isNaN(x)는 항상 거짓, x가 실제 숫자가 아닐지라도 +// 하지만 산술 식에 그대로 +// 사용될 수 있습니다 +increment(""); // 1: ""는 0으로 변환됩니다 +increment(new String()); // 1: 빈 문자열을 나타내는 String 객체는 0으로 변환됩니다 +increment([]); // 1: []는 0으로 변환됩니다 +increment(new Array()); // 1: 빈 배열을 나타내는 Array 객체는 0으로 변환됩니다 +increment("0"); // 1: "0"은 0으로 변환됩니다 +increment("1"); // 2: "1"은 1로 변환됩니다 +increment("0.1"); // 1.1: "0.1"은 0.1로 변환됩니다 +increment("Infinity"); // Infinity: "Infinity"는 Infinity로 변환됩니다 +increment(null); // 1: null은 0으로 변환됩니다 +increment(false); // 1: false는 0으로 변환됩니다 +increment(true); // 2: true는 1로 변환됩니다 +increment(new Date()); // 밀리초로 현재 date/time + 1을 반환합니다 + +// 함수의 인수 x에 대해 다음 경우에, +// isNaN(x)는 항상 거짓이고 x는 실제로 숫자입니다 +increment(-1); // 0 +increment(-0.1); // 0.9 +increment(0); // 1 +increment(1); // 2 +increment(2); // 3 +// ... 등등 ... +increment(Infinity); // Infinity + +// 함수의 인수 x에 대해 다음 경우에, +// isNaN(x)는 항상 참이고 x는 실제로 숫자가 아닙니다, +// 따라서 함수는 인수를 0으로 대체하고 1을 반환합니다 +increment(String); // 1 +increment(Array); // 1 +increment("blabla"); // 1 +increment("-blabla"); // 1 +increment(0/0); // 1 +increment("0/0"); // 1 +increment(Infinity/Infinity); // 1 +increment(NaN); // 1 +increment(undefined); // 1 +increment(); // 1 + +// isNaN(x)는 항상 isNaN(Number(x))과 같지만, +// x의 존재는 여기서 필수입니다! +isNaN(x) == isNaN(Number(x)) // x == undefined 포함 x의 어떤 값도 참, + // isNaN(undefined) == true 및 Number(undefined)가 NaN을 반환하기에, + // 하지만 ... +isNaN() == isNaN(Number()) // 거짓, isNaN() == true 및 Number() == 0 때문에 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.1.2.4', 'isNaN')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-isnan-number', 'isNaN')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-isnan-number', 'isNaN')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div id="compat-mobile">{{Compat("javascript.builtins.isNaN")}}</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("NaN")}}</li> + <li>{{jsxref("Number.isNaN()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/json/index.html b/files/ko/web/javascript/reference/global_objects/json/index.html new file mode 100644 index 0000000000..ef21cfc534 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/json/index.html @@ -0,0 +1,122 @@ +--- +title: JSON +slug: Web/JavaScript/Reference/Global_Objects/JSON +tags: + - JSON + - JavaScript + - Object + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/JSON +--- +<div>{{JSRef}}</div> + +<p><strong><code>JSON</code></strong> 객체는 <a class="external" href="http://json.org/">JavaScript Object Notation</a>({{glossary("JSON")}})을 분석하거나 값을 JSON으로 변환하는 메서드를 가지고 있습니다. <code>JSON</code>을 직접 호출하거나 인스턴스를 생성할 수 없으며, 두 개의 메서드를 제외하면 자신만의 흥미로운 기능은 없습니다.</p> + +<h2 id="JavaScript와_JSON의_차이">JavaScript와 JSON의 차이</h2> + +<p>JSON은 객체, 배열, 숫자, 문자열, 불리언과 {{jsxref("null")}}을 직렬화하기 위한 구문으로, JavaScript 구문에 기반을 두고 있지만 분명한 차이점을 가지고 있습니다. 즉, 어떤 JavaScript는 JSON이 아닙니다.</p> + +<dl> + <dt>객체와 배열</dt> + <dd>속성의 이름은 반드시 큰따옴표로 표시된 문자열이어야 합니다. <a href="/ko/docs/Web/JavaScript/Reference/Trailing_commas">후행 쉼표</a>는 허용하지 않습니다.</dd> + <dt>숫자</dt> + <dd>선행 0은 허용하지 않습니다. 소숫점 뒤에는 적어도 한 자릿수가 뒤따라야 합니다. {{jsxref("NaN")}}과 {{jsxref("Infinity")}}는 지원하지 않습니다.</dd> + <dt>모든 JSON 텍스트는 유효한 JavaScript 표현식...</dt> + <dd>...이지만,<a href="https://github.com/tc39/proposal-json-superset"> 모든 JSON 텍스트를 올바른 ECMA-262로 만드는 제안</a>을 구현한 JavaScript 엔진에서만 그러합니다. 다른 엔진에서는, U+2028 LINE SEPARATOR와 U+2029 PARAGRAPH SEPARATOR를 JSON에서 스트링 리터럴과 속성의 키로 사용할 수 있지만, JavaScript 문자열 리터럴에서 사용하면 {{jsxref("SyntaxError")}}가 발생합니다.</dd> +</dl> + +<p>{{jsxref("JSON.parse()")}}로 JSON 문자열을 분석하고 {{jsxref("eval")}}이 JavaScript 문자열로 실행하는 다음 예시를 참고하세요.</p> + +<pre class="brush: js">const code = '"\u2028\u2029"' +JSON.parse(code) // 모든 엔진에서 "\u2028\u2029"로 평가 +eval(code) // 오래된 엔진에서 SyntaxError +</pre> + +<p>다른 차이점으로는 문자열의 작은따옴표 금지와, 주석 및 {{jsxref("undefined")}} 미지원이 있습니다. JSON에 기반한, 보다 사람 친화적인 설정 형식을 원하면 Babel 컴파일러가 사용하는 <a href="https://json5.org/">JSON5</a>가 있고, 좀 더 많이 쓰이는 <a href="https://ko.wikipedia.org/wiki/YAML">YAML</a>도 있습니다.</p> + +<h2 id="전체_JSON_구문">전체 JSON 구문</h2> + +<pre><var>JSON</var> = <strong>null</strong> + <em>or</em> <strong>true</strong> <em>or</em> <strong>false</strong> + <em>or</em> <var>JSONNumber</var> + <em>or</em> <var>JSONString</var> + <em>or</em> <var>JSONObject</var> + <em>or</em> <var>JSONArray</var> + +<var>JSONNumber</var> = <strong>-</strong> <var>PositiveNumber</var> + <em>or</em> <var>PositiveNumber</var> +<var>PositiveNumber</var> = DecimalNumber + <em>or</em> <var>DecimalNumber</var> <strong>.</strong> <var>Digits</var> + <em>or</em> <var>DecimalNumber</var> <strong>.</strong> <var>Digits</var> <var>ExponentPart</var> + <em>or</em> <var>DecimalNumber</var> <var>ExponentPart</var> +<var>DecimalNumber</var> = <strong>0</strong> + <em>or</em> <var>OneToNine</var> <var>Digits</var> +<var>ExponentPart</var> = <strong>e</strong> <var>Exponent</var> + <em>or</em> <strong>E</strong> <var>Exponent</var> +<var>Exponent</var> = <var>Digits</var> + <em>or</em> <strong>+</strong> <var>Digits</var> + <em>or</em> <strong>-</strong> <var>Digits</var> +<var>Digits</var> = <var>Digit</var> + <em>or</em> <var>Digits</var> <var>Digit</var> +<var>Digit</var> = <strong>0</strong> through <strong>9</strong> +<var>OneToNine</var> = <strong>1</strong> through <strong>9</strong> + +<var>JSONString</var> = <strong>""</strong> + <em>or</em> <strong>"</strong> <var>StringCharacters</var> <strong>"</strong> +<var>StringCharacters</var> = <var>StringCharacter</var> + <em>or</em> <var>StringCharacters</var> <var>StringCharacter</var> +<var>StringCharacter</var> = any character + <em>except</em> <strong>"</strong> <em>or</em> <strong>\</strong> <em>or</em> U+0000 through U+001F + <em>or</em> <var>EscapeSequence</var> +<var>EscapeSequence</var> = <strong>\"</strong> <em>or</em> <strong>\/</strong> <em>or</em> <strong>\\</strong> <em>or</em> <strong>\b</strong> <em>or</em> <strong>\f</strong> <em>or</em> <strong>\n</strong> <em>or</em> <strong>\r</strong> <em>or</em> <strong>\t</strong> + <em>or</em> <strong>\u</strong> <var>HexDigit</var> <var>HexDigit</var> <var>HexDigit</var> <var>HexDigit</var> +<var>HexDigit</var> = <strong>0</strong> through <strong>9</strong> + <em>or</em> <strong>A</strong> through <strong>F</strong> + <em>or</em> <strong>a</strong> through <strong>f</strong> + +<var>JSONObject</var> = <strong>{</strong> <strong>}</strong> + <em>or</em> <strong>{</strong> <var>Members</var> <strong>}</strong> +<var>Members</var> = <var>JSONString</var> <strong>:</strong> <var>JSON</var> + <em>or</em> <var>Members</var> <strong>,</strong> <var>JSONString</var> <strong>:</strong> <var>JSON</var> + +<var>JSONArray</var> = <strong>[</strong> <strong>]</strong> + <em>or</em> <strong>[</strong> <var>ArrayElements</var> <strong>]</strong> +<var>ArrayElements</var> = <var>JSON</var> + <em>or</em> <var>ArrayElements</var> <strong>,</strong> <var>JSON</var> +</pre> + +<p>중요하지 않은 공백은 <code><var>JSONNumber</var></code>(숫자에는 공백이 없어야 함) 또는 <code><var>JSONString</var></code>(문자열에서 해당 문자로 해석되거나 오류를 일으킴) 내를 제외하고 어디에나 존재할 수 있습니다. 탭 문자(<a href="http://unicode-table.com/en/0009/">U+0009</a>), 캐리지 리턴(<a href="http://unicode-table.com/en/000D/">U+000D</a>), 라인 피드(<a href="http://unicode-table.com/en/000A/">U+000A</a>) 및 스페이스(<a href="http://unicode-table.com/en/0020/">U+0020</a>) 문자만이 유효한 공백 문자입니다.</p> + +<h2 id="메서드">메서드</h2> + +<dl> + <dt>{{jsxref("JSON.parse()")}}</dt> + <dd>문자열을 JSON으로서 구문 분석하고, 선택적으로 분석 결과의 값과 속성을 변환해 반환합니다.</dd> + <dt>{{jsxref("JSON.stringify()")}}</dt> + <dd>주어진 값에 해당하는 JSON 문자열을 반환합니다. 선택 사항으로 특정 속성만 포함하거나 사용자 정의 방식으로 속성을 대체합니다.</dd> +</dl> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-json-object', 'JSON')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div class="hidden">The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</div> + +<p>{{Compat("javascript.builtins.JSON")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Date.prototype.toJSON()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/json/parse/index.html b/files/ko/web/javascript/reference/global_objects/json/parse/index.html new file mode 100644 index 0000000000..fa32b3711e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/json/parse/index.html @@ -0,0 +1,123 @@ +--- +title: JSON.parse() +slug: Web/JavaScript/Reference/Global_Objects/JSON/parse +tags: + - ECMAScript 5 + - JSON + - JavaScript + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/JSON/parse +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary"><strong><code>JSON.parse()</code></strong> 메서드는 JSON 문자열의 구문을 분석하고, 그 결과에서 JavaScript 값이나 객체를 생성합니다.</span> 선택적으로, <code>reviver</code> 함수를 인수로 전달할 경우, 결과를 반환하기 전에 변형할 수 있습니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/json-parse.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">JSON.parse(<var>text</var>[, <var>reviver</var>])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>text</code></dt> + <dd>JSON으로 변환할 문자열. JSON 구문은 {{jsxref("JSON")}} 객체의 설명을 참고하세요.</dd> + <dt><code>reviver</code> {{optional_inline}}</dt> + <dd>함수라면, 변환 결과를 반환하기 전에 이 인수에 전달해 변형함.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 JSON 문자열에 대응하는 {{jsxref("Object")}}.</p> + +<h3 id="예외">예외</h3> + +<p>변환할 문자열이 유효한 JSON이 아닐 경우 {{jsxref("SyntaxError")}}.</p> + +<h2 id="예제">예제</h2> + +<h3 id="JSON.parse()_사용하기"><code>JSON.parse()</code> 사용하기</h3> + +<pre class="brush: js">JSON.parse('{}'); // {} +JSON.parse('true'); // true +JSON.parse('"foo"'); // "foo" +JSON.parse('[1, 5, "false"]'); // [1, 5, "false"] +JSON.parse('null'); // null +</pre> + +<h3 id="reviver_매개변수_사용하기"><code>reviver</code> 매개변수 사용하기</h3> + +<p><code>reviver</code>가 주어지면 분석한 값을 반환하기 전에 변환합니다. 구체적으로는, 분석한 값과 그 모든 속성(가장 깊게 중첩된 속성부터 시작해 제일 바깥의 원래 값까지)을 각각 <code>reviver</code>에 전달합니다. <code>reviver</code>의 <code>this</code> 문맥은 분석한 값으로 설정되고, 속성 명(문자열)과 값을 인자로 전달받습니다. <code>reviver</code>가 {{jsxref("undefined")}}를 반환하거나 반환하지 않는다면, 예컨대 함수가 중간에 실패한다면 그 속성은 최종 결과에서 제외됩니다. 그 외에는 반환 값으로 속성의 값을 재설정합니다.</p> + +<p>만약 <code>reviver</code>가 일부 값만 변환하고 나머지는 건드리지 않는다면, 나머지 값을 그대로 반환하는걸 잊지 마세요. 그렇지 않으면 변환한 값 외에는 결과에서 모두 제외됩니다.</p> + +<pre class="brush: js">JSON.parse('{"p": 5}', (key, value) => + typeof value === 'number' + ? value * 2 // 숫자라면 2배 + : value // 나머진 그대로 +); + +// { p: 10 } + +JSON.parse('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}', (key, value) => { + console.log(key); // 현재 속성명 출력, 마지막은 빈 문자열("") + return value; // 변환하지 않고 그대로 반환 +}); + +// 1 +// 2 +// 4 +// 6 +// 5 +// 3 +// ""</pre> + +<h3 id="후행_쉼표_사용_불가">후행 쉼표 사용 불가</h3> + +<pre class="example-bad brush: js">// 둘 다 SyntaxError +JSON.parse('[1, 2, 3, 4, ]'); +JSON.parse('{"foo" : 1, }'); +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.12.2', 'JSON.parse')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.7.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-json.parse', 'JSON.parse')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-json.parse', 'JSON.parse')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.JSON.parse")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("JSON.stringify()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/json/stringify/index.html b/files/ko/web/javascript/reference/global_objects/json/stringify/index.html new file mode 100644 index 0000000000..12de82705b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/json/stringify/index.html @@ -0,0 +1,230 @@ +--- +title: JSON.stringify() +slug: Web/JavaScript/Reference/Global_Objects/JSON/stringify +tags: + - JSON + - JavaScript + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/JSON/stringify +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary"><strong><code>JSON.stringify()</code></strong> 메서드는 JavaScript 값이나 객체를 JSON 문자열로 변환합니다.</span> 선택적으로, <code>replacer</code>를 함수로 전달할 경우 변환 전 값을 변형할 수 있고, 배열로 전달할 경우 지정한 속성만 결과에 포함합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/json-stringify.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox notranslate">JSON.stringify(<var>value</var>[, <var>replacer</var>[, <var>space</var>]])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>value</code></dt> + <dd>JSON 문자열로 변환할 값.</dd> + <dt><code>replacer</code> {{optional_inline}}</dt> + <dd>문자열화 동작 방식을 변경하는 함수, 혹은 JSON 문자열에 포함될 값 객체의 속성들을 선택하기 위한 화이트리스트(whitelist)로 쓰이는 {{jsxref("String")}} 과 {{jsxref("Number")}} 객체들의 배열. 이 값이 null 이거나 제공되지 않으면, 객체의 모든 속성들이 JSON 문자열 결과에 포함된다.</dd> +</dl> + +<dl> + <dt><code>space</code> {{optional_inline}}</dt> + <dd>가독성을 목적으로 JSON 문자열 출력에 공백을 삽입하는데 사용되는 {{jsxref("String")}} 또는 {{jsxref("Number")}} 객체. 이것이 <code>Number</code> 라면, 공백으로 사용되는 스페이스(space)의 수를 나타낸다; 이 수가 10 보다 크면 10 으로 제한된다. 1 보다 작은 값은 스페이스가 사용되지 않는 것을 나타낸다. 이것이 <code>String</code> 이라면, 그 문자열(만약 길이가 10 보다 길다면, 첫번째 10 개의 문자)이 공백으로 사용된다. 이 매개 변수가 제공되지 않는다면(또는 null 이면), 공백이 사용되지 않는다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 값과 대응하는 JSON 문자열.</p> + +<h3 id="예외">예외</h3> + +<p>순환 참조를 발견할 경우 {{jsxref("TypeError")}}(<code>cyclic object value</code>).</p> + +<h2 id="설명">설명</h2> + +<p><code>JSON.stringify()</code>는 값을 JSON 표기법으로 변환한다.</p> + +<ul> + <li>배열이 아닌 객체의 속성들은 어떤 특정한 순서에 따라 문자열화 될 것이라고 보장되지 않는다. 같은 객체의 문자열화에 있어서 속성의 순서에 의존하지 않는다.</li> + <li>{{jsxref("Boolean")}}, {{jsxref("Number")}}, {{jsxref("String")}} 객체들은 문자열화 될 때 전통적인 변환 의미에 따라 연관된 기본형(primitive) 값으로 변환된다.</li> + <li>{{jsxref("undefined")}}, 함수, 심볼(symbol)은 변환될 때 생략되거나(객체 안에 있을 경우) {{jsxref("null")}} 로 변환된다(배열 안에 있을 경우).</li> + <li>심볼을 키로 가지는 속성들은 <code>replacer</code> 함수를 사용하더라도 완전히 무시된다.</li> + <li>열거 불가능한 속성들은 무시된다.</li> +</ul> + +<pre class="brush: js notranslate">JSON.stringify({}); // '{}' +JSON.stringify(true); // 'true' +JSON.stringify('foo'); // '"foo"' +JSON.stringify([1, 'false', false]); // '[1,"false",false]' +JSON.stringify({ x: 5 }); // '{"x":5}' + +JSON.stringify(new Date(2006, 0, 2, 15, 4, 5)) +// '"2006-01-02T15:04:05.000Z"' + +JSON.stringify({ x: 5, y: 6 }); +// '{"x":5,"y":6}' or '{"y":6,"x":5}' +JSON.stringify([new Number(1), new String('false'), new Boolean(false)]); +// '[1,"false",false]' + +// Symbols: +JSON.stringify({ x: undefined, y: Object, z: Symbol('') }); +// '{}' +JSON.stringify({ [Symbol('foo')]: 'foo' }); +// '{}' +JSON.stringify({ [Symbol.for('foo')]: 'foo' }, [Symbol.for('foo')]); +// '{}' +JSON.stringify({ [Symbol.for('foo')]: 'foo' }, function(k, v) { + if (typeof k === 'symbol') { + return 'a symbol'; + } +}); +// '{}' + +// Non-enumerable properties: +JSON.stringify( Object.create(null, { x: { value: 'x', enumerable: false }, y: { value: 'y', enumerable: true } }) ); +// '{"y":"y"}' + +</pre> + +<h3 id="replacer_매개_변수"><code>replacer</code> 매개 변수</h3> + +<p><code>replacer</code> 매개변수는 함수 또는 배열이 될 수 있다. 함수일 때는 문자열화 될 key 와 value, 2개의 매개변수를 받는다. key 가 발견된 객체는 리플레이서의 <code>this</code> 매개변수로 제공된다. 맨 처음에는 문자열화될 그 객체를 나타내는 비어 있는 key와 함께 호출되고, 그 다음에는 문자열화될 그 객체나 배열의 각 속성에 대해 호출된다. 이것은 JSON 문자열에 추가되어야 하는 값을 반환해야한다:</p> + +<ul> + <li>{{jsxref("Number")}} 를 반환하면, JSON 문자열에 추가될 때 그 수를 나타내는 문자열이 그 속성의 값으로 사용된다.</li> + <li>{{jsxref("String")}} 을 반환하면, 그것이 JSON 문자열에 추가될 때 속성의 값으로 사용된다.</li> + <li>{{jsxref("Boolean")}} 을 반환하면, 그것이 JSON 문자열에 추가될 때 "true" 또는 "false" 이 속성의 값으로 사용된다.</li> + <li>다른 객체를 반환하면, 그 객체는 <code>replacer</code> 함수를 각각의 속성에 대해 호출하며 순환적으로 JSON 문자열로 문자열화된다. 그 객체가 함수인 경우에는 JSON 문자열에 아무것도 추가되지 않는다.</li> + <li><code>undefined</code> 를 반환하면, 그 속성은 JSON 문자열 결과에 포함되지 않는다.</li> +</ul> + +<div class="note"><strong>유의:</strong> <code>replacer</code> 함수를 배열로부터 값을 제거하기위해 사용할 수 없다. 만약 <code>undefined</code> 나 함수를 반환한다면 <code>null</code> 이 대신 사용될 것이다.</div> + +<h4 id="함수에_대한_예제">함수에 대한 예제</h4> + +<pre class="brush: js notranslate">function replacer(key, value) { + if (typeof value === "string") { + return undefined; + } + return value; +} + +var foo = {foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7}; +var jsonString = JSON.stringify(foo, replacer); +</pre> + +<p>JSON 문자열 결과는 <code>{"week":45,"month":7}</code> 이다.</p> + +<h4 id="배열에_대한_예제">배열에 대한 예제</h4> + +<p><code>replacer</code> 가 배열인 경우, 그 배열의 값은 JSON 문자열의 결과에 포함되는 속성의 이름을 나타낸다.</p> + +<pre class="brush: js notranslate">JSON.stringify(foo, ['week', 'month']); +// '{"week":45,"month":7}', 단지 "week" 와 "month" 속성을 포함한다 +</pre> + +<h3 id="space_매개_변수"><code>space</code> 매개 변수</h3> + +<p><code>space</code> 매개변수는 최종 문자열의 간격을 제어한다. 숫자일 경우 최대 10자 만큼의 공백 문자 크기로 들여쓰기되며, 문자열인 경우 해당 문자열 또는 처음 10자 만큼 들여쓰기 된다.</p> + +<pre class="brush: js notranslate">JSON.stringify({ a: 2 }, null, ' '); +// '{ +// "a": 2 +// }' +</pre> + +<p>'\t'를 사용하면 일반적으로 들여쓰기 된 코드스타일과 유사함.</p> + +<pre class="brush: js notranslate">JSON.stringify({ uno: 1, dos: 2 }, null, '\t'); +// returns the string: +// '{ +// "uno": 1, +// "dos": 2 +// }' +</pre> + +<h3 id="toJSON_작동"><code>toJSON()</code> 작동</h3> + +<p>If an object being stringified has a property named <code>toJSON</code> whose value is a function, then the <code>toJSON()</code> method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the <code>toJSON()</code> method when called will be serialized. For example:</p> + +<pre class="brush: js notranslate">var obj = { + foo: 'foo', + toJSON: function() { + return 'bar'; + } +}; +JSON.stringify(obj); // '"bar"' +JSON.stringify({ x: obj }); // '{"x":"bar"}' +</pre> + +<h3 id="Example_of_using_JSON.stringify_with_localStorage">Example of using <code>JSON.stringify()</code> with <code>localStorage</code></h3> + +<p>In a case where you want to store an object created by your user and allowing it to be restored even after the browser has been closed, the following example is a model for the applicability of <code>JSON.stringify()</code>:</p> + +<div class="warning"> +<p>Functions are not a valid JSON data type so they will not work. However, they can be displayed if first converted to a string (e.g. in the replacer), via the function's toString method. Also, some objects like {{jsxref("Date")}} will be a string after {{jsxref("JSON.parse()")}}.</p> +</div> + +<pre class="brush: js notranslate">// Creating an example of JSON +var session = { + 'screens': [], + 'state': true +}; +session.screens.push({ 'name': 'screenA', 'width': 450, 'height': 250 }); +session.screens.push({ 'name': 'screenB', 'width': 650, 'height': 350 }); +session.screens.push({ 'name': 'screenC', 'width': 750, 'height': 120 }); +session.screens.push({ 'name': 'screenD', 'width': 250, 'height': 60 }); +session.screens.push({ 'name': 'screenE', 'width': 390, 'height': 120 }); +session.screens.push({ 'name': 'screenF', 'width': 1240, 'height': 650 }); + +// Converting the JSON string with JSON.stringify() +// then saving with localStorage in the name of session +localStorage.setItem('session', JSON.stringify(session)); + +// Example of how to transform the String generated through +// JSON.stringify() and saved in localStorage in JSON object again +var restoredSession = JSON.parse(localStorage.getItem('session')); + +// Now restoredSession variable contains the object that was saved +// in localStorage +console.log(restoredSession); +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.12.3', 'JSON.stringify')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.7.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-json.stringify', 'JSON.stringify')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-json.stringify', 'JSON.stringify')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.JSON.stringify")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("JSON.parse()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/map/@@tostringtag/index.html b/files/ko/web/javascript/reference/global_objects/map/@@tostringtag/index.html new file mode 100644 index 0000000000..7a1cd5002b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/map/@@tostringtag/index.html @@ -0,0 +1,51 @@ +--- +title: 'Map.prototype[@@toStringTag]' +slug: Web/JavaScript/Reference/Global_Objects/Map/@@toStringTag +translation_of: Web/JavaScript/Reference/Global_Objects/Map/@@toStringTag +--- +<div>{{JSRef}}</div> + +<p><strong><code>Map[@@toStringTag]</code></strong> 프로퍼티의 초기값은 "Map"입니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/map-prototype-@@tostringtag.html")}}</div> + + + +<div>{{js_property_attributes(0,0,1)}}</div> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox">Map[Symbol.toStringTag]</pre> + +<h2 id="예제">예제</h2> + +<pre class="brush:js">Object.prototype.toString.call(new Map()) // "[object Map]" +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-map.prototype-@@tostringtag', 'Map.prototype[@@toStringTag]')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-map.prototype-@@tostringtag', 'Map.prototype[@@toStringTag]')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Map.@@toStringTag")}}</p> diff --git a/files/ko/web/javascript/reference/global_objects/map/clear/index.html b/files/ko/web/javascript/reference/global_objects/map/clear/index.html new file mode 100644 index 0000000000..fc63ff96d6 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/map/clear/index.html @@ -0,0 +1,75 @@ +--- +title: Map.prototype.clear() +slug: Web/JavaScript/Reference/Global_Objects/Map/clear +tags: + - ECMAScript 2015 + - JavaScript + - Map + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Map/clear +--- +<div>{{JSRef}}</div> + +<p><code><strong>clear()</strong></code> 메서드는 <code>Map</code> 객체의 모든 요소를 제거합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/map-prototype-clear.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><em>myMap</em>.clear(); +</pre> + +<h2 id="예제">예제</h2> + +<h3 id="clear()_사용하기"><code>clear()</code> 사용하기</h3> + +<pre class="brush: js">var myMap = new Map(); +myMap.set('bar', 'baz'); +myMap.set(1, 'foo'); + +myMap.size; // 2 +myMap.has('bar'); // true + +myMap.clear(); + +myMap.size; // 0 +myMap.has('bar') // false +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-map.prototype.clear', 'Map.prototype.clear')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-map.prototype.clear', 'Map.prototype.clear')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Map.clear")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Map")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/map/delete/index.html b/files/ko/web/javascript/reference/global_objects/map/delete/index.html new file mode 100644 index 0000000000..41110a28a9 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/map/delete/index.html @@ -0,0 +1,79 @@ +--- +title: Map.prototype.delete() +slug: Web/JavaScript/Reference/Global_Objects/Map/delete +tags: + - ECMAScript 2015 + - JavaScript + - Map + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Map/delete +--- +<div>{{JSRef}}</div> + +<p><code><strong>delete()</strong></code> 메서드는 <code>Map</code> 객체에서 특정 요소를 제거합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/map-prototype-delete.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">myMap.delete(<em>key</em>);</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>key</code></dt> + <dd><code>Map</code> 객체에서 제거할 요소의 키.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>요소가 <code>Map</code> 객체에 존재해서 제거했을 경우 <code>true</code>, 존재하지 않았으면 <code>false</code>.</p> + +<h2 id="예제">예제</h2> + +<h3 id="delete()_사용하기"><code>delete()</code> 사용하기</h3> + +<pre class="brush: js">var myMap = new Map(); +myMap.set('bar', 'foo'); + +myMap.delete('bar'); // Returns true. Successfully removed. +myMap.has('bar'); // Returns false. The "bar" element is no longer present. +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-map.prototype.delete', 'Map.prototype.delete')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-map.prototype.delete', 'Map.prototype.delete')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Map.delete")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Map")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/map/entries/index.html b/files/ko/web/javascript/reference/global_objects/map/entries/index.html new file mode 100644 index 0000000000..54242f373b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/map/entries/index.html @@ -0,0 +1,78 @@ +--- +title: Map.prototype.entries() +slug: Web/JavaScript/Reference/Global_Objects/Map/entries +tags: + - ECMAScript 2015 + - JavaScript + - Map + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Map/entries +--- +<div>{{JSRef}}</div> + +<p><code><strong>entries()</strong></code> 메서드는 <code>Map</code> 객체의 각 요소에 해당하는 <code>[키, 값]</code> 쌍을 <code>Map</code>에 등록한 순서대로 포함한 새로운 <strong><a href="/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators">Iterator</a></strong> 객체를 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/map-prototype-entries.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><em>myMap</em>.entries()</code></pre> + +<h3 id="반환_값">반환 값</h3> + +<p>A new {{jsxref("Map")}} iterator object.</p> + +<h2 id="예제">예제</h2> + +<h3 id="entries()_사용하기"><code>entries()</code> 사용하기</h3> + +<pre class="brush:js">var myMap = new Map(); +myMap.set('0', 'foo'); +myMap.set(1, 'bar'); +myMap.set({}, 'baz'); + +var mapIter = myMap.entries(); + +console.log(mapIter.next().value); // ["0", "foo"] +console.log(mapIter.next().value); // [1, "bar"] +console.log(mapIter.next().value); // [Object, "baz"] +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-map.prototype.entries', 'Map.prototype.entries')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-map.prototype.entries', 'Map.prototype.entries')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Map.entries")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Map.prototype.keys()")}}</li> + <li>{{jsxref("Map.prototype.values()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/map/foreach/index.html b/files/ko/web/javascript/reference/global_objects/map/foreach/index.html new file mode 100644 index 0000000000..48b96eb570 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/map/foreach/index.html @@ -0,0 +1,98 @@ +--- +title: Map.prototype.forEach() +slug: Web/JavaScript/Reference/Global_Objects/Map/forEach +translation_of: Web/JavaScript/Reference/Global_Objects/Map/forEach +--- +<div>{{JSRef}}</div> + +<p><code><strong>forEach()</strong></code><strong> </strong>메소드는 <code>Map</code> 오브젝트 내의 key/value 쌍의 개수 만큼 주어진 함수를 순서대로 실행합니다. </p> + +<div>{{EmbedInteractiveExample("pages/js/map-prototype-foreach.html")}}</div> + + + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox"><code><em>myMap</em>.forEach(<em>callback</em>[, <em>thisArg</em>])</code></pre> + +<h3 id="파라미터">파라미터</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>각각의 요소를 처리하기 위한 함수.</dd> + <dt><code>thisArg</code></dt> + <dd> <code>callback</code> 을 실행할때 <code>this</code> 로 사용되는 값.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>{{jsxref("undefined")}}.</p> + +<h2 id="설명">설명</h2> + +<p><code>forEach</code> 메서드는 map의 각각의 키마다 주어진 <code>callback</code> 함수를 실행합니다. 삭제된 키에대해서는 호출되지 않습니다. 그러나, 값이 존재하지만 <code>undefined</code> 인 값에 대해서는 실행됩니다.</p> + +<p><code>callback</code> 은 <strong>3가지 인수</strong>로 호출됩니다.</p> + +<ul> + <li><strong>요소의 value</strong></li> + <li><strong>요소의 key</strong></li> + <li><strong><code><font face="Arial, x-locale-body, sans-serif"><span style="background-color: #ffffff;">사용될 </span></font>Map</code> 객체</strong></li> +</ul> + +<p><code>thisArg</code> 파라미터가 <code>forEach</code> 에 제공되면, <code>this</code> 값으로 사용하기 위해 호출될때 <code>callback</code> 으로 넘겨집니다. 그렇지 않으면 <code>undefined</code> 값이 <code>this</code> 값으로 넘겨질 것입니다. 궁극적으로 <code>callback</code> 으로 보여지게 된 <code>this</code> 값은 <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">함수에 의해 보여지는 this 를 결정하기 위한 일반적인 규칙에 따라 결정됩니다.</a></p> + +<p>각각의 value는 한번씩 사용됩니다. 다만 <code>forEach</code> 가 끝나기 전에 value가 삭제되거나 재추가 된 경우는 예외입니다. <code>callback</code> 은 사용되기 전에 삭제된 value에 의해 호출되지 않습니다. <code>forEach</code> 가 끝나기 전에 새롭게 추가된 value가 사용 됩니다.</p> + +<p><code>forEach</code> 는 <code>Map</code> 오브젝트 내에 있는 각각의 요소마다 <code>callback</code> 함수를 실행합니다; 깂을 반환하지 않습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="Map_오브젝트의_내용을_출력"><code>Map</code> 오브젝트의 내용을 출력</h3> + +<p>아래의 코드는 <code>Map</code> 오브젝트 내의 각각 요소들을 행별로 출력합니다:</p> + +<pre class="brush:js">function logMapElements(value, key, map) { + console.log(`map.get('${key}') = ${value}`); +} +new Map([['foo', 3], ['bar', {}], ['baz', undefined]]).forEach(logMapElements); +// logs: +// "map.get('foo') = 3" +// "map.get('bar') = [object Object]" +// "map.get('baz') = undefined" +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-map.prototype.foreach', 'Map.prototype.forEach')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-map.prototype.foreach', 'Map.prototype.forEach')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.builtins.Map.forEach")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Array.prototype.forEach()")}}</li> + <li>{{jsxref("Set.prototype.forEach()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/map/get/index.html b/files/ko/web/javascript/reference/global_objects/map/get/index.html new file mode 100644 index 0000000000..835c8c3e6e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/map/get/index.html @@ -0,0 +1,80 @@ +--- +title: Map.prototype.get() +slug: Web/JavaScript/Reference/Global_Objects/Map/get +tags: + - ECMAScript 2015 + - JavaScript + - Map + - Method + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Map/get +--- +<div>{{JSRef}}</div> + +<p><code><strong>get()</strong></code> 메서드는 <code>Map</code> 객체에서 지정한 요소를 회수합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/map-prototype-get.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><em>myMap</em>.get(<em>key</em>);</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>key</code></dt> + <dd><code>Map</code> 객체에서 회수할 요소의 키.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 키와 연결된 요소. 그런 요소가 없으면 {{jsxref("undefined")}}.</p> + +<h2 id="예제">예제</h2> + +<h3 id="get_사용하기"><code>get</code> 사용하기</h3> + +<pre class="brush: js">var myMap = new Map(); +myMap.set('bar', 'foo'); + +myMap.get('bar'); // "foo" 반환. +myMap.get('baz'); // undefined 반환. +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-map.prototype.get', 'Map.prototype.get')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-map.prototype.get', 'Map.prototype.get')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Map.get")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Map")}}</li> + <li>{{jsxref("Map.prototype.set()")}}</li> + <li>{{jsxref("Map.prototype.has()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/map/has/index.html b/files/ko/web/javascript/reference/global_objects/map/has/index.html new file mode 100644 index 0000000000..60c5c03dfb --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/map/has/index.html @@ -0,0 +1,81 @@ +--- +title: Map.prototype.has() +slug: Web/JavaScript/Reference/Global_Objects/Map/has +tags: + - ECMAScript 2015 + - JavaScript + - Map + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Map/has +--- +<div>{{JSRef}}</div> + +<p><code><strong>has()</strong></code> 메서드는 주어진 키를 가진 요소가 <code>Map</code>에 존재하는지를 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/map-prototype-has.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><em>myMap</em>.has(<em>key</em>);</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>key</code></dt> + <dd>존재 여부를 판별할 키값.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 키를 가진 요소가 있으면 <code>true</code>, 아니면 <code>false</code>.</p> + +<h2 id="예제">예제</h2> + +<h3 id="has()_사용하기"><code>has()</code> 사용하기</h3> + +<pre class="brush: js">var myMap = new Map(); +myMap.set('bar', "foo"); + +myMap.has('bar'); // returns true +myMap.has('baz'); // returns false +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-map.prototype.has', 'Map.prototype.has')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-map.prototype.has', 'Map.prototype.has')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Map.has")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Map")}}</li> + <li>{{jsxref("Map.prototype.set()")}}</li> + <li>{{jsxref("Map.prototype.get()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/map/index.html b/files/ko/web/javascript/reference/global_objects/map/index.html new file mode 100644 index 0000000000..f8b29bdf6e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/map/index.html @@ -0,0 +1,244 @@ +--- +title: Map +slug: Web/JavaScript/Reference/Global_Objects/Map +tags: + - ECMAScript 2015 + - JavaScript + - Map + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Map +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary"><strong><code>Map</code> </strong>객체는 키-값 쌍을 저장하며 각 쌍의 삽입 순서도 기억하는 콜렉션입니다.</span> 아무 값(객체와 {{Glossary("Primitive", "원시 값")}})이라도 키와 값으로 사용할 수 있습니다.</p> + +<h2 id="설명">설명</h2> + +<p><code>Map</code> 객체는 요소의 삽입 순서대로 원소를 순회합니다. {{jsxref("Statements/for...of", "for...of")}} 반복문은 각 순회에서 <code>[key, value]</code>로 이루어진 배열을 반환합니다.</p> + +<h3 id="키_동일성">키 동일성</h3> + +<ul> + <li>키 동일성은 <a href="/ko/docs/Web/JavaScript/Equality_comparisons_and_sameness#등가0_같음"><code>sameValueZero</code></a> 알고리즘에 기반합니다.</li> + <li><code>NaN !== NaN</code>이지만, 그럼에도 <code>NaN</code>은 <code>NaN</code>과 일치한다고 간주하며, 다른 모든 값은 <code>===</code> 연산자의 결과를 따릅니다.</li> + <li>현 ECMAScript 명세는 <code>-0</code>과 <code>+0</code>을 같은 값으로 처리하지만 초기 명세에서는 그렇지 않았습니다. {{anch("브라우저 호환성")}}의 "<em>Key equality for -0 and 0</em>"을 참고하세요.</li> +</ul> + +<h3 id="jsxrefObject와_Map_비교">{{jsxref("Object")}}와 <code>Map</code> 비교</h3> + +<p>{{jsxref("Object")}}는 값에 키를 할당할 수 있고, 그 키로 값을 얻을 수 있고, 키를 삭제할 수 있으며 어떤 키에 값이 존재하는지 확인할 수 있다는 점에서 <code>Map</code>과 유사합니다. 이런 이유에 더해, 이전에는 내장된 대체제가 없었기 때문에, <code>Object</code>를 <code>Map</code> 대신 사용하곤 했습니다.</p> + +<p>그러나 어떤 상황에선, <code>Map</code>을 선호해야 할 몇 가지 중요한 차이점이 있습니다.</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="row"></th> + <th scope="col"><code>Map</code></th> + <th scope="col"><code>Object</code></th> + </tr> + </thead> + <tbody> + <tr> + <th scope="row">의도치 않은 키</th> + <td><code>Map</code>은 명시적으로 제공한 키 외에는 어떤 키도 가지지 않습니다.</td> + <td> + <p><code>Object</code>는 프로토타입을 가지므로 기본 키가 존재할 수 있습니다. 주의하지 않으면 직접 제공한 키와 충돌할 수도 있습니다.</p> + + <div class="blockIndicator note"> + <p><strong>참고:</strong> ES5부터, 프로토타입으로 인한 키 충돌은 {{jsxref("Object.create", "Object.create(null)")}}로 해결할 수 있지만, 실제로 쓰이는 경우는 적습니다.</p> + </div> + </td> + </tr> + <tr> + <th scope="row">키 자료형</th> + <td><code>Map</code>의 키는 함수, 객체 등을 포함한 모든 값이 가능합니다.</td> + <td><code>Object</code>의 키는 반드시 {{jsxref("String")}} 또는 {{jsxref("Symbol")}}이어야 합니다.</td> + </tr> + <tr> + <th scope="row">키 순서</th> + <td> + <p><code>Map</code>의 키는 정렬됩니다. 따라서 <code>Map</code>의 순회는 삽입순으로 이뤄집니다.</p> + </td> + <td> + <p><code>Object</code>의 키는 정렬되지 않습니다.</p> + + <div class="blockIndicator note"> + <p><strong>참고:</strong> ECMAScript 201 이후로, 객체도 문자열과 <code>Symbol</code> 키의 생성 순서를 유지합니다. ECMEScript 2015 명세를 준수하는 JavaScript 엔진에서 문자열 키만 가진 객체를 순회하면 삽입 순을 따라갑니다.</p> + </div> + </td> + </tr> + <tr> + <th scope="row">크기</th> + <td><code>Map</code>의 항목 수는 {{jsxref("Map.prototype.size", "size")}} 속성을 통해 쉽게 알아낼 수 있습니다.</td> + <td><code>Object</code>의 항목 수는 직접 알아내야 합니다.</td> + </tr> + <tr> + <th scope="row">순회</th> + <td><code>Map</code>은 <a href="/ko/docs/Web/JavaScript/Reference/Iteration_protocols">순회 가능</a>하므로, 바로 순회할 수 있습니다.</td> + <td><code>Object</code>를 순회하려면 먼저 모든 키를 알아낸 후, 그 키의 배열을 순회해야 합니다.</td> + </tr> + <tr> + <th scope="row">성능</th> + <td>잦은 키-값 쌍의 추가와 제거에서 더 좋은 성능을 보입니다.</td> + <td>잦은 키-값 쌍의 추가와 제거를 위한 최적화가 없습니다.</td> + </tr> + </tbody> +</table> + +<h2 id="생성자">생성자</h2> + +<dl> + <dt>{{jsxref("Map.Map", "Map()")}}</dt> + <dd>새로운 <code>Map</code> 객체를 생성합니다.</dd> +</dl> + +<h2 id="속성">속성</h2> + +<dl> + <dt><code>Map.length</code></dt> + <dd>값이 0인 속성입니다.<br> + 요소의 수는 {{jsxref("Map.prototype.size")}}로 알아낼 수 있습니다.</dd> + <dt>{{jsxref("Map.@@species", "get Map[@@species]")}}</dt> + <dd>파생 객체를 생성하는데 사용하는 생성자 함수입니다.</dd> + <dt>{{jsxref("Map.prototype")}}</dt> + <dd><code>Map</code> 생성자의 프로토타입을 나타냅니다. 모든 <code>Map</code> 인스턴스에 속성을 추가할 수 있습니다.</dd> +</dl> + +<h2 id="Map_인스턴스"><code>Map</code> 인스턴스</h2> + +<p>모든 <code>Map</code> 인스턴스는 {{jsxref("Map.prototype")}}을 상속합니다.</p> + +<h3 id="속성_2">속성</h3> + +<p>{{page('ko/Web/JavaScript/Reference/Global_Objects/Map/prototype','Properties')}}</p> + +<h3 id="메서드">메서드</h3> + +<p>{{page('ko/Web/JavaScript/Reference/Global_Objects/Map/prototype','Methods')}}</p> + +<h2 id="예제">예제</h2> + +<h3 id="Map_객체_사용하기"><code>Map</code> 객체 사용하기</h3> + +<pre class="brush: js">let myMap = new Map() + +let keyString = '문자열' +let keyObj = {} +let keyFunc = function() {} + +// 값 설정 +myMap.set(keyString, "'문자열'과 관련된 값") +myMap.set(keyObj, 'keyObj와 관련된 값') +myMap.set(keyFunc, 'keyFunc와 관련된 값') + +myMap.size // 3 + +// getting the values +myMap.get(keyString) // "'문자열'과 관련된 값" +myMap.get(keyObj) // "keyObj와 관련된 값" +myMap.get(keyFunc) // "keyFunc와 관련된 값" + +myMap.get('문자열') // "'문자열'과 관련된 값" + // keyString === '문자열'이기 때문 +myMap.get({}) // undefined, keyObj !== {} +myMap.get(function() {}) // undefined, keyFunc !== function () {}</pre> + +<h3 id="Map의_키로_NaN_사용하기"><code>Map</code>의 키로 <code>NaN</code> 사용하기</h3> + +<p>{{jsxref("NaN")}}도 키로서 사용할 수 있습니다. 모든 <code>NaN</code>은 자기 자신과 동일하지 않지만(<code>NaN !== NaN</code>), <code>NaN</code>을 서로 구분할 수도 없기 때문에 아래 예제도 잘 동작합니다.</p> + +<pre class="brush: js">let myMap = new Map() +myMap.set(NaN, 'not a number') + +myMap.get(NaN) +// "not a number" + +let otherNaN = Number('foo') +myMap.get(otherNaN) +// "not a number"</pre> + +<h3 id="for..of로_Map_순회하기"><code>for..of</code><font face="Open Sans, arial, sans-serif">로 </font><code>Map</code> 순회하기</h3> + +<p><code>Map</code>은 <code>for..of</code> 반복문을 사용해 순회할 수 있습니다.</p> + +<pre class="brush: js">let myMap = new Map() +myMap.set(0, 'zero') +myMap.set(1, 'one') + +for (let [key, value] of myMap) { + console.log(key + ' = ' + value) +} +// 0 = zero +// 1 = one + +for (let key of myMap.keys()) { + console.log(key) +} +// 0 +// 1 + +for (let value of myMap.values()) { + console.log(value) +} +// zero +// one + +for (let [key, value] of myMap.entries()) { + console.log(key + ' = ' + value) +} +// 0 = zero +// 1 = one</pre> + +<h3 id="forEach로_Map_순회하기"><code>forEach()</code>로 <code>Map</code> 순회하기</h3> + +<p><code>Map</code>은 {{jsxref("Map.prototype.forEach", "forEach()")}} 메서드로 순회할 수 있습니다.</p> + +<pre class="brush: js">myMap.forEach(function(value, key) { + console.log(key + ' = ' + value) +}) +// 0 = zero +// 1 = one</pre> + +<h3 id="Array_객체와의_관계"><code>Array</code> 객체와의 관계</h3> + +<pre class="brush: js">let kvArray = [['key1', 'value1'], ['key2', 'value2']] + +// Use the regular Map constructor to transform a 2D key-value Array into a map +let myMap = new Map(kvArray) + +myMap.get('key1') // returns "value1" + +// Use Array.from() to transform a map into a 2D key-value Array +console.log(Array.from(myMap)) // Will show you exactly the same Array as kvArray + +// A succinct way to do the same, using the spread syntax +console.log([...myMap]) + +// Or use the keys() or values() iterators, and convert them to an array +console.log(Array.from(myMap.keys())) // ["key1", "key2"]</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-map-objects', 'Map')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.Map")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Set")}}</li> + <li>{{jsxref("WeakMap")}}</li> + <li>{{jsxref("WeakSet")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/map/map/index.html b/files/ko/web/javascript/reference/global_objects/map/map/index.html new file mode 100644 index 0000000000..012772eec5 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/map/map/index.html @@ -0,0 +1,60 @@ +--- +title: Map() 생성자 +slug: Web/JavaScript/Reference/Global_Objects/Map/Map +tags: + - Constructor + - JavaScript + - Map + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Map/Map +--- +<div>{{JSRef}}</div> + +<p><strong><code>Map()</code> 생성자</strong>는 {{jsxref("Map")}} 객체를 생성합니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">new Map([<var>iterable</var>])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code><var>iterable</var></code></dt> + <dd>요소가 키-값 쌍인, {{jsxref("Array")}} 또는 다른 순회 가능한 객체(예: <code>[[1, 'one'], [2, 'two']]</code>). 각 키-값 쌍은 새로운 <code>Map</code>에 포함됩니다.</dd> +</dl> + +<h2 id="예제">예제</h2> + +<pre class="brush: js">let myMap = new Map([ + [1, 'one'], + [2, 'two'], + [3, 'three'], +]) +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-map-constructor', 'Map constructor')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Map.Map")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Set")}}</li> + <li>{{jsxref("WeakMap")}}</li> + <li>{{jsxref("WeakSet")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/map/prototype/index.html b/files/ko/web/javascript/reference/global_objects/map/prototype/index.html new file mode 100644 index 0000000000..633d2c785e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/map/prototype/index.html @@ -0,0 +1,86 @@ +--- +title: Map.prototype +slug: Web/JavaScript/Reference/Global_Objects/Map/prototype +tags: + - ECMAScript 2015 + - JavaScript + - Map + - Property + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Map +--- +<div>{{JSRef}}</div> + +<p><code><strong>Map</strong></code><strong><code>.prototype</code></strong> property는 {{jsxref("Map")}}의 프로토 타입을 나타낸다.</p> + +<div>{{js_property_attributes(0,0,0)}}</div> + +<h2 id="Description">Description</h2> + +<p>{{jsxref("Map")}} instance는 {{jsxref("Map.prototype")}}를 상속한다. Constructor의 프로토타입에 property와 method를 추가함으로써 모든 <code>Map</code> 인스턴스에서 사용 가능하게끔 만들 수 있다.</p> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt><code>Map.prototype.constructor</code></dt> + <dd>인스턴스의 프로토타입을 만드는 함수를 반환한다. 이것 {{jsxref("Map")}} 함수의 기본 값이다.</dd> + <dt>{{jsxref("Map.prototype.size")}}</dt> + <dd><code>Map</code> 객체에 들어있는 key/value pair의 수를 반환한다.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{jsxref("Map.prototype.clear()")}}</dt> + <dd><code>Map</code> 객체의 모든 key/value pair를 제거한다.</dd> + <dt>{{jsxref("Map.delete", "Map.prototype.delete(key)")}}</dt> + <dd>주어진 키(Key)와 해당되는 값(Value)를 제거하고 제거하기 전에 <code>Map.prototype.has(key)가 반환했던 값을 반환한다.</code> 그 후의 <code>Map.prototype.has(key)<font face="Open Sans, arial, sans-serif">는 </font></code><code>false를 반환한다.</code></dd> + <dt>{{jsxref("Map.prototype.entries()")}}</dt> + <dd><code>Map</code> 객체 안의 모든 요소들을 <strong><code>[key, value] 형태의 </code>array </strong>로 집어넣은 순서대로 가지고 있는 <code>Iterator 객체를 반환한다.</code></dd> + <dt>{{jsxref("Map.forEach", "Map.prototype.forEach(callbackFn[, thisArg])")}}</dt> + <dd><code>Map</code> 객체 안에 존재하는 각각의 key/value pair에 집어넣은 순서대로 callbackFn을 부른다. 만약 thisArg 매개변수가 제공되면, 이것이 각 callback의 this 값으로 사용된다.</dd> + <dt>{{jsxref("Map.get", "Map.prototype.get(key)")}}</dt> + <dd>주어진 키(Key)에 해당되는 값(value)을 반환하고, 만약 없으면 <code>undefined를 반환한다.</code></dd> + <dt>{{jsxref("Map.has", "Map.prototype.has(key)")}}</dt> + <dd><code>Map 객체 안에 주어진 </code>key/value pair가 있는지 검사하고 Boolean 값을 반환한다.</dd> + <dt>{{jsxref("Map.prototype.keys()")}}</dt> + <dd><code>Map</code> 객체 안의 모든 <strong>키(Key)</strong>들을 집어넣은 순서대로 가지고 있는 <code>Iterator 객체를 반환한다.</code></dd> + <dt>{{jsxref("Map.set", "Map.prototype.set(key, value)")}}</dt> + <dd><code>Map 객체에 주어진 키</code>(Key)에 값(Value)를 집어넣고, <code>Map 객체를 반환한다.</code></dd> + <dt>{{jsxref("Map.prototype.values()")}}</dt> + <dd><code>Map</code> 객체 안의 모든 <strong>값</strong><strong>(Value)</strong>들을 집어넣은 순서대로 가지고 있는 <code>Iterator 객체를 반환한다.</code></dd> + <dt>{{jsxref("Map.@@iterator", "Map.prototype[@@iterator]()")}}</dt> + <dd><code>Map</code> 객체 안의 모든 요소들을 <strong><code>[key, value] 형태의 </code>array </strong>로 집어넣은 순서대로 가지고 있는 <code>Iterator 객체를 반환한다.</code></dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-map.prototype', 'Map.prototype')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-map.prototype', 'Map.prototype')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{Compat("javascript.builtins.Map.prototype")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Set.prototype")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/map/set/index.html b/files/ko/web/javascript/reference/global_objects/map/set/index.html new file mode 100644 index 0000000000..a6c5afb140 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/map/set/index.html @@ -0,0 +1,96 @@ +--- +title: Map.prototype.set() +slug: Web/JavaScript/Reference/Global_Objects/Map/set +tags: + - ECMAScript 2015 + - JavaScript + - Map + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Map/set +--- +<div>{{JSRef}}</div> + +<p><code><strong>set()</strong></code> 메서드는 Map 객체에서 주어진 키를 가진 요소를 추가하고, 키의 요소가 이미 있다면 대체합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/map-prototype-set.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><em>myMap</em>.set(<em>key</em>, <em>value</em>);</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>key</code></dt> + <dd><code>Map</code>에 추가하거나 변경할 요소의 키.</dd> + <dt><code>value</code></dt> + <dd><code>Map</code>에 추가하거나 변경할 요소의 값.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>호출한 <code>Map</code> 객체.</p> + +<h2 id="예제">예제</h2> + +<h3 id="set()_사용하기"><code>set()</code> 사용하기</h3> + +<pre class="brush: js">var myMap = new Map(); + +// Add new elements to the map +myMap.set('bar', 'foo'); +myMap.set(1, 'foobar'); + +// Update an element in the map +myMap.set('bar', 'baz'); +</pre> + +<h3 id="set()_체이닝"><code>set()</code> 체이닝</h3> + +<p><code>set()</code>이 같은 <code>Map</code>을 반환하므로 메서드를 여러 번 연속해서 호출할 수 있습니다.</p> + +<pre class="brush: js">// Add new elements to the map with chaining. +myMap.set('bar', 'foo') + .set(1, 'foobar') + .set(2, 'baz'); +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-map.prototype.set', 'Map.prototype.set')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-map.prototype.set', 'Map.prototype.set')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Map.set")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Map")}}</li> + <li>{{jsxref("Map.prototype.get()")}}</li> + <li>{{jsxref("Map.prototype.has()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/map/size/index.html b/files/ko/web/javascript/reference/global_objects/map/size/index.html new file mode 100644 index 0000000000..371d8b3110 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/map/size/index.html @@ -0,0 +1,62 @@ +--- +title: Map.prototype.size +slug: Web/JavaScript/Reference/Global_Objects/Map/size +translation_of: Web/JavaScript/Reference/Global_Objects/Map/size +--- +<div>{{JSRef}}</div> + +<p><code><strong>size</strong></code> 접근자 프로퍼티는 {{jsxref("Map")}} 객체의 요소 갯수를 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/map-prototype-size.html")}}</div> + + + +<h2 id="설명">설명</h2> + +<p><code>size</code> 값은 얼마나 많은 엔트리를 <code>Map</code> 객체가 가지고 있는지를 표현합니다. <code>size</code> 를 설정할 수 있는 접근자 함수는 <code>undefined</code> 입니다. 당신은 이 프로퍼티를 변경할 수 없습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="Using_size">Using <code>size</code></h3> + +<pre class="brush:js">var myMap = new Map(); +myMap.set('a', 'alpha'); +myMap.set('b', 'beta'); +myMap.set('g', 'gamma'); + +myMap.size // 3 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-get-map.prototype.size', 'Map.prototype.size')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-get-map.prototype.size', 'Map.prototype.size')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Map.size")}}</p> + +<h2 id="더_보기">더 보기</h2> + +<ul> + <li>{{jsxref("Map")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/math/abs/index.html b/files/ko/web/javascript/reference/global_objects/math/abs/index.html new file mode 100644 index 0000000000..c66172647d --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/abs/index.html @@ -0,0 +1,104 @@ +--- +title: Math.abs() +slug: Web/JavaScript/Reference/Global_Objects/Math/abs +tags: + - JavaScript + - Math + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/abs +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary"><strong><code>Math.abs()</code></strong> 함수는 주어진 숫자의 절대값을 반환합니다.</span> 즉,</p> + +<p><math display="block"><semantics><mrow><mstyle mathvariant="monospace"><mrow><mo lspace="0em" rspace="thinmathspace">Math.abs</mo><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo></mrow></mstyle><mo>=</mo><mrow><mo stretchy="false">|</mo><mi>x</mi><mo stretchy="false">|</mo></mrow><mo>=</mo><mrow><mo>{</mo><mtable columnalign="left left"><mtr><mtd><mi>x</mi></mtd><mtd><mtext>if</mtext><mspace width="1em"></mspace><mi>x</mi><mo>></mo><mn>0</mn></mtd></mtr><mtr><mtd><mi>0</mi></mtd><mtd><mtext>if</mtext><mspace width="1em"></mspace><mi>x</mi><mo>=</mo><mn>0</mn></mtd></mtr><mtr><mtd><mo>-</mo><mi>x</mi></mtd><mtd><mtext>if</mtext><mspace width="1em"></mspace><mi>x</mi><mo><</mo><mn>0</mn></mtd></mtr></mtable></mrow></mrow><annotation encoding="TeX">{\mathtt{\operatorname{Math.abs}(x)}} = {|x|} = \begin{cases} x & \text{if} \quad x \geq 0 \\ -x & \text{if} \quad x < 0 \end{cases} </annotation></semantics></math></p> + +<div>{{EmbedInteractiveExample("pages/js/math-abs.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">Math.abs(<var>x</var>)</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>x</code></dt> + <dd>숫자.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 숫자의 절대값.</p> + +<h2 id="설명">설명</h2> + +<p><code>abs()</code>는 <code>Math</code>의 정적 메서드이므로, 사용자가 생성한 <code>Math</code> 객체의 메서드로 호출할 수 없고 항상 <code>Math.abs()</code>를 사용해야 합니다. (<code>Math</code>는 생성자가 아닙니다)</p> + +<h2 id="예제">예제</h2> + +<h3 id="Math.abs()의_작동_방식"><code>Math.abs()</code>의 작동 방식</h3> + +<p>빈 객체, 하나 이상의 요소를 가진 배열, 숫자가 아닌 문자열, {{jsxref("undefined")}}나 빈 매개변수를 받으면 {{jsxref("NaN")}}을 반환합니다. {{jsxref("null")}}, 빈 문자열이나 빈 배열을 제공하면 0을 반환합니다.</p> + +<pre class="brush: js" dir="rtl">Math.abs('-1'); // 1 +Math.abs(-2); // 2 +Math.abs(null); // 0 +Math.abs(''); // 0 +Math.abs([]); // 0 +Math.abs([2]); // 2 +Math.abs([1,2]); // NaN +Math.abs({}); // NaN +Math.abs('string'); // NaN +Math.abs(); // NaN +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8.2.1', 'Math.abs')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.abs', 'Math.abs')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.abs', 'Math.abs')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Math.abs")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Math.ceil()")}}</li> + <li>{{jsxref("Math.floor()")}}</li> + <li>{{jsxref("Math.round()")}}</li> + <li>{{jsxref("Math.sign()")}}</li> + <li>{{jsxref("Math.trunc()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/math/acos/index.html b/files/ko/web/javascript/reference/global_objects/math/acos/index.html new file mode 100644 index 0000000000..83cc67d786 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/acos/index.html @@ -0,0 +1,103 @@ +--- +title: Math.acos() +slug: Web/JavaScript/Reference/Global_Objects/Math/acos +tags: + - JavaScript + - Math + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/acos +--- +<div>{{JSRef}}</div> + +<p><strong><code>Math.acos()</code></strong> 함수는 주어진 수의 아크코사인 값을 숫자(라디안)로 반환합니다. 즉,</p> + +<p><math display="block"><semantics><mrow><mo>∀</mo><mi>x</mi><mo>∊</mo><mo stretchy="false">[</mo><mrow><mo>-</mo><mn>1</mn></mrow><mo>;</mo><mn>1</mn><mo stretchy="false">]</mo><mo>,</mo><mspace width="thickmathspace"></mspace><mstyle mathvariant="monospace"><mrow><mo lspace="0em" rspace="thinmathspace">Math.acos</mo><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo></mrow></mstyle><mo>=</mo><mo lspace="0em" rspace="0em">arccos</mo><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><mtext> the unique </mtext><mspace width="thickmathspace"></mspace><mi>y</mi><mo>∊</mo><mo stretchy="false">[</mo><mn>0</mn><mo>;</mo><mi>π</mi><mo stretchy="false">]</mo><mspace width="thinmathspace"></mspace><mtext>such that</mtext><mspace width="thickmathspace"></mspace><mo lspace="0em" rspace="0em">cos</mo><mo stretchy="false">(</mo><mi>y</mi><mo stretchy="false">)</mo><mo>=</mo><mi>x</mi></mrow><annotation encoding="TeX">\forall x \in [{-1};1],\;\mathtt{\operatorname{Math.acos}(x)} = \arccos(x) = \text{ the unique } \; y \in [0; \pi] \, \text{such that} \; \cos(y) = x</annotation></semantics></math></p> + +<div>{{EmbedInteractiveExample("pages/js/math-acos.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code>Math.acos(<var>x</var>)</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>x</code></dt> + <dd>각도를 나타내는 라디안.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>-1과 1 사이의 값이 주어진 경우, 그 값의 아크코사인. 아닐 경우 {{jsxref("NaN")}}</p> + +<h2 id="설명">설명</h2> + +<p>The <code>Math.acos()</code> method returns a numeric value between 0 and π radians for <code>x</code> between -1 and 1. If the value of <code>x</code> is outside this range, it returns {{jsxref("NaN")}}.</p> + +<p>Because <code>acos()</code> is a static method of <code>Math</code>, you always use it as <code>Math.acos()</code>, rather than as a method of a <code>Math</code> object you created (<code>Math</code> is not a constructor).</p> + +<h2 id="예제">예제</h2> + +<h3 id="Using_Math.acos()">Using <code>Math.acos()</code></h3> + +<pre class="brush: js">Math.acos(-2); // NaN +Math.acos(-1); // 3.141592653589793 +Math.acos(0); // 1.5707963267948966 +Math.acos(0.5); // 1.0471975511965979 +Math.acos(1); // 0 +Math.acos(2); // NaN +</pre> + +<p>For values less than -1 or greater than 1, <code>Math.acos()</code> returns {{jsxref("NaN")}}.</p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8.2.2', 'Math.acos')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.acos', 'Math.acos')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.acos', 'Math.acos')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Math.acos")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Math.asin()")}}</li> + <li>{{jsxref("Math.atan()")}}</li> + <li>{{jsxref("Math.atan2()")}}</li> + <li>{{jsxref("Math.cos()")}}</li> + <li>{{jsxref("Math.sin()")}}</li> + <li>{{jsxref("Math.tan()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/math/cbrt/index.html b/files/ko/web/javascript/reference/global_objects/math/cbrt/index.html new file mode 100644 index 0000000000..20a5f3ee3a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/cbrt/index.html @@ -0,0 +1,98 @@ +--- +title: Math.cbrt() +slug: Web/JavaScript/Reference/Global_Objects/Math/cbrt +tags: + - JavaScript + - Math + - Method + - Reference + - 세제곱근 +translation_of: Web/JavaScript/Reference/Global_Objects/Math/cbrt +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary"><strong><code>Math.cbrt()</code></strong> 함수는 주어진 수의 세제곱근을 반환합니다.</span> 즉,</p> + +<p><math display="block"><semantics><mrow><mstyle mathvariant="monospace"><mrow><mi>M</mi><mi>a</mi><mi>t</mi><mi>h</mi><mo>.</mo><mi>c</mi><mi>b</mi><mi>r</mi><mi>t</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo></mrow></mstyle><mo>=</mo><mroot><mi>x</mi><mn>3</mn></mroot><mo>=</mo><mtext>the unique</mtext><mspace width="thickmathspace"></mspace><mi>y</mi><mspace width="thickmathspace"></mspace><mtext>such that</mtext><mspace width="thickmathspace"></mspace><msup><mi>y</mi><mn>3</mn></msup><mo>=</mo><mi>x</mi></mrow><annotation encoding="TeX">\mathtt{Math.cbrt(x)} = \sqrt[3]{x} = \text{the unique} \; y \; \text{such that} \; y^3 = x</annotation></semantics></math></p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code>Math.cbrt(<var>x</var>)</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>x</code></dt> + <dd>숫자.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 수의 세제곱근.</p> + +<h2 id="설명">설명</h2> + +<p><code>cbrt()</code>는 <code>Math</code>의 정적 메서드이므로, 사용자가 생성한 <code>Math</code> 객체의 메서드로 호출할 수 없고 항상 <code>Math.cbrt()</code>를 사용해야 합니다. (<code>Math</code>는 생성자가 아닙니다)</p> + +<h2 id="예제">예제</h2> + +<h3 id="Math.cbrt()_사용하기"><code>Math.cbrt()</code> 사용하기</h3> + +<pre class="brush: js">Math.cbrt(NaN); // NaN +Math.cbrt(-1); // -1 +Math.cbrt(-0); // -0 +Math.cbrt(-Infinity); // -Infinity +Math.cbrt(0); // 0 +Math.cbrt(1); // 1 +Math.cbrt(Infinity); // Infinity +Math.cbrt(null); // 0 +Math.cbrt(2); // 1.2599210498948734 +</pre> + +<h2 id="폴리필">폴리필</h2> + +<p>모든 <math><semantics><mrow><mi>x</mi><mo>≥</mo><mn>0</mn></mrow><annotation encoding="TeX">x \geq 0</annotation></semantics></math>에서 <math><semantics><mrow><mroot><mi>x</mi><mn>3</mn></mroot><mo>=</mo><msup><mi>x</mi><mrow><mn>1</mn><mo>/</mo><mn>3</mn></mrow></msup></mrow><annotation encoding="TeX">\sqrt[3]{x} = x^{1/3}</annotation></semantics></math> 이므로, <code>Math.cbrt()</code>는 다음 함수로 폴리필할 수 있습니다.</p> + +<pre class="brush: js">if (!Math.cbrt) { + Math.cbrt = (function(pow) { + return function cbrt(){ + // ensure negative numbers remain negative: + return x < 0 ? -pow(-x, 1/3) : pow(x, 1/3); + }; + })(Math.pow); // localize Math.pow to increase efficiency +}</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.cbrt', 'Math.cbrt')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.cbrt', 'Math.cbrt')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Math.cbrt")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Math.pow()")}}</li> + <li>{{jsxref("Math.sqrt()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/math/ceil/index.html b/files/ko/web/javascript/reference/global_objects/math/ceil/index.html new file mode 100644 index 0000000000..ee5998fa83 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/ceil/index.html @@ -0,0 +1,209 @@ +--- +title: Math.ceil() +slug: Web/JavaScript/Reference/Global_Objects/Math/ceil +translation_of: Web/JavaScript/Reference/Global_Objects/Math/ceil +--- +<div>{{JSRef}}</div> + +<div>Math.ceil() 함수는 주어진 숫자보다 크거나 같은 숫자 중 가장 작은 숫자를 integer 로 반환합니다.</div> + +<div> </div> + +<h2 id="Syntax_(문법)">Syntax (문법)</h2> + +<pre class="syntaxbox"><code>Math.ceil(<var>x</var>)</code></pre> + +<h3 id="Parameters_(매개변수)">Parameters (매개변수)</h3> + +<dl> + <dt><code>x</code></dt> + <dd>숫자</dd> +</dl> + +<h3 id="Return_value_(반환값)">Return value (반환값)</h3> + +<p>주어진 숫자보다 크거나 같은 숫자 중 가장 작은 숫자</p> + +<h2 id="Description_(설명)">Description (설명)</h2> + +<p>ceil() 은 Math 의 정적 메소드이므로, 사용자가 생성하는 Math 객체의 메소드처럼 사용하지 않고, 언제나 Math.ceil() 의 형태로 사용 합니다. (Math 는 생성자가 아님)</p> + +<h2 id="Examples_(예제)">Examples (예제)</h2> + +<h3 id="Math.ceil()_사용_예">Math.ceil() 사용 예</h3> + +<p>다음은 Math.ceil() 의 사용 예입니다.</p> + +<pre class="brush: js">Math.ceil(.95); // 1 +Math.ceil(4); // 4 +Math.ceil(7.004); // 8 +Math.ceil(-0.95); // -0 +Math.ceil(-4); // -4 +Math.ceil(-7.004); // -7 +</pre> + +<h3 id="소수점_처리">소수점 처리</h3> + +<pre class="brush: js">// Closure +(function() { + /** + * Decimal adjustment of a number. + * + * @param {String} type The type of adjustment. + * @param {Number} value The number. + * @param {Integer} exp The exponent (the 10 logarithm of the adjustment base). + * @returns {Number} The adjusted value. + */ + function decimalAdjust(type, value, exp) { + // If the exp is undefined or zero... + if (typeof exp === 'undefined' || +exp === 0) { + return Math[type](value); + } + value = +value; + exp = +exp; + // If the value is not a number or the exp is not an integer... + if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) { + return NaN; + } + // Shift + value = value.toString().split('e'); + value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp))); + // Shift back + value = value.toString().split('e'); + return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp)); + } + + // Decimal round + if (!Math.round10) { + Math.round10 = function(value, exp) { + return decimalAdjust('round', value, exp); + }; + } + // Decimal floor + if (!Math.floor10) { + Math.floor10 = function(value, exp) { + return decimalAdjust('floor', value, exp); + }; + } + // Decimal ceil + if (!Math.ceil10) { + Math.ceil10 = function(value, exp) { + return decimalAdjust('ceil', value, exp); + }; + } +})(); + +// Round +Math.round10(55.55, -1); // 55.6 +Math.round10(55.549, -1); // 55.5 +Math.round10(55, 1); // 60 +Math.round10(54.9, 1); // 50 +Math.round10(-55.55, -1); // -55.5 +Math.round10(-55.551, -1); // -55.6 +Math.round10(-55, 1); // -50 +Math.round10(-55.1, 1); // -60 +// Floor +Math.floor10(55.59, -1); // 55.5 +Math.floor10(59, 1); // 50 +Math.floor10(-55.51, -1); // -55.6 +Math.floor10(-51, 1); // -60 +// Ceil +Math.ceil10(55.51, -1); // 55.6 +Math.ceil10(51, 1); // 60 +Math.ceil10(-55.59, -1); // -55.5 +Math.ceil10(-59, 1); // -50 +</pre> + +<h2 id="Specifications_(사용법)">Specifications (사용법)</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8.2.6', 'Math.ceil')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.ceil', 'Math.ceil')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.ceil', 'Math.ceil')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility_(브라우저_호환성)">Browser compatibility (브라우저 호환성)</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also_(추가_참조)">See also (추가 참조)</h2> + +<ul> + <li>{{jsxref("Math.abs()")}}</li> + <li>{{jsxref("Math.floor()")}}</li> + <li>{{jsxref("Math.round()")}}</li> + <li>{{jsxref("Math.sign()")}}</li> + <li>{{jsxref("Math.trunc()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/math/e/index.html b/files/ko/web/javascript/reference/global_objects/math/e/index.html new file mode 100644 index 0000000000..d2d4060bed --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/e/index.html @@ -0,0 +1,84 @@ +--- +title: Math.E +slug: Web/JavaScript/Reference/Global_Objects/Math/E +tags: + - JavaScript + - Math + - Property + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/E +--- +<div>{{JSRef}}</div> + +<p><strong><code>Math.E</code></strong> 속성은 자연로그의 밑 값 e를 나타내며 약 2.718의 값을 가집니다.</p> + +<p><math display="block"><semantics><mrow><mstyle mathvariant="monospace"><mi>Math.E</mi></mstyle><mo>=</mo><mi>e</mi><mo>≈</mo><mn>2.718</mn></mrow><annotation encoding="TeX">\mathtt{\mi{Math.E}} = e \approx 2.718</annotation></semantics></math></p> + +<div>{{EmbedInteractiveExample("pages/js/math-e.html")}}</div> + + + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="설명">설명</h2> + +<p><code>E</code>는 <code>Math</code>의 정적 속성이므로, 사용자가 생성한 <code>Math</code> 객체의 속성으로 접근할 수 없고 항상 <code>Math.E</code>를 사용해야 합니다. (<code>Math</code>는 생성자가 아닙니다)</p> + +<h2 id="예제">예제</h2> + +<h3 id="Math.E_사용하기"><code>Math.E</code> 사용하기</h3> + +<p>다음 함수는 e 값을 반환합니다.</p> + +<pre class="brush: js">function getNapier() { + return Math.E; +} + +getNapier(); // 2.718281828459045 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8.1.1', 'Math.E')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.e', 'Math.E')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.e', 'Math.E')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Math.E")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Math.exp()")}}</li> + <li>{{jsxref("Math.log()")}}</li> + <li>{{jsxref("Math.log1p()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/math/exp/index.html b/files/ko/web/javascript/reference/global_objects/math/exp/index.html new file mode 100644 index 0000000000..c00f391045 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/exp/index.html @@ -0,0 +1,90 @@ +--- +title: Math.exp() +slug: Web/JavaScript/Reference/Global_Objects/Math/exp +translation_of: Web/JavaScript/Reference/Global_Objects/Math/exp +--- +<div>{{JSRef}}</div> + +<p> <strong><code>Math.exp()</code></strong>함수는 <code>x</code>를 인수로 하는 <code>e<sup>x</sup></code> 값을 반환합니다. 그리고 <code>e</code>는 {{jsxref("Math.E", "오일러 상수(또는 네이피어 상수)", "", 1)}}는 자연 로그의 밑입니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/math-exp.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code>Math.exp(<var>x</var>)</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>x</code></dt> + <dd>숫자</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p><code>e</code>는 {{jsxref("Math.E", "오일러 상수", "", 1)}}이고 <code>x</code>는 인수인 <code>e<sup>x</sup></code>값</p> + +<h2 id="Description">Description</h2> + +<p><code>exp()</code>는 <code>Math</code>의 정적 메소드이기 때문에 새로 작성한 <code>Math</code> 오브젝트 대신에 항상 <code>Math.exp()</code>의 형태로 써야 합니다. (<code>Math</code>는 생성자가 아닙니다.)</p> + +<h2 id="예시">예시</h2> + +<h3 id="Math.exp_사용_예"> <code>Math.exp()</code> 사용 예</h3> + +<pre class="brush: js">Math.exp(-1); // 0.36787944117144233 +Math.exp(0); // 1 +Math.exp(1); // 2.718281828459045 +</pre> + +<h2 id="설명">설명</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">설명</th> + <th scope="col">상태</th> + <th scope="col">비고</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>최초의 정의. JavaScript 1.0.에서 첫 시행.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8.2.8', 'Math.exp')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.exp', 'Math.exp')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.exp', 'Math.exp')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Math.exp")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Math.E")}}</li> + <li>{{jsxref("Math.expm1()")}}</li> + <li>{{jsxref("Math.log()")}}</li> + <li>{{jsxref("Math.log10()")}}</li> + <li>{{jsxref("Math.log1p()")}}</li> + <li>{{jsxref("Math.log2()")}}</li> + <li>{{jsxref("Math.pow()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/math/floor/index.html b/files/ko/web/javascript/reference/global_objects/math/floor/index.html new file mode 100644 index 0000000000..cd749b07c8 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/floor/index.html @@ -0,0 +1,171 @@ +--- +title: Math.floor() +slug: Web/JavaScript/Reference/Global_Objects/Math/floor +tags: + - JavaScript + - Math + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/floor +--- +<div>{{JSRef}}</div> + +<p><strong><code>Math.floor()</code></strong> 함수는 주어진 숫자와 같거나 작은 정수 중에서 가장 큰 수를 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/math-floor.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">Math.floor(<var>x</var>)</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>x</code></dt> + <dd>숫자.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 수 이하의 가장 큰 정수.</p> + +<h2 id="설명">설명</h2> + +<p><code>floor()</code>는 <code>Math</code>의 정적 메서드이므로, 사용자가 생성한 <code>Math</code> 객체의 메서드로 호출할 수 없고 항상 <code>Math.floor()</code>를 사용해야 합니다. (<code>Math</code>는 생성자가 아닙니다)</p> + +<div class="blockIndicator note"> +<p><strong>참고</strong>: <code>Math.floor(null)</code>은 {{jsxref("NaN")}} 대신 0을 반환합니다.</p> +</div> + +<h2 id="예제">예제</h2> + +<h3 id="Math.floor()_사용하기"><code>Math.floor()</code> 사용하기</h3> + +<pre class="brush: js">Math.floor( 45.95); // 45 +Math.floor( 45.05); // 45 +Math.floor( 4 ); // 4 +Math.floor(-45.05); // -46 +Math.floor(-45.95); // -46 +</pre> + +<h3 id="십진수_조절">십진수 조절</h3> + +<pre class="brush: js">// Closure +(function() { + /** + * Decimal adjustment of a number. + * + * @param {String} type The type of adjustment. + * @param {Number} value The number. + * @param {Integer} exp The exponent (the 10 logarithm of the adjustment base). + * @returns {Number} The adjusted value. + */ + function decimalAdjust(type, value, exp) { + // If the exp is undefined or zero... + if (typeof exp === 'undefined' || +exp === 0) { + return Math[type](value); + } + value = +value; + exp = +exp; + // If the value is not a number or the exp is not an integer... + if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) { + return NaN; + } + // Shift + value = value.toString().split('e'); + value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp))); + // Shift back + value = value.toString().split('e'); + return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp)); + } + + // Decimal round + if (!Math.round10) { + Math.round10 = function(value, exp) { + return decimalAdjust('round', value, exp); + }; + } + // Decimal floor + if (!Math.floor10) { + Math.floor10 = function(value, exp) { + return decimalAdjust('floor', value, exp); + }; + } + // Decimal ceil + if (!Math.ceil10) { + Math.ceil10 = function(value, exp) { + return decimalAdjust('ceil', value, exp); + }; + } +})(); + +// Round +Math.round10(55.55, -1); // 55.6 +Math.round10(55.549, -1); // 55.5 +Math.round10(55, 1); // 60 +Math.round10(54.9, 1); // 50 +Math.round10(-55.55, -1); // -55.5 +Math.round10(-55.551, -1); // -55.6 +Math.round10(-55, 1); // -50 +Math.round10(-55.1, 1); // -60 +// Floor +Math.floor10(55.59, -1); // 55.5 +Math.floor10(59, 1); // 50 +Math.floor10(-55.51, -1); // -55.6 +Math.floor10(-51, 1); // -60 +// Ceil +Math.ceil10(55.51, -1); // 55.6 +Math.ceil10(51, 1); // 60 +Math.ceil10(-55.59, -1); // -55.5 +Math.ceil10(-59, 1); // -50 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8.2.9', 'Math.floor')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.floor', 'Math.floor')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.floor', 'Math.floor')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Math.floor")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Math.abs()")}}</li> + <li>{{jsxref("Math.ceil()")}}</li> + <li>{{jsxref("Math.round()")}}</li> + <li>{{jsxref("Math.sign()")}}</li> + <li>{{jsxref("Math.trunc()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/math/fround/index.html b/files/ko/web/javascript/reference/global_objects/math/fround/index.html new file mode 100644 index 0000000000..6fd328a2db --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/fround/index.html @@ -0,0 +1,130 @@ +--- +title: Math.fround() +slug: Web/JavaScript/Reference/Global_Objects/Math/fround +tags: + - JavaScript + - Math + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/fround +--- +<div>{{JSRef}}</div> + +<p><strong><code>Math.fround()</code></strong> 함수는 <a class="external" href="https://en.wikipedia.org/wiki/Single-precision_floating-point_format" title="link to the wikipedia page on single-precision floating-point format">single precision</a> 포맷으로 표현할 수 있는 실수들 중에서 가장 가까운 숫자를 리턴합니다.</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox"><code>Math.fround(<var>x</var>)</code></pre> + +<h3 id="파라메터">파라메터</h3> + +<dl> + <dt><code>x</code></dt> + <dd>숫자.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p><code>fround()</code> 가 <code>Math</code> 객체의 정적 메소드이기 때문에, 반드시 <code>Math.fround()</code> 같은 형태로 사용해야 합니다. <code>Math</code> 객체를 직접 만들어서 호출하는 방식으로 사용하지 않습니다 (<code>Math</code> 는 생성자가 아닙니다).</p> + +<h2 id="예제">예제</h2> + +<h3 id="Math.fround()_사용법"><code>Math.fround() 사용법</code></h3> + +<pre class="brush: js">Math.fround(0); // 0 +Math.fround(1); // 1 +Math.fround(1.337); // 1.3370000123977661 +Math.fround(1.5); // 1.5 +Math.fround(NaN); // NaN +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>만약 {{jsxref("Float32Array")}} 가 지원된다면, Math.fround() 를 다음 함수로 흉내낼 수 있습니다.</p> + +<pre class="brush: js">Math.fround = Math.fround || (function (array) { + return function(x) { + return array[0] = x, array[0]; + }; +})(Float32Array(1)); +</pre> + +<h2 id="스펙">스펙</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">비고</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.fround', 'Math.fround')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.fround', 'Math.fround')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("38")}}</td> + <td>{{CompatGeckoDesktop("26")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatOpera("25")}}</td> + <td>{{CompatSafari("7.1")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>8</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Math.round()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/math/imul/index.html b/files/ko/web/javascript/reference/global_objects/math/imul/index.html new file mode 100644 index 0000000000..e5f7a919ab --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/imul/index.html @@ -0,0 +1,130 @@ +--- +title: Math.imul() +slug: Web/JavaScript/Reference/Global_Objects/Math/imul +tags: + - JavaScript + - Math + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/imul +--- +<div>{{JSRef}}</div> + +<p><strong><code>Math.imul()</code></strong> 함수는 C 언어와 같은 양식으로 2개 파라메터의 32-bit 곱셈 결과를 리턴합니다.</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox"><code>Math.imul(<var>a</var>, <var>b</var>)</code></pre> + +<h3 id="파라메터">파라메터</h3> + +<dl> + <dt><code>a</code></dt> + <dd>첫 번째 숫자.</dd> + <dt><code>b</code></dt> + <dd>두 번째 숫자.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p><code>Math.imul()</code> 를 쓰면 C 언어와 같은 양식의 빠른 32-bit 정수 곱셈이 가능합니다. 이 기능은 <a href="http://en.wikipedia.org/wiki/Emscripten">Emscripten</a> 같은 프로젝트에 유용합니다. <code>imul()</code> 이 <code>Math </code> 객체의 정적 메소드이기 때문에, <code>Math 객체를 직접 만들어서 사용하지 않고 (Math 는 생성자가 아닙니다), Math.imul()</code> 같은 형태로 사용합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="Math.imul()_사용법"><code>Math.imul() 사용법</code></h3> + +<pre class="brush: js">Math.imul(2, 4); // 8 +Math.imul(-1, 8); // -8 +Math.imul(-2, -2); // 4 +Math.imul(0xffffffff, 5); // -5 +Math.imul(0xfffffffe, 5); // -10 +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>다음과 같은 함수로 Math.imul() 을 흉내낼 수 있습니다.</p> + +<pre class="brush: js">Math.imul = Math.imul || function(a, b) { + var ah = (a >>> 16) & 0xffff; + var al = a & 0xffff; + var bh = (b >>> 16) & 0xffff; + var bl = b & 0xffff; + // the shift by 0 fixes the sign on the high part + // the final |0 converts the unsigned value into a signed value + return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0)|0); +}; +</pre> + +<h2 id="스펙">스펙</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">비고</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.imul', 'Math.imul')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.imul', 'Math.imul')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("28")}}</td> + <td>{{CompatGeckoDesktop("20")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatOpera("16")}}</td> + <td>{{CompatSafari("7")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("20")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>7</td> + </tr> + </tbody> +</table> +</div> diff --git a/files/ko/web/javascript/reference/global_objects/math/index.html b/files/ko/web/javascript/reference/global_objects/math/index.html new file mode 100644 index 0000000000..3ce1a0638c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/index.html @@ -0,0 +1,155 @@ +--- +title: Math +slug: Web/JavaScript/Reference/Global_Objects/Math +tags: + - JavaScript + - Math + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary"><strong><code>Math</code></strong>는 수학적인 상수와 함수를 위한 속성과 메서드를 가진 내장 객체입니다.</span> 함수 객체가 아닙니다.</p> + +<p><code>Math</code>는 {{jsxref("Number")}} 자료형만 지원하며 {{jsxref("BigInt")}}와는 사용할 수 없습니다.</p> + +<h2 id="설명">설명</h2> + +<p>다른 전역 객체와 달리 <code>Math</code>는 생성자가 아닙니다. <code>Math</code>의 모든 속성과 메서드는 정적입니다. 파이 상수는 <code>Math.PI</code>로 참조할 수 있고, 사인 함수는 매개변수 <code>x</code>에 대해 <code>Math.sin(x)</code>와 같이 호출할 수 있습니다. 상수는 JavaScript에서 가능한 최대 실수 정밀도로 정의되어 있습니다.</p> + +<h2 id="속성">속성</h2> + +<dl> + <dt>{{jsxref("Math.E")}}</dt> + <dd> + <p>오일러의 상수이며 자연로그의 밑. 약 <code>2.718</code>.</p> + </dd> + <dt>{{jsxref("Math.LN2")}}</dt> + <dd> + <p><code>2</code>의 자연로그. 약 <code>0.693</code>.</p> + </dd> + <dt>{{jsxref("Math.LN10")}}</dt> + <dd><code>10</code>의 자연로그. 약 <code>2.303</code>.</dd> + <dt>{{jsxref("Math.LOG2E")}}</dt> + <dd>밑이 <code>2</code>인 로그 E. 약 <code>1.443</code>.</dd> + <dt>{{jsxref("Math.LOG10E")}}</dt> + <dd>밑이 <code>10</code>인 로그 E. 약 <code>0.434</code>.</dd> + <dt>{{jsxref("Math.PI")}}</dt> + <dd>원의 둘레와 지름의 비율. 약 <code>3.14159</code>.</dd> + <dt>{{jsxref("Math.SQRT1_2")}}</dt> + <dd>½의 제곱근. 약 <code>0.707</code>.</dd> + <dt>{{jsxref("Math.SQRT2")}}</dt> + <dd><code>2</code>의 제곱근. 약 <code>1.414</code>.</dd> +</dl> + +<h2 id="메서드">메서드</h2> + +<div class="note"> +<p><strong>참고:</strong> 삼각 함수(<code>sin()</code>, <code>cos()</code>, <code>tan()</code>, <code>asin()</code>, <code>acos()</code>, <code>atan()</code>, <code>atan2()</code>)는 매개변수와 반환값 모두 호도법(라디안)을 사용합니다.</p> + +<p>라디안 값을 각도 값으로 변환하려면 <code>(Math.PI / 180)</code>으로 나누세요. 반대로 각도 값에 곱하면 라디안 값이 됩니다.</p> +</div> + +<div class="note"> +<p><strong>참고:</strong> 많은 수의 <code>Math</code> 함수 정확도는 구현에 따라 다를 수 있습니다. 즉, 각 브라우저의 결과가 다를 수 있으며, 서로 같은 JS 엔진이라도 운영체제나 아키텍쳐에 따라서 불일치하는 값을 반환할 수 있습니다.</p> +</div> + +<dl> + <dt>{{jsxref("Global_Objects/Math/abs", "Math.abs(x)")}}</dt> + <dd>숫자의 절댓값을 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/acos", "Math.acos(x)")}}</dt> + <dd>숫자의 아크코사인 값을 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/acosh", "Math.acosh(x)")}} </dt> + <dd>숫자의 쌍곡아크코사인 값을 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/asin", "Math.asin(x)")}}</dt> + <dd>숫자의 아크사인 값을 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/asinh", "Math.asinh(x)")}} </dt> + <dd>숫자의 쌍곡아크사인 값을 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/atan", "Math.atan(x)")}}</dt> + <dd>숫자의 아크탄젠트 값을 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/atanh", "Math.atanh(x)")}} </dt> + <dd>숫자의 쌍곡아크탄젠트 값을 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/atan2", "Math.atan2(y, x)")}}</dt> + <dd>인수 몫의 아크탄젠트 값을 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/cbrt", "Math.cbrt(x)")}} </dt> + <dd>숫자의 세제곱근을 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/ceil", "Math.ceil(x)")}}</dt> + <dd>인수보다 크거나 같은 수 중에서 가장 작은 정수를 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/clz32", "Math.clz32(x)")}} </dt> + <dd>주어진 32비트 정수의 선행 0 개수를 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/cos", "Math.cos(x)")}}</dt> + <dd>숫자의 코사인 값을 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/cosh", "Math.cosh(x)")}} </dt> + <dd>숫자의 쌍곡코사인 값을 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/exp", "Math.exp(x)")}}</dt> + <dd>E<sup>x</sup> 를 반환합니다. <var>x</var>는 인수이며 E 는 오일러 상수(<code>2.718</code>...) 또는 자연로그의 밑입니다.</dd> + <dt>{{jsxref("Global_Objects/Math/expm1", "Math.expm1(x)")}} </dt> + <dd><code>exp(x)</code>에서 <code>1</code>을 뺀 값을 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/floor", "Math.floor(x)")}}</dt> + <dd>인수보다 작거나 같은 수 중에서 가장 큰 정수를 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/fround", "Math.fround(x)")}} </dt> + <dd>인수의 가장 가까운 단일 정밀도 표현을 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/hypot", "Math.hypot([x[, y[, …]]])")}} </dt> + <dd>인수의 제곱합의 제곱근을 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/imul", "Math.imul(x, y)")}} </dt> + <dd>두 32비트 정수의 곱을 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/log", "Math.log(x)")}}</dt> + <dd>숫자의 자연로그(log<sub>e</sub> 또는 ln) 값을 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/log1p", "Math.log1p(x)")}} </dt> + <dd>숫자 <code>x</code>에 대해 <code>1 + x</code>의 자연로그(log<sub>e</sub> 또는 ln) 값을 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/log10", "Math.log10(x)")}} </dt> + <dd>숫자의 밑이 10인 로그를 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/log2", "Math.log2(x)")}} </dt> + <dd>숫자의 밑이 2인 로그를 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/max", "Math.max([x[, y[, …]]])")}}</dt> + <dd>0개 이상의 인수에서 제일 큰 수를 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/min", "Math.min([x[, y[, …]]])")}}</dt> + <dd>0개 이상의 인수에서 제일 작은 수를 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/pow", "Math.pow(x, y)")}}</dt> + <dd>x의 y 제곱을 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/random", "Math.random()")}}</dt> + <dd>0과 1 사이의 난수를 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/round", "Math.round(x)")}}</dt> + <dd>숫자에서 가장 가까운 정수를 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/sign", "Math.sign(x)")}} </dt> + <dd>x의 양의 수인지 음의 수인지 나타내는 부호를 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/sin", "Math.sin(x)")}}</dt> + <dd>숫자의 사인 값을 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/sinh", "Math.sinh(x)")}} </dt> + <dd>숫자의 쌍곡사인 값을 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/sqrt", "Math.sqrt(x)")}}</dt> + <dd>숫자의 제곱근을 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/tan", "Math.tan(x)")}}</dt> + <dd>숫자의 탄젠트 값을 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/tanh", "Math.tanh(x)")}} </dt> + <dd>숫자의 쌍곡탄젠트 값을 반환합니다.</dd> + <dt><code>Math.toSource()</code> {{non-standard_inline}}</dt> + <dd>문자열 <code>"Math"</code>를 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/Math/trunc", "Math.trunc(x)")}} </dt> + <dd>숫자의 정수 부분을 반환합니다.</dd> +</dl> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math-object', 'Math')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Math")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Number")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/math/ln10/index.html b/files/ko/web/javascript/reference/global_objects/math/ln10/index.html new file mode 100644 index 0000000000..57ab837e50 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/ln10/index.html @@ -0,0 +1,84 @@ +--- +title: Math.LN10 +slug: Web/JavaScript/Reference/Global_Objects/Math/LN10 +tags: + - JavaScript + - Math + - Property + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/LN10 +--- +<div>{{JSRef}}</div> + +<p><strong><code>Math.LN10</code></strong> 속성은 10의 자연로그 값, 약 2.302의 값을 가집니다.</p> + +<p><math display="block"><semantics><mrow><mstyle mathvariant="monospace"><mi>Math.LN10</mi></mstyle><mo>=</mo><mo lspace="0em" rspace="0em">ln</mo><mo stretchy="false">(</mo><mn>10</mn><mo stretchy="false">)</mo><mo>≈</mo><mn>2.302</mn></mrow><annotation encoding="TeX">\mathtt{\mi{Math.LN10}} = \ln(10) \approx 2.302</annotation></semantics></math></p> + +<div>{{EmbedInteractiveExample("pages/js/math-ln10.html")}}</div> + + + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="설명">설명</h2> + +<p><code>LN10</code>은 <code>Math</code>의 정적 속성이므로, 사용자가 생성한 <code>Math</code> 객체의 속성으로 접근할 수 없고 항상 <code>Math.LN10</code>을 사용해야 합니다. (<code>Math</code>는 생성자가 아닙니다)</p> + +<h2 id="예제">예제</h2> + +<h3 id="Math.LN10_사용하기"><code>Math.LN10</code> 사용하기</h3> + +<p>다음 함수는 10의 자연 로그 값을 반환합니다.</p> + +<pre class="brush:js">function getNatLog10() { + return Math.LN10; +} + +getNatLog10(); // 2.302585092994046 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8.1.2', 'Math.LN10')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.ln10', 'Math.LN10')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.ln10', 'Math.LN10')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Math.LN10")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Math.exp()")}}</li> + <li>{{jsxref("Math.log()")}}</li> + <li>{{jsxref("Math.log10()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/math/ln2/index.html b/files/ko/web/javascript/reference/global_objects/math/ln2/index.html new file mode 100644 index 0000000000..202558fd59 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/ln2/index.html @@ -0,0 +1,86 @@ +--- +title: Math.LN2 +slug: Web/JavaScript/Reference/Global_Objects/Math/LN2 +tags: + - JavaScript + - Math + - Property + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/LN2 +--- +<div>{{JSRef}}</div> + +<p>The <strong><code>Math.LN2</code></strong> property represents the natural logarithm of 2, approximately 0.693:</p> + +<p><strong><code>Math.LN2</code></strong> 속성은 2의 자연로그 값, 약 0.693의 값을 가집니다.</p> + +<p><math display="block"><semantics><mrow><mstyle mathvariant="monospace"><mi>Math.LN2</mi></mstyle><mo>=</mo><mo lspace="0em" rspace="0em">ln</mo><mo stretchy="false">(</mo><mn>2</mn><mo stretchy="false">)</mo><mo>≈</mo><mn>0.693</mn></mrow><annotation encoding="TeX">\mathtt{\mi{Math.LN2}} = \ln(2) \approx 0.693</annotation></semantics></math></p> + +<div>{{EmbedInteractiveExample("pages/js/math-ln2.html")}}</div> + + + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="설명">설명</h2> + +<p><code>LN2</code>는 <code>Math</code>의 정적 속성이므로, 사용자가 생성한 <code>Math</code> 객체의 속성으로 접근할 수 없고 항상 <code>Math.LN2</code>를 사용해야 합니다. (<code>Math</code>는 생성자가 아닙니다)</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Math.LN2_사용하기"><code>Math.LN2</code> 사용하기</h3> + +<p>다음 함수는 2의 자연 로그 값을 반환합니다.</p> + +<pre class="brush:js">function getNatLog2() { + return Math.LN2; +} + +getNatLog2(); // 0.6931471805599453 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8.1.3', 'Math.LN2')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.ln2', 'Math.LN2')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.ln2', 'Math.LN2')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Math.LN2")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Math.exp()")}}</li> + <li>{{jsxref("Math.log()")}}</li> + <li>{{jsxref("Math.log2()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/math/log/index.html b/files/ko/web/javascript/reference/global_objects/math/log/index.html new file mode 100644 index 0000000000..a343fa27a6 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/log/index.html @@ -0,0 +1,104 @@ +--- +title: Math.log() +slug: Web/JavaScript/Reference/Global_Objects/Math/log +translation_of: Web/JavaScript/Reference/Global_Objects/Math/log +--- +<div>{{JSRef}}</div> + +<p><strong><code>Math.log()</code></strong> 함수는 자연 로가리즘은 ({{jsxref("Math.E", "e")}} 를 기초) 의 수를 계산합니다, 이건 다음의</p> + +<p><math display="block"><semantics><mrow><mo>∀</mo><mi>x</mi><mo>></mo><mn>0</mn><mo>,</mo><mstyle mathvariant="monospace"><mrow><mo lspace="0em" rspace="thinmathspace">Math.log</mo><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo></mrow></mstyle><mo>=</mo><mo lspace="0em" rspace="0em">ln</mo><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><mtext>the unique</mtext><mspace width="thickmathspace"></mspace><mi>y</mi><mspace width="thickmathspace"></mspace><mtext>such that</mtext><mspace width="thickmathspace"></mspace><msup><mi>e</mi><mi>y</mi></msup><mo>=</mo><mi>x</mi></mrow><annotation encoding="TeX">\forall x > 0, \mathtt{\operatorname{Math.log}(x)} = \ln(x) = \text{고유값} \; y \; \text{같이} \; e^y = x</annotation></semantics></math></p> + +<p>자바스크립트 <strong><code>Math.log()</code> </strong>함수는 <em>ln(x)</em> 수학적으로 같습니다.</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox"><code>Math.log(<var>x</var>)</code></pre> + +<h3 id="인자">인자</h3> + +<dl> + <dt><code>x</code></dt> + <dd>실수값.</dd> +</dl> + +<h3 id="반환값">반환값</h3> + +<p>자연 로가리즘은 ({{jsxref("Math.E", "e")}} 를 기초) 실수값으로 줍니다. 마이너스 실수값, {{jsxref("NaN")}} 계산됩니다.</p> + +<h2 id="설명">설명</h2> + +<p>만일 값 <code>x</code> 가 마이너스라면, 항상 다음값이 계산됩니다 {{jsxref("NaN")}}.</p> + +<p><code>왜그렇냐면 </code> <code>Math의 log() 가 정적 메서드이기 때문</code>,에 매번 다음처럼 <code>Math.log() 써야합니다</code> (생성자로 초기화된 <code>Math</code> 개체가 아니기 때문입니다).</p> + +<p>자연로그 2 나 10, 상수로쓸때 {{jsxref("Math.LN2")}} or {{jsxref("Math.LN10")}} . 로가리즘 기초값 2 나 10, 쓸때는 {{jsxref("Math.log2()")}} 혹은 {{jsxref("Math.log10()")}} . 로가리즘 다른 기초값은 Math.log(x) / Math.log(기초값) 처럼 예제참고; 미리계산하여 1 / Math.log(기초값) 할 수 있습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="Math.log()_사용"><code>Math.log() 사용</code></h3> + +<pre class="brush: js">Math.log(-1); // NaN, 정의범위 초과 +Math.log(0); // -Infinity, 무한 +Math.log(1); // 0 +Math.log(10); // 2.302585092994046 +</pre> + +<h3 id="Math.log()_다른_기초값_사용"><code>Math.log()</code> 다른 기초값 사용</h3> + +<p>이 함수는 로가리즘 <code>y 에 대한것으로</code> 기초값 <code>x</code> (ie. <math><semantics><mrow><msub><mo>log</mo><mi>x</mi></msub><mi>y</mi></mrow><annotation encoding="TeX">\log_x y</annotation></semantics></math>): 입니다</p> + +<pre class="brush: js">function getBaseLog(x, y) { + return Math.log(y) / Math.log(x); +} +</pre> + +<p>다음을 실행하면 <code>getBaseLog(10, 1000)</code> 다음 <code>2.9999999999999996 계산되는데</code> 적당히 반올림하니다, 거의 3 에 가깝습니다.</p> + +<h2 id="명세서">명세서</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">비고</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8.2.10', 'Math.log')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.log', 'Math.log')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.log', 'Math.log')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Math.log")}}</p> + +<h2 id="같이보기">같이보기</h2> + +<ul> + <li>{{jsxref("Math.exp()")}}</li> + <li>{{jsxref("Math.log1p()")}}</li> + <li>{{jsxref("Math.log10()")}}</li> + <li>{{jsxref("Math.log2()")}}</li> + <li>{{jsxref("Math.pow()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/math/log10e/index.html b/files/ko/web/javascript/reference/global_objects/math/log10e/index.html new file mode 100644 index 0000000000..bb864c8aa3 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/log10e/index.html @@ -0,0 +1,84 @@ +--- +title: Math.LOG10E +slug: Web/JavaScript/Reference/Global_Objects/Math/LOG10E +tags: + - JavaScript + - Math + - Property + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/LOG10E +--- +<div>{{JSRef}}</div> + +<p><strong><code>Math.LOG10E</code></strong> 속성은 e의 로그 10 값, 약 0.434의 값을 가집니다.</p> + +<p><math display="block"><semantics><mrow><mstyle mathvariant="monospace"><mi>Math.LOG10E</mi></mstyle><mo>=</mo><msub><mo lspace="0em" rspace="0em">log</mo><mn>10</mn></msub><mo stretchy="false">(</mo><mi>e</mi><mo stretchy="false">)</mo><mo>≈</mo><mn>0.434</mn></mrow><annotation encoding="TeX">\mathtt{\mi{Math.LOG10E}} = \log_10(e) \approx 0.434</annotation></semantics></math></p> + +<div>{{EmbedInteractiveExample("pages/js/math-log10e.html")}}</div> + + + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="설명">설명</h2> + +<p><code>LOG10E</code>는 <code>Math</code>의 정적 속성이므로, 사용자가 생성한 <code>Math</code> 객체의 속성으로 접근할 수 없고 항상 <code>Math.LOG10E</code>를 사용해야 합니다. (<code>Math</code>는 생성자가 아닙니다)</p> + +<h2 id="예제">예제</h2> + +<h3 id="Math.LOG10E_사용하기"><code>Math.LOG10E</code> 사용하기</h3> + +<p>다음 함수는 e의 로그 10 값을 반환합니다.</p> + +<pre class="brush:js">function getLog10e() { + return Math.LOG10E; +} + +getLog10e(); // 0.4342944819032518 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8.1.5', 'Math.LOG10E')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.log10e', 'Math.LOG10E')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.log10e', 'Math.LOG10E')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Math.LOG10E")}}</p> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("Math.exp()")}}</li> + <li>{{jsxref("Math.log()")}}</li> + <li>{{jsxref("Math.log10()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/math/log2/index.html b/files/ko/web/javascript/reference/global_objects/math/log2/index.html new file mode 100644 index 0000000000..7cfd72531c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/log2/index.html @@ -0,0 +1,96 @@ +--- +title: Math.log2() +slug: Web/JavaScript/Reference/Global_Objects/Math/log2 +translation_of: Web/JavaScript/Reference/Global_Objects/Math/log2 +--- +<div>{{JSRef}}</div> + +<p> <strong><code>Math.log2()</code></strong> 함수는 숫자를 log<sub>2</sub>(숫자)로 반환합니다.</p> + +<p><math display="block"><semantics><mrow><mo>∀</mo><mi>x</mi><mo>></mo><mn>0</mn><mo>,</mo><mstyle mathvariant="monospace"><mrow><mo lspace="0em" rspace="thinmathspace">Math.log2</mo><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo></mrow></mstyle><mo>=</mo><msub><mo lspace="0em" rspace="0em">log</mo><mn>2</mn></msub><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><mtext>the unique</mtext><mspace width="thickmathspace"></mspace><mi>y</mi><mspace width="thickmathspace"></mspace><mtext>such that</mtext><mspace width="thickmathspace"></mspace><msup><mn>2</mn><mi>y</mi></msup><mo>=</mo><mi>x</mi></mrow><annotation encoding="TeX">\forall x > 0, \mathtt{\operatorname{Math.log2}(x)} = \log_2(x) = \text{the unique} \; y \; \text{such that} \; 2^y = x</annotation></semantics></math></p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox"><code>Math.log2(<var>x</var>)</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>x</code></dt> + <dd>숫자.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 숫자는 log<sub>2</sub>(숫자)로 계산합니다. 만약 숫자가 음수라면 {{jsxref("NaN")}}를 반환합니다.</p> + +<h2 id="설명">설명</h2> + +<p>만약 <code>x</code> 의 값이 0보다 작다면(음수) 값은 항상 {{jsxref("NaN")}}로 반환합니다.</p> + +<p><code>log<sub>2</sub>()</code>는 <code>Math</code>의 정적 메서드이므로 만든 <code>Math</code> 객체의 메서드가 아니라 항상 <code>Math.log2()</code>함수를 사용해야합니다. (<code>Math</code>는 생성자가 없습니다.)</p> + +<p>이 함수는 Math.log(x) / Math.log(2)와 같습니다.</p> + +<p>따라서 log<sub>2</sub>(e)는 {{jsxref("Math.LOG2E")}}와 같습니다. </p> + +<p>그리고 위 함수는 1 / {{jsxref("Math.LN2")}}과 같습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="Math.log2()"><code>Math.log2()</code></h3> + +<pre class="brush: js">Math.log2(3); // 1.584962500721156 +Math.log2(2); // 1 +Math.log2(1); // 0 +Math.log2(0); // -Infinity +Math.log2(-2); // NaN +Math.log2(1024); // 10 +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>This Polyfill emulates the <code>Math.log2</code> function. Note that it returns imprecise values on some inputs (like 1 << 29), wrap into {{jsxref("Math.round()")}} if working with bit masks.</p> + +<pre class="brush: js">Math.log2 = Math.log2 || function(x) { + return Math.log(x) * Math.LOG2E; +}; +</pre> + +<h2 id="표준">표준</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">표준</th> + <th scope="col">상태</th> + <th scope="col">비고</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-math.log2', 'Math.log2')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.log2', 'Math.log2')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Math.log2")}}</p> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("Math.exp()")}}</li> + <li>{{jsxref("Math.log()")}}</li> + <li>{{jsxref("Math.log10()")}}</li> + <li>{{jsxref("Math.log1p()")}}</li> + <li>{{jsxref("Math.pow()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/math/log2e/index.html b/files/ko/web/javascript/reference/global_objects/math/log2e/index.html new file mode 100644 index 0000000000..244224df3d --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/log2e/index.html @@ -0,0 +1,84 @@ +--- +title: Math.LOG2E +slug: Web/JavaScript/Reference/Global_Objects/Math/LOG2E +tags: + - JavaScript + - Math + - Property + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/LOG2E +--- +<div>{{JSRef}}</div> + +<p><strong><code>Math.LOG2E</code></strong> 속성은 e의 로그 2 값, 약 1.442의 값을 가집니다.</p> + +<p><math display="block"><semantics><mrow><mstyle mathvariant="monospace"><mi>Math.LOG2E</mi></mstyle><mo>=</mo><msub><mo lspace="0em" rspace="0em">log</mo><mn>2</mn></msub><mo stretchy="false">(</mo><mi>e</mi><mo stretchy="false">)</mo><mo>≈</mo><mn>1.442</mn></mrow><annotation encoding="TeX">\mathtt{\mi{Math.LOG2E}} = \log_2(e) \approx 1.442</annotation></semantics></math></p> + +<div>{{EmbedInteractiveExample("pages/js/math-log2e.html")}}</div> + + + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="설명">설명</h2> + +<p><code>LOG2E</code>는 <code>Math</code>의 정적 속성이므로, 사용자가 생성한 <code>Math</code> 객체의 속성으로 접근할 수 없고 항상 <code>Math.LOG2E</code>를 사용해야 합니다. (<code>Math</code>는 생성자가 아닙니다)</p> + +<h2 id="설명_2">설명</h2> + +<h3 id="Math.LOG2E_사용하기"><code>Math.LOG2E</code> 사용하기</h3> + +<p>다음 함수는 e의 로그 2 값을 반환합니다.</p> + +<pre class="brush: js">function getLog2e() { + return Math.LOG2E; +} + +getLog2e(); // 1.4426950408889634 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8.1.4', 'Math.LOG2E')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.log2e', 'Math.LOG2E')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.log2e', 'Math.LOG2E')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Math.LOG2E")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Math.exp()")}}</li> + <li>{{jsxref("Math.log()")}}</li> + <li>{{jsxref("Math.log2()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/math/max/index.html b/files/ko/web/javascript/reference/global_objects/math/max/index.html new file mode 100644 index 0000000000..e315e5027b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/max/index.html @@ -0,0 +1,110 @@ +--- +title: Math.max() +slug: Web/JavaScript/Reference/Global_Objects/Math/max +tags: + - Math + - 메소드 + - 자바스크립트 + - 참조 +translation_of: Web/JavaScript/Reference/Global_Objects/Math/max +--- +<div>{{JSRef}}</div> + +<p><strong>Math.max()</strong>함수는 입력값으로 받은 0개 이상의 숫자 중 가장 큰 숫자를 반환합니다.</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox notranslate"><code>Math.max([<var>값1</var>[, <var>값2</var>[, ...]]])</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>값1, 값2, ...</code></dt> + <dd>숫자들.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>입력된 숫자 중 가장 큰 숫자를 반환합니다. 만약 인수 중 하나라도 숫자로 변환하지 못한다면 {{jsxref("NaN")}}로 반환합니다.</p> + +<h2 id="설명">설명</h2> + +<p>max ()는 Math의 정적 메서드이기 때문에 만든 Math 개체의 메서드가 아닌 항상 Math.max ()로 사용해야합니다. (Math는 생성자가 아닙니다).</p> + +<p>만약 아무 요소도 주어지지 않았다면 {{jsxref("-Infinity")}}로 반환합니다.</p> + +<p>만약 한 개 이상의 요소가 숫자로 변환되지 않는다면 {{jsxref("NaN")}}로 반환됩니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="Math.max함수_사용하기"><code>Math.max()함수 사용하기</code></h3> + +<pre class="brush: js notranslate">Math.max(10, 20); // 20 +Math.max(-10, -20); // -10 +Math.max(-10, 20); // 20 +</pre> + +<p>다음 함수는 {{jsxref ( "Function.prototype.apply ()")}}을 사용하여 숫자 배열에서 최대 요소를 찾습니다. getMaxOfArray ([1, 2, 3])는 Math.max (1, 2, 3)와 동일하지만 프로그래밍 방식으로 생성 된 모든 크기의 배열에서 getMaxOfArray ()를 사용할 수 있습니다.</p> + +<pre class="brush: js notranslate">function getMaxOfArray(numArray) { + return Math.max.apply(null, numArray); +} +</pre> + +<p>{{jsxref("Array.prototype.reduce", "Array.reduce()")}} 이 함수 또한 배열의 각 값을 비교하여 가장 큰 숫자를 얻을 수 있습니다.</p> + +<pre class="brush: js notranslate">var arr = [1,2,3]; +var max = arr.reduce(function(a, b) { + return Math.max(a, b); +}); +</pre> + +<p>또한 {{jsxref("Operators/Spread_operator", "spread operator")}}이 함수를 사용하면 배열의 숫자들 중 가장 큰 숫자를 쉽게 얻을 수 있습니다.</p> + +<pre class="brush: js notranslate">var arr = [1, 2, 3]; +var max = Math.max(...arr); +</pre> + +<h2 id="표준">표준</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">표준</th> + <th scope="col">상태</th> + <th scope="col">비고</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8.2.11', 'Math.max')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.max', 'Math.max')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.max', 'Math.max')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Math.max")}}</p> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("Math.min()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/math/min/index.html b/files/ko/web/javascript/reference/global_objects/math/min/index.html new file mode 100644 index 0000000000..7bf84ee57c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/min/index.html @@ -0,0 +1,103 @@ +--- +title: Math.min() +slug: Web/JavaScript/Reference/Global_Objects/Math/min +translation_of: Web/JavaScript/Reference/Global_Objects/Math/min +--- +<div>{{JSRef}}</div> + +<p><strong><code>Math.min()</code></strong> 함수는 주어진 숫자들 중 가장 작은 값을 반환합니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code>Math.min([<var>value1</var>[, <var>value2</var>[, ...]]])</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>value1, value2, ...</code></dt> + <dd>숫자형</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>주어진 숫자들 중 가장 작은 값. 만약 적어도 1개 이상의 인자값이 숫자형으로 변환이 불가능 한 경우 이 함수는 {{jsxref("NaN")}} 를 반환 합니다.</p> + +<h2 id="Description">Description</h2> + +<p><code>min()</code> 함수는 <code>Math</code> 의 정적 메소드 이므로, 사용자가 생성한 <code>Math</code> 객체의 메소드로 호출하는 것이 아닌 항상 <code>Math.min()</code> 으로 호출되어야 합니다. (<code>Math</code> 는 생성자가 아닙니다).</p> + +<p>만약 주어진 인자값이 없을 경우, {{jsxref("Infinity")}} 가 반환됩니다.</p> + +<p>만약 적어도 1개 이상의 인자값이 숫자형으로 변환이 불가능 한 경우, {{jsxref("NaN")}} 가 반환됩니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_Math.min()">Using <code>Math.min()</code></h3> + +<p>아래 수식은 <code>x</code> 와<code>y</code> 중 작은 값을 찾아 <code>z</code> 에 할당 합니다. </p> + +<pre class="brush: js">var x = 10, y = -20; +var z = Math.min(x, y); +</pre> + +<h3 id="Clipping_a_value_with_Math.min()">Clipping a value with <code>Math.min()</code></h3> + +<p><code>Math.min()</code> 함수는 때때로 값 제한, 즉 항상 기준 보다 작거나 같은 값으로 제한하는 용도로 사용됩니다. 예를 들면,</p> + +<pre class="brush: js">var x = f(foo); + +if (x > boundary) { + x = boundary; +} +</pre> + +<p> 위 코드는 다음과 같이 쓸 수 있습니다.</p> + +<pre class="brush: js">var x = Math.min(f(foo), boundary); +</pre> + +<p>{{jsxref("Math.max()")}} 함수 또한 같은 방식으로 기준보다 크거나 같은 값으로 제한하는 용도로 사용할 수 있습니다.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8.2.12', 'Math.min')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.min', 'Math.min')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.min', 'Math.min')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Math.min")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Math.max()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/math/pi/index.html b/files/ko/web/javascript/reference/global_objects/math/pi/index.html new file mode 100644 index 0000000000..8223a68df6 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/pi/index.html @@ -0,0 +1,82 @@ +--- +title: Math.PI +slug: Web/JavaScript/Reference/Global_Objects/Math/PI +tags: + - JavaScript + - Math + - Property + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/PI +--- +<div>{{JSRef}}</div> + +<p><strong><code>Math.PI</code></strong> 속성은 원의 둘레와 지름의 비율, 약 3.14159의 값을 가집니다.</p> + +<p><math display="block"><semantics><mrow><mstyle mathvariant="monospace"><mi>Math.PI</mi></mstyle><mo>=</mo><mi>π</mi><mo>≈</mo><mn>3.14159</mn></mrow><annotation encoding="TeX">\mathtt{\mi{Math.PI}} = \pi \approx 3.14159</annotation></semantics></math></p> + +<div>{{EmbedInteractiveExample("pages/js/math-pi.html")}}</div> + + + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="설명">설명</h2> + +<p><code>PI</code>는 <code>Math</code>의 정적 속성이므로, 사용자가 생성한 <code>Math</code> 객체의 속성으로 접근할 수 없고 항상 <code>Math.PI</code>를 사용해야 합니다. (<code>Math</code>는 생성자가 아닙니다)</p> + +<h2 id="예제">예제</h2> + +<h3 id="Math.PI_사용하기"><code>Math.PI</code> 사용하기</h3> + +<p>다음 함수는 <code>Math.PI</code>를 사용해 주어진 원의 반지름에서 둘레를 계산합니다.</p> + +<pre class="brush: js">function calculateCircumference(radius) { + return Math.PI * (radius + radius); +} + +calculateCircumference(1); // 6.283185307179586 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">사양</th> + <th scope="col">등급</th> + <th scope="col">주석</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8.1.6', 'Math.PI')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.pi', 'Math.PI')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.pi', 'Math.PI')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Math.PI")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Math")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/math/random/index.html b/files/ko/web/javascript/reference/global_objects/math/random/index.html new file mode 100644 index 0000000000..9ce02207de --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/random/index.html @@ -0,0 +1,106 @@ +--- +title: Math.random() +slug: Web/JavaScript/Reference/Global_Objects/Math/random +translation_of: Web/JavaScript/Reference/Global_Objects/Math/random +--- +<div>{{JSRef}}</div> + +<p><strong><code>Math.random()</code></strong> 함수는 0 이상 1 미만의 구간에서 근사적으로 균일한(approximately uniform) 부동소숫점 의사난수를 반환하며, 이 값은 사용자가 원하는 범위로 변형할 수 있다. 난수 생성 알고리즘에 사용되는 초기값은 구현체가 선택하며, 사용자가 선택하거나 초기화할 수 없다.</p> + +<div class="note"> +<p><code>Math.random()</code>은 암호학적으로 안전한 난수를 <strong>제공하지 않으므로</strong>, 보안과 관련된 어떤 것에도 이 함수를 사용해서는 안 된다. 그 대신 Web Crypto API의 {{domxref("RandomSource.getRandomValues()", "window.crypto.getRandomValues()")}} 메소드를 이용하여야 한다.</p> +</div> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox"><code>Math.random()</code> +</pre> + +<h3 id="반환_값">반환 값</h3> + +<p>0 이상 1 미만의 부동소숫점 의사 난수.</p> + +<h2 id="예제">예제</h2> + +<h3 id="Math.random_사용"><code>Math.random()</code> 사용</h3> + +<p>JavaScript의 수(number)는 가까운 짝수로 반올림되는(round-to-nearest-even behavior) IEEE 754 부동소수점 실수이므로, 아래 함수들(<code>Math.random()</code> 자체에 대한 사항은 제외)에 명시된 범위는 정확하지 않음을 유의하라. 지나치게 큰 범위(2<sup>53</sup> 이상)를 선택할 경우, <em>매우</em> 드문 경우 원래 포함되어서는 안 될 최댓값이 포함되는 경우가 있다.</p> + +<h3 id="0_이상_1_미만의_난수_생성하기">0 이상 1 미만의 난수 생성하기</h3> + +<pre class="brush: js">function getRandom() { + return Math.random(); +} +</pre> + +<h3 id="두_값_사이의_난수_생성하기">두 값 사이의 난수 생성하기</h3> + +<p>이 예제는 주어진 두 값 사이의 난수를 생성한다. 함수의 반환값은 <code>min</code>보다 크거나 같으며, <code>max</code>보다 작다.</p> + +<pre class="brush: js">function getRandomArbitrary(min, max) { + return Math.random() * (max - min) + min; +} +</pre> + +<h3 id="두_값_사이의_정수_난수_생성하기">두 값 사이의 정수 난수 생성하기</h3> + +<p>이 예제는 주어진 두 값 사이의 <u>정수인</u> 난수를 생성한다. 반환값은 <code>min</code>(단, <code>min</code>이 정수가 아니면 <code>min</code>보다 큰 최소의 정수)보다 크거나 같으며, <code>max</code>보다 작다.</p> + +<pre class="brush: js">function getRandomInt(min, max) { + min = Math.ceil(min); + max = Math.floor(max); + return Math.floor(Math.random() * (max - min)) + min; //최댓값은 제외, 최솟값은 포함 +} +</pre> + +<div class="note"> +<p>이 예제에서 <code>Math.round()</code>를 대신 사용하려고 할 수 있으나, 이렇게 하면 난수가 고르게 분포하지 않게 된다.</p> +</div> + +<h3 id="최댓값을_포함하는_정수_난수_생성하기">최댓값을 포함하는 정수 난수 생성하기</h3> + +<p>위의<code>getRandomInt()</code> 함수는 최솟값을 포함하지만, 최댓값은 포함하지 않는다. 최솟값과 최댓값을 모두 포함하는 결과가 필요할 경우, 아래의 <code>getRandomIntInclusive()</code> 함수를 사용할 수 있다.</p> + +<pre class="brush: js">function getRandomIntInclusive(min, max) { + min = Math.ceil(min); + max = Math.floor(max); + return Math.floor(Math.random() * (max - min + 1)) + min; //최댓값도 포함, 최솟값도 포함 +}</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">비고</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>초기 정의. JavaScript 1.0 (유닉스 전용) / JavaScript 1.1 (모든 플랫폼).</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8.2.14', 'Math.random')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.random', 'Math.random')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.random', 'Math.random')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Math.random")}}</p> diff --git a/files/ko/web/javascript/reference/global_objects/math/round/index.html b/files/ko/web/javascript/reference/global_objects/math/round/index.html new file mode 100644 index 0000000000..e163c4459e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/round/index.html @@ -0,0 +1,92 @@ +--- +title: Math.round() +slug: Web/JavaScript/Reference/Global_Objects/Math/round +translation_of: Web/JavaScript/Reference/Global_Objects/Math/round +--- +<div>{{JSRef}}</div> + +<p><strong><code>Math.round()</code></strong> 함수는 입력값을 반올림한 수와 가장 가까운 정수 값을 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/math-round.html")}}</div> + + + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox">Math.round(<var>x</var>)</pre> + +<h3 id="매개_변수">매개 변수</h3> + +<dl> + <dt><code>x</code></dt> + <dd>수</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>입력값을 반올림한 값과 가장 가까운 정수를 의미합니다.</p> + +<h2 id="Description">Description</h2> + +<p>If the fractional portion of the argument is greater than 0.5, the argument is rounded to the integer with the next higher absolute value. If it is less than 0.5, the argument is rounded to the integer with the lower absolute value. If the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +∞. <strong>Note that this differs from many languages' <code>round()</code> functions, which often round this case to the next integer <em>away from zero</em></strong>, instead giving a different result in the case of negative numbers with a fractional part of exactly 0.5.</p> + +<p>Because <code>round()</code> is a static method of <code>Math</code>, you always use it as <code>Math.round()</code>, rather than as a method of a <code>Math</code> object you created (<code>Math</code> has no constructor).</p> + +<h2 id="Examples">Examples</h2> + +<pre class="brush: js">Math.round( 20.49); // 20 +Math.round( 20.5 ); // 21 +Math.round( 42 ); // 42 +Math.round(-20.5 ); // -20 +Math.round(-20.51); // -21 +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8.2.15', 'Math.round')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.round', 'Math.round')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.round', 'Math.round')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Math.round")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Number.toPrecision()")}}</li> + <li>{{jsxref("Number.toFixed()")}}</li> + <li>{{jsxref("Math.abs()")}}</li> + <li>{{jsxref("Math.ceil()")}}</li> + <li>{{jsxref("Math.floor()")}}</li> + <li>{{jsxref("Math.sign()")}}</li> + <li>{{jsxref("Math.trunc()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/math/sign/index.html b/files/ko/web/javascript/reference/global_objects/math/sign/index.html new file mode 100644 index 0000000000..adb5f15354 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/sign/index.html @@ -0,0 +1,112 @@ +--- +title: Math.sign() +slug: Web/JavaScript/Reference/Global_Objects/Math/sign +tags: + - JavaScript + - Math + - 메소드 + - 참조 +translation_of: Web/JavaScript/Reference/Global_Objects/Math/sign +--- +<div>{{JSRef}}</div> + +<p><strong><code>Math.sign()</code></strong> 함수는 어떤 수의 부호를 반환합니다. 이것은 그 수가 양수, 음수 또는 0인지를 나나냅니다.</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox"><code>Math.sign(<var>x</var>)</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>x</code></dt> + <dd>수치.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 인수의 부호를 나타내는 수치. 인수가 양수, 음수, 양수인 영 또는 음수인 영이면, 이 함수는 <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">1</span></font>, <code>-1</code>, <code>0,</code> <code>-0</code>을 각각 반환합니다. 그렇지 않으면, {{jsxref("NaN")}} 이 반환됩니다.</p> + +<h2 id="설명">설명</h2> + +<p><code>sign()</code> 이<code>Math</code>의 정적 메소드이기 때문에 항상 <code>Math.sign()</code>으로 사용합니다. 사용자가 만든 <code>Math</code> 개체의 메소드로 가 아닙니다. (<code>Math</code> 는 생성자가 아닙니다).</p> + +<p>이 함수는 반환 값이 5 가지이며, <code>1</code>, <code>-1</code>, <code>0</code>, <code>-0</code>, <code>NaN 입니다.</code> 각각 "양수", "음수", "양의 영", "음의 영", {{jsxref("NaN")}} 입니다.</p> + +<p>이 함수에 전달된 인수는 묵시적으로 <code>수치</code> 로 변환됩니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="Math.sign()을_사용하기"> <code>Math.sign()</code>을 사용하기</h3> + +<pre class="brush: js">Math.sign(3); // 1 +Math.sign(-3); // -1 +Math.sign('-3'); // -1 +Math.sign(0); // 0 +Math.sign(-0); // -0 +Math.sign(NaN); // NaN +Math.sign('foo'); // NaN +Math.sign(); // NaN +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js">if (!Math.sign) { + Math.sign = function(x) { + // x 가 NaN 이면, 결과는 NaN 입니다. + // x 가 -0 이면, 결과는 -0 입니다. + // x 가 +0 이면, 결과는 +0 입니다. + // x 가 음수이면서 -0 이 아니면, 결과는 -1 입니다. + // x 가 양수이면서 +0 이 아니면, 결과는 +1 입니다. + return ((x > 0) - (x < 0)) || +x; + // A more aesthetical persuado-representation is shown below + // + // ( (x > 0) ? 0 : 1 ) // if x is negative then negative one + // + // else (because you cant be both - and +) + // ( (x < 0) ? 0 : -1 ) // if x is positive then positive one + // || // if x is 0, -0, or NaN, or not a number, + // +x // Then the result will be x, (or) if x is + // // not a number, then x converts to number + }; +} +</pre> + +<p>위의 polyfill에서는, <code>(x > 0) 또는 (x < 0)</code> 인 수치들을 만드는 데에 어떤 추가의 타입-강제하기도 필요하지 않은 것은 그 수치들을 서로에게서 빼는 것이 불린형에서 수치로의 형 변환을 강요하기 때문입니다.</p> + +<h2 id="규격명세">규격명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">규격명세</th> + <th scope="col">상태</th> + <th scope="col">코멘트</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.sign', 'Math.sign')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>최초의 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.sign', 'Math.sign')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">이 페이지에서 호환성 표는 구조화된 자료로부터 생성됩니다. 그 자료에 기여하시려면, <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> 를 확인하시고 저희에게 pull 요청을 보내십시오.</p> + +<p>{{Compat("javascript.builtins.Math.sign")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Math.abs()")}}</li> + <li>{{jsxref("Math.ceil()")}}</li> + <li>{{jsxref("Math.floor()")}}</li> + <li>{{jsxref("Math.round()")}}</li> + <li>{{jsxref("Math.trunc()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/math/sin/index.html b/files/ko/web/javascript/reference/global_objects/math/sin/index.html new file mode 100644 index 0000000000..1978d7f8e8 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/sin/index.html @@ -0,0 +1,97 @@ +--- +title: Math.sin() +slug: Web/JavaScript/Reference/Global_Objects/Math/sin +tags: + - 레퍼런스 + - 메소드 + - 수학 + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Global_Objects/Math/sin +--- +<div>{{JSRef}}</div> + +<p> <strong><code>Math.sin()</code></strong> 함수는 숫자의 사인값을 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/math-sin.html")}}</div> + + + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code>Math.sin(<var>x</var>)</code></pre> + +<h3 id="파라미터">파라미터</h3> + +<dl> + <dt><code>x</code></dt> + <dd>숫자 (라디안으로 주어짐).</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 숫자의 사인 값</p> + +<h2 id="설명">설명</h2> + +<p><code>Math.sin()</code> 메소드는 라디안으로 주어진 각도의 사인 값인 -1과 1 사이의 수를 반환합니다.</p> + +<p> <code>sin()</code> 은 <code>Math</code>의 스태틱 메소드이기 때문에, <code>Math</code> 오브젝트 의 메소드로 사용하지 말고 항상 <code>Math.sin()</code>로 사용해야합니다. (<code>Math</code> 는 생성자가 아닙니다).</p> + +<h2 id="예">예</h2> + +<h3 id="Using_Math.sin()">Using <code>Math.sin()</code></h3> + +<pre class="brush: js">Math.sin(0); // 0 +Math.sin(1); // 0.8414709848078965 + +Math.sin(Math.PI / 2); // 1 +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>최초 정의. JavaScript 1.0. 에서 구현됨</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8.2.16', 'Math.sin')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.sin', 'Math.sin')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.sin', 'Math.sin')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Math.sin")}}</p> + +<h2 id="함께_보기">함께 보기</h2> + +<ul> + <li>{{jsxref("Math.acos()")}}</li> + <li>{{jsxref("Math.asin()")}}</li> + <li>{{jsxref("Math.atan()")}}</li> + <li>{{jsxref("Math.atan2()")}}</li> + <li>{{jsxref("Math.cos()")}}</li> + <li>{{jsxref("Math.tan()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/math/sinh/index.html b/files/ko/web/javascript/reference/global_objects/math/sinh/index.html new file mode 100644 index 0000000000..9a3bb3a6ab --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/sinh/index.html @@ -0,0 +1,96 @@ +--- +title: Math.sinh() +slug: Web/JavaScript/Reference/Global_Objects/Math/sinh +translation_of: Web/JavaScript/Reference/Global_Objects/Math/sinh +--- +<div>{{JSRef}}</div> + +<p><strong><code>Math.sinh()</code></strong> 함수(쌍곡선 함수)는 사인값을 반환합니다 이 값은 아래와같은 식을통해서 표현할 수 있습니다.{{jsxref("Math.E", "constant e", "", 1)}}:</p> + +<p><math display="block"><semantics><mrow><mstyle mathvariant="monospace"><mo lspace="0em" rspace="thinmathspace">Math.sinh(x)</mo></mstyle><mo>=</mo><mfrac><mrow><msup><mi>e</mi><mi>x</mi></msup><mo>-</mo><msup><mi>e</mi><mrow><mo>-</mo><mi>x</mi></mrow></msup></mrow><mn>2</mn></mfrac></mrow><annotation encoding="TeX">\mathtt{\operatorname{Math.sinh(x)}} = \frac{e^x - e^{-x}}{2}</annotation></semantics></math></p> + +<div>{{EmbedInteractiveExample("pages/js/math-sinh.html")}}</div> + +<p class="hidden">이 대화식 예제의 소스는 GitHub Repository에 저장됩니다. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code>Math.sinh(<var>x</var>)</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>x</code></dt> + <dd>숫자.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>사인값.</p> + +<h2 id="Description">Description</h2> + +<p><code>sinh()</code> 는 <code>Math</code> 의 정적 함수이기 때문에, 자바스크립트 어디든 <code>Math.sinh()</code> 를 사용할 수 있습니다, 따라서 <code>Math</code> 오브젝트를 생성해서는 안됩니다. (<code>Math</code> 는 constructor(생성자) 가 아닙니다.).</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Math.sinh_사용하기"><code>Math.sinh()</code> 사용하기</h3> + +<pre class="brush: js">Math.sinh(0); // 0 +Math.sinh(1); // 1.1752011936438014 +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>This can be emulated with the help of the {{jsxref("Math.exp()")}} function:</p> + +<pre class="brush: js">Math.sinh = Math.sinh || function(x) { + return (Math.exp(x) - Math.exp(-x)) / 2; +} +</pre> + +<p>or using only one call to the {{jsxref("Math.exp()")}} function:</p> + +<pre class="brush: js">Math.sinh = Math.sinh || function(x) { + var y = Math.exp(x); + return (y - 1 / y) / 2; +} +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-math.sinh', 'Math.sinh')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.sinh', 'Math.sinh')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Math.sinh")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Math.acosh()")}}</li> + <li>{{jsxref("Math.asinh()")}}</li> + <li>{{jsxref("Math.atanh()")}}</li> + <li>{{jsxref("Math.cosh()")}}</li> + <li>{{jsxref("Math.tanh()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/math/sqrt/index.html b/files/ko/web/javascript/reference/global_objects/math/sqrt/index.html new file mode 100644 index 0000000000..f03af42e6f --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/sqrt/index.html @@ -0,0 +1,90 @@ +--- +title: Math.sqrt() +slug: Web/JavaScript/Reference/Global_Objects/Math/sqrt +translation_of: Web/JavaScript/Reference/Global_Objects/Math/sqrt +--- +<div>{{JSRef}}</div> + +<p> <strong><code>Math.sqrt()</code></strong> 함수는 숫자의 제곱근을 반환합니다.</p> + +<p><math display="block"><semantics><mrow><mo>∀</mo><mi>x</mi><mo>≥</mo><mn>0</mn><mo>,</mo><mstyle mathvariant="monospace"><mrow><mi>M</mi><mi>a</mi><mi>t</mi><mi>h</mi><mo>.</mo><mi>s</mi><mi>q</mi><mi>r</mi><mi>t</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo></mrow></mstyle><mo>=</mo><msqrt><mi>x</mi></msqrt><mo>=</mo><mtext>the unique</mtext><mspace width="thickmathspace"></mspace><mi>y</mi><mo>≥</mo><mn>0</mn><mspace width="thickmathspace"></mspace><mtext>such that</mtext><mspace width="thickmathspace"></mspace><msup><mi>y</mi><mn>2</mn></msup><mo>=</mo><mi>x</mi></mrow><annotation encoding="TeX">\forall x \geq 0, \mathtt{Math.sqrt(x)} = \sqrt{x} = \text{the unique} \; y \geq 0 \; \text{such that} \; y^2 = x</annotation></semantics></math></p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox"><code>Math.sqrt(<var>x</var>)</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>x</code></dt> + <dd>숫자.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 숫자에 루트(<strong>√ </strong>)를 씌웁니다. 만약 숫자가 음수이면 {{jsxref("NaN")}}를 반환합니다.</p> + +<h2 id="설명">설명</h2> + +<p>만약 <code>x</code> 가 음수라면 <code>Math.sqrt()</code> 함수는 {{jsxref("NaN")}}를 반환합니다.</p> + +<p><code>sqrt()</code>는 <code>Math</code>의 정적 메서드 이므로 만든 <code>Math</code> 객체의 메서드가 아니라 항상 <code>Math.sqrt()</code>함수를 사용해야합니다. (<code>Math</code>는 생성자가 없습니다.)</p> + +<h2 id="예제">예제</h2> + +<h3 id="Math.sqrt()"> <code>Math.sqrt()</code></h3> + +<pre class="brush: js">Math.sqrt(9); // 3 +Math.sqrt(2); // 1.414213562373095 + +Math.sqrt(1); // 1 +Math.sqrt(0); // 0 +Math.sqrt(-1); // NaN +</pre> + +<h2 id="표준">표준</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">표준</th> + <th scope="col">상태</th> + <th scope="col">비고</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8.2.17', 'Math.sqrt')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.sqrt', 'Math.sqrt')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.sqrt', 'Math.sqrt')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Math.sqrt")}}</p> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("Math.cbrt()")}}</li> + <li>{{jsxref("Math.exp()")}}</li> + <li>{{jsxref("Math.log()")}}</li> + <li>{{jsxref("Math.pow()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/math/sqrt1_2/index.html b/files/ko/web/javascript/reference/global_objects/math/sqrt1_2/index.html new file mode 100644 index 0000000000..ee347e46eb --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/sqrt1_2/index.html @@ -0,0 +1,59 @@ +--- +title: Math.SQRT1_2 +slug: Web/JavaScript/Reference/Global_Objects/Math/SQRT1_2 +translation_of: Web/JavaScript/Reference/Global_Objects/Math/SQRT1_2 +--- +<div>{{JSRef}}</div> + +<p><strong><code>Math.SQRT1_2</code></strong> 프로퍼티는 약 0.707의 값을 나타내는 루트 1/2을 나타냅니다:</p> + +<p><math display="block"><semantics><mrow><mstyle mathvariant="monospace"><mi>Math.SQRT1_2</mi></mstyle><mo>=</mo><msqrt><mfrac><mn>1</mn><mn>2</mn></mfrac></msqrt><mo>=</mo><mfrac><mn>1</mn><msqrt><mn>2</mn></msqrt></mfrac><mo>≈</mo><mn>0.707</mn></mrow><annotation encoding="TeX">\mathtt{\mi{Math.SQRT1_2}} = \sqrt{\frac{1}{2}} = \frac{1}{\sqrt{2}} \approx 0.707</annotation></semantics></math></p> + +<div>{{EmbedInteractiveExample("pages/js/math-sqrt1_2.html", "shorter")}}</div> + +<p class="hidden">이 상호적인 예시의 소스는 깃헙에 저장되어 있습니다. 만약 상호적인 예시 프로젝트에 기여하고 싶으시다면, <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a>를 클론한 후, 풀 리퀘스트를 보내주시기 바랍니다.</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="설명">설명</h2> + +<p><code>SQRT1_2</code> 는 <code>Math</code>의 정적 프로퍼티이기 때문에, 당신이 생성한 <code>Math</code> 오브젝트의 프로퍼티보다는 항상 <code>Math.SQRT1_2</code>의 형태로 사용합니다 (<code>Math</code>는 컨스트럭터가 아닙니다).</p> + +<h2 id="예시">예시</h2> + +<h3 id="Math.SQRT1_2_의_사용"><code>Math.SQRT1_2</code> 의 사용</h3> + +<p>다음은 루트 1/2를 출력합니다:</p> + +<pre class="brush:js">function getRoot1_2() { + return Math.SQRT1_2; +} + +getRoot1_2(); // 0.7071067811865476 +</pre> + +<h2 id="사양">사양</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">사양</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.sqrt1_2', 'Math.SQRT1_2')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden"><span>이 페이지의 호환성 표는 구조화된 데이터에서 생성됩니다.</span> 데이터에 기여하고 싶으시다면, <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>을 확인하고 풀 리퀘스트를 보내 주시기 바랍니다.</p> + +<p>{{Compat("javascript.builtins.Math.SQRT1_2")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Math.pow()")}}</li> + <li>{{jsxref("Math.sqrt()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/math/sqrt2/index.html b/files/ko/web/javascript/reference/global_objects/math/sqrt2/index.html new file mode 100644 index 0000000000..1ad86df55b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/sqrt2/index.html @@ -0,0 +1,74 @@ +--- +title: Math.SQRT2 +slug: Web/JavaScript/Reference/Global_Objects/Math/SQRT2 +translation_of: Web/JavaScript/Reference/Global_Objects/Math/SQRT2 +--- +<div>{{JSRef}}</div> + +<p> <strong><code>Math.SQRT2</code></strong> 는 2의 제곱근을 나타내고 약 1.414 입니다:</p> + +<p><math display="block"><semantics><mrow><mstyle mathvariant="monospace"><mi>Math.SQRT2</mi></mstyle><mo>=</mo><msqrt><mn>2</mn></msqrt><mo>≈</mo><mn>1.414</mn></mrow><annotation encoding="TeX">\mathtt{\mi{Math.SQRT2}} = \sqrt{2} \approx 1.414</annotation></semantics></math></p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="설명">설명</h2> + +<p> <code>SQRT2</code> 는 <code>Math</code>의 정적 메서드 이므로 만든 <code>Math</code> 객체의 메서드가 아니라 항상 <code>Math.SQRT2</code> 함수를 사용해야합니다. (<code>Math</code>는 생성자가 없습니다.)</p> + +<h2 id="예제">예제</h2> + +<h3 id="Math.SQRT2"><code>Math.SQRT2</code></h3> + +<p>이 함수는 2의 제곱근을 반환합니다.</p> + +<pre class="brush: js">function getRoot2() { + return Math.SQRT2; +} + +getRoot2(); // 1.4142135623730951 +</pre> + +<h2 id="표준">표준</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">표준</th> + <th scope="col">상태</th> + <th scope="col">비고</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8.1.8', 'Math.SQRT2')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.sqrt2', 'Math.SQRT2')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.sqrt2', 'Math.SQRT2')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Math.SQRT2")}}</p> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("Math.pow()")}}</li> + <li>{{jsxref("Math.sqrt()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/math/tan/index.html b/files/ko/web/javascript/reference/global_objects/math/tan/index.html new file mode 100644 index 0000000000..64a1468020 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/tan/index.html @@ -0,0 +1,102 @@ +--- +title: Math.tan() +slug: Web/JavaScript/Reference/Global_Objects/Math/tan +tags: + - 레퍼런스 + - 메소드 + - 수학 + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Global_Objects/Math/tan +--- +<div>{{JSRef}}</div> + +<p><strong><code>Math.tan()</code></strong> 함수는 탄젠트 값을 반환합니다</p> + +<div>{{EmbedInteractiveExample("pages/js/math-tan.html")}}</div> + + + +<h2 id="신텍스">신텍스</h2> + +<pre class="syntaxbox"><code>Math.tan(<var>x</var>)</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>x</code></dt> + <dd>라디안 각도 </dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 수의 탄젠트 값</p> + +<h2 id="설명">설명</h2> + +<p><code>Math.tan()</code> 메소드는 각도의 탄젠트 값을 수로 반환합니다.</p> + +<p><code>tan()</code>은 <code>Math</code>의 정적 메서드이므로 사용자가 만든 <code>Math</code> 객체의 메서드가 아닌 항상 <code>Math.tan()</code>으로 사용합니다 (<code>Math</code> 는 생성자가 아닙니다).</p> + +<h2 id="예">예</h2> + +<h3 id="Using_Math.tan()">Using <code>Math.tan()</code></h3> + +<pre class="brush: js">Math.tan(1); // 1.5574077246549023 +</pre> + +<p><code>Math.tan()</code>함수는 라디안 값으로 받지만 각도로 작업하는 것이 더 쉽기 때문에 다음 함수는 각도로 값을 받아서 라디안으로 변환하고 탄젠트를 반환합니다.</p> + +<pre class="brush: js">function getTanDeg(deg) { + var rad = deg * Math.PI/180; + return Math.tan(rad); +} +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8.2.18', 'Math.tan')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.tan', 'Math.tan')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.tan', 'Math.tan')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Math.tan")}}</p> + +<h2 id="함께_보기">함께 보기</h2> + +<ul> + <li>{{jsxref("Math.acos()")}}</li> + <li>{{jsxref("Math.asin()")}}</li> + <li>{{jsxref("Math.atan()")}}</li> + <li>{{jsxref("Math.atan2()")}}</li> + <li>{{jsxref("Math.cos()")}}</li> + <li>{{jsxref("Math.sin()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/math/tanh/index.html b/files/ko/web/javascript/reference/global_objects/math/tanh/index.html new file mode 100644 index 0000000000..97055e165b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/tanh/index.html @@ -0,0 +1,85 @@ +--- +title: Math.tanh() +slug: Web/JavaScript/Reference/Global_Objects/Math/tanh +tags: + - ECMAScript 2015 + - 레퍼런스 + - 메서드 + - 수학 + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Global_Objects/Math/tanh +--- +<div>{{JSRef}}</div> + +<p><strong><code>Math.tanh()</code></strong> 함수는 쌍곡탄젠트 값을 반환합니다. 수식으로는 아래와 같습니다.</p> + +<p><math display="block"><semantics><mrow><mo lspace="0em" rspace="0em">tanh</mo><mi>x</mi><mo>=</mo><mfrac><mrow><mo lspace="0em" rspace="0em">sinh</mo><mi>x</mi></mrow><mrow><mo lspace="0em" rspace="0em">cosh</mo><mi>x</mi></mrow></mfrac><mo>=</mo><mfrac><mrow><msup><mi>e</mi><mi>x</mi></msup><mo>-</mo><msup><mi>e</mi><mrow><mo>-</mo><mi>x</mi></mrow></msup></mrow><mrow><msup><mi>e</mi><mi>x</mi></msup><mo>+</mo><msup><mi>e</mi><mrow><mo>-</mo><mi>x</mi></mrow></msup></mrow></mfrac><mo>=</mo><mfrac><mrow><msup><mi>e</mi><mrow><mn>2</mn><mi>x</mi></mrow></msup><mo>-</mo><mn>1</mn></mrow><mrow><msup><mi>e</mi><mrow><mn>2</mn><mi>x</mi></mrow></msup><mo>+</mo><mn>1</mn></mrow></mfrac></mrow><annotation encoding="TeX">\tanh x = \frac{\sinh x}{\cosh x} = \frac {e^x - e^{-x}} {e^x + e^{-x}} = \frac{e^{2x} - 1}{e^{2x}+1}</annotation></semantics></math></p> + +<div>{{EmbedInteractiveExample("pages/js/math-tanh.html")}}</div> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code>Math.tanh(<var>x</var>)</code></pre> + +<h3 id="파라미터">파라미터</h3> + +<dl> + <dt><code>x</code></dt> + <dd>숫자.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 수의 쌍곡탄젠트 값</p> + +<h2 id="설명">설명</h2> + +<p><code>tanh()</code> 은 <code>Math</code>의 정적 메서드이므로 사용자가 만든 <code>Math</code> 객체의 메서드가 아닌 항상 <code>Math.tanh()</code> 으로 사용합니다 (<code>Math</code> 는 생성자가 아닙니다.).</p> + +<h2 id="예">예</h2> + +<h3 id="Using_Math.tanh">Using <code>Math.tanh()</code></h3> + +<pre class="brush: js">Math.tanh(0); // 0 +Math.tanh(Infinity); // 1 +Math.tanh(1); // 0.7615941559557649 +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>This can be emulated with the help of the {{jsxref("Math.exp()")}} function:</p> + +<pre class="brush: js">Math.tanh = Math.tanh || function(x){ + var a = Math.exp(+x), b = Math.exp(-x); + return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (a + b); +} +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.tanh', 'Math.tanh')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Math.tanh")}}</p> + +<h2 id="함께_보기">함께 보기</h2> + +<ul> + <li>{{jsxref("Math.acosh()")}}</li> + <li>{{jsxref("Math.asinh()")}}</li> + <li>{{jsxref("Math.atanh()")}}</li> + <li>{{jsxref("Math.cosh()")}}</li> + <li>{{jsxref("Math.sinh()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/math/trunc/index.html b/files/ko/web/javascript/reference/global_objects/math/trunc/index.html new file mode 100644 index 0000000000..0f63fd1e58 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/trunc/index.html @@ -0,0 +1,96 @@ +--- +title: Math.trunc() +slug: Web/JavaScript/Reference/Global_Objects/Math/trunc +translation_of: Web/JavaScript/Reference/Global_Objects/Math/trunc +--- +<div>{{JSRef}}</div> + +<p><strong><code>Math.trunc()</code></strong> 함수는 주어진 값의 소수부분을 제거하고 숫자의 정수부분을 반환합니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">Math.trunc(<var>x</var>) +</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>x</code></dt> + <dd>숫자형</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>주어진 숫자의 정수부분</p> + +<h2 id="Description">Description</h2> + +<p>Math의 유사함수 3개 : {{jsxref("Math.floor()")}}, {{jsxref("Math.ceil()")}} and {{jsxref("Math.round()")}} 와는 다르게, <code>Math.trunc()</code> 함수는 주어진 값이 양수이건 음수이건 상관없이 소수점 이하 우측부분을 제거하는 매우 단순한 동작을 합니다.</p> + +<p>함수인자는 암묵적으로 number형으로 변환되어 메소드에 전달됩니다.</p> + +<p><code>trunc()</code> 함수는 Math의 정적 메소드이기 때문에 사용자가 생성한 <code>Math</code> 객체의 메소드로 호출하는 것이 아닌 항상 <code>Math.trunc()</code> 형태로 호출해야 합니다. (<code>Math</code> 는 생성자가 아닙니다).</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_Math.trunc()">Using <code>Math.trunc()</code></h3> + +<pre class="brush: js">Math.trunc(13.37); // 13 +Math.trunc(42.84); // 42 +Math.trunc(0.123); // 0 +Math.trunc(-0.123); // -0 +Math.trunc('-1.123'); // -1 +Math.trunc(NaN); // NaN +Math.trunc('foo'); // NaN +Math.trunc(); // NaN +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js">Math.trunc = Math.trunc || function(x) { + if (isNaN(x)) { + return NaN; + } + if (x > 0) { + return Math.floor(x); + } + return Math.ceil(x); +};</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-math.trunc', 'Math.trunc')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.trunc', 'Math.trunc')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Math.trunc")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Math.abs()")}}</li> + <li>{{jsxref("Math.ceil()")}}</li> + <li>{{jsxref("Math.floor()")}}</li> + <li>{{jsxref("Math.round()")}}</li> + <li>{{jsxref("Math.sign()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/nan/index.html b/files/ko/web/javascript/reference/global_objects/nan/index.html new file mode 100644 index 0000000000..4e6e3a8c42 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/nan/index.html @@ -0,0 +1,91 @@ +--- +title: NaN +slug: Web/JavaScript/Reference/Global_Objects/NaN +tags: + - JavaScript + - Property + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/NaN +--- +<div>{{jsSidebar("Objects")}}</div> + +<p>전역 <code><strong>NaN</strong></code> 속성은 Not-A-Number(숫자가 아님)를 나타냅니다.</p> + +<p>{{js_property_attributes(0,0,0)}}</p> + +<div>{{EmbedInteractiveExample("pages/js/globalprops-nan.html")}}</div> + + + +<h2 id="Description" name="Description">설명</h2> + +<p><code>NaN</code>은 전역 객체의 속성입니다. 즉 전역 스코프의 변수입니다.</p> + +<p><code>NaN</code>의 초기값은 Not-A-Number(숫자가 아님)로, {{jsxref("Number.NaN")}}의 값과 같습니다. 최신 브라우저에서 <code style="font-style: normal;">NaN</code>은 설정 불가, 쓰기 불가 속성입니다. 그렇지 않다고 하더라도 덮어쓰는건 피하는게 좋습니다.</p> + +<p><code>NaN</code>을 반환하는 연산에는 다섯 가지 종류가 있습니다.</p> + +<ul> + <li>숫자로서 읽을 수 없음 (<code>parseInt("어쩌구")</code>, <code>Number(undefined)</code>)</li> + <li>결과가 허수인 수학 계산식 (<code>Math.sqrt(-1)</code>)</li> + <li>피연산자가 <code>NaN</code> (<code>7 ** NaN</code>)</li> + <li>정의할 수 없는 계산식 (<code>0 * Infinity</code>)</li> + <li>문자열을 포함하면서 덧셈이 아닌 계산식 (<code>"가" / 3</code>)</li> +</ul> + +<h2 id="예제">예제</h2> + +<h3 id="NaN_판별"><code>NaN</code> 판별</h3> + +<p><code>NaN</code>은 다른 모든 값과 비교(<code>==</code>, <code>!=</code>, <code>===</code>, <code>!==</code>)했을 때 같지 않으며, 다른 NaN과도 같지 않습니다. NaN의 판별은 {{jsxref("Number.isNaN()")}} 또는 {{jsxref("Global_Objects/isNaN", "isNaN()")}}을 사용하면 제일 분명하게 수행할 수 있습니다. 아니면, 오로지 NaN만이 자기자신과 비교했을 때 같지 않음을 이용할 수도 있습니다.</p> + +<pre class="brush: js notranslate">NaN === NaN; // false +Number.NaN === NaN; // false +isNaN(NaN); // true +isNaN(Number.NaN); // true + +function valueIsNaN(v) { return v !== v; } +valueIsNaN(1); // false +valueIsNaN(NaN); // true +valueIsNaN(Number.NaN); // true +</pre> + +<p>그러나 <code>isNaN()</code>과 <code>Number.isNaN()</code>의 차이를 주의해야 합니다. <code>isNaN</code>은 현재 값이 <code>NaN</code>이거나, 숫자로 변환했을 때 <code>NaN</code>이 되면 참을 반환하지만, <code>Number.isNaN</code>은 현재 값이 <code>NaN</code>이어야만 참을 반환합니다.</p> + +<pre class="brush: js notranslate">isNaN('hello world'); // true +Number.isNaN('hello world'); // false +</pre> + +<p>덧붙여서, 일부 배열 메서드는 NaN을 찾을 수 없습니다.</p> + +<pre class="brush: js notranslate">let arr = [2, 4, NaN, 12]; +arr.indexOf(NaN); // -1 (false) +arr.includes(NaN); // true +arr.findIndex(n => Number.isNaN(n)); // 2</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-value-properties-of-the-global-object-nan', 'NaN')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.NaN")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Number.NaN")}}</li> + <li>{{jsxref("Number.isNaN()")}}</li> + <li>{{jsxref("isNaN", "isNaN()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/null/index.html b/files/ko/web/javascript/reference/global_objects/null/index.html new file mode 100644 index 0000000000..e69295c9f6 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/null/index.html @@ -0,0 +1,69 @@ +--- +title: 'null' +slug: Web/JavaScript/Reference/Global_Objects/null +tags: + - JavaScript + - Literal + - Primitive + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/null +--- +<div>{{jsSidebar("Objects")}}</div> + +<p><strong><code>null</code></strong>은 JavaScript의 {{Glossary("Primitive", "원시 값")}} 중 하나로, 어떤 값이 의도적으로 비어있음을 표현하며 불리언 연산에서는 {{glossary("falsy", "거짓")}}으로 취급합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/globalprops-null.html")}}</div> + + + +<h2 id="설명">설명</h2> + +<p><code>null</code>은 리터럴로서, <code>null</code>로 작성할 수 있습니다. <code>null</code>은 {{jsxref("undefined")}}와 같은 전역 객체의 식별자가 아닙니다. 대신 식별되지 않은 상태를 나타내며 해당 변수가 어떠한 객체도 가리키고 있지 않음을 표시합니다. API에서는 대개 객체를 기대했지만, 어떤 적합한 객체도 존재하지 않을 때 반환합니다.</p> + +<pre class="brush: js">// 정의되지 않고 초기화된 적도 없는 foo +foo; //ReferenceError: foo is not defined + +// 존재하지만 값이나 자료형이 존재하지 않는 foo +var foo = null; +foo; //null +</pre> + +<h3 id="null과_undefined의_차이"><code>null</code>과 <code>undefined</code>의 차이</h3> + +<p><code>null</code> 또는 <code>undefined</code>를 검사할 때, <a href="/ko/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">동등 연산자(==)와 일치 연산자(===)의 차이</a>를 주의하세요. 동등 연산자는 자료형 변환을 수행합니다.</p> + +<pre class="brush: js">typeof null // "object" (하위호환 유지를 위해 "null"이 아님) +typeof undefined // "undefined" +null === undefined // false +null == undefined // true +null === null // true +null == null // true +!null // true +isNaN(1 + null) // false +isNaN(1 + undefined) // true</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-null-value', 'null value')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.null")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("undefined")}}</li> + <li>{{jsxref("NaN")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/number/epsilon/index.html b/files/ko/web/javascript/reference/global_objects/number/epsilon/index.html new file mode 100644 index 0000000000..730fd8ae87 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/epsilon/index.html @@ -0,0 +1,61 @@ +--- +title: Number.EPSILON +slug: Web/JavaScript/Reference/Global_Objects/Number/EPSILON +tags: + - ECMAScript6 + - JavaScript + - Number + - 속성 +translation_of: Web/JavaScript/Reference/Global_Objects/Number/EPSILON +--- +<div>{{JSRef}}</div> + +<p> <strong><code>Number.EPSILON</code></strong> 속성(property)은 {{jsxref("Number")}} 형으로 표현될 수 있는 1과 1보다 큰 값 중에서 가장 작은 값의, 차입니다.</p> + +<p>당신은 이 정적 속성에 접근하기 위하여 {{jsxref("Number")}} 객체를 생성할 필요가 없습니다. <code>Number.EPSILON</code>을 쓰면 됩니다.</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="설명">설명</h2> + +<p>이 <code>EPSILON</code> 속성은 대략 <code>2.2204460492503130808472633361816E-16</code> 또는 <code>2<sup>-52</sup></code>의 값을 갖습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="동일성_확인하기">동일성 확인하기</h3> + +<pre class="brush: js">const x = 0.2, y = 0.3, z = 0.1; +let equal = (Math.abs(x - y + z) < Number.EPSILON); +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">비고</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.epsilon', 'Number.EPSILON')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>최초로 정의됨.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.epsilon', 'Number.EPSILON')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.Number.EPSILON")}}</p> + +<h2 id="관련된_문서">관련된 문서</h2> + +<ul> + <li>이 속성을 가지고 있는 {{jsxref("Number")}} 객체</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/number/index.html b/files/ko/web/javascript/reference/global_objects/number/index.html new file mode 100644 index 0000000000..2a2592dcc8 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/index.html @@ -0,0 +1,177 @@ +--- +title: Number +slug: Web/JavaScript/Reference/Global_Objects/Number +tags: + - JavaScript + - Number + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Number +--- +<div>{{JSRef}}</div> + +<p><strong><code>Number</code></strong> 객체는 숫자 값으로 작업할 수 있게 해주는 래퍼<sup>wrapper</sup> 객체입니다. <code>Number</code> 객체는 <strong><code>Number()</code> 생성자</strong>를 사용하여 만듭니다. 원시 숫자 자료형은 <strong><code>Number()</code> 함수</strong>를 사용해 생성합니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">new Number(<em>value</em>); +var <em>a</em> = new Number('123'); // a === 123은 false +var <em>b</em> = Number('123'); // b === 123은 true +<em>a</em> instanceof Number; // true +<em>b</em> instanceof Number; // false</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>value</code></dt> + <dd>생성할 객체의 숫자 값.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p><code>Number</code> 객체의 주된 용도는 다음과 같습니다.</p> + +<ul> + <li>만약 인수를 숫자로 변환할 수 없으면 {{jsxref("NaN")}}을 리턴합니다.</li> + <li>생성자로써 사용하지 않으면({{jsxref("Operators/new", "new")}} 연산자를 사용하지 않으면) <code>Number</code>를 사용하여 형변환을 할 수 있습니다.</li> +</ul> + +<h2 id="속성">속성</h2> + +<dl> + <dt>{{jsxref("Number.EPSILON")}}</dt> + <dd>두 개의 표현 가능한 숫자 사이의 최소 간격.</dd> + <dt>{{jsxref("Number.MAX_SAFE_INTEGER")}}</dt> + <dd>JavaScript에서 안전한 최대 정수. (<code>2<sup>53</sup> - 1</code>)</dd> + <dt>{{jsxref("Number.MAX_VALUE")}}</dt> + <dd>표현 가능한 가장 큰 양수.</dd> + <dt>{{jsxref("Number.MIN_SAFE_INTEGER")}}</dt> + <dd>JavaScript에서 안전한 최소 정수. (<code>-(2<sup>53</sup> - 1)</code>)</dd> + <dt>{{jsxref("Number.MIN_VALUE")}}</dt> + <dd>표현 가능한 가장 작은 양수. 즉, 0보다 크지만 0에 가장 가까운 양수.</dd> + <dt>{{jsxref("Number.NaN")}}</dt> + <dd>"숫자가 아님"을 나타내는 특별한 값.</dd> + <dt>{{jsxref("Number.NEGATIVE_INFINITY")}}</dt> + <dd>음의 무한대를 나타내는 특수한 값. 오버플로우 시 반환됩니다.</dd> + <dt>{{jsxref("Number.POSITIVE_INFINITY")}}</dt> + <dd>양의 무한대를 나타내는 특수한 값. 오버플로우 시 반환됩니다.</dd> + <dt>{{jsxref("Number.prototype")}}</dt> + <dd><code>Number</code> 객체에 속성을 추가할 수 있습니다.</dd> +</dl> + +<h2 id="메서드">메서드</h2> + +<dl> + <dt>{{jsxref("Number.isNaN()")}}</dt> + <dd>주어진 값이 <code>NaN</code>인지 확인합니다.</dd> + <dt>{{jsxref("Number.isFinite()")}}</dt> + <dd>주어진 값이 유한수 인지 확인합니다.</dd> + <dt>{{jsxref("Number.isInteger()")}}</dt> + <dd>주어진 값이 정수인지 확인합니다.</dd> + <dt>{{jsxref("Number.isSafeInteger()")}}</dt> + <dd>주어진 값이 안전한 정수(<code>-(2<sup>53</sup> - 1)</code>과 <code>2<sup>53</sup> - 1</code> 사이의 정수)인지 확인합니다.</dd> + <dt><s class="obsoleteElement">{{jsxref("Number.toInteger()")}} {{obsolete_inline}}</s></dt> + <dd><s class="obsoleteElement">전달 된 값을 평가하고 이를 정수(혹은 {{jsxref("Infinity", "Infinity")}})로 변환하는데 사용되지만, 제거되었습니다.</s></dd> + <dt>{{jsxref("Number.parseFloat()")}}</dt> + <dd>전역 객체 {{jsxref("parseFloat", "parseFloat()")}}와 동일한 값입니다.</dd> + <dt>{{jsxref("Number.parseInt()")}}</dt> + <dd>전역 객체 {{jsxref("parseInt", "parseInt()")}}와 동일한 값입니다.</dd> +</dl> + +<h2 id="Number_인스턴스"><code>Number</code> 인스턴스</h2> + +<p>모든 <code>Number</code> 인스턴스는 {{jsxref("Number.prototype")}}를 상속합니다. <code>Number</code> 생성자의 프로토타입 객체는 모든 <code>Number</code> 인스턴스에 영향을 미치도록 수정할 수 있습니다.</p> + +<h3 id="메서드_2">메서드</h3> + +<div>{{page('/ko/docs/Web/JavaScript/Reference/Global_Objects/Number/prototype', 'Methods')}}</div> + +<h2 id="예제">예제</h2> + +<h3 id="Number_객체를_사용해_숫자형_변수에_할당"><code>Number</code> 객체를 사용해 숫자형 변수에 할당</h3> + +<p>다음 예제에서는 <code>Number</code> 객체의 속성을 사용하여, 여러 숫자 변수에 값을 할당합니다:</p> + +<pre class="brush: js">var biggestNum = Number.MAX_VALUE; +var smallestNum = Number.MIN_VALUE; +var infiniteNum = Number.POSITIVE_INFINITY; +var negInfiniteNum = Number.NEGATIVE_INFINITY; +var notANum = Number.NaN; +</pre> + +<h3 id="Number의_정수_범위"><code>Number</code>의 정수 범위</h3> + +<p>다음 예제는 <code>Number</code> 객체가 표현할 수 있는 정수의 최소값과 최대값을 보여줍니다. (자세한 내용은 ECMAScript 표준, <em><a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-number-type">6.1.6 The Number Type</a> 장을 참고하세요)</em></p> + +<pre class="brush: js">var biggestInt = 9007199254740992; +var smallestInt = -9007199254740992; +</pre> + +<p>JSON으로 직렬화한 데이터를 읽을 때, 위의 범위를 벗어나는 수는 JSON 분석기의 <code>Number</code> 형변환 시 손상될 수 있습니다. 이 때는 {{jsxref("String")}}을 대신 사용하는 것도 방법입니다.</p> + +<h3 id="Number를_사용해_Date_객체_숫자로_변환"><code>Number</code>를 사용해 <code>Date</code> 객체 숫자로 변환</h3> + +<p>다음 예제는 <code>Number</code>를 함수로 사용하여 {{jsxref("Date")}} 객체를 숫자 값으로 변환합니다.</p> + +<pre class="brush: js">var d = new Date('December 17, 1995 03:24:00'); +console.log(Number(d)); +</pre> + +<p><code>819199440000</code>가 기록됩니다.</p> + +<h3 id="숫자형_문자열에서_숫자로_변환">숫자형 문자열에서 숫자로 변환</h3> + +<pre class="brush: js">Number('123') // 123 +Number('12.3') // 12.3 +Number('123e-1') // 12.3 +Number('') // 0 +Number(null) // 0 +Number('0x11') // 17 +Number('0b11') // 3 +Number('0o11') // 9 +Number('foo') // NaN +Number('100a') // NaN</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7', 'Number')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number-objects', 'Number')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>New methods and properties added: ({{jsxref("Number.EPSILON", "EPSILON")}}, {{jsxref("Number.isFinite", "isFinite")}}, {{jsxref("Number.isInteger", "isInteger")}}, {{jsxref("Number.isNaN", "isNaN")}}, {{jsxref("Number.parseFloat", "parseFloat")}}, {{jsxref("Number.parseInt", "parseInt")}})</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number-objects', 'Number')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div> +<p>{{Compat("javascript.builtins.Number")}}</p> +</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("NaN")}}</li> + <li>{{jsxref("Math")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/number/isfinite/index.html b/files/ko/web/javascript/reference/global_objects/number/isfinite/index.html new file mode 100644 index 0000000000..13c76c4d8d --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/isfinite/index.html @@ -0,0 +1,90 @@ +--- +title: Number.isFinite() +slug: Web/JavaScript/Reference/Global_Objects/Number/isFinite +tags: + - JavaScript + - Method + - Number + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Number/isFinite +--- +<div>{{JSRef}}</div> + +<p><strong><code>Number.isFinite()</code></strong> 메서드는 주어진 값이 유한수인지 판별합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/number-isfinite.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">Number.isFinite(<var>value</var>)</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>value</code></dt> + <dd>유한수인지 판별할 값.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>유한수 여부에 대한 {{jsxref("Boolean")}} 값.</p> + +<h2 id="설명">설명</h2> + +<p>전역 함수 {{jsxref("isFinite", "isFinite()")}}와 비교했을 때, <code>Number.isFinite()</code> 메서드는 매개변수를 숫자로 변환하지 않습니다. 즉 값이 숫자이며 동시에 유한수일 때만 <code>true</code>를 반환합니다.</p> + +<h2 id="예제">예제</h2> + +<pre class="brush: js">Number.isFinite(Infinity); // false +Number.isFinite(NaN); // false +Number.isFinite(-Infinity); // false + +Number.isFinite(0); // true +Number.isFinite(2e64); // true + +Number.isFinite('0'); // false + // 전역함수 isFinite('0')라면 true +Number.isFinite(null); // false + // 전역함수 isFinite(null)라면 true +</pre> + +<h2 id="폴리필">폴리필</h2> + +<pre class="brush: js">if (Number.isFinite === undefined) Number.isFinite = function(value) { + return typeof value === 'number' && isFinite(value); +}</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.isfinite', 'Number.isInteger')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.isfinite', 'Number.isInteger')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.Number.isFinite")}}</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>메서드가 속한 {{jsxref("Number")}} 객체.</li> + <li>전역 함수 {{jsxref("isFinite")}}.</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/number/isinteger/index.html b/files/ko/web/javascript/reference/global_objects/number/isinteger/index.html new file mode 100644 index 0000000000..c2be9f56f1 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/isinteger/index.html @@ -0,0 +1,96 @@ +--- +title: Number.isInteger() +slug: Web/JavaScript/Reference/Global_Objects/Number/isInteger +tags: + - JavaScript + - Method + - Number + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Number/isInteger +--- +<div>{{JSRef}}</div> + +<p><strong><code>Number.isInteger()</code> </strong>메서드는 주어진 값이 정수인지 판별합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/number-isinteger.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">Number.isInteger(v<var>alue</var>)</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>value</code></dt> + <dd>정수인지 확인하려는 값.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 값의 정수 여부를 나타내는 {{jsxref("Boolean")}}.</p> + +<h2 id="설명">설명</h2> + +<p>매개변수의 값이 정수면 <code>true</code>를, 아니면 <code>false</code>를 반환합니다. 값이 {{jsxref("NaN")}}이거나 {{jsxref("Infinity")}}여도 <code>false</code>를 반환합니다.</p> + +<h2 id="예제">예제</h2> + +<pre>Number.isInteger(0); // true +Number.isInteger(1); // true +Number.isInteger(-100000); // true +Number.isInteger(99999999999999999999999); // true + +Number.isInteger(0.1); // false +Number.isInteger(Math.PI); // false + +Number.isInteger(NaN); // false +Number.isInteger(Infinity); // false +Number.isInteger(-Infinity); // false +Number.isInteger('10'); // false +Number.isInteger(true); // false +Number.isInteger(false); // false +Number.isInteger([1]); // false +</pre> + +<h2 id="폴리필">폴리필</h2> + +<pre class="brush: js">Number.isInteger = Number.isInteger || function(value) { + return typeof value === "number" && + isFinite(value) && + Math.floor(value) === value; +}; +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.isinteger', 'Number.isInteger')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.isinteger', 'Number.isInteger')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.Number.isInteger")}}</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>메서드가 속한 {{jsxref("Number")}} 객체.</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/number/isnan/index.html b/files/ko/web/javascript/reference/global_objects/number/isnan/index.html new file mode 100644 index 0000000000..ff5ae793de --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/isnan/index.html @@ -0,0 +1,100 @@ +--- +title: Number.isNaN() +slug: Web/JavaScript/Reference/Global_Objects/Number/isNaN +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Number + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Number/isNaN +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary"><strong><code>Number.isNaN()</code></strong> 메서드는 주어진 값이 {{jsxref("NaN")}}인지 판별합니다.</span> 기존부터 존재한 전역 {{jsxref("isNaN", "isNaN()")}} 함수의 더 엄격한 버전입니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/number-isnan.html", "taller")}}</div> + +<div class="hidden">The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</div> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">Number.isNaN(v<var>alue</var>)</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>value</code></dt> + <dd>{{jsxref("NaN")}}인지 판별할 값.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 값의 유형이 {{jsxref("Number")}}이고 값이 {{jsxref("NaN")}}이면 <code>true</code>, 아니면 <code>false</code>.</p> + +<h2 id="설명">설명</h2> + +<p>{{jsxref("NaN")}}이 <code>NaN</code>인지 계산할 때, 두 동일 연산자 <code>==</code>과 <code>===</code> 모두 <code>false</code>로 평가되므로 값의 <code>NaN</code> 여부를 알아내려면 <code>Number.isNaN()</code>이 필요합니다. 이 상황은 다른 모든 JavaScript와 다른 특별한 경우입니다.</p> + +<p>전역 {{jsxref("isNaN", "isNaN()")}} 함수와 달리, <code>Number.isNaN()</code>은 강제로 매개변수를 숫자로 변환하는 문제를 겪지 않습니다. 이는 이제 보통{{jsxref("NaN")}}으로 변환됐을 값이 안전하게 전달되지만, 실제로는 {{jsxref("NaN")}}과 같은 값이 아님을 의미합니다. 이는 또한 오직 숫자형이고 또한 {{jsxref("NaN")}}인 값만이 <code>true</code>를 반환함을 뜻합니다.</p> + +<h2 id="예제">예제</h2> + +<pre class="brush: js">Number.isNaN(NaN); // true +Number.isNaN(Number.NaN); // true +Number.isNaN(0 / 0) // true + +// 예를 들면 이들은 global isNaN()으로는 true가 됐을 것임 +Number.isNaN("NaN"); // false +Number.isNaN(undefined); // false +Number.isNaN({}); // false +Number.isNaN("blabla"); // false + +// 모두 +Number.isNaN(true); +Number.isNaN(null); +Number.isNaN(37); +Number.isNaN("37"); +Number.isNaN("37.37"); +Number.isNaN(""); +Number.isNaN(" "); +</pre> + +<h2 id="폴리필">폴리필</h2> + +<pre class="brush: js">Number.isNaN = Number.isNaN || function(value) { + return value !== value; +}</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.isnan', 'Number.isnan')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.isnan', 'Number.isnan')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.Number.isNaN")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Number")}}</li> + <li>{{jsxref("isNaN", "isNaN()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/number/issafeinteger/index.html b/files/ko/web/javascript/reference/global_objects/number/issafeinteger/index.html new file mode 100644 index 0000000000..8c1af0e54d --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/issafeinteger/index.html @@ -0,0 +1,100 @@ +--- +title: Number.isSafeInteger() +slug: Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Number + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger +--- +<div>{{JSRef}}</div> + +<p><strong><code>Number.isSafeInteger()</code></strong> 메서드는 전달된 값이 안전한 정숫값인지 확인합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/number-issafeinteger.html")}}</div> + + + +<p>안전한 정숫값이란 다음과 같습니다.</p> + +<ul> + <li>IEEE-754 배정도수 형태로 정확히 표현될 수 있는 수이고</li> + <li>IEEE-754 표현에 맞게 반올림하는 다른 정수의 결과가 아닌 IEEE-754 표현.</li> +</ul> + +<p>예를 들어, <code>2<sup>53</sup> - 1</code>은 안전한 정수입니다. 이 정수는 정확히 표현될 수 있으며, IEEE-754 반올림 모드에서 다른 정숫값이 이 값을 반올림하지 않습니다. 반면에, <code>2<sup>53</sup></code> 는 안전하지 않은 정수입니다. 이 정수는 정확히 IEEE-754로 표현될 수 있지만, 정수 <code>2<sup>53</sup> + 1</code>은 IEEE-754로 직접 표현될 수 없으며 가까운 수로 반올림하는 것과 0으로 반올림하는 것으로 <code>2<sup>53 </sup></code>을 반올림합니다.</p> + +<p>안전한 정숫값은 <code>-(2<sup>53</sup> - 1)</code> 부터 <code>2<sup>53</sup> - 1</code> 사이의 모든 정수값으로 구성됩니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">Number.isSafeInteger(<var>testValue</var>) +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>testValue</code></dt> + <dd>안전한 정수인지 확인할 값.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 값이 안전한 정숫값인지 나타내는 {{jsxref("Boolean")}}.</p> + +<h2 id="예시">예시</h2> + +<pre class="brush: js">Number.isSafeInteger(3); // true +Number.isSafeInteger(Math.pow(2, 53)); // false +Number.isSafeInteger(Math.pow(2, 53) - 1); // true +Number.isSafeInteger(NaN); // false +Number.isSafeInteger(Infinity); // false +Number.isSafeInteger('3'); // false +Number.isSafeInteger(3.1); // false +Number.isSafeInteger(3.0); // true +</pre> + +<h2 id="폴리필">폴리필</h2> + +<pre class="brush: js">Number.isSafeInteger = Number.isSafeInteger || function (value) { + return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER; +}; +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-number.issafeinteger', 'Number.isSafeInteger')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.issafeinteger', 'Number.isSafeInteger')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Number.isSafeInteger")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>메서드가 속한 {{jsxref("Number")}} 객체.</li> + <li>{{jsxref("Number.MIN_SAFE_INTEGER")}}</li> + <li>{{jsxref("Number.MAX_SAFE_INTEGER")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/number/max_safe_integer/index.html b/files/ko/web/javascript/reference/global_objects/number/max_safe_integer/index.html new file mode 100644 index 0000000000..c8b4d679d0 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/max_safe_integer/index.html @@ -0,0 +1,76 @@ +--- +title: Number.MAX_SAFE_INTEGER +slug: Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER +tags: + - ECMAScript 2015 + - JavaScript + - Number + - Property +translation_of: Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER +--- +<div>{{JSRef}}</div> + +<p><strong><code>Number.MAX_SAFE_INTEGER</code></strong> 상수는 JavaScript에서 안전한 최대 정수값을 나타냅니다. (<code>2<sup>53</sup> - 1</code>).</p> + +<div>{{EmbedInteractiveExample("pages/js/number-maxsafeinteger.html")}}</div> + + + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="설명">설명</h2> + +<p><code>MAX_SAFE_INTEGER</code> 상수는 <code>9007199254740991</code>(9,007,199,254,740,991 또는 약 9000조)의 값을 갖고 있습니다. 이 값의 이유는 JavaScript가 <a href="http://en.wikipedia.org/wiki/IEEE_floating_point">IEEE 754</a>에 기술된 <a href="http://en.wikipedia.org/wiki/Double_precision_floating-point_format">배정밀도 부동소숫점 형식 숫자체계</a>를 사용하기 때문으로, 이로 인해 <code>-(2<sup>53</sup> - 1)</code>과 <code>2<sup>53</sup> - 1</code> 사이의 수만 안전하게 표현할 수 있습니다.</p> + +<p>여기서의 안전함이란 정수를 정확하고 올바르게 비교할 수 있음을 의미합니다. 예를 들어 <code>Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2</code>는 참으로 평가되며 이는 수학적으로 올바르지 않습니다. 더 자세한 내용은 {{jsxref("Number.isSafeInteger()")}}를 참고하세요.</p> + +<p><code>MAX_SAFE_INTEGER</code>는 {{jsxref("Number")}}의 정적 속성이기 때문에, 직접 생성한 {{jsxref("Number")}} 객체의 속성이 아니라 <code>Number.MAX_SAFE_INTEGER</code> 형식으로 사용해야 합니다.</p> + +<h2 id="예제">예제</h2> + +<pre class="brush: js">Number.MAX_SAFE_INTEGER // 9007199254740991 +Number.MAX_SAFE_INTEGER * Number.EPSILON // 2 because in floating points, the value is actually the decimal trailing "1" + // except for in subnormal precision cases such as zero +</pre> + +<h2 id="폴리필">폴리필</h2> + +<pre class="brush: js"><code>if (!Number.MAX_SAFE_INTEGER) { + Number.MAX_SAFE_INTEGER = Math.pow(2, 53) - 1; // 9007199254740991 +}</code></pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-number.max_safe_integer', 'Number.MAX_SAFE_INTEGER')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.max_safe_integer', 'Number.MAX_SAFE_INTEGER')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Number.MAX_SAFE_INTEGER")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Number.MIN_SAFE_INTEGER")}}</li> + <li>{{jsxref("Number.isSafeInteger()")}}</li> + <li>{{jsxref("BigInt")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/number/max_value/index.html b/files/ko/web/javascript/reference/global_objects/number/max_value/index.html new file mode 100644 index 0000000000..c80ae8f84a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/max_value/index.html @@ -0,0 +1,81 @@ +--- +title: Number.MAX_VALUE +slug: Web/JavaScript/Reference/Global_Objects/Number/MAX_VALUE +tags: + - JavaScript + - Number + - Property +translation_of: Web/JavaScript/Reference/Global_Objects/Number/MAX_VALUE +--- +<div>{{JSRef}}</div> + +<p><strong><code>Number.MAX_VALUE</code></strong> 속성은 JavaScript가 표현할 수 있는 제일 큰 양의 숫자 값을 나타냅니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/number-maxvalue.html")}}</div> + + + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="설명">설명</h2> + +<p><code>MAX_VALUE</code>의 값은 약 <code>1.79E+308</code>, 2<sup>1024</sup>입니다. <code>MAX_VALUE</code>보다 큰 값은 {{jsxref("Infinity")}}로 표현됩니다.</p> + +<p><code>MAX_VALUE</code>는 {{jsxref("Number")}}의 정적 속성이기 때문에, 직접 생성한 {{jsxref("Number")}} 객체의 속성이 아니라 <code>Number.MAX_VALUE</code> 형식으로 사용해야 합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="MAX_VALUE_사용하기"><code>MAX_VALUE</code> 사용하기</h3> + +<p>다음 코드는 두 개의 수를 곱합니다. 만약 결과가 <code>MAX_VALUE</code> 이하면 <code>func1</code>을 호출하고, 그렇지 않으면 <code>func2</code>를 호출합니다.</p> + +<pre class="brush: js">if (num1 * num2 <= Number.MAX_VALUE) { + func1(); +} else { + func2(); +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7.3.2', 'Number.MAX_VALUE')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.max_value', 'Number.MAX_VALUE')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.max_value', 'Number.MAX_VALUE')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Number.MAX_VALUE")}}</p> + +<h2 id="참고">참고</h2> + +<ul> + <li>{{jsxref("Number.MIN_VALUE")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/number/min_safe_integer/index.html b/files/ko/web/javascript/reference/global_objects/number/min_safe_integer/index.html new file mode 100644 index 0000000000..67efd0e681 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/min_safe_integer/index.html @@ -0,0 +1,66 @@ +--- +title: Number.MIN_SAFE_INTEGER +slug: Web/JavaScript/Reference/Global_Objects/Number/MIN_SAFE_INTEGER +tags: + - ECMAScript 2015 + - JavaScript + - Number + - Property +translation_of: Web/JavaScript/Reference/Global_Objects/Number/MIN_SAFE_INTEGER +--- +<div>{{JSRef}}</div> + +<p><strong><code>Number.MIN_SAFE_INTEGER</code></strong> 상수는 JavaScript에서 안전한 최소 정수값을 나타냅니다. (<code>-(2<sup>53</sup> - 1)</code>)</p> + +<div>{{EmbedInteractiveExample("pages/js/number-min-safe-integer.html")}}</div> + + + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="설명">설명</h2> + +<p><code>MIN_SAFE_INTEGER</code> 상수는 <code>-9007199254740991</code>(-9,007,199,254,740,991 또는 약 -9000조)의 값을 갖고 있습니다. 이 값의 이유는 JavaScript가 <a href="http://en.wikipedia.org/wiki/IEEE_floating_point">IEEE 754</a>에 기술된 <a href="http://en.wikipedia.org/wiki/Double_precision_floating-point_format">배정밀도 부동소숫점 형식 숫자체계</a>를 사용하기 때문으로, 이로 인해 <code>-(2<sup>53</sup> - 1)</code>과 <code>2<sup>53</sup> - 1</code> 사이의 수만 안전하게 표현할 수 있습니다.</p> + +<p><code>MIN_SAFE_INTEGER</code>는 {{jsxref("Number")}}의 정적 속성이기 때문에, 직접 생성한 {{jsxref("Number")}} 객체의 속성이 아니라 <code>Number.MIN_SAFE_INTEGER</code> 형식으로 사용해야 합니다.</p> + +<h2 id="설명_2">설명</h2> + +<pre class="brush: js">Number.MIN_SAFE_INTEGER // -9007199254740991 +-(Math.pow(2, 53) - 1) // -9007199254740991 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-number.min_safe_integer', 'Number.MIN_SAFE_INTEGER')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.min_safe_integer', 'Number.MIN_SAFE_INTEGER')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Number.MIN_SAFE_INTEGER")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Number.MAX_SAFE_INTEGER")}}</li> + <li>{{jsxref("Number.isSafeInteger()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/number/min_value/index.html b/files/ko/web/javascript/reference/global_objects/number/min_value/index.html new file mode 100644 index 0000000000..66b4985942 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/min_value/index.html @@ -0,0 +1,84 @@ +--- +title: Number.MIN_VALUE +slug: Web/JavaScript/Reference/Global_Objects/Number/MIN_VALUE +tags: + - JavaScript + - Number + - Property + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Number/MIN_VALUE +--- +<div>{{JSRef}}</div> + +<p><strong><code>Number.MIN_VALUE</code></strong> 속성은 JavaScript가 표현할 수 있는 제일 작은 양의 숫자 값을 나타냅니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/number-min-value.html")}}</div> + + + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="설명">설명</h2> + +<p><code>MIN_VALUE</code> 속성은 JavaScript에서 표현할 수 있는, 0에 가장 가깝지만 음수는 아닌 수입니다.</p> + +<p><code>MIN_VALUE</code>의 값은 약 <code>5e-324</code>입니다. <code>MIN_VALUE</code>보다 작은 값("언더플로우 값")은 0으로 변환됩니다.</p> + +<p><code>MIN_VALUE</code>는 {{jsxref("Number")}}의 정적 속성이기 때문에, 직접 생성한 {{jsxref("Number")}} 객체의 속성이 아니라 <code>Number.MIN_VALUE</code> 형식으로 사용해야 합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="MIN_VALUE_사용하기"><code>MIN_VALUE</code> 사용하기</h3> + +<p>다음 코드는 숫자를 두 개의 수를 받아 나누기 연산을 합니다. 만약 결과가 <code>MIN_VALUE</code> 보다 크거나 같으면 <code>func1</code> 함수를 호출하고, 그렇지 않으면 <code>func2</code> 함수를 호출합니다.</p> + +<pre class="brush: js">if (num1 / num2 >= Number.MIN_VALUE) { + func1(); +} else { + func2(); +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7.3.3', 'Number.MIN_VALUE')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.min_value', 'Number.MIN_VALUE')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.min_value', 'Number.MIN_VALUE')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Number.MIN_VALUE")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Number.MAX_VALUE")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/number/nan/index.html b/files/ko/web/javascript/reference/global_objects/number/nan/index.html new file mode 100644 index 0000000000..348820c376 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/nan/index.html @@ -0,0 +1,62 @@ +--- +title: Number.NaN +slug: Web/JavaScript/Reference/Global_Objects/Number/NaN +tags: + - JavaScript + - Number + - Property +translation_of: Web/JavaScript/Reference/Global_Objects/Number/NaN +--- +<div>{{JSRef}}</div> + +<p><strong><code>Number.NaN</code></strong> 속성은 Not-A-Number(숫자가 아님)를 나타냅니다. {{jsxref("NaN")}}과 같습니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/number-nan.html")}}<br> + 정적 속성이므로 접근하기 위해 {{jsxref("Number")}} 객체를 생성할 필요는 없습니다. (<code>Number.NaN</code> 사용)</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>초기 정의. JavaScript 1.1에서 구현됨.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7.3.4', 'Number.NaN')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.nan', 'Number.NaN')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.nan', 'Number.NaN')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.Number.NaN")}}</div> + +<div id="compat-desktop"> </div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>전역 {{jsxref("NaN")}} 객체.</li> + <li>본 속성이 속한 {{jsxref("Number")}} 객체.</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/number/negative_infinity/index.html b/files/ko/web/javascript/reference/global_objects/number/negative_infinity/index.html new file mode 100644 index 0000000000..d6567e687e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/negative_infinity/index.html @@ -0,0 +1,82 @@ +--- +title: Number.NEGATIVE_INFINITY +slug: Web/JavaScript/Reference/Global_Objects/Number/NEGATIVE_INFINITY +tags: + - JavaScript + - Number + - Property + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Number/NEGATIVE_INFINITY +--- +<div>{{JSRef}}</div> + +<p><strong><code>Number.NEGATIVE_INFINITY</code></strong> 속성은 음의 무한대를 나타냅니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/number-negative-infinity.html")}}</div> + + + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="설명">설명</h2> + +<p><code>Number.NEGATIVE_INFINITY</code>의 값은 전역 객체 {{jsxref("Infinity")}} 속성의 부호를 바꾼 값과 동일합니다.</p> + +<p><code>NEGATIVE_INFINITY</code>는 수학에서의 무한대와 약간 다릅니다.</p> + +<ul> + <li>{{jsxref("Number.POSITIVE_INFINITY", "POSITIVE_INFINITY")}}를 포함한 아무 양의 수와 <code>NEGATIVE_INFINITY</code>를 곱한 결과는 <code>NEGATIVE_INFINITY</code>입니다.</li> + <li><code>NEGATIVE_INFINITY</code>를 포함한 아무 음의 수와 <code>NEGATIVE_INFINITY</code>를 곱한 결과는 {{jsxref("Number.POSITIVE_INFINITY", "POSITIVE_INFINITY")}}입니다.</li> + <li>아무 양의 수를 <code>NEGATIVE_INFINITY</code>로 나눈 결과는 음의 부호를 가진 0입니다.</li> + <li>아무 음의 수를 <code>NEGATIVE_INFINITY</code>로 나눈 결과는 0입니다.</li> + <li>0을 <code>NEGATIVE_INFINITY</code>로 나눈 결과는 {{jsxref("NaN")}}입니다.</li> + <li>{{jsxref("NaN")}}에 <code>NEGATIVE_INFINITY</code>를 곱한 결과는 {{jsxref("NaN")}}입니다.</li> + <li><code>NEGATIVE_INFINITY</code>를, <code>NEGATIVE_INFINITY</code>를 제외한 아무 음의 수로 나눈 결과는 {{jsxref("Number.POSITIVE_INFINITY", "POSITIVE_INFINITY")}}입니다.</li> + <li><code>NEGATIVE_INFINITY</code>를, {{jsxref("Number.POSITIVE_INFINITY", "POSITIVE_INFINITY")}}를 제외한 아무 양의 수로 나눈 결과는 <code>NEGATIVE_INFINITY</code>입니다.</li> + <li><code>NEGATIVE_INFINITY</code>를 <code>NEGATIVE_INFINITY</code> 또는 {{jsxref("Number.POSITIVE_INFINITY", "POSITIVE_INFINITY")}}로 나눈 결과는 {{jsxref("NaN")}}입니다.</li> +</ul> + +<p><code>Number.NEGATIVE_INFINITY</code>를 사용해 성공 시 유한수를 반환하는 식의 결과를 판별할 수 있습니다. 그러나 이런 경우 {{jsxref("isFinite", "isFinite()")}}를 사용하는 편이 더 적합합니다.</p> + +<p><code>NEGATIVE_INFINITY</code>는 {{jsxref("Number")}}의 정적 속성이기 때문에, 직접 생성한 {{jsxref("Number")}} 객체의 속성이 아니라 <code>Number.NEGATIVE_INFINITY</code>의 형식으로 사용해야 합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="NEGATIVE_INFINITY_사용하기"><code>NEGATIVE_INFINITY</code> 사용하기</h3> + +<p>다음 코드에서 <code>smallNumber</code>는 JavaScript의 최솟값보다 작은 값을 할당받습니다. {{jsxref("Statements/if...else", "if")}} 문이 실행되면, <code>smallNumber</code>의 값이 <code>-Infinity</code>이므로 <code>smallNumber</code>는 계산에 좀 더 적합한 값을 다시 할당합니다.</p> + +<pre class="brush: js notranslate">var smallNumber = (-Number.MAX_VALUE) * 2; + +if (smallNumber === Number.NEGATIVE_INFINITY) { + smallNumber = returnFinite(); +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.negative_infinity', 'Number.NEGATIVE_INFINITY')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Number.NEGATIVE_INFINITY")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Number.POSITIVE_INFINITY")}}</li> + <li>{{jsxref("Number.isFinite()")}}</li> + <li>{{jsxref("Infinity")}}</li> + <li>{{jsxref("isFinite", "isFinite()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/number/parsefloat/index.html b/files/ko/web/javascript/reference/global_objects/number/parsefloat/index.html new file mode 100644 index 0000000000..763c28a42d --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/parsefloat/index.html @@ -0,0 +1,79 @@ +--- +title: Number.parseFloat() +slug: Web/JavaScript/Reference/Global_Objects/Number/parseFloat +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Number +translation_of: Web/JavaScript/Reference/Global_Objects/Number/parseFloat +--- +<div>{{JSRef}}</div> + +<p><strong><code>Number.parseFloat()</code></strong> 메서드는 문자열을 분석해 부동소수점 실수로 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/number-parsefloat.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">Number.parseFloat(<var>string</var>)</pre> + +<h3 id="매개변수">매개변수</h3> + +<p>{{page("ko/docs/Web/JavaScript/Reference/Global_Objects/parseFloat", "매개변수")}}</p> + +<h3 id="반환_값">반환 값</h3> + +<p>{{page("ko/docs/Web/JavaScript/Reference/Global_Objects/parseFloat", "반환 값")}}</p> + +<h2 id="설명">설명</h2> + +<p><code>Number.parseFloat()</code> 메서드는 전역 {{jsxref("parseFloat", "parseFloat()")}} 함수와 같은 기능을 가지고 있습니다.</p> + +<pre>Number.parseFloat === parseFloat; // true</pre> + +<p><code>Number.parseFloat()는</code> ECMAScript 2015에서 전역 범위의 모듈화를 위해 추가됐습니다. 상세한 정보와 예제는 {{jsxref("parseFloat", "parseFloat()")}}를 참고하세요.</p> + +<h2 id="폴리필">폴리필</h2> + +<pre class="brush: js">if (Number.parseFloat === undefined) { + Number.parseFloat = parseFloat; +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-number.parsefloat', 'Number.parseFloat')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.parsefloat', 'Number.parseFloat')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<div>{{Compat("javascript.builtins.Number.parseFloat")}}</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>메서드가 속한 {{jsxref("Number")}} 객체.</li> + <li>전역 {{jsxref("parseFloat", "parseFloat()")}} 메서드.</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/number/parseint/index.html b/files/ko/web/javascript/reference/global_objects/number/parseint/index.html new file mode 100644 index 0000000000..0b0a052016 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/parseint/index.html @@ -0,0 +1,78 @@ +--- +title: Number.parseInt() +slug: Web/JavaScript/Reference/Global_Objects/Number/parseInt +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Number + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Number/parseInt +--- +<div>{{JSRef}}</div> + +<p><strong><code>Number.parseInt()</code></strong> 메서드는 문자열을 분석하고 특정 진수를 사용한 정수로 변환해 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/number-parseint.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">Number.parseInt(<var>string,</var>[ <var>radix</var>]) +</pre> + +<h3 id="매개변수">매개변수</h3> + +<div>{{page("ko/docs/Web/JavaScript/Reference/Global_Objects/parseInt", "매개변수")}}</div> + +<h3 id="반환_값">반환 값</h3> + +<p>{{page("ko/docs/Web/JavaScript/Reference/Global_Objects/parseInt", "반환 값")}}</p> + +<h2 id="설명">설명</h2> + +<p><code>Number.parseInt()</code> 메서드는 전역 {{jsxref("parseInt", "parseInt()")}} 함수와 같은 기능을 가지고 있습니다.</p> + +<pre class="brush: js">Number.parseInt === parseInt; // true</pre> + +<p><code>Number.parseInt()</code>는 ECMAScript 2015에서 전역 범위의 모듈화를 위해 추가됐습니다. 상세한 정보와 예제는 {{jsxref("parseInt", "parseInt()")}}를 참고하세요.</p> + +<h2 id="폴리필">폴리필</h2> + +<pre class="brush: js">if (Number.parseInt === undefined) { + Number.parseInt = window.parseInt; +}</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.parseint', 'Number.parseInt')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.parseint', 'Number.parseInt')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.Number.parseInt")}}</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>메서드가 속한 {{jsxref("Number")}} 객체.</li> + <li>전역 {{jsxref("parseInt", "parseInt()")}} 메서드.</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/number/positive_infinity/index.html b/files/ko/web/javascript/reference/global_objects/number/positive_infinity/index.html new file mode 100644 index 0000000000..b1012fcdbf --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/positive_infinity/index.html @@ -0,0 +1,82 @@ +--- +title: Number.POSITIVE_INFINITY +slug: Web/JavaScript/Reference/Global_Objects/Number/POSITIVE_INFINITY +tags: + - JavaScript + - Number + - Property + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Number/POSITIVE_INFINITY +--- +<div>{{JSRef}}</div> + +<p><strong><code>Number.POSITIVE_INFINITY</code></strong> 속성은 양의 무한대를 나타냅니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/number-positive-infinity.html")}}</div> + + + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="설명">설명</h2> + +<p><code>Number.POSITIVE_INFINITY</code>의 값은 전역 객체 {{jsxref("Infinity")}} 속성의 값과 동일합니다.</p> + +<p><code>POSITIVE_INFINITY</code>는 수학에서의 무한대와 약간 다릅니다.</p> + +<ul> + <li><code>POSITIVIE_INFINITY</code>를 포함한 아무 양의 수와 <code>POSITIVE_INFINITY</code>를 곱한 결과는 <code>POSITIVE_INFINITY</code>입니다.</li> + <li>{{jsxref("Number.NEGATIVE_INFINITY", "NEGATIVE_INFINITY")}}를 포함한 아무 음의 수와 <code>POSITIVE_INFINITY</code>를 곱한 결과는 {{jsxref("Number.NEGATIVE_INFINITY", "NEGATIVE_INFINITY")}}입니다.</li> + <li>아무 양의 수를 <code>POSITIVE_INFINITY</code>로 나눈 결과는 0입니다.</li> + <li>아무 음의 수를 <code>POSITIVE_INFINITY</code>로 나눈 결과는 음의 부호를 가진 0입니다.</li> + <li>0을 <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">POSITIVE_INFINITY</span></font>로 나눈 결과는 {{jsxref("NaN")}}입니다.</li> + <li>{{jsxref("NaN")}}에 <code>POSITIVE_INFINITY</code>를 곱한 결과는 {{jsxref("NaN")}}입니다.</li> + <li><code>POSITIVE_INFINITY</code>를, {{jsxref("Number.NEGATIVE_INFINITY", "NEGATIVE_INFINITY")}}를 제외한 아무 음의 수로 나눈 결과는 {{jsxref("Number.NEGATIVE_INFINITY", "NEGATIVE_INFINITY")}}입니다.</li> + <li><font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">POSITIVE_INFINITY<code>를</code></span></font>, <code>POSITIVE_INFINITY</code>를 제외한 아무 양의 수로 나눈 결과는 <code>NEGATIVE_INFINITY</code>입니다.</li> + <li><code>POSITIVE_INFINITY</code>를 {{jsxref("Number.NEGATIVE_INFINITY", "NEGATIVE_INFINITY")}} 또는 <code>POSITIVE_INFINITY</code>로 나눈 결과는 {{jsxref("NaN")}}입니다.</li> +</ul> + +<p><code>Number.POSITIVE_INFINITY</code>를 사용해 성공 시 유한수를 반환하는 식의 결과를 판별할 수 있습니다. 그러나 이런 경우 {{jsxref("isFinite", "isFinite()")}}를 사용하는 편이 더 적합합니다.</p> + +<p><code>POSITIVE_INFINITY</code>는 {{jsxref("Number")}}의 정적 속성이기 때문에, 직접 생성한 {{jsxref("Number")}} 객체의 속성이 아니라 <code>Number.POSITIVE_INFINITY</code>의 형식으로 사용해야 합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="POSITIVE_INFINITY_사용하기"><code>POSITIVE_INFINITY</code> 사용하기</h3> + +<p>다음 코드에서 <code>smallNumber</code>는 JavaScript의 최댓값보다 큰 값을 할당받습니다. {{jsxref("Statements/if...else", "if")}} 문이 실행되면, <code>bigNumber</code>의 값이 <code>Infinity</code>이므로 <code>bigNumber</code>는 계산에 좀 더 적합한 유한값을 다시 할당합니다.</p> + +<pre class="brush: js notranslate">var bigNumber = (Number.MAX_VALUE) * 2; + +if (bigNumber === Number.POSITIVE_INFINITY) { + bigNumber = returnFinite(); +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.positive_infinity', 'Number.POSITIVE_INFINITY')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Number.POSITIVE_INFINITY")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Number.NEGATIVE_INFINITY")}}</li> + <li>{{jsxref("Number.isFinite()")}}</li> + <li>{{jsxref("Infinity")}}</li> + <li>{{jsxref("isFinite", "isFinite()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/number/prototype/index.html b/files/ko/web/javascript/reference/global_objects/number/prototype/index.html new file mode 100644 index 0000000000..e9b3f20362 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/prototype/index.html @@ -0,0 +1,90 @@ +--- +title: Number.prototype +slug: Web/JavaScript/Reference/Global_Objects/Number/prototype +tags: + - JavaScript + - Number + - Property + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Number +--- +<div>{{JSRef}}</div> + +<p><strong><code>Number.prototype</code></strong> 속성은 {{jsxref("Number")}} 생성자의 프로토타입을 나타냅니다.</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="설명">설명</h2> + +<p>모든 {{jsxref("Number")}} 인스턴스는 <code>Number.prototype</code>을 상속합니다. {{jsxref("Number")}} 생성자의 프로토타입 객체는 모든 {{jsxref( "Number")}} 인스턴스에 영향을 미치도록 수정할 수 있습니다.</p> + +<h2 id="속성">속성</h2> + +<dl> + <dt><code>Number.prototype.constructor</code></dt> + <dd>이 객체의 인스턴스를 생성한 함수를 반환합니다. 기본적으로 {{jsxref("Number")}} 객체 입니다.</dd> +</dl> + +<h2 id="메서드">메서드</h2> + +<dl> + <dt>{{jsxref("Number.prototype.toExponential()")}}</dt> + <dd>숫자의 지수표기법 표현을 문자열로 반환합니다.</dd> + <dt>{{jsxref("Number.prototype.toFixed()")}}</dt> + <dd>숫자의 고정소수점 표현을 문자열로 반환합니다.</dd> + <dt>{{jsxref("Number.prototype.toLocaleString()")}}</dt> + <dd>숫자의 표현을 특정 언어에 맞춘 형식의 문자열로 반환합니다. {{jsxref("Object.prototype.toLocaleString()")}} 메서드를 오버라이드 합니다.</dd> + <dt>{{jsxref("Number.prototype.toPrecision()")}}</dt> + <dd>지정한 정밀도로 숫자를 나타내는 문자열을 반환합니다. 고정소수점 혹은 지수표기법으로 표현합니다.</dd> + <dt>{{jsxref("Number.prototype.toSource()")}} {{non-standard_inline}}</dt> + <dd>지정한 {{jsxref("Number")}} 객체를 나타내는 객체 리터럴을 반환합니다. 이 값을 사용하여 새 객체를 만들 수 있습니다. {{jsxref("Object.prototype.toSource()")}} 메서드를 오버라이드 합니다.</dd> + <dt>{{jsxref("Number.prototype.toString()")}}</dt> + <dd>지정된 기수(기본 10진수)로 지정된 객체를 문자열로 반환합니다. {{jsxref("Object.prototype.toString()")}} 메서드를 오버라이드 합니다.</dd> + <dt>{{jsxref("Number.prototype.valueOf()")}}</dt> + <dd>지정한 객체의 기본 자료형(primitive) 값을 반환합니다. {{jsxref("Object.prototype.valueOf()")}} 메서드를 오버라이드 합니다.</dd> +</dl> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7.4', 'Number')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-properties-of-the-number-prototype-object', 'Number')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-properties-of-the-number-prototype-object', 'Number')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Number.prototype")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Number")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/number/toexponential/index.html b/files/ko/web/javascript/reference/global_objects/number/toexponential/index.html new file mode 100644 index 0000000000..cb24e88364 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/toexponential/index.html @@ -0,0 +1,108 @@ +--- +title: Number.prototype.toExponential() +slug: Web/JavaScript/Reference/Global_Objects/Number/toExponential +tags: + - JavaScript + - Method + - Number + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Number/toExponential +--- +<div>{{JSRef}}</div> + +<p><strong><code>toExponential()</code></strong> 메서드는 숫자를 지수 표기법으로 표기해 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/number-toexponential.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>numObj</var>.toExponential([<var>fractionDigits</var>])</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>fractionDigits</code> {{optional_inline}}</dt> + <dd>소수점 이하로 표현할 자릿수입니다. 기본값은 주어진 값을 나타내는데 필요한 자릿수입니다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 {{jsxref("Number")}} 값을 숫자 한자리와 소수점, 소수점 이하 <code>fractionDigits</code> 자릿수만큼 반올림하여 지수 표기법으로 나타낸 문자열을 반환합니다.</p> + +<h3 id="예외">예외</h3> + +<dl> + <dt>{{jsxref("RangeError")}}</dt> + <dd><code>fractionDigits</code>가 너무 작거나 너무 크면 {{jsxref("RangeError")}} 에러가 발생합니다. <code>fractionDigits</code>가 0에서 20 사이의 값이면 {{jsxref("RangeError")}} 에러는 발생하지 않습니다. 구현에 따라 더 크거나 작은 값도 사용 할 수 있습니다.</dd> + <dt>{{jsxref("TypeError")}}</dt> + <dd>{{jsxref("Number")}}가 아닌 객체가 이 메서드를 실행시키면 {{jsxref("RangeError")}} 에러가 발생합니다.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p><code>fractionDigits</code> 매개변수를 생략하면, 기본적으로 주어진 값을 특정하기 위해 필요한 자릿수만큼이 소수점 이하 자릿수가 됩니다.</p> + +<p>지수나 소수점이 없는 숫자 리터럴에 <code>toExponential()</code> 메서드를 사용하려면, 점 앞에 공백을 두어 점이 소수점으로 해석되는 것을 막도록 합니다.</p> + +<p>주어진 값의 자릿수가 <code>fractionDigits</code> 매개변수보다 크다면, 주어진 값은 <code>fractionDigits</code>에 가까운 자릿수로 반올림되어 표현됩니다. {{jsxref("Number.prototype.toFixed", "toFixed()")}} 메서드의 반올림에 관한 설명이 <code>toExponential()</code> 메서드에도 마찬가지로 적용됩니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="toExponential_사용하기"><code>toExponential</code> 사용하기</h3> + +<pre class="brush: js">var numObj = 77.1234; + +console.log(numObj.toExponential()); // logs 7.71234e+1 +console.log(numObj.toExponential(4)); // logs 7.7123e+1 +console.log(numObj.toExponential(2)); // logs 7.71e+1 +console.log(77.1234.toExponential()); // logs 7.71234e+1 +console.log(77 .toExponential()); // logs 7.7e+1 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>초기 정의. JavaScript 1.5에서 구현됨.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7.4.6', 'Number.prototype.toExponential')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.prototype.toexponential', 'Number.prototype.toExponential')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.prototype.toexponential', 'Number.prototype.toExponential')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Number.toExponential")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Number.prototype.toFixed()")}}</li> + <li>{{jsxref("Number.prototype.toPrecision()")}}</li> + <li>{{jsxref("Number.prototype.toString()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/number/tofixed/index.html b/files/ko/web/javascript/reference/global_objects/number/tofixed/index.html new file mode 100644 index 0000000000..cf383f2265 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/tofixed/index.html @@ -0,0 +1,109 @@ +--- +title: Number.prototype.toFixed() +slug: Web/JavaScript/Reference/Global_Objects/Number/toFixed +tags: + - JavaScript + - Method + - Number + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Number/toFixed +--- +<div>{{JSRef}}</div> + +<p><code><strong>toFixed()</strong></code> 메서드는 숫자를 고정 소수점 표기법으로 표기해 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/number-tofixed.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>numObj</var>.toFixed([<var>digits</var>])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>digits</code> {{optional_inline}}</dt> + <dd>소수점 뒤에 나타날 자릿수. 0 이상 20 이하의 값을 사용할 수 있으며, 구현체에 따라 더 넓은 범위의 값을 지원할 수도 있습니다. 값을 지정하지 않으면 0을 사용합니다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>고정 소수점 표기법을 사용하여 나타낸 수.</p> + +<h3 id="예외">예외</h3> + +<dl> + <dt>{{jsxref("RangeError")}}</dt> + <dd><code>digits</code>가 너무 작거나 너무 클 때. 값이 0과 100사이의 값이라면 {{jsxref("RangeError")}}를 유발하지 않습니다. 구현체에 따라 더 크거나 작은 값을 지원할 수 있습니다.</dd> + <dt>{{jsxref("TypeError")}}</dt> + <dd>{{jsxref("Number")}}가 아닌 객체에서 호출한 경우.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p><code>toFixed()</code>는 {{jsxref("Number")}} 객체를 주어진 <code>digits</code> 만큼의 소수점 이하 자리수를 정확하게 갖는 문자열 표현으로 반환합니다. 소수점 이하가 길면 숫자를 반올림하고, 짧아서 부족할 경우 뒤를 0으로 채울 수 있습니다. 메서드를 호출한 숫자의 크기가 1e+21보다 크다면 {{jsxref("Number.prototype.toString()")}}을 호출하여 받은 지수 표기법 결과를 대신 반환합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="toFixed()_사용하기"><code>toFixed()</code> 사용하기</h3> + +<pre class="brush: js">var numObj = 12345.6789; + +numObj.toFixed(); // Returns '12346': 반올림하며, 소수 부분을 남기지 않습니다. +numObj.toFixed(1); // Returns '12345.7': 반올림합니다. +numObj.toFixed(6); // Returns '12345.678900': 빈 공간을 0으로 채웁니다. +(1.23e+20).toFixed(2); // Returns '123000000000000000000.00' +(1.23e-10).toFixed(2); // Returns '0.00' +2.34.toFixed(1); // Returns '2.3' +2.35.toFixed(1); // Returns '2.4'. 이 경우에는 올림을 합니다. +-2.34.toFixed(1); // Returns -2.3 (연산자의 적용이 우선이기 때문에, 음수의 경우 문자열로 반환하지 않습니다...) +(-2.34).toFixed(1); // Returns '-2.3' (...괄호를 사용할 경우 문자열을 반환합니다.) +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.5.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7.4.5', 'Number.prototype.toFixed')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.prototype.tofixed', 'Number.prototype.toFixed')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.prototype.tofixed', 'Number.prototype.toFixed')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Number.toFixed")}}</p> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("Number.prototype.toExponential()")}}</li> + <li>{{jsxref("Number.prototype.toPrecision()")}}</li> + <li>{{jsxref("Number.prototype.toString()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/number/toprecision/index.html b/files/ko/web/javascript/reference/global_objects/number/toprecision/index.html new file mode 100644 index 0000000000..83cf3017e3 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/toprecision/index.html @@ -0,0 +1,110 @@ +--- +title: Number.prototype.toPrecision() +slug: Web/JavaScript/Reference/Global_Objects/Number/toPrecision +tags: + - JavaScript + - Method + - Number + - Prototype + - toPrecision +translation_of: Web/JavaScript/Reference/Global_Objects/Number/toPrecision +--- +<div>{{JSRef}}</div> + +<p><strong><code>toPrecision()</code></strong> 메서드는 {{jsxref("Number")}} 객체를 지정된 정밀도로 나타내는 문자열을 반환한다.</p> + +<div>{{EmbedInteractiveExample("pages/js/number-toprecision.html")}}</div> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox"><var>numObj</var>.toPrecision([<var>precision</var>])</pre> + +<h3 id="파라미터">파라미터</h3> + +<dl> + <dt><code>precision</code></dt> + <dd>선택적 파라미터. 유효 자릿수를 지정하는 정수.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>고정 소수점 또는 지수 표기법의 {{jsxref("Number")}} 객체를 정밀 유효 숫자로 반올림 한 문자열입니다. <code>toPrecision()</code>에도 적용되는 {{jsxref("Number.prototype.toFixed()")}} 메서드에 대한 설명에서 반올림에 대한 설명을 참조하세요.</p> + +<p><code>precision(정밀도)</code> 인수가 생략되면 {{jsxref("Number.prototype.toString()")}}처럼 작동합니다. <code>precision(정밀도)</code> 인수가 정수가 아닌 값이면 가장 가까운 정수로 반올림됩니다.</p> + +<p> </p> + +<h3 id="예외">예외</h3> + +<dl> + <dt>{{jsxref("Global_Objects/RangeError", "RangeError")}}</dt> + <dd><code>precision(정밀도)</code>가 1에서 100 사이가 아닌 경우 {{jsxref("RangeError")}}가 발생합니다. 구현은 더 큰 값과 더 작은 값을 지원할 수 있습니다. ECMA-262는 최대 21 자리의 정밀도 만을 요구합니다.</dd> +</dl> + +<h2 id="예제">예제</h2> + +<h3 id="toPrecision_사용"><code>toPrecision</code> 사용</h3> + +<pre class="brush: js">var numObj = 5.123456; + +console.log(numObj.toPrecision()); // logs '5.123456' +console.log(numObj.toPrecision(5)); // logs '5.1235' +console.log(numObj.toPrecision(2)); // logs '5.1' +console.log(numObj.toPrecision(1)); // logs '5' + +numObj = 0.000123 + +console.log(numObj.toPrecision()); // logs '0.000123' +console.log(numObj.toPrecision(5)); // logs '0.00012300' +console.log(numObj.toPrecision(2)); // logs '0.00012' +console.log(numObj.toPrecision(1)); // logs '0.0001' + +// 일부 상황에서는 지수 표기법이 반환 될 수 있습니다 +console.log((1234.5).toPrecision(2)); // logs '1.2e+3' +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.5.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7.4.7', 'Number.prototype.toPrecision')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.prototype.toprecision', 'Number.prototype.toPrecision')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.prototype.toprecision', 'Number.prototype.toPrecision')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Number.toPrecision")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Number.prototype.toFixed()")}}</li> + <li>{{jsxref("Number.prototype.toExponential()")}}</li> + <li>{{jsxref("Number.prototype.toString()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/number/tostring/index.html b/files/ko/web/javascript/reference/global_objects/number/tostring/index.html new file mode 100644 index 0000000000..2c1366ad5b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/tostring/index.html @@ -0,0 +1,112 @@ +--- +title: Number.prototype.toString() +slug: Web/JavaScript/Reference/Global_Objects/Number/toString +tags: + - JavaScript + - Method + - Number + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Number/toString +--- +<div>{{JSRef}}</div> + +<p><strong><code>toString()</code> </strong>메서드는 특정한 {{jsxref("Number")}} 객체를 나타내는 문자열을 반환합니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/number-tostring.html")}}</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>numObj</var>.toString([<var>radix</var>])</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>radix</code> {{optional_inline}}</dt> + <dd>수의 값을 나타내기 위해 사용되기 위한 기준을 정하는 2와 36사이의 정수. (진수를 나타내는 기수의 값.)</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>{{jsxref("Number")}} 객체를 명시하는 문자열.</p> + +<h3 id="예외">예외</h3> + +<dl> + <dt>{{jsxref("RangeError")}}</dt> + <dd>만약 <code>toString()</code>에<code> 2</code>와<code> 36</code>의 사잇 값이 아닌 <code>radix</code>가 주어지면, {{jsxref("RangeError")}} 에러가 발생합니다.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p>{{jsxref("Number")}} 객체는 {{jsxref("Object")}} 객체의 <code>toString() </code>메소드를 오버라이딩하며, {{jsxref("Object.prototype.toString()")}} 를 상속받지 않습니다. {{jsxref( "Number")}} 객체에서 <code>toString()</code> 메소드는 특정 진수로 객체를 표현한 문자열을 환원합니다.</p> + +<p><code>toString() </code>메소드는 메소드의 첫 번째 아규먼트를 파싱하여, 메소드는 특정 기수(radix)를 기준으로 한 진수 값의 문자열을 환원하기 위한 시도를 합니다. 진수를 나타내는 기수 값(radix) 이 10 이상의 값일 때는, 알파벳의 글자는 9보다 큰 수를 나타냅니다. 예를 들면, 16진수(base 16)는, 알파벳 f 까지 사용하여 표현됩니다.</p> + +<p>만약에 <code>radix</code>값 이 지정되지 않으면, 임의로 10진수로 가정하게 됩니다.</p> + +<p>또, <code>numObj</code>가 음수라면, - 부호는 유지됩니다. 이는 기수(radix) 값이 2일 경우에라도 적용됩니다. 리턴된 문자열은 - 부호가 앞에 있는 <code>numObj</code> 의 양의 2진수 표시이지, <code>numObj</code>의 두 개의 조합이 아니기 때문입니다.</p> + +<p><code>numObj</code> 가 정수가 아니면, 점(.) 부호는 소수 자리와 분리하기 위해 사용됩니다. </p> + +<h2 id="예제">예제</h2> + +<h3 id="toString_사용"><code>toString</code> 사용</h3> + +<pre class="brush: js">var count = 10; + +console.log(count.toString()); // displays '10' +console.log((17).toString()); // displays '17' +console.log((17.2).toString()); // displays '17.2' + +var x = 6; + +console.log(x.toString(2)); // displays '110' +console.log((254).toString(16)); // displays 'fe' + +console.log((-10).toString(2)); // displays '-1010' +console.log((-0xff).toString(2)); // displays '-11111111' +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>초기 정의. JavaScript 1.1에서 구현됨.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7.4.2', 'Number.prototype.tostring')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.prototype.tostring', 'Number.prototype.tostring')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.prototype.tostring', 'Number.prototype.tostring')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.Number.toString")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Number.prototype.toFixed()")}}</li> + <li>{{jsxref("Number.prototype.toExponential()")}}</li> + <li>{{jsxref("Number.prototype.toPrecision()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/number/valueof/index.html b/files/ko/web/javascript/reference/global_objects/number/valueof/index.html new file mode 100644 index 0000000000..344fa96ca2 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/valueof/index.html @@ -0,0 +1,86 @@ +--- +title: Number.prototype.valueOf() +slug: Web/JavaScript/Reference/Global_Objects/Number/valueOf +tags: + - JavaScript + - Method + - Number + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Number/valueOf +--- +<div>{{JSRef}}</div> + +<p><strong><code>valueOf()</code></strong> 메서드는 {{jsxref("Number")}} 객체가 감싼<sup>wrapped</sup> {{Glossary("primitive", "원시")}} 값을 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/number-valueof.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>numObj</var>.valueOf()</pre> + +<h3 id="반환_값">반환 값</h3> + +<p>{{jsxref("Number")}} 객체의 원시 값.</p> + +<h2 id="설명">설명</h2> + +<p><code>valueOf()</code> 메서드는 보통 JavaScript에 의해 내부적으로 호출되고, 웹 코드에서는 명시적으로 호출하지 않습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="valueOf_사용하기"><code>valueOf</code> 사용하기</h3> + +<pre class="brush: js">var numObj = new Number(10); +console.log(typeof numObj); // object + +var num = numObj.valueOf(); +console.log(num); // 10 +console.log(typeof num); // number +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7.4.4', 'Number.prototype.valueOf')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.prototype.valueof', 'Number.prototype.valueOf')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-number.prototype.valueof', 'Number.prototype.valueOf')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Number.valueOf")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Number.prototype.toSource()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/object/__definegetter__/index.html b/files/ko/web/javascript/reference/global_objects/object/__definegetter__/index.html new file mode 100644 index 0000000000..2ded710fda --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/__definegetter__/index.html @@ -0,0 +1,99 @@ +--- +title: Object.prototype.__defineGetter__() +slug: Web/JavaScript/Reference/Global_Objects/Object/__defineGetter__ +translation_of: Web/JavaScript/Reference/Global_Objects/Object/__defineGetter__ +--- +<div>{{JSRef}}</div> + +<div class="warning"> +<p>이 기능은 object initializer 문법 혹은 {{jsxref("Object.defineProperty()")}} API를 사용한 getter 정의가 표준화됨으로써 비표준화되었습니다.<br> + 이 기능은 이제까지의 ECMAScript 사양에서만 사용되고 있습니다.<br> + 보다 좋은 방법이 있으므로, 이 메소드는 사용하지 말아야합니다.</p> +</div> + +<p><code><strong>__defineGetter__</strong></code> 메소드는 오브젝트의 프로퍼티와 함수를 바인드합니다.<br> + 프로퍼티의 값이 조회될 때 바인드된 함수가 호출됩니다.</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox"><var>obj</var>.__defineGetter__(<var>prop</var>, <var>func</var>)</pre> + +<h3 id="인자">인자</h3> + +<dl> + <dt><code>prop</code></dt> + <dd>함수와 바인드된 프로퍼티의 이름을 나타내는 문자열</dd> + <dt><code>func</code></dt> + <dd>프로퍼티 값이 조회되었을 때 호출되는 함수</dd> +</dl> + +<h3 id="리턴_값">리턴 값</h3> + +<p>{{jsxref("undefined")}}.</p> + +<h2 id="Description">Description</h2> + +<p><code>__defineGetter__</code> 를 사용하여 기존 오브젝트의 {{jsxref("Operators/get", "getter", "", 1)}}를 사용할 수 있습니다.</p> + +<h2 id="Examples">Examples</h2> + +<pre class="brush: js">// Non-standard and deprecated way + +var o = {}; +o.__defineGetter__('gimmeFive', function() { return 5; }); +console.log(o.gimmeFive); // 5 + + +// Standard-compliant ways + +// Using the get operator +var o = { get gimmeFive() { return 5; } }; +console.log(o.gimmeFive); // 5 + +// Using Object.defineProperty +var o = {}; +Object.defineProperty(o, 'gimmeFive', { + get: function() { + return 5; + } +}); +console.log(o.gimmeFive); // 5 +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="spectable standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.prototype.__defineGetter__', 'Object.prototype.__defineGetter__()')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Included in the (normative) annex for additional ECMAScript legacy features for Web browsers (note that the specification codifies what is already in implementations).</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Object.defineGetter")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Object.prototype.__defineSetter__()")}}</li> + <li>{{jsxref("Operators/get", "get")}} operator</li> + <li>{{jsxref("Object.defineProperty()")}}</li> + <li>{{jsxref("Object.prototype.__lookupGetter__()")}}</li> + <li>{{jsxref("Object.prototype.__lookupSetter__()")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters">JS Guide: Defining Getters and Setters</a></li> + <li><a href="https://whereswalden.com/2010/04/16/more-spidermonkey-changes-ancient-esoteric-very-rarely-used-syntax-for-creating-getters-and-setters-is-being-removed/">[Blog Post] Deprecation of __defineGetter__ and __defineSetter__</a></li> + <li>{{bug(647423)}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/object/assign/index.html b/files/ko/web/javascript/reference/global_objects/object/assign/index.html new file mode 100644 index 0000000000..38b25d0bd8 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/assign/index.html @@ -0,0 +1,284 @@ +--- +title: Object.assign() +slug: Web/JavaScript/Reference/Global_Objects/Object/assign +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Object + - Reference + - polyfill + - 객체 + - 레퍼런스 + - 메소드 +translation_of: Web/JavaScript/Reference/Global_Objects/Object/assign +--- +<div>{{JSRef}}</div> + +<p><strong><code>Object.assign()</code> </strong>메소드는 열거할 수 있는 하나 이상의 출처 객체로부터 대상 객체로 속성을 복사할 때 사용합니다. 대상 객체를 반환합니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/object-assign.html")}}</p> + +<div class="hidden"> +<p>The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p> +</div> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">Object.assign(<var>target</var>, ...<var>sources</var>)</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>target</code></dt> + <dd>대상 객체.</dd> + <dt><code>sources</code></dt> + <dd>하나 이상의 출처 객체.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>대상 객체.</p> + +<h2 id="설명">설명</h2> + +<p>동일한 키가 존재할 경우 대상 객체의 속성은 출처 객체의 속성으로 덮어쓰여집니다. 후에 출처의 속성은 이전의 출처의 속성과 유사하게 덮어씁니다.</p> + +<p><code>Object.assign()</code> 메소드는 열거할 수 있는 출처 객체의 속성만 대상 객체로 복사합니다. 이 메소드는 출처 객체의 <code>[[Get]]</code>, 대상 객체의 <code>[[Set]]</code> 을 사용하여 getter 와 setter 를 호출합니다. 따라서 이는 속성을 단순히 복사하거나 새롭게 정의하는 것이 아니라 할당하는 것입니다. 병합 출처가 getter 를 포함하는 경우 프로토타입으로 새로운 속성을 병합하는 것이 적절하지 않을 수 있습니다. 프로토타입으로 속성의 열거성을 포함한 속성의 정의를 복사하려면 대신 {{jsxref("Object.getOwnPropertyDescriptor()")}} 와 {{jsxref("Object.defineProperty()")}} 를 사용해야합니다.</p> + +<p>{{jsxref("String")}} 과 {{jsxref("Symbol")}} 속성 모두가 복사됩니다.</p> + +<p>에러가 발생할 수 있는 상황에서는(예, 프로퍼티가 쓰기 불가인 경우), {{jsxref("TypeError")}} 가 발생하며, 에러가 발생하기 전에 속성이 추가되었다면 <code>target</code> 객체는 변경될 수 있습니다.</p> + +<p><code>Object.assign()</code> 메소드는 {{jsxref("null")}} 또는 {{jsxref("undefined")}} 출처 값에 대해서는 오류를 던지지 않음을 유의하세요.</p> + +<h2 id="예시">예시</h2> + +<h3 id="객체_클로닝">객체 클로닝</h3> + +<pre class="brush: js">const obj = { a: 1 }; +const copy = Object.assign({}, obj); +console.log(copy); // { a: 1 } +</pre> + +<h3 id="Deep_Clone" name="Deep_Clone">깊은 클로닝에 대한 주의사항</h3> + +<p>깊은 클로닝에 대해서, <code>Object.assign()</code> 은 속성의 값을 복사하기때문에 다른 대안을 사용해야합니다. 출처 값이 객체에 대한 참조인 경우, 참조 값만을 복사합니다.</p> + +<pre class="brush: js">function test() { + 'use strict'; + + let obj1 = { a: 0 , b: { c: 0}}; + let obj2 = Object.assign({}, obj1); + console.log(JSON.stringify(obj2)); // { a: 0, b: { c: 0}} + + obj1.a = 1; + console.log(JSON.stringify(obj1)); // { a: 1, b: { c: 0}} + console.log(JSON.stringify(obj2)); // { a: 0, b: { c: 0}} + + obj2.a = 2; + console.log(JSON.stringify(obj1)); // { a: 1, b: { c: 0}} + console.log(JSON.stringify(obj2)); // { a: 2, b: { c: 0}} + + obj2.b.c = 3; // obj1, obj2 모두에 영향을 줌 + console.log(JSON.stringify(obj1)); // { a: 1, b: { c: 3}} + console.log(JSON.stringify(obj2)); // { a: 2, b: { c: 3}} + + // 깊은 클론 + obj1 = { a: 0 , b: { c: 0}}; + let obj3 = JSON.parse(JSON.stringify(obj1)); + obj1.a = 4; + obj1.b.c = 4; + console.log(JSON.stringify(obj3)); // { a: 0, b: { c: 0}} +} + +test();</pre> + +<h3 id="객체_병합">객체 병합</h3> + +<pre class="brush: js">const o1 = { a: 1 }; +const o2 = { b: 2 }; +const o3 = { c: 3 }; + +const obj = Object.assign(o1, o2, o3); +console.log(obj); // { a: 1, b: 2, c: 3 } +console.log(o1); // { a: 1, b: 2, c: 3 }, 대상 객체 자체가 변경됨.</pre> + +<h3 id="같은_속성을_가진_객체_병합">같은 속성을 가진 객체 병합</h3> + +<pre class="brush: js">const o1 = { a: 1, b: 1, c: 1 }; +const o2 = { b: 2, c: 2 }; +const o3 = { c: 3 }; + +const obj = Object.assign({}, o1, o2, o3); +console.log(obj); // { a: 1, b: 2, c: 3 }</pre> + +<p>속성은 파라미터 순서에서 더 뒤에 위치한 동일한 속성을 가진 다른 객체에 의해 덮어쓰입니다.</p> + +<h3 id="심볼형_속성_복사">심볼형 속성 복사</h3> + +<pre class="brush: js">const o1 = { a: 1 }; +const o2 = { [Symbol('foo')]: 2 }; + +const obj = Object.assign({}, o1, o2); +console.log(obj); // { a : 1, [Symbol("foo")]: 2 } (cf. bug 1207182 on Firefox) +Object.getOwnPropertySymbols(obj); // [Symbol(foo)] +</pre> + +<h3 id="프로토타입_체인의_속성과_열거_불가형_속성은_복사_불가">프로토타입 체인의 속성과 열거 불가형 속성은 복사 불가</h3> + +<pre class="brush: js">const obj = Object.create({ foo: 1 }, { // foo 는 obj 의 프로토타입 체인상에 있음. + bar: { + value: 2 // bar 는 열거 불가능한 속성임. + }, + baz: { + value: 3, + enumerable: true // baz 는 자체 열거형 속성임. + } +}); + +const copy = Object.assign({}, obj); +console.log(copy); // { baz: 3 } +</pre> + +<h3 id="원시_자료형은_객체로_래핑">원시 자료형은 객체로 래핑</h3> + +<pre class="brush: js">var v1 = 'abc'; +var v2 = true; +var v3 = 10; +var v4 = Symbol('foo'); + +var obj = Object.assign({}, v1, null, v2, undefined, v3, v4); +// 원시 자료형은 래핑되지만, null 과 undefined 는 무시됨. +// 스트링 래퍼만 자체 열거형 속성을 가짐을 유의. +console.log(obj); // { "0": "a", "1": "b", "2": "c" } +</pre> + +<h3 id="예외에_의해_진행중인_복사_작업_중단">예외에 의해 진행중인 복사 작업 중단</h3> + +<pre class="brush: js">var target = Object.defineProperty({}, 'foo', { + value: 1, + writable: false +}); // target.foo 는 읽기 전용 속성 + +Object.assign(target, { bar: 2 }, { foo2: 3, foo: 3, foo3: 3 }, { baz: 4 }); +// TypeError: "foo" is read-only +// target.foo 에 할당할 때 예외 발생 + +console.log(target.bar); // 2, 첫 번째 출처 객체는 성공적으로 복사되었음. +console.log(target.foo2); // 3, 두 번째 출처 객체의 첫 번째 프로퍼티도 성공적으로 복사되었음. +console.log(target.foo); // 1, 여기에서 예외가 발생. +console.log(target.foo3); // undefined, assign 메소드가 종료되었음, foo3 은 복사되지 않음. +console.log(target.baz); // undefined, 세 번째 출처도 복사되지 않음. +</pre> + +<h3 id="접근자_복사">접근자 복사</h3> + +<pre class="brush: js">var obj = { + foo: 1, + get bar() { + return 2; + } +}; + +var copy = Object.assign({}, obj); +console.log(copy); +// { foo: 1, bar: 2 }, copy.bar 의 값은 obj.bar 의 getter 의 반환 값임. + +// 모든 descriptors 를 복사하는 할당 함수 +function completeAssign(target, ...sources) { + sources.forEach(source => { + let descriptors = Object.keys(source).reduce((descriptors, key) => { + descriptors[key] = Object.getOwnPropertyDescriptor(source, key); + return descriptors; + }, {}); + // 기본적으로, Object.assign 는 열거형 Symbol 도 복사함. + Object.getOwnPropertySymbols(source).forEach(sym => { + let descriptor = Object.getOwnPropertyDescriptor(source, sym); + if (descriptor.enumerable) { + descriptors[sym] = descriptor; + } + }); + Object.defineProperties(target, descriptors); + }); + return target; +} + +var copy = completeAssign({}, obj); +console.log(copy); +// { foo:1, get bar() { return 2 } } +</pre> + +<h2 id="폴리필">폴리필</h2> + +<p>ES5 에는 심볼이 없기 때문에 다음 {{Glossary("Polyfill","폴리필")}} 은 심볼 속성을 지원하지 않습니다.</p> + +<pre class="brush: js">if (typeof Object.assign != 'function') { + // Must be writable: true, enumerable: false, configurable: true + Object.defineProperty(Object, "assign", { + value: function assign(target, varArgs) { // .length of function is 2 + 'use strict'; + if (target == null) { // TypeError if undefined or null + throw new TypeError('Cannot convert undefined or null to object'); + } + + var to = Object(target); + + for (var index = 1; index < arguments.length; index++) { + var nextSource = arguments[index]; + + if (nextSource != null) { // Skip over if undefined or null + for (var nextKey in nextSource) { + // Avoid bugs when hasOwnProperty is shadowed + if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) { + to[nextKey] = nextSource[nextKey]; + } + } + } + } + return to; + }, + writable: true, + configurable: true + }); +}</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">코멘트</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.assign', 'Object.assign')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-object.assign', 'Object.assign')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>초기 정의.</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div class="hidden"> +<p>The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> +</div> + +<p>{{Compat("javascript.builtins.Object.assign")}}</p> + +<div id="compat-mobile"> </div> + +<h2 id="함께_보기">함께 보기</h2> + +<ul> + <li>{{jsxref("Object.defineProperties()")}}</li> + <li><a href="/ko/docs/Web/JavaScript/Enumerability_and_ownership_of_properties">속성의 열거성과 소유권</a></li> + <li><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Spread_syntax#Spread_in_object_literals">객체 리터럴에서의 Spread</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/object/constructor/index.html b/files/ko/web/javascript/reference/global_objects/object/constructor/index.html new file mode 100644 index 0000000000..0162140d9c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/constructor/index.html @@ -0,0 +1,155 @@ +--- +title: Object.prototype.constructor +slug: Web/JavaScript/Reference/Global_Objects/Object/constructor +tags: + - JavaScript + - Object + - Property + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Object/constructor +--- +<div>{{JSRef}}</div> + +<p>인스턴스의 프로토타입을 만든 {{jsxref("Object")}} 함수의 참조를 반환합니다. 이 속성값은 함수 자체의 참조임을 주의하세요, 함수 이름을 포함하는 문자열이 아니라. 그 값은 <code>1</code>, <code>true</code> 및 <code>"test"</code>와 같은 원시(primitive) 값에 대해서만 읽기 전용입니다.</p> + +<h2 id="설명">설명</h2> + +<p>모든 객체는 자신의 <code>prototype</code>으로부터 <code>constructor</code> 속성을 상속합니다:</p> + +<pre>var o = {}; +o.constructor === Object; // true + +var o = new Object; +o.constructor === Object; // true + +var a = []; +a.constructor === Array; // true + +var a = new Array; +a.constructor === Array; // true + +var n = new Number(3); +n.constructor === Number; // true</pre> + +<h2 id="예제">예제</h2> + +<h3 id="객체의_생성자_표시하기">객체의 생성자 표시하기</h3> + +<p>다음 예는 프로토타입이 <code>Tree</code>인 그 형의 객체 <code>theTree</code>를 만듭니다. 그 다음 객체 <code>theTree</code>의 <code>constructor</code>를 표시합니다.</p> + +<pre class="brush: js">function Tree(name) { + this.name = name; +} + +var theTree = new Tree('Redwood'); +console.log('theTree.constructor is ' + theTree.constructor); +</pre> + +<p>이 예는 다음 출력을 표시합니다:</p> + +<pre class="brush: js">theTree.constructor is function Tree(name) { + this.name = name; +} +</pre> + +<h3 id="객체의_생성자_바꾸기">객체의 생성자 바꾸기</h3> + +<p>다음 예는 일반 객체의 constructor 값을 수정하는 법을 보입니다. <code>true</code>, <code>1</code> 및 <code>"test"</code>만이 원래 읽기 전용 생성자를 갖기에 영향을 받지 않습니다. 이 예는 객체의 <code>constructor</code> 속성에 의존하는 게 항상 안전하지는 않음을 보입니다.</p> + +<pre class="brush:js">function Type () {} + +var types = [ + new Array(), + [], + new Boolean(), + true, // 바뀌지 않음 + new Date(), + new Error(), + new Function(), + function () {}, + Math, + new Number(), + 1, // 바뀌지 않음 + new Object(), + {}, + new RegExp(), + /(?:)/, + new String(), + 'test' // 바뀌지 않음 +]; + +for (var i = 0; i < types.length; i++) { + types[i].constructor = Type; + types[i] = [types[i].constructor, types[i] instanceof Type, types[i].toString()]; +} + +console.log(types.join('\n')); +</pre> + +<p>이 예는 다음 출력을 표시합니다:</p> + +<pre class="brush: js">function Type() {},false, +function Type() {},false, +function Type() {},false,false +function Boolean() { + [native code] +},false,true +function Type() {},false,Mon Sep 01 2014 16:03:49 GMT+0600 +function Type() {},false,Error +function Type() {},false,function anonymous() { + +} +function Type() {},false,function () {} +function Type() {},false,[object Math] +function Type() {},false,0 +function Number() { + [native code] +},false,1 +function Type() {},false,[object Object] +function Type() {},false,[object Object] +function Type() {},false,/(?:)/ +function Type() {},false,/(?:)/ +function Type() {},false, +function String() { + [native code] +},false,test +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>초기 정의. JavaScript 1.1에서 구현됨.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.4.1', 'Object.prototype.constructor')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.prototype.constructor', 'Object.prototype.constructor')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.prototype.constructor', 'Object.prototype.constructor')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.Object.constructor")}}</div> + +<div id="compat-mobile"> </div> diff --git a/files/ko/web/javascript/reference/global_objects/object/create/index.html b/files/ko/web/javascript/reference/global_objects/object/create/index.html new file mode 100644 index 0000000000..87a672aace --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/create/index.html @@ -0,0 +1,271 @@ +--- +title: Object.create() +slug: Web/JavaScript/Reference/Global_Objects/Object/create +tags: + - ECMAScript5 + - JavaScript + - Method + - Object + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Object/create +--- +<div>{{JSRef}}</div> + +<p><code><strong>Object.create()</strong></code> 메서드는 지정된 프로토타입 객체 및 속성(property)을 갖는 새 객체를 만듭니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">Object.create(<var>proto</var>[, <var>propertiesObject</var>])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>proto</code></dt> + <dd>새로 만든 객체의 프로토타입이어야 할 객체.</dd> + <dt><code>propertiesObject</code></dt> + <dd>선택사항. 지정되고 {{jsxref("undefined")}}가 아니면, 자신의 속성(즉, 자체에 정의되어 그 프로토타입 체인에서 열거가능하지 <em>않은</em> 속성)이 열거가능한 객체는 해당 속성명으로 새로 만든 객체에 추가될 속성 설명자(descriptor)를 지정합니다. 이러한 속성은 {{jsxref("Object.defineProperties()")}}의 두 번째 인수에 해당합니다.</dd> +</dl> + +<h3 id="반환값">반환값</h3> + +<p>지정된 프로토타입 개체와 속성을 갖는 새로운 개체.</p> + +<h3 id="예외">예외</h3> + +<p><code>proto</code> 매개변수가 {{jsxref("null")}} 또는 객체가 아닌 경우 {{jsxref("TypeError")}} 예외가 발생(throw).</p> + +<h2 id="예">예</h2> + +<h3 id="Object.create()를_사용한_고전적인_상속방법"><code>Object.create()</code>를 사용한 고전적인 상속방법</h3> + +<p>아래는 고전적인 상속방법으로 사용된 <code>Object.create()</code> 사용 예입니다. 이는 단일 상속 용으로, JavaScript가 지원하는 전부입니다.</p> + +<pre class="brush: js">// Shape - 상위클래스 +function Shape() { + this.x = 0; + this.y = 0; +} + +// 상위클래스 메서드 +Shape.prototype.move = function(x, y) { + this.x += x; + this.y += y; + console.info('Shape moved.'); +}; + +// Rectangle - 하위클래스 +function Rectangle() { + Shape.call(this); // super 생성자 호출. +} + +// 하위클래스는 상위클래스를 확장 +Rectangle.prototype = Object.create(Shape.prototype); +Rectangle.prototype.constructor = Rectangle; + +var rect = new Rectangle(); + +console.log('Is rect an instance of Rectangle?', rect instanceof Rectangle); // true +console.log('Is rect an instance of Shape?', rect instanceof Shape); // true +rect.move(1, 1); // Outputs, 'Shape moved.' +</pre> + +<p>여러 객체에서 상속하고 싶은 경우엔 mixin이 사용가능합니다.</p> + +<pre class="brush: js">function MyClass() { + SuperClass.call(this); + OtherSuperClass.call(this); +} + +MyClass.prototype = Object.create(SuperClass.prototype); // 상속 +mixin(MyClass.prototype, OtherSuperClass.prototype); // mixin + +MyClass.prototype.myMethod = function() { + // 기능 수행 +}; +</pre> + +<p><code>mixin</code> 함수는 상위(super)클래스 프로토타입에서 하위(sub)클래스 프로토타입으로 함수를 복사하고, mixin 함수는 사용자에 의해 공급될 필요가 있습니다. mixin 같은 함수의 예는 <a href="https://api.jquery.com/jQuery.extend/">jQuery.extend()</a>입니다.</p> + +<h3 id="Object.create()와_함께_propertiesObject_인수_사용하기"><code>Object.create()<font face="Open Sans, Arial, sans-serif">와 함께 </font></code><code>propertiesObject</code> 인수 사용하기</h3> + +<pre class="brush: js">var o; + +// 프로토타입이 null인 객체 생성 +o = Object.create(null); + + +o = {}; +// 위는 아래와 같습니다: +o = Object.create(Object.prototype); + + +// 샘플 속성 두개를 갖는 객체를 만드는 예. +// (두 번째 매개변수는 키를 *속성 설명자*에 맵핑함을 주의하세요.) +o = Object.create(Object.prototype, { + // foo는 정규 '값 속성' + foo: { writable: true, configurable: true, value: 'hello' }, + // bar는 접근자(accessor, getter-및-setter) 속성 + bar: { + configurable: false, + get: function() { return 10; }, + set: function(value) { console.log('Setting `o.bar` to', value); } +/* ES5 접근자로 코드는 이렇게 할 수 있습니다 + get function() { return 10; }, + set function(value) { console.log('setting `o.bar` to', value); } */ + } +}); + + +function Constructor() {} +o = new Constructor(); +// 위는 아래와 같습니다: +o = Object.create(Constructor.prototype); +// 물론, 생성자 함수에 실제 초기화 코드가 있다면 +// Object.create()는 그것을 반영할 수 없습니다 + + +// 빈 새 객체가 프로토타입인 새 객체를 만들고 +// 값이 42인 단일 속성 'p' 추가. +o = Object.create({}, { p: { value: 42 } }); + +// 기본으로 writable, enumerable 또는 configurable 속성은 false: +o.p = 24; +o.p; +// 42 + +o.q = 12; +for (var prop in o) { + console.log(prop); +} +// 'q' + +delete o.p; +// false + +// ES3 속성을 지정하기 위해 +o2 = Object.create({}, { + p: { + value: 42, + writable: true, + enumerable: true, + configurable: true + } +}); +</pre> + +<h2 id="폴리필">폴리필</h2> + +<p>이 폴리필에서는 새 개체에 대한 프로토타입이 선택되었지만 두번째 인수가 없이 개체를 생성하는 사례를 보여줍니다.</p> + +<p><code>[[Prototype]]</code>에 <code>null</code> 을 설정하는 것이 실제 ES5 <code>Object.create</code>에서는 지원되지만, ECMAScript 5 보다 낮은 버전에서는 상속에 제한이 있기 때문에 이 폴리필에서는 지원할 수 없음에 주의하세요.</p> + +<pre class="brush: js">if (typeof Object.create != 'function') { + Object.create = (function(undefined) { + var Temp = function() {}; + return function (prototype, propertiesObject) { + if(prototype !== Object(prototype) && prototype !== null) { + throw TypeError('Argument must be an object, or null'); + } + Temp.prototype = prototype || {}; + if (propertiesObject !== undefined) { + Object.defineProperties(Temp.prototype, propertiesObject); + } + var result = new Temp(); + Temp.prototype = null; + // Object.create(null)인 경우 모방 + if(prototype === null) { + result.__proto__ = null; + } + return result; + }; + })(); +}</pre> + +<h2 id="스펙">스펙</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.5', 'Object.create')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>초기 정의. JavaScript 1.8.5에서 구현됨.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.create', 'Object.create')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.create', 'Object.create')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("5")}}</td> + <td>{{CompatGeckoDesktop("2")}}</td> + <td>{{CompatIE("9")}}</td> + <td>{{CompatOpera("11.60")}}</td> + <td>{{CompatSafari("5")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("2")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatOperaMobile("11.5")}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("Object.defineProperty()")}}</li> + <li>{{jsxref("Object.defineProperties()")}}</li> + <li>{{jsxref("Object.prototype.isPrototypeOf()")}}</li> + <li>John Resig의 <a href="http://ejohn.org/blog/objectgetprototypeof/">getPrototypeOf()</a> 포스트</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/object/defineproperties/index.html b/files/ko/web/javascript/reference/global_objects/object/defineproperties/index.html new file mode 100644 index 0000000000..a0949f78f2 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/defineproperties/index.html @@ -0,0 +1,191 @@ +--- +title: Object.defineProperties() +slug: Web/JavaScript/Reference/Global_Objects/Object/defineProperties +translation_of: Web/JavaScript/Reference/Global_Objects/Object/defineProperties +--- +<div>{{JSRef}}</div> + +<p><code><strong>Object.defineProperties()</strong></code> 메서드는 객체에 새로운 속성을 정의하거나 기존의 속성을 수정하고, 그 객체를 반환한다.</p> + +<div>{{EmbedInteractiveExample("pages/js/object-defineproperties.html")}}</div> + + + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox"><code>Object.defineProperties(<var>obj</var>, <var>props</var>)</code></pre> + +<h3 id="인자">인자</h3> + +<dl> + <dt><code><var>obj</var></code></dt> + <dd>속성을 정의하거나 수정할 객체.</dd> + <dt><code><var>props</var></code></dt> + <dd>정의하거나 수정할 속성의 이름을 키로, 그 속성을 서술하는 객체를 값으로 갖는 객체. <code>props</code>의 각 값은 데이터 서술자(data descriptor) 혹은 접근자 서술자(accessor descriptor) 중 하나여야 하며, 동시에 두 유형을 포함할 수 없다({{jsxref("Object.defineProperty()")}} 참조).</dd> + <dd>데이터 서술자와 접근자 서술자 모두 다음 키를 선택적으로 포함할 수 있다:</dd> + <dd> + <dl> + <dt><code>configurable</code></dt> + <dd><code>true</code>일 경우 이 속성 서술자의 형태를 변경하거나, 속성을 해당 객체에서 삭제할 수 있다.<br> + <strong>기본값은 <code>false</code>이다.</strong></dd> + <dt><code>enumerable</code></dt> + <dd><code>true</code>일 경우 해당 객체의 속성을 열거할 때 이 속성이 열거된다.<br> + <strong>기본값은 <code>false</code>이다.</strong></dd> + </dl> + + <p>데이터 서술자의 경우 다음 키를 추가로 포함할 수 있다:</p> + + <dl> + <dt><code>value</code></dt> + <dd>이 속성에 설정할 값. 올바른 자바스크립트 값(숫자, 객체, 함수 등)이면 무엇이든 설정할 수 있다.<br> + <strong>기본값은 {{jsxref("undefined")}}이다.</strong></dd> + <dt><code>writable</code></dt> + <dd><code>true</code>일 경우 이 속성에 설정된 값을 {{jsxref("Operators/Assignment_Operators", "할당 연산자", "", 1)}}로 수정할 수 있다.<br> + <strong>기본값은 <code>false</code>이다.</strong></dd> + </dl> + + <p>접근자 서술자의 경우 다음 키를 추가로 포함할 수 있다:</p> + + <dl> + <dt><code>get</code></dt> + <dd>해당 속성의 getter가 될 함수, 혹은 getter가 없을 경우 {{jsxref("undefined")}}. 이 함수의 반환값이 속성의 값으로 사용된다.<br> + <strong>기본값은 {{jsxref("undefined")}}이다.</strong></dd> + <dt><code>set</code></dt> + <dd>해당 속성의 setter가 될 함수, 혹은 setter가 없을 경우 {{jsxref("undefined")}}. 이 함수는 이 속성에 할당되는 새로운 값을 유일한 인자로 받는다.<br> + <strong>기본값은 {{jsxref("undefined")}}이다.</strong></dd> + </dl> + + <p>서술자가 <code>value</code>, <code>writable</code>, <code>get</code>, <code>set</code> 키를 모두 가지고 있지 않을 경우 데이터 서술자로 취급한다. 서술자가 <code>value</code>이나 <code>writable</code>과 <code>get</code>이나 <code>set</code> 키를 모두 가지고 있을 경우 예외가 발생한다.</p> + </dd> +</dl> + +<h3 id="반환값">반환값</h3> + +<p>함수에 넘겨주었던 객체.</p> + +<h2 id="설명">설명</h2> + +<p><code>Object.defineProperties</code>는 기본적으로 <code>props</code>의 모든 열거가능한 속성에 따라 객체 <code>obj</code>의 속성을 정의한다.</p> + +<h2 id="예시">예시</h2> + +<pre class="brush: js">var obj = {}; +Object.defineProperties(obj, { + 'property1': { + value: true, + writable: true + }, + 'property2': { + value: 'Hello', + writable: false + } + // 등등 +}); +</pre> + +<h2 id="폴리필">폴리필</h2> + +<p>모든 이름과 속성이 원래 값을 가리키는 깨끗한 실행 환경에서 <code>Object.defineProperties</code>는 다음 자바스크립트 재구현과 거의 완벽하게 똑같이(<code>isCallable</code>의 주석에 주목) 실행된다.</p> + +<pre class="brush: js;highlight:[8]">function defineProperties(obj, properties) { + function convertToDescriptor(desc) { + function hasProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + function isCallable(v) { + // NB: 함수가 아닌 값이 호출가능할 경우 필요할 시 수정할 것 + return typeof v === 'function'; + } + + if (typeof desc !== 'object' || desc === null) + throw new TypeError('bad desc'); + + var d = {}; + + if (hasProperty(desc, 'enumerable')) + d.enumerable = !!desc.enumerable; + if (hasProperty(desc, 'configurable')) + d.configurable = !!desc.configurable; + if (hasProperty(desc, 'value')) + d.value = desc.value; + if (hasProperty(desc, 'writable')) + d.writable = !!desc.writable; + if (hasProperty(desc, 'get')) { + var g = desc.get; + + if (!isCallable(g) && typeof g !== 'undefined') + throw new TypeError('bad get'); + d.get = g; + } + if (hasProperty(desc, 'set')) { + var s = desc.set; + if (!isCallable(s) && typeof s !== 'undefined') + throw new TypeError('bad set'); + d.set = s; + } + + if (('get' in d || 'set' in d) && ('value' in d || 'writable' in d)) + throw new TypeError('identity-confused descriptor'); + + return d; + } + + if (typeof obj !== 'object' || obj === null) + throw new TypeError('bad obj'); + + properties = Object(properties); + + var keys = Object.keys(properties); + var descs = []; + + for (var i = 0; i < keys.length; i++) + descs.push([keys[i], convertToDescriptor(properties[keys[i]])]); + + for (var i = 0; i < descs.length; i++) + Object.defineProperty(obj, descs[i][0], descs[i][1]); + + return obj; +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.7', 'Object.defineProperties')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>초기 정의. 자바스크립트 1.8.5에 구현됨</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.defineproperties', 'Object.defineProperties')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.defineproperties', 'Object.defineProperties')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_지원_현황">브라우저 지원 현황</h2> + + + +<p>{{Compat("javascript.builtins.Object.defineProperties")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Object.defineProperty()")}}</li> + <li>{{jsxref("Object.keys()")}}</li> + <li><a href="/en-US/docs/Enumerability_and_ownership_of_properties">Enumerability and ownership of properties</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/object/defineproperty/index.html b/files/ko/web/javascript/reference/global_objects/object/defineproperty/index.html new file mode 100644 index 0000000000..0d4a803316 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/defineproperty/index.html @@ -0,0 +1,417 @@ +--- +title: Object.defineProperty() +slug: Web/JavaScript/Reference/Global_Objects/Object/defineProperty +tags: + - ECMAScript 5 + - JavaScript + - Method + - Object + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Object/defineProperty +--- +<div>{{JSRef}}</div> + +<p><code><strong>Object.defineProperty()</strong></code> 정적 메서드는 객체에 직접 새로운 속성을 정의하거나 이미 존재하는 속성을 수정한 후, 그 객체를 반환합니다.</p> + +<div class="blockIndicator note"> +<p><strong>참고:</strong> <code>defineProperty</code>는 {{jsxref("Object")}} 인스턴스가 아니라 생성자에서 바로 호출해야 합니다.</p> +</div> + +<div>{{EmbedInteractiveExample("pages/js/object-defineproperty.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code>Object.defineProperty(<var>obj</var>, <var>prop</var>, <var>descriptor</var>)</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>속성을 정의할 객체.</dd> + <dt><code>prop</code></dt> + <dd>새로 정의하거나 수정하려는 속성의 이름 또는 {{jsxref("Symbol")}}.</dd> + <dt><code>descriptor</code></dt> + <dd>새로 정의하거나 수정하려는 속성을 기술하는 객체.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 대상 <code>obj</code>.</p> + +<h2 id="설명">설명</h2> + +<p><code>defineProperty</code>는 객체의 속성을 정교하게 추가하거나 수정할 수 있습니다. 할당을 통해 속성을 추가하는 일반적인 방법을 사용하면 속성 열거<sup>enumeration</sup>({{jsxref("Statements/for...in", "for...in")}} 반복문이나 {{jsxref("Object.keys")}} 메서드)를 통해 노출되어 값을 변경하거나 {{jsxref("Operators/delete", "delete")}} 연산자로 삭제할 수 있습니다. <code>defineProperty</code>를 사용하면 이런 부분을 상세하게 조절할 수 있습니다. <code>Object.defineProperty()</code>로 추가한 속성은 기본적으로 불변합니다.</p> + +<p>속성 서술자<sup>property descriptors</sup>는 객체로 나타내며 데이터 서술자<sup>data descriptors</sup>와 접근자 서술자<sup>accessor descriptors</sup>의 두 가지 유형을 갖습니다. 데이터 서술자는 값을 가지는 속성으로, 덮어쓰거나 쓸 수 없습니다. 접근자 서술자는 접근자<sup>getter</sup>-설정자<sup>setter</sup> 한 쌍을 가지는 속성입니다. 서술자는 두 유형 중 하나여야 하며, 동시에 두 유형일 수는 없습니다.</p> + +<p>데이터 서술자와 접근자 서술자 모두 객체이며 다음과 같은 키를 공유합니다.</p> + +<dl> + <dt><code>configurable</code></dt> + <dd>이 속성의 값을 변경할 수 있고, 대상 객체에서 삭제할 수도 있다면 <code>true</code>.<br> + 기본값은<strong> </strong><code>false</code>.</dd> + <dt><code>enumerable</code></dt> + <dd>이 속성이 대상 객체의 속성 열거 시 노출된다면 <code>true</code>.<br> + 기본값은<strong> </strong><code>false</code>.</dd> +</dl> + +<p>데이터 서술자는 다음 키를 선택사항으로 가집니다.</p> + +<dl> + <dt><code>value</code></dt> + <dd>속성에 연관된 값. 아무 유효한 JavaScript 값(숫자, 객체, 함수 등)이나 가능합니다.<br> + 기본값은 {{jsxref("undefined")}}</dd> + <dt><code>writable</code></dt> + <dd>{{jsxref("Operators/Assignment_Operators", "할당 연산자", "", 1)}}로 속성의 값을 바꿀 수 있다면 <code>true</code>.<br> + 기본값은<strong> </strong><code>false</code>.</dd> +</dl> + +<p>접근자 서술자는 다음 키를 선택사항으로 가집니다.</p> + +<dl> + <dt><code>get</code></dt> + <dd>속성 접근자로 사용할 함수, 접근자가 없다면 {{jsxref("undefined")}}. 속성에 접근하면 이 함수를 매개변수 없이 호출하고, 그 반환값이 속성의 값이 됩니다. 이 때 <code>this</code> 값은 이 속성을 가진 객체(상속으로 인해 원래 정의한 객체가 아닐 수 있음)입니다.<br> + 기본값은 {{jsxref("undefined")}}.</dd> + <dt><code>set</code></dt> + <dd>속성 설정자로 사용할 함수, 설정자가 없다면 {{jsxref("undefined")}}. 속성에 값을 할당하면 이 함수를 하나의 매개변수(할당하려는 값)로 호출합니다. 이 때 <code>this</code> 값은 이 속성을 가진 객체입니다.<br> + 기본값은 {{jsxref("undefined")}}.</dd> +</dl> + +<p>서술자가 <code>value</code>, <code>writable</code>, <code>get</code>, <code>set</code> 키를 모두 지니고 있지 않으면 데이터 서술자로 간주합니다. 반면 <code>value</code> 또는 <code>writable</code>과 동시에 <code>get</code> 또는 <code>set</code> 키를 함께 가지고 있으면 오류가 발생합니다.</p> + +<p>각 설정값이 서술자 스스로의 속성일 필요는 없습니다. 따라서 서술자가 상속받은 값도 영향을 줍니다. 기본 설정값을 확실하게 보존하려면 {{jsxref("Object.prototype")}}을 먼저 동결하거나, 모든 속성을 명시적으로 지정하거나, {{jsxref("Object.create", "Object.create(null)")}}로 {{jsxref("null")}}을 가리키세요.</p> + +<pre class="brush: js">// __proto__ 사용 +var obj = {}; +var descriptor = Object.create(null); // 상속받은 속성 없음 +// 기본으로 열거 불가, 설정 불가, 변경 불가 +descriptor.value = 'static'; +Object.defineProperty(obj, 'key', descriptor); + +// 명시적 +Object.defineProperty(obj, 'key', { + enumerable: false, + configurable: false, + writable: false, + value: 'static' +}); + +// 같은 객체를 재활용하기 +function withValue(value) { + var d = withValue.d || ( + withValue.d = { + enumerable: false, + writable: false, + configurable: false, + value: null + } + ); + d.value = value; + return d; +} +Object.defineProperty(obj, 'key', withValue('static')); + +// Object.freeze가 존재하면 +// 속성의 추가/제거 방지 +// (value, get, set, enumerable, writable, configurable) +(Object.freeze || Object)(Object.prototype); +</pre> + +<h2 id="예제">예제</h2> + +<p>이진 플래그 형태로 <code>defineProperty</code>를 사용하는 예제는 <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty/Additional_examples">additional examples</a>에 있습니다.</p> + +<h3 id="속성_생성하기">속성 생성하기</h3> + +<p><code>Object.defineProperty()</code>는 지정한 속성이 객체에 존재하지 않으면 주어진 서술자를 사용해 새로 생성합니다. 서술자의 일부 항목은 생략 가능하며, 생략한 항목은 기본값을 대신 사용합니다.</p> + +<pre class="brush: js">var o = {}; // 새로운 객체 생성 + +// 데이터 속성 서술자와 defineProperty로 +// 새로운 속성을 추가하는 예시 +Object.defineProperty(o, 'a', { + value: 37, + writable: true, + enumerable: true, + configurable: true +}); +// 'a' 속성이 o 객체에 존재하고 값은 37 + +// 접근자 속성 기술자와 defineProperty로 +// 새로운 속성을 추가하는 예시 +var bValue = 38; +Object.defineProperty(o, 'b', { + // ES2015 단축 메서드명 사용 + // 아래 코드와 같음 + // get: function() { return bValue; } + // set: function(newValue) { bValue = newValue; }, + get() { return bValue; }, + set(newValue) { bValue = newValue; }, + enumerable: true, + configurable: true +}); +o.b; // 38 +// 'b' 속성이 o 객체에 존재하고 값은 38 +// o.b를 재정의하지 않는 이상 +// o.b의 값은 항상 bValue와 동일함 + +// 두 가지를 혼용할 수 없음 +Object.defineProperty(o, 'conflict', { + value: 0x9f91102, + get: function() { return 0xdeadbeef; } +}); +// TypeError 발생 +// value는 데이터 서술자에만, +// get은 접근자 서술자에만 나타날 수 있음</pre> + +<h3 id="속성_수정하기">속성 수정하기</h3> + +<p><code>ObjectdefineProperty()</code>는 지정한 속성이 객체에 이미 존재하면 주어진 서술자와 객체의 기존 설정을 사용해 속성의 수정을 시도합니다. 기존 속성 서술자의 <code>configurable</code>이 <code>false</code>이면 속성이 "설정 불가능"하다고 말하고, 이 속성의 어떤 특성도 수정할 수 없습니다. 다만 쓰기 가능한 데이터 속성의 경우 값을 바꾸거나 <code>writable</code> 특성을 <code>true</code>에서 <code>false</code>로 바꾸는건 가능합니다. 속성이 설정 불가능한 경우 속성의 유형을 데이터에서 접근자, 또는 접근자에서 데이터로 바꿀 수 없습니다.</p> + +<p>설정 불가능한 속성의 특성을 바꾸려고 시도하면 {{jsxref("TypeError")}}가 발생합니다. 단, 기존 값과 신규 값이 같은 경우, 혹은 쓰기 가능한 속성의 <code>value</code>와 <code>writable</code>은 수정할 수 있습니다.</p> + +<h4 id="writable_특성"><code>writable</code> 특성</h4> + +<p>속성의 <code>writable</code> 특성이 <code>false</code>인 경우는 "쓰기 불가능"하여 다시 할당할 수 없습니다.</p> + +<pre class="brush: js">var o = {}; // 새로운 객체 생성 + +Object.defineProperty(o, 'a', { + value: 37, + writable: false +}); + +console.log(o.a); // 37 기록 +o.a = 25; // 오류 발생하지 않음 +// 엄격 모드에서는 값이 같더라도 +// 오류가 발생함 +console.log(o.a); // 37 기록, 할당하지 못했음 + +// 엄격 모드 +(function() { + 'use strict'; + var o = {}; + Object.defineProperty(o, 'b', { + value: 2, + writable: false + }); + o.b = 3; // TypeError: "b" is read-only + return o.b; // 윗줄이 없다면 2 반환 +}()); +</pre> + +<p>위의 예제가 보이듯, 비엄격 모드에서는 쓰기 불가능한 속성의 값에 쓰려고 시도하면 값이 바뀌지 않고, 오류도 발생하지도 않습니다.</p> + +<h4 id="Enumerable_속성">Enumerable 속성</h4> + +<p><code>enumerable</code>은 해당 속성이 {{jsxref("Statements/for...in", "for...in")}} 루프나 {{jsxref("Object.keys()")}} 에서 노출될지 말지를 정의한다.</p> + +<pre class="brush: js">var o = {}; +Object.defineProperty(o, 'a', { + value: 1, + enumerable: true +}); +Object.defineProperty(o, 'b', { + value: 2, + enumerable: false +}); +Object.defineProperty(o, 'c', { + value: 3 +}); // enumerable defaults to false +o.d = 4; // enumerable defaults to true + // when creating a property by setting it +Object.defineProperty(o, Symbol.for('e'), { + value: 5, + enumerable: true +}); +Object.defineProperty(o, Symbol.for('f'), { + value: 6, + enumerable: false +}); + +for (var i in o) { + console.log(i); +} +// logs 'a' and 'd' (in undefined order) + +Object.keys(o); // ['a', 'd'] + +o.propertyIsEnumerable('a'); // true +o.propertyIsEnumerable('b'); // false +o.propertyIsEnumerable('c'); // false +o.propertyIsEnumerable('d'); // true +o.propertyIsEnumerable(Symbol.for('e')); // true +o.propertyIsEnumerable(Symbol.for('f')); // false + +var p = { ...o } +p.a // 1 +p.b // undefined +p.c // undefined +p.d // 4 +p[Symbol.for('e')] // 5 +p[Symbol.for('f')] // undefined +</pre> + +<h4 id="Configurable_속성">Configurable 속성</h4> + +<p><code>configurable</code> 은 객체에서 해당키가 제거될 수 있는지와 (<code>writable</code>을 제외한)기술속성을 변경할 수 있는지에 대한 여부를 동시에 통제한다.</p> + +<pre class="brush: js">var o = {}; +Object.defineProperty(o, 'a', { + get() { return 1; }, + configurable: false +}); + +Object.defineProperty(o, 'a', { + configurable: true +}); // throws a TypeError +Object.defineProperty(o, 'a', { + enumerable: true +}); // throws a TypeError +Object.defineProperty(o, 'a', { + set() {} +}); // throws a TypeError (set was undefined previously) +Object.defineProperty(o, 'a', { + get() { return 1; } +}); // throws a TypeError +// (even though the new get does exactly the same thing) +Object.defineProperty(o, 'a', { + value: 12 +}); // throws a TypeError + +console.log(o.a); // logs 1 +delete o.a; // Nothing happens +console.log(o.a); // logs 1 +</pre> + +<p><font face="Courier New">o.a</font>의 <font face="Courier New">configurable</font> 가 <font face="Courier New">true</font>라면, 위의 예외는 발생하지 않고 속성은 마지막에 제거되었을 것이다.</p> + +<h3 id="속성에_기본값_추가하기">속성에 기본값 추가하기</h3> + +<p>속성을 정의할 때 기본값을 제공하는 방식은 중요하다. 간단히 점구문을 이용해 할당한 값과 <code>Object.defineProperty</code>를 사용한 경우는 꽤 다르다. 아래 예를 보자.</p> + +<pre class="brush: js">var o = {}; + +o.a = 1; +// 위의 표현은 아래와 같다: +Object.defineProperty(o, 'a', { + value: 1, + writable: true, + configurable: true, + enumerable: true +}); + + +// 만약 다음과 같이 표현한다면, +Object.defineProperty(o, 'a', { value: 1 }); +// 아래의 의미를 지니게 된다: +Object.defineProperty(o, 'a', { + value: 1, + writable: false, + configurable: false, + enumerable: false +}); +</pre> + +<h3 id="사용자_정의_Setters_와_Getters">사용자 정의 Setters 와 Getters</h3> + +<p>아래의 예는 어떻게 스스로 변화를 기록해두는 객체를 만드는지 보여준다. <code>temperature</code> 속성의 값을 바꾸면 <code>archive</code> 배열에도 로그가 쌓인다.</p> + +<pre class="brush: js">function Archiver() { + var temperature = null; + var archive = []; + + Object.defineProperty(this, 'temperature', { + get: function() { + console.log('get!'); + return temperature; + }, + set: function(value) { + temperature = value; + archive.push({ val: temperature }); + } + }); + + this.getArchive = function() { return archive; }; +} + +var arc = new Archiver(); +arc.temperature; // 'get!' +arc.temperature = 11; +arc.temperature = 13; +arc.getArchive(); // [{ val: 11 }, { val: 13 }] +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.6', 'Object.defineProperty')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.8.5.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.defineproperty', 'Object.defineProperty')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.defineproperty', 'Object.defineProperty')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Object.defineProperty")}}</p> + +<h2 id="호환성_참고사항">호환성 참고사항</h2> + +<h3 id="Redefining_the_length_property_of_an_Array_object">Redefining the <code>length</code> property of an <code>Array</code> object</h3> + +<p>It is possible to redefine the {{jsxref("Array.length", "length")}} property of arrays, subject to the usual redefinition restrictions. (The {{jsxref("Array.length", "length")}} property is initially non-configurable, non-enumerable, and writable. Thus on an unaltered array it is possible to change the {{jsxref("Array.length", "length")}} property's value, or to make it non-writable. It is not allowed to change its enumerability or configurability, or if it is non-writable to change its value or writability.) However, not all browsers permit this redefinition.</p> + +<p>Firefox 4 through 22 will throw a {{jsxref("Global_Objects/TypeError", "TypeError")}} on any attempt whatsoever (whether permitted or not) to redefine the {{jsxref("Array.length", "length")}} property of an array.</p> + +<p>Versions of Chrome which implement <code>Object.defineProperty()</code> in some circumstances ignore a length value different from the array's current {{jsxref("Array.length", "length")}} property. In some circumstances changing writability seems to silently not work (and not throw an exception). Also, relatedly, some array-mutating methods like {{jsxref("Array.prototype.push")}} don't respect a non-writable length.</p> + +<p>Versions of Safari which implement <code>Object.defineProperty()</code> ignore a <code>length</code> value different from the array's current {{jsxref("Array.length", "length")}} property, and attempts to change writability execute without error but do not actually change the property's writability.</p> + +<p>Only Internet Explorer 9 and later, and Firefox 23 and later, appear to fully and correctly implement redefinition of the {{jsxref("Array.length", "length")}} property of arrays. For now, don't rely on redefining the {{jsxref("Array.length", "length")}} property of an array to either work, or to work in a particular manner. And even when you <em>can</em> rely on it, <a href="http://whereswalden.com/2013/08/05/new-in-firefox-23-the-length-property-of-an-array-can-be-made-non-writable-but-you-shouldnt-do-it/">there's really no good reason to do so</a>.</p> + +<h3 id="Internet_Explorer_8_specific_notes">Internet Explorer 8 specific notes</h3> + +<p>Internet Explorer 8 implemented a <code>Object.defineProperty()</code> method that could <a class="external" href="http://msdn.microsoft.com/en-us/library/dd229916%28VS.85%29.aspx">only be used on DOM objects</a>. A few things need to be noted:</p> + +<ul> + <li>Trying to use <code>Object.defineProperty()</code> on native objects throws an error.</li> + <li>Property attributes must be set to some values. <code>Configurable</code>, <code>enumerable</code> and <code>writable</code> attributes should all be set to <code>true</code> for data descriptor and <code>true</code> for <code>configurable</code>, <code>false</code> for <code>enumerable</code> for accessor descriptor.(?) Any attempt to provide other value(?) will result in an error being thrown.</li> + <li>Reconfiguring a property requires first deleting the property. If the property isn't deleted, it stays as it was before the reconfiguration attempt.</li> +</ul> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Enumerability_and_ownership_of_properties">Enumerability and ownership of properties</a></li> + <li>{{jsxref("Object.defineProperties()")}}</li> + <li>{{jsxref("Object.propertyIsEnumerable()")}}</li> + <li>{{jsxref("Object.getOwnPropertyDescriptor()")}}</li> + <li>{{jsxref("Object.prototype.watch()")}}</li> + <li>{{jsxref("Object.prototype.unwatch()")}}</li> + <li>{{jsxref("Operators/get", "get")}}</li> + <li>{{jsxref("Operators/set", "set")}}</li> + <li>{{jsxref("Object.create()")}}</li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty/Additional_examples">Additional <code>Object.defineProperty</code> examples</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/object/entries/index.html b/files/ko/web/javascript/reference/global_objects/object/entries/index.html new file mode 100644 index 0000000000..3056d99d31 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/entries/index.html @@ -0,0 +1,145 @@ +--- +title: Object.entries() +slug: Web/JavaScript/Reference/Global_Objects/Object/entries +translation_of: Web/JavaScript/Reference/Global_Objects/Object/entries +--- +<div>{{JSRef}}</div> + +<p><code><strong>Object.entries()</strong></code> 메서드는 {{jsxref("Statements/for...in", "for...in")}}와 같은 순서로 주어진 객체 자체의 enumerable 속성 <code>[key, value]</code> 쌍의 배열을 반환합니다. (<code>for-in</code> 루프가 다른점은 프로토 타입 체인의 속성도 열거한다는 점입니다).</p> + +<p><code><strong>Object.entries()</strong></code> 에 의해 반환된 배열(array)의 순서는 객체가 정의된 방법과 관련이 없습니다. 배열 순서가 쓸 곳이 있다면, 다음과 같이 정렬을 먼저 하시는 것이 좋습니다 <code>Object.entries(obj).sort((a, b) => b[0].localeCompare(a[0]));</code>.</p> + +<div>{{EmbedInteractiveExample("pages/js/object-entries.html", "taller")}}</div> + + + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox notranslate">Object.entries(<var>obj</var>)</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>객체 자체의 열거 가능한 문자열 키를 가진 속성 <code>[key, value]</code> 쌍이 반환되는 객체입니다.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>지정된 객체 자체의 열거 가능한 문자속성 <code>[key, value]</code> 쌍의 배열입니다.</p> + +<h2 id="Description">Description</h2> + +<p><code>Object.entries()</code>는 <code>object</code>에 직접있는 enumerable 속성 <code>[key, value]</code> 쌍에 해당하는 배열을 반환합니다. 속성의 순서는 개체의 속성 값을 수동으로 반복하여 주어진 순서와 동일합니다.</p> + +<h2 id="Polyfill">Polyfill</h2> + +<p>기본적으로 지원하지 않는 이전 환경에서 호환 가능한 <code>Object.entries</code> 지원을 추가하려면 <a href="https://github.com/tc39/proposal-object-values-entries">tc39/proposal-object-values-entries</a>에 Object.entries의 데모 구현을 찾을 수 있습니다 (IE에 대한 지원이 필요하지 않은 경우) , <a href="https://github.com/es-shims/Object.entries">es-shims/Object.entries</a> 저장소에있는 polyfill을 사용하거나 아래에 나열된 polyfill을 간단하게 배치 할 수 있습니다.</p> + +<pre class="brush: js notranslate">if (!Object.entries) + Object.entries = function( obj ){ + var ownProps = Object.keys( obj ), + i = ownProps.length, + resArray = new Array(i); // preallocate the Array + while (i--) + resArray[i] = [ownProps[i], obj[ownProps[i]]]; + + return resArray; + }; +</pre> + +<p>For the above polyfill code snippet, if you need support for IE < 9, then you will also need an Object.keys polyfill (such as the one found on the {{jsxref("Object.keys")}} page).</p> + +<p>위의 polyfill 코드 스 니펫의 경우 Internet Explorer (9버전 이전)를 지원해야하는 경우 Object.keys polyfill ( {{jsxref("Object.keys")}} 페이지에 있는 것과 같은)도 필요합니다.</p> + +<h2 id="Examples">Examples</h2> + +<pre class="brush: js notranslate">const obj = { foo: 'bar', baz: 42 }; +console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ] + +// array like object +const obj = { 0: 'a', 1: 'b', 2: 'c' }; +console.log(Object.entries(obj)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ] + +// array like object with random key ordering +const anObj = { 100: 'a', 2: 'b', 7: 'c' }; +console.log(Object.entries(anObj)); // [ ['2', 'b'], ['7', 'c'], ['100', 'a'] ] + +// getFoo is property which isn't enumerable +const myObj = Object.create({}, { getFoo: { value() { return this.foo; } } }); +myObj.foo = 'bar'; +console.log(Object.entries(myObj)); // [ ['foo', 'bar'] ] + +// non-object argument will be coerced to an object +console.log(Object.entries('foo')); // [ ['0', 'f'], ['1', 'o'], ['2', 'o'] ] + +// returns an empty array for any primitive type, since primitives have no own properties +console.log(Object.entries(100)); // [ ] + +// iterate through key-value gracefully +const obj = { a: 5, b: 7, c: 9 }; +for (const [key, value] of Object.entries(obj)) { + console.log(`${key} ${value}`); // "a 5", "b 7", "c 9" +} + +// Or, using array extras +Object.entries(obj).forEach(([key, value]) => { +console.log(`${key} ${value}`); // "a 5", "b 7", "c 9" +}); +</pre> + +<h3 id="Converting_an_Object_to_a_Map">Converting an <code>Object</code> to a <code>Map</code></h3> + +<p>{{jsxref("Map", "new Map()")}} 생성자는 반복 가능한 항목을 허용합니다. <code>Object.entries</code>를 사용하면 {{jsxref("Object")}}에서 {{jsxref("Map")}}로 쉽게 변환 할 수 있습니다.</p> + + + +<pre class="brush: js notranslate">const obj = { foo: 'bar', baz: 42 }; +const map = new Map(Object.entries(obj)); +console.log(map); // Map { foo: "bar", baz: 42 } +</pre> + +<h3 id="Iterating_through_an_Object">Iterating through an <code>Object</code></h3> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Array_destructuring">Array Destructuring</a>을 사용하면 객체를 쉽게 반복 할 수 있습니다.</p> + +<pre class="brush: js notranslate">const obj = { foo: 'bar', baz: 42 }; +Object.entries(obj).forEach(([key, value]) => console.log(`${key}: ${value}`)); // "foo: bar", "baz: 42" +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.entries', 'Object.entries')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Object.entries")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Enumerability_and_ownership_of_properties">Enumerability and ownership of properties</a></li> + <li>{{jsxref("Object.keys()")}}</li> + <li>{{jsxref("Object.values()")}}</li> + <li>{{jsxref("Object.prototype.propertyIsEnumerable()")}}</li> + <li>{{jsxref("Object.create()")}}</li> + <li>{{jsxref("Object.getOwnPropertyNames()")}}</li> + <li>{{jsxref("Map.prototype.entries()")}}</li> + <li>{{jsxref("Map.prototype.keys()")}}</li> + <li>{{jsxref("Map.prototype.values()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/object/freeze/index.html b/files/ko/web/javascript/reference/global_objects/object/freeze/index.html new file mode 100644 index 0000000000..6eaca7b708 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/freeze/index.html @@ -0,0 +1,257 @@ +--- +title: Object.freeze() +slug: Web/JavaScript/Reference/Global_Objects/Object/freeze +tags: + - ECMAScript 5 + - JavaScript + - Method + - Object + - Reference + - 동결 + - 변경 + - 변경가능성 + - 불변 + - 불변성 + - 잠금 +translation_of: Web/JavaScript/Reference/Global_Objects/Object/freeze +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary"><code><strong>Object.freeze()</strong></code> 메서드는 객체를 <strong>동결</strong>합니다. 동결된 객체는 더 이상 변경될 수 없습니다. 즉, 동결된 객체는 새로운 속성을 추가하거나 존재하는 속성을 제거하는 것을 방지하며 존재하는 속성의 불변성, 설정 가능성(configurability), 작성 가능성이 변경되는 것을 방지하고, 존재하는 속성의 값이 변경되는 것도 방지합니다.</span> 또한, 동결 객체는 그 프로토타입이 변경되는것도 방지합니다. <code>freeze()</code>는 전달된 동일한 객체를 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/object-freeze.html")}}</div> + + + +<h2 id="Syntax" name="Syntax">구문</h2> + +<pre class="syntaxbox">Object.freeze(<var>obj</var>)</pre> + +<h3 id="Parameters" name="Parameters">매개변수</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>동결할 객체.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>함수로 전달된 객체.</p> + +<h2 id="Description" name="Description">설명</h2> + +<p>동결 객체의 속성 집합에는 어떠한 것도 추가하거나 제거할 수 없으며, 그리 하려는 모든 시도는 조용히 넘어가거나, {{jsxref("TypeError")}} 예외가 발생하며 실패합니다. 예외 발생은 보통 {{jsxref("Strict_mode", "엄격 모드", "", 1)}}인 경우 발생하지만, 반드시 엄격 모드로만 제한되는 것은 아닙니다.</p> + +<p>동결 객체가 가진 데이터 속성에 대해선, 값을 변경할 수 없으며 설정 가능 여부와 쓰기 가능 여부 속성 모두 거짓이 됩니다. 접근자 속성(접근자와 설정자)도 동일하게 동작합니다(또한 값을 변경하고 있다는 환상을 줍니다). 수정되는 값이 객체이고 동결된 것이 아니라면 여전히 수정이 가능함을 유의하세요. 객체로써, 배열도 동결될 수 있습니다. 동결한 이후에는 그 엘리먼트를 변경할 수 없으며 배열에 어떠한 엘리먼트도 추가하거나 제거할 수 없습니다.</p> + +<p><code>freeze()</code>는 함수에 전달한 객체를 그대로 반환하며, 동결된 객체 사본을 생성하는 것이 아닙니다.</p> + +<h2 id="Examples" name="Examples">예제</h2> + +<h3 id="객체_동결하기">객체 동결하기</h3> + +<pre class="brush: js">var obj = { + prop: function() {}, + foo: 'bar' +}; + +// 동결 이전: 새 속성을 추가할 수 있고, +// 기존 속성을 변경하거나 제거할 수 있음 +obj.foo = 'baz'; +obj.lumpy = 'woof'; +delete obj.prop; + +// 동결 +var o = Object.freeze(obj); + +// 반환 값은 전달된 객체와 동일함. +o === obj; // true + +// 객체가 동결 상태가 됨. +Object.isFrozen(obj); // === true + +// 이제 모든 변경 시도는 실패함 +obj.foo = 'quux'; // 조용하게 아무것도 하지 않음 +// 조용하게 속성을 추가하지 않음 +obj.quaxxor = 'the friendly duck'; + +// 엄격 모드에서는 이러한 시도에 대해 TypeError 발생 +function fail(){ + 'use strict'; + obj.foo = 'sparky'; // TypeError 발생 + delete obj.foo; // TypeError 발생 + delete obj.quaxxor; // 'quaxxor' 속성은 추가된 적이 없으므로 true 반환 + obj.sparky = 'arf'; // TypeError 발생 +} + +fail(); + +// Object.defineProperty를 통한 변경 시도 +// 아래 두 구문 모두에서 TypeError 발생 +Object.defineProperty(obj, 'ohai', { value: 17 }); +Object.defineProperty(obj, 'foo', { value: 'eit' }); + +// 프로토타입을 변경하는 것 또한 불가함 +// 아래 두 구문 모두에서 TypeError 발생 +Object.setPrototype(obj, { x: 20 }); +obj.__proto__ = { x: 20 }; + +</pre> + +<h3 id="배열_동결">배열 동결</h3> + +<pre class="brush: js">let a = [0]; +Object.freeze(a); // 이제 배열을 수정할 수 없음. + +a[0]=1; // 조용하게 실패 +a.push(2); // 조용하게 실패 + +// 엄격 모드에서는 이런 시도에 대해 TypeError 발생 +function fail() { + "use strict" + a[0] = 1; + a.push(2); +} + +fail();</pre> + +<p>동결된 객체는 변경할 수 없습니다. 하지만, 꼭 그렇지만은 않습니다. 다음 예제는 동결된 객체가 변경될 수 있음을(얕은 동결) 보여줍니다.</p> + +<pre class="brush: js">obj = { + internal: {} +}; + +Object.freeze(obj); +obj.internal.a = 'aValue'; + +obj.internal.a // 'aValue' +</pre> + +<p>변경될 수 없는 객체가 되려면, 모든 참조 그래프(다른 객체로의 직간접적 참조)가 오로지 불변의 동결 객체만을 참조해야 합니다. 동결된 객체는 객체 내의 모든 상태(다른 객체로의 값과 참조)가 고정되기 때문에 불변하다고 합니다. 문자열, 숫자, 불리언 값은 언제나 불변하고, 함수와 배열은 객체임을 유의하세요.</p> + +<h4 id="얕은_동결이_무엇인가요">"얕은 동결"이 무엇인가요?</h4> + +<p><code>Object.freeze(object)</code> 호출의 결과는 <code>object</code> 스스로의 직속 속성에만 적용되며, <code>object</code>에 대해서만 속성 추가, 제거, 재할당 연산을 방지합니다. 만약 그 속성의 값이 객체라면, 그 객체는 동결되지 않으며 속성 추가, 제거, 재할당의 대상이 될 수 있습니다.</p> + +<pre class="brush: js">var employee = { + name: "Mayank", + designation: "Developer", + address: { + street: "Rohini", + city: "Delhi" + } +}; + +Object.freeze(employee); + +employee.name = "Dummy"; // 비엄격 모드에서 조용하게 실패 +employee.address.city = "Noida"; // 자식 객체의 속성은 수정 가능 + +console.log(employee.address.city) // 출력: "Noida" +</pre> + +<p>객체를 불변하게 만들려면, 각 객체 타입의 속성을 재귀적으로 동결해야합니다(깊은 동결). 객체가 그 참조 그래프에서 {{interwiki("wikipedia", "Cycle_(graph_theory)", "순환")}}을 포함하지 않는다는 것을 인지하고 있을 때, 디자인을 기반으로 상황에 따라 패턴을 적용해야하며, 그렇지 않을 경우 반복문이 무한히 실행될 수 있습니다. <code>deepFreeze()</code>에 대한 개선은 객체가 불변하게 되는 과정에 있을 때 <code>deepFreeze()</code>의 재귀적인 호출을 차단할 수 있도록 경로(예, 배열) 인자를 받는 내부 함수를 소유하는 것입니다. [window]와 같은, 동결되면 안되는 객체를 동결하는 것에 대한 위험은 여전히 남아 있습니다.</p> + +<pre class="brush: js">function deepFreeze(object) { + + // 객체에 정의된 속성명을 추출 + var propNames = Object.getOwnPropertyNames(object); + + // 스스로를 동결하기 전에 속성을 동결 + + for (let name of propNames) { + let value = object[name]; + + object[name] = value && typeof value === "object" ? + deepFreeze(value) : value; + } + + return Object.freeze(object); +} + +var obj2 = { + internal: { + a: null + } +}; + +deepFreeze(obj2); + +obj2.internal.a = 'anotherValue'; // 비엄격 모드에서 조용하게 실패 +obj2.internal.a; // null +</pre> + +<h2 id="Notes" name="Notes">사용 노트</h2> + +<p>ES5에서는, 이 메소드에 대한 인자가 객체(원시형)가 아닐 경우, {{jsxref("TypeError")}}가 발생합니다. ES2015에서는, 비객체 인자가 동결된 평범한 객체인것처럼 다루어져 반환됩니다.</p> + +<pre class="brush: js">> Object.freeze(1) +TypeError: 1 is not an object // ES5 code + +> Object.freeze(1) +1 // ES2015 code +</pre> + +<p>엘리먼트를 갖는 {{domxref("ArrayBufferView")}}는 메모리를 통한 뷰이므로 다른 가능한 문제를 유발 할 수 있어 {{jsxref("TypeError")}}가 발생합니다.</p> + +<pre class="brush: js">> Object.freeze(new Uint8Array(0)) // 엘리먼트가 없음 +Uint8Array [] + +> Object.freeze(new Uint8Array(1)) // 엘리먼트를 가짐 +TypeError: Cannot freeze array buffer views with elements + +> Object.freeze(new DataView(new ArrayBuffer(32))) // 엘리먼트가 없음 +DataView {} + +> Object.freeze(new Float64Array(new ArrayBuffer(64), 63, 0)) // 엘리먼트가 없음 +Float64Array [] + +> Object.freeze(new Float64Array(new ArrayBuffer(64), 32, 2)) // 엘리먼트를 가짐 +TypeError: Cannot freeze array buffer views with elements</pre> + +<p>세 가지 표준 속성(<code>buf.byteLength</code>, <code>buf.byteOffset</code>, <code>buf.buffer</code>)은 읽기 전용(이들은 {jsxref("ArrayBuffer")}} 또는 {{jsxref("SharedArrayBuffer")}}이므로)이므로, 이러한 속성에 대해 동결을 시도할 이유가 없음을 유의합니다.</p> + +<h3 id="Object.seal과의_비교"><code>Object.seal()</code>과의 비교</h3> + +<p>{{jsxref("Object.seal()")}}을 사용해 봉인된 객체는 존재하는 속성을 변경할 수 있습니다. <code>Object.freeze()</code>로 동결된 객체에서는 존재하는 속성이 불변입니다.</p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">코멘트</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.9', 'Object.freeze')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>초기 정의. JavaScript 1.8.5에서 구현됨.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.freeze', 'Object.freeze')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.freeze', 'Object.freeze')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.Object.freeze")}}</p> + +<h2 id="함께_보기">함께 보기</h2> + +<ul> + <li>{{jsxref("Object.isFrozen()")}}</li> + <li>{{jsxref("Object.preventExtensions()")}}</li> + <li>{{jsxref("Object.isExtensible()")}}</li> + <li>{{jsxref("Object.seal()")}}</li> + <li>{{jsxref("Object.isSealed()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/object/fromentries/index.html b/files/ko/web/javascript/reference/global_objects/object/fromentries/index.html new file mode 100644 index 0000000000..4d74fc326a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/fromentries/index.html @@ -0,0 +1,98 @@ +--- +title: Object.fromEntries() +slug: Web/JavaScript/Reference/Global_Objects/Object/fromEntries +tags: + - JavaScript + - Method + - Object + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Object/fromEntries +--- +<div>{{JSRef}}</div> + +<p><code><strong>Object.fromEntries()</strong></code> 메서드는 키값 쌍의 목록을 객체로 바꿉니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/object-fromentries.html")}}</div> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">Object.fromEntries(<var>iterable</var>);</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>iterable</code></dt> + <dd>반복 가능한 객체. 즉, {{jsxref("Array")}}, {{jsxref("Map")}} 또는 <a href="/ko/docs/Web/JavaScript/Reference/Iteration_protocols">반복 규약</a>을 구현한 기타 객체.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>속성의 키와 값을 반복 가능한 객체에서 가져온 새로운 객체.</p> + +<h2 id="설명">설명</h2> + +<p><code>Object.fromEntries()</code> 메서드는 키값 쌍 목록을 받고, 그 목록을 사용해 속성을 부여한 새로운 객체를 반환합니다. <code>iterable</code> 인자는 <code>@@iterator</code> 메서드를 구현하여 반복기 객체를 반환해야 하고, 그 반복기는 또 배열 형태의 객체로 요소 2개를 반환해야 합니다. 반환된 요소 중 첫 번째는 생성할 객체의 속성 키로, 두 번째는 속성 값으로 사용합니다.</p> + +<p><code>Object.fromEntries()</code>는{{jsxref("Object.entries()")}}의 역을 수행합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="Map에서_Object로"><code>Map</code>에서 <code>Object</code>로</h3> + +<pre class="brush: js">const map = new Map([ ['foo', 'bar'], ['baz', 42] ]); +const obj = Object.fromEntries(map); +console.log(obj); // { foo: "bar", baz: 42 } +</pre> + +<h3 id="Array에서_Object로"><code>Array</code>에서 <code>Object</code>로</h3> + +<pre class="brush: js">const arr = [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]; +const obj = Object.fromEntries(arr); +console.log(obj); // { 0: "a", 1: "b", 2: "c" } +</pre> + +<h3 id="객체_변환">객체 변환</h3> + +<p><code>Object.fromEntries()</code>와 그 역인 {{jsxref("Object.entries()")}}, 그리고 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Array#메서드_2">배열 변형 메서드</a>를 통해 객체를 변환할 수 있습니다.</p> + +<pre class="brush: js">const object1 = { a: 1, b: 2, c: 3 }; + +const object2 = Object.fromEntries( + Object.entries(object1) + .map(([ key, val ]) => [ key, val * 2 ]) +); + +console.log(object2); +// { a: 2, b: 4, c: 6 }</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + </tr> + </thead> + <tbody> + <tr> + <td><a href="https://tc39.github.io/proposal-object-from-entries/">https://tc39.github.io/proposal-object-from-entries</a></td> + <td>Stage 3</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.Object.fromEntries")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Object.entries()")}}</li> + <li>{{jsxref("Object.keys()")}}</li> + <li>{{jsxref("Object.values()")}}</li> + <li>{{jsxref("Map.prototype.entries()")}}</li> + <li>{{jsxref("Map.prototype.keys()")}}</li> + <li>{{jsxref("Map.prototype.values()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/object/getownpropertydescriptor/index.html b/files/ko/web/javascript/reference/global_objects/object/getownpropertydescriptor/index.html new file mode 100644 index 0000000000..c3be0cbaae --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/getownpropertydescriptor/index.html @@ -0,0 +1,126 @@ +--- +title: Object.getOwnPropertyDescriptor() +slug: Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor +tags: + - ECMAScript5 + - JavaScript + - Method + - Object +translation_of: Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor +--- +<div>{{JSRef}}</div> + +<p><code><strong>Object.getOwnPropertyDescriptor()</strong></code> 메서드는 주어진 객체 <dfn>자신의 속성</dfn>(즉, 객체에 직접 제공하는 속성, 객체의 프로토타입 체인을 따라 존재하는 덕택에 제공하는 게 아닌)에 대한 속성 설명자(descriptor)를 반환합니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code>Object.getOwnPropertyDescriptor(<var>obj</var>, <var>prop</var>)</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>속성을 찾을 대상 객체.</dd> + <dt><code>prop</code></dt> + <dd>설명이 검색될 속성명.</dd> +</dl> + +<h3 id="반환값">반환값</h3> + +<p>객체에 존재하는 경우 주어진 속성의 속성 설명자, 없으면 {{jsxref("undefined")}}.</p> + +<h2 id="설명">설명</h2> + +<p>이 메서드는 정확한 속성 설명의 검사를 허용합니다. JavaScript에서 <dfn>속성</dfn>은 문자열 값인 이름과 속성 설명자로 구성됩니다. 속성 설명자 유형과 attribute에 관한 자세한 정보는 {{jsxref("Object.defineProperty()")}}에서 찾을 수 있습니다.</p> + +<p><dfn>속성 설명자</dfn>는 다음 attribute 중 일부의 기록입니다:</p> + +<dl> + <dt><code>value</code></dt> + <dd>속성과 관련된 값 (데이터 설명자만).</dd> + <dt><code><strong>writable</strong></code></dt> + <dd>속성과 관련된 값이 변경될 수 있는 경우에만 <code>true</code> (데이터 설명자만).</dd> + <dt><code>get</code></dt> + <dd>속성에 대해 getter로서 제공하는 함수 또는 getter가 없는 경우 {{jsxref("undefined")}} (접근자 설명자만).</dd> + <dt><code>set</code></dt> + <dd>속성에 대해 setter로서 제공하는 함수 또는 setter가 없는 경우 {{jsxref("undefined")}} (접근자 설명자만).</dd> + <dt><code>configurable</code></dt> + <dd>이 속성 설명자의 유형이 바뀔 수 있는 경우에만 그리고 속성이 해당 객체에서 삭제될 수 있는 경우 <code>true</code>.</dd> + <dt><code>enumerable</code></dt> + <dd>이 속성이 해당 객체의 속성 열거 중에 나타나는 경우에만 <code>true</code>.</dd> +</dl> + +<h2 id="예">예</h2> + +<pre class="brush: js">var o, d; + +o = { get foo() { return 17; } }; +d = Object.getOwnPropertyDescriptor(o, 'foo'); +// d는 { configurable: true, enumerable: true, get: /* getter 함수 */, set: undefined } + +o = { bar: 42 }; +d = Object.getOwnPropertyDescriptor(o, 'bar'); +// d는 { configurable: true, enumerable: true, value: 42, writable: true } + +o = {}; +Object.defineProperty(o, 'baz', { value: 8675309, writable: false, enumerable: false }); +d = Object.getOwnPropertyDescriptor(o, 'baz'); +// d는 { value: 8675309, writable: false, enumerable: false, configurable: false } +</pre> + +<h2 id="주의">주의</h2> + +<p>ES5에서, 이 메서드의 첫 번째 인수가 비객체(원시형)인 경우, 그러면 {{jsxref("TypeError")}}가 발생합니다. ES6에서, 비객체 첫 번째 인수는 먼저 객체로 강제됩니다.</p> + +<pre class="brush: js">Object.getOwnPropertyDescriptor("foo", 0); +// TypeError: "foo"는 객체가 아닙니다 // ES5 코드 + +Object.getOwnPropertyDescriptor("foo", 0); +// {configurable:false, enumerable:true, value:"f", writable:false} // ES6 코드 +</pre> + +<h2 id="스펙">스펙</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.3', 'Object.getOwnPropertyDescriptor')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>초기 정의. JavaScript 1.8.5에서 구현됨.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.getownpropertydescriptor', 'Object.getOwnPropertyDescriptor')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.getownpropertydescriptor', 'Object.getOwnPropertyDescriptor')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div> +<div> + + +<p>{{Compat("javascript.builtins.Object.getOwnPropertyDescriptor")}}</p> +</div> +</div> + +<p> </p> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("Object.defineProperty()")}}</li> + <li>{{jsxref("Reflect.getOwnPropertyDescriptor()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/object/getprototypeof/index.html b/files/ko/web/javascript/reference/global_objects/object/getprototypeof/index.html new file mode 100644 index 0000000000..12a65e24de --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/getprototypeof/index.html @@ -0,0 +1,134 @@ +--- +title: Object.getPrototypeOf() +slug: Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf +tags: + - ECMAScript5 + - JavaScript + - Method + - Object +translation_of: Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf +--- +<div>{{JSRef}}</div> + +<p><code><strong>Object.getPrototypeOf()</strong></code> 메서드는 지정된 객체의 프로토타입(가령 내부 <code>[[Prototype]]</code> 속성값)을 반환합니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code>Object.getPrototypeOf(<var>obj</var>)</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>자신의 프로토타입이 반환되는 객체.</dd> +</dl> + +<h2 id="예">예</h2> + +<pre class="brush: js">var proto = {}; +var obj = Object.create(proto); +Object.getPrototypeOf(obj) === proto; // true +</pre> + +<h2 id="주의">주의</h2> + +<p>ES5에서, <code>obj</code> 매개변수가 객체가 아닌 경우 {{jsxref("TypeError")}} 예외가 발생합니다. ES6에서, 매개변수는 {{jsxref("Object")}}로 강제됩니다.</p> + +<pre class="brush: js">Object.getPrototypeOf("foo"); +// TypeError: "foo"는 객체가 아닙니다 (ES5 코드) +Object.getPrototypeOf("foo"); +// String.prototype (ES6 코드) +</pre> + +<h2 id="스펙">스펙</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.2', 'Object.getPrototypeOf')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.getprototypeof', 'Object.getProtoypeOf')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.getprototypeof', 'Object.getProtoypeOf')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("5")}}</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>{{CompatIE("9")}}</td> + <td>{{CompatOpera("12.10")}}</td> + <td>{{CompatSafari("5")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Opera_전용_주의사항">Opera 전용 주의사항</h2> + +<p>이전 Opera 버전이 <code>Object.getPrototypeOf()</code>를 아직 지원하지 않지만, Opera는 Opera 10.50 이후로 비표준 {{jsxref("Object.proto", "__proto__")}} 속성을 지원합니다.</p> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("Object.prototype.isPrototypeOf()")}}</li> + <li>{{jsxref("Object.setPrototypeOf()")}}</li> + <li>{{jsxref("Object.prototype.__proto__")}}</li> + <li>John Resig의 <a class="external" href="http://ejohn.org/blog/objectgetprototypeof/">getPrototypeOf</a> 포스트</li> + <li>{{jsxref("Reflect.getPrototypeOf()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/object/hasownproperty/index.html b/files/ko/web/javascript/reference/global_objects/object/hasownproperty/index.html new file mode 100644 index 0000000000..40a544043c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/hasownproperty/index.html @@ -0,0 +1,146 @@ +--- +title: Object.prototype.hasOwnProperty() +slug: Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty +tags: + - JavaScript + - Method + - Object + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty +--- +<div>{{JSRef}}</div> + +<p><code><strong>hasOwnProperty()</strong></code> 메소드는 객체가 특정 프로퍼티를 가지고 있는지를 나타내는 불리언 값을 반환한다.</p> + +<div>{{EmbedInteractiveExample("pages/js/object-prototype-hasownproperty.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>obj</var>.hasOwnProperty(<var>prop</var>)</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>prop</code></dt> + <dd>테스트하려는 프로퍼티의 명칭</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p>모든 객체는 <code>hasOwnProperty</code> 를 상속하는 {{jsxref("Object")}}의 자식이다. 이 메소드는 객체가 특정 프로퍼티를 자기만의 직접적인 프로퍼티로서 소유하고 있는지를 판단하는데 사용된다. {{jsxref("Operators/in", "in")}} 연산과는 다르게, 이 메소드는 객체의 프로토타입 체인을 확인하지는 않는다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="프로퍼티의_존재_여부를_테스트하기_위한_hasOwnProperty의_사용">프로퍼티의 존재 여부를 테스트하기 위한 <code>hasOwnProperty</code>의 사용</h3> + +<p>다음은 o 객체가 prop라는 명칭을 지닌 프로퍼티를 포함하는지를 판단하는 예제이다.</p> + +<pre class="brush: js">o = new Object(); +o.prop = 'exists'; + +function changeO() { + o.newprop = o.prop; + delete o.prop; +} + +o.hasOwnProperty('prop'); // returns true +changeO(); +o.hasOwnProperty('prop'); // returns false +</pre> + +<h3 id="직접_프로퍼티와_상속된_프로퍼티의_비교">직접 프로퍼티와 상속된 프로퍼티의 비교</h3> + +<p>다음은 직접 프로퍼티와 프로토타입 체인에서 상속된 프로퍼티 간의 차이점을 비교하는 예제이다.</p> + +<pre class="brush: js">o = new Object(); +o.prop = 'exists'; +o.hasOwnProperty('prop'); // returns true +o.hasOwnProperty('toString'); // returns false +o.hasOwnProperty('hasOwnProperty'); // returns false +</pre> + +<h3 id="객체의_프로퍼티들을_순환하기">객체의 프로퍼티들을 순환하기</h3> + +<p>The following example shows how to iterate over the properties of an object without executing on inherit properties. Note that the {{jsxref("Statements/for...in", "for...in")}} loop is already only iterating enumerable items, so one should not assume based on the lack of non-enumerable properties shown in the loop that <code>hasOwnProperty</code> itself is confined strictly to enumerable items (as with {{jsxref("Object.getOwnPropertyNames()")}}).</p> + +<pre class="brush: js">var buz = { + fog: 'stack' +}; + +for (var name in buz) { + if (buz.hasOwnProperty(name)) { + console.log('this is fog (' + name + ') for sure. Value: ' + buz[name]); + } + else { + console.log(name); // toString or something else + } +} +</pre> + +<h3 id="프로퍼티의_명칭으로서_hasOwnProperty_를_사용하기">프로퍼티의 명칭으로서 <code>hasOwnProperty </code>를 사용하기</h3> + +<p>자바스크립트는 프로퍼티 명칭으로서 <code>hasOwnProperty</code>를 보호하지 않습니다. 그러므로, 이 명칭을 사용하는 프로퍼티를 가지는 객체가 존재하려면, 올바른 결과들을 얻기 위해서는 외부 <code>hasOwnProperty</code> 를 사용해야합니다.</p> + +<pre class="brush: js">var foo = { + hasOwnProperty: function() { + return false; + }, + bar: 'Here be dragons' +}; + +foo.hasOwnProperty('bar'); // always returns false + +// Use another Object's hasOwnProperty and call it with 'this' set to foo +({}).hasOwnProperty.call(foo, 'bar'); // true + +// It's also possible to use the hasOwnProperty property from the Object prototype for this purpose +Object.prototype.hasOwnProperty.call(foo, 'bar'); // true +</pre> + +<p>Note that in the last case there are no newly created objects.</p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">비고</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.5.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.4.5', 'Object.prototype.hasOwnProperty')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.prototype.hasownproperty', 'Object.prototype.hasOwnProperty')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Object.hasOwnProperty")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/en-US/docs/Enumerability_and_ownership_of_properties">Enumerability and ownership of properties</a></li> + <li>{{jsxref("Object.getOwnPropertyNames()")}}</li> + <li>{{jsxref("Statements/for...in", "for...in")}}</li> + <li>{{jsxref("Operators/in", "in")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Inheritance_Revisited">JavaScript Guide: Inheritance revisited</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/object/index.html b/files/ko/web/javascript/reference/global_objects/object/index.html new file mode 100644 index 0000000000..ce7e6c6603 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/index.html @@ -0,0 +1,177 @@ +--- +title: Object +slug: Web/JavaScript/Reference/Global_Objects/Object +tags: + - Constructor + - JavaScript + - Object + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Object +--- +<div>{{JSRef}}</div> + +<p><strong><code>Object</code></strong> 생성자는 객체 래퍼(wrapper)를 생성합니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">// 객체 초기자 또는 리터럴 +{ [ <var>nameValuePair1</var>[, <var>nameValuePair2</var>[, ...<var>nameValuePairN</var>] ] ] } + +// 생성자 +new Object([<var>value</var>])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>nameValuePair1, nameValuePair2, ... nameValuePair<em>N</em></code></dt> + <dd>콜론으로 나뉘어져 있는 키(문자열)와 값(어떤 값이나 가능)의 쌍.</dd> + <dt><code>value</code></dt> + <dd>아무 값.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p><code>Object</code> 생성자는 주어진 값의 객체 래퍼를 생성합니다. 주어진 값이 {{jsxref("null")}}이거나 {{jsxref("undefined")}}면 빈 객체를 생성해 반환하고, 그렇지 않으면 값에 맞는 자료형의 객체를 반환합니다. 만약 값이 이미 객체이면 그 값을 그대로 반환합니다.</p> + +<p>생성자가 아닌 맥락에서 호출하면 <code>Object</code>는 <code>new Object()</code>와 동일하게 동작합니다.</p> + +<p><a href="/ko/docs/Web/JavaScript/Reference/Operators/Object_initializer">객체 초기자(리터럴 구문)</a>도 참고하세요.</p> + +<h2 id="Object_생성자의_속성"><code>Object</code> 생성자의 속성</h2> + +<dl> + <dt><code>Object.length</code></dt> + <dd>1의 값을 가집니다.</dd> +</dl> + +<dl> + <dt>{{jsxref("Object.prototype")}}</dt> + <dd><code>Object</code> 형의 모든 객체에 속성을 추가할 수 있습니다.</dd> +</dl> + +<h2 id="Object_생성자의_메서드"><code>Object</code> 생성자의 메서드</h2> + +<dl> + <dt>{{jsxref("Object.assign()")}}</dt> + <dd>하나 이상의 원본 객체들로부터 모든 열거가능한 속성들을 대상 객체로 복사합니다.</dd> + <dt>{{jsxref("Object.create()")}}</dt> + <dd>주어진 프로토타입(prototype)의 객체와 속성들을 갖고 있는 새 객체를 생성합니다.</dd> + <dt>{{jsxref("Object.defineProperty()")}}</dt> + <dd>주어진 기술자(descriptor)에 의해 기술된(described) 이름붙은 속성을 객체에 추가합니다.</dd> + <dt>{{jsxref("Object.defineProperties()")}}</dt> + <dd>주어진 기술자들에 맞는 이름붙은 속성들을 객체에 추가합니다.</dd> + <dt>{{jsxref("Object.freeze()")}}</dt> + <dd>객체를 프리징(freeze)합니다. 즉, 다른 곳의 코드에서 객체의 속성을 지우거나 바꿀 수 없습니다.</dd> + <dt>{{jsxref("Object.getOwnPropertyDescriptor()")}}</dt> + <dd>객체의 이름붙은 속성의 기술자를 반환합니다.</dd> + <dt>{{jsxref("Object.getOwnPropertyNames()")}}</dt> + <dd>주어진 객체 <strong>자신만의</strong> 열거가능하거나 열거불가능한 속성들의 이름을 포함하는 배열(array)을 반환합니다.</dd> + <dt>{{jsxref("Object.getOwnPropertySymbols()")}}</dt> + <dd>주어진 객체에서 바로 찾을 수 있는 모든 심볼 속성을 배열로 반환합니다.</dd> + <dt>{{jsxref("Object.getPrototypeOf()")}}</dt> + <dd>명시된 객체의 프로토타입을 반환.</dd> + <dt>{{jsxref("Object.is()")}}</dt> + <dd>두 값이 같은지를 비교합니다. 모든 NaN 값은 같다고 처리됩니다.(다른 추상적 또는 엄격한 등호 비교에서는 다르게 처리됩니다)</dd> + <dt>{{jsxref("Object.isExtensible()")}}</dt> + <dd>객체의 확장이 가능한지 확인합니다.</dd> + <dt>{{jsxref("Object.isFrozen()")}}</dt> + <dd>객체가 프리징 되었는지 확인합니다.</dd> + <dt>{{jsxref("Object.isSealed()")}}</dt> + <dd>객체가 실링(seal) 되었는지 확인합니다.</dd> + <dt>{{jsxref("Object.keys()")}}</dt> + <dd>주어진 객체 <strong>자신의 </strong>열거가능한 속성들의 이름의 배열을 반환합니다.</dd> + <dt>{{jsxref("Object.preventExtensions()")}}</dt> + <dd>객체가 확장되는 것을 못하도록 합니다.</dd> + <dt>{{jsxref("Object.seal()")}}</dt> + <dd>다른 코드가 객체의 속성을 삭제하지 못하도록 합니다.</dd> + <dt>{{jsxref("Object.setPrototypeOf()")}}</dt> + <dd>프로토타입(즉, 내부의 <code>[[Prototype]]</code> 속성)을 설정합니다.</dd> +</dl> + +<dl> + <dt>{{jsxref("Object.values()")}}</dt> + <dd>주어진 객체의 열거가능한 모든 스트링 속성들의 값들을 포함하고 있는 배열을 반환합니다.</dd> +</dl> + +<h2 id="Object_instances" name="Object_instances"><code>Object</code> 인스턴스와 <code>Object</code> 프로토타입 객체</h2> + +<p>JavaScript에서 모든 객체들은 <code>Object</code>의 자손입니다. 모든 객체는 {{jsxref("Object.prototype")}}으로부터 메서드와 속성을 상속하는데, 나중에 덮어 쓸 수도 있습니다. 예를 들어, 다른 생성자의 프로토타입은 그 <code>constructor</code> 속성을 덮어쓰고 자신의 <code>toString()</code> 메소드들을 제공합니다. <code>Object</code> 프로토타입 객체에 대한 변경 내용은 그 변경 내용에 영향을 받는 속성들과 메소드들이 프로토타입 체인(chain)을 따라 더이상 무시되지 않는한, 모든 객체들로 전달됩니다.</p> + +<h3 id="속성">속성</h3> + +<div>{{page('/ko/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', '속성') }}</div> + +<h3 id="메서드">메서드</h3> + +<div>{{page('/ko/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', '메서드') }}</div> + +<h2 id="Examples" name="Examples">예제</h2> + +<h3 id="Example.3A_Using_Object_given_undefined_and_null_types" name="Example.3A_Using_Object_given_undefined_and_null_types"><code>undefined</code>와 <code>null</code>을 지정</h3> + +<p>다음 예제는 변수 <code>o</code>에 빈 <code>Object</code> 객체를 저장합니다.</p> + +<pre class="brush: js">var o = new Object(); +</pre> + +<pre class="brush: js">var o = new Object(undefined); +</pre> + +<pre class="brush: js">var o = new Object(null); +</pre> + +<h3 id="Object로_Boolean_객체_생성하기"><code>Object</code>로 <code>Boolean</code> 객체 생성하기</h3> + +<p>다음 예제는 변수 <code>o</code>에 {{jsxref("Boolean")}} 객체를 저장합니다.</p> + +<pre class="brush: js">// o = new Boolean(true)과 같음 +var o = new Object(true); +</pre> + +<pre class="brush: js">// o = new Boolean(false)과 같음 +var o = new Object(Boolean()); +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>ECMAScript 1st Edition.</td> + <td>Standard</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2', 'Object')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object-objects', 'Object')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Added Object.assign, Object.getOwnPropertySymbols, Object.setPrototypeOf, Object.is</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object-objects', 'Object')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Added Object.entries, Object.values and Object.getOwnPropertyDescriptors.</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Object")}}</p> + +<h2 id="See_also" name="See_also">같이 보기</h2> + +<ul> + <li><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Object_initializer">Object initializer</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/object/is/index.html b/files/ko/web/javascript/reference/global_objects/object/is/index.html new file mode 100644 index 0000000000..2ead91a88a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/is/index.html @@ -0,0 +1,124 @@ +--- +title: Object.is() +slug: Web/JavaScript/Reference/Global_Objects/Object/is +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Object + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Object/is +--- +<div>{{JSRef}}</div> + +<p><code><strong>Object.is()</strong></code> 메서드는 두 값이 <a href="/ko/docs/Web/JavaScript/Equality_comparisons_and_sameness">같은 값</a>인지 결정합니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code>Object.is(<var>value1</var>, <var>value2</var>);</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>value1</code></dt> + <dd>비교할 첫 번째 값.</dd> + <dt><code>value2</code></dt> + <dd>비교할 두 번째 값.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>두 인수가 같은 값인지 여부를 나타내는 {{jsxref("Boolean")}}.</p> + +<h2 id="설명">설명</h2> + +<p><code>Object.is()</code>는 두 값이 <a href="/ko/docs/Web/JavaScript/Equality_comparisons_and_sameness">같은 값</a>인지 결정합니다. 다음 중 하나를 만족하면 두 값은 같습니다.</p> + +<ul> + <li>둘 다 {{jsxref("undefined")}}</li> + <li>둘 다 {{jsxref("null")}}</li> + <li>둘 다 <code>true</code> 또는 둘 다 <code>false</code></li> + <li>둘 다 같은 문자에 같은 길이인 문자열</li> + <li>둘 다 같은 객체</li> + <li>둘 다 숫자이며 + <ul> + <li>둘 다 <code>+0</code></li> + <li>둘 다 <code>-0</code></li> + <li>둘 다 {{jsxref("NaN")}}</li> + <li>둘 다 0이나 {{jsxref("NaN")}}이 아니고 같은 값을 지님</li> + </ul> + </li> +</ul> + +<p>이는 {{jsxref("Operators/Comparison_Operators", "==", "#Equality")}} 연산자에 따른 같음과 같지 <em>않습니다</em>. {{jsxref("Operators/Comparison_Operators", "==", "#Equality")}} 연산자는 같음을 테스트하기 전에 양 쪽(이 같은 형이 아니라면)에 다양한 강제(coercion)를 적용하지만(<code>"" == false</code>가 <code>true</code>가 되는 그런 행동을 초래), <code>Object.is</code>는 어느 값도 강제하지 않습니다.</p> + +<p>이는 {{jsxref("Operators/Comparison_Operators", "===", "#Identity")}} 연산자에 따른 같음과도 같지 <em>않습니다</em>. {{jsxref("Operators/Comparison_Operators", "===", "#Identity")}} 연산자(와 {{jsxref("Operators/Comparison_Operators", "==", "#Equality")}} 연산자 역시)는 숫자값 <code>-0</code>과 <code>+0</code>을 같게 {{jsxref("Number.NaN")}}은 {{jsxref("NaN")}}과 같지 않게 여깁니다.</p> + +<h2 id="예제">예제</h2> + +<pre class="brush: js">Object.is('foo', 'foo'); // true +Object.is(window, window); // true + +Object.is('foo', 'bar'); // false +Object.is([], []); // false + +var test = { a: 1 }; +Object.is(test, test); // true + +Object.is(null, null); // true + +// 특별한 경우 +Object.is(0, -0); // false +Object.is(-0, -0); // true +Object.is(NaN, 0/0); // true +</pre> + +<h2 id="폴리필">폴리필</h2> + +<pre class="brush: js">if (!Object.is) { + Object.is = function(x, y) { + // SameValue 알고리즘 + if (x === y) { // Steps 1-5, 7-10 + // Steps 6.b-6.e: +0 != -0 + return x !== 0 || 1 / x === 1 / y; + } else { + // Step 6.a: NaN == NaN + return x !== x && y !== y; + } + }; +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.is', 'Object.is')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.is', 'Object.is')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Object.is")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Equality_comparisons_and_sameness">같음 비교 및 똑같음</a> — 똑같음 내장 기능 3가지 모두 비교</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/object/isextensible/index.html b/files/ko/web/javascript/reference/global_objects/object/isextensible/index.html new file mode 100644 index 0000000000..bfe247c6e8 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/isextensible/index.html @@ -0,0 +1,110 @@ +--- +title: Object.isExtensible() +slug: Web/JavaScript/Reference/Global_Objects/Object/isExtensible +tags: + - ECMAScript 5 + - JavaScript + - Method + - Object +translation_of: Web/JavaScript/Reference/Global_Objects/Object/isExtensible +--- +<div>{{JSRef}}</div> + +<p><strong><code>Object.isExtensible()</code></strong> 메서드는 객체가 확장 가능한지(객체에 새 속성을 추가할 수 있는지 여부)를 결정합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/object-isextensible.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code>Object.isExtensible(<var>obj</var>)</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>판별할 객체.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>객체의 확장 가능 여부를 나타내는 {{jsxref("Boolean")}}.</p> + +<h2 id="설명">설명</h2> + +<p>객체는 기본으로 확장 가능입니다: 새로운 속성이 추가될 수 있고 ({{jsxref("Object.proto", "__proto__")}} {{deprecated_inline}} 속성을 지원하는 엔진에서는) 수정될 수 있습니다. 객체는 {{jsxref("Object.preventExtensions()")}}, {{jsxref("Object.seal()")}} 또는 {{jsxref("Object.freeze()")}}를 사용하여 확장 불가로 표시될 수 있습니다.</p> + +<h2 id="예제">예제</h2> + +<pre class="brush: js">// 새로운 객체는 확장 가능입니다. +var empty = {}; +Object.isExtensible(empty); // === true + +// ...하지만 변경될 수 있습니다. +Object.preventExtensions(empty); +Object.isExtensible(empty); // === false + +// 봉인된 객체는 정의에 의해 확장 불가입니다. +var sealed = Object.seal({}); +Object.isExtensible(sealed); // === false + +// 동결된 객체 또한 정의에 의해 확장 불가입니다. +var frozen = Object.freeze({}); +Object.isExtensible(frozen); // === false +</pre> + +<h2 id="주의">주의</h2> + +<p>ES5에서, 이 메서드의 인수가 비객체(원시형)인 경우, 그러면 {{jsxref("TypeError")}}가 발생합니다. ES6에서, 비객체 인수는 확장 불가인 보통 객체처럼 다뤄집니다, 그저 <code>false</code>를 반환하는.</p> + +<pre class="brush: js">Object.isExtensible(1); +// TypeError: 1은 객체가 아닙니다 (ES5 코드) + +Object.isExtensible(1); +// false (ES6 코드) +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.13', 'Object.isExtensible')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>초기 정의. JavaScript 1.8.5에서 구현됨.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.isextensible', 'Object.isExtensible')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.isextensible', 'Object.isExtensible')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Object.isExtensible")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Object.preventExtensions()")}}</li> + <li>{{jsxref("Object.seal()")}}</li> + <li>{{jsxref("Object.isSealed()")}}</li> + <li>{{jsxref("Object.freeze()")}}</li> + <li>{{jsxref("Object.isFrozen()")}}</li> + <li>{{jsxref("Reflect.isExtensible()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/object/isfrozen/index.html b/files/ko/web/javascript/reference/global_objects/object/isfrozen/index.html new file mode 100644 index 0000000000..0d8999fc4f --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/isfrozen/index.html @@ -0,0 +1,155 @@ +--- +title: Object.isFrozen() +slug: Web/JavaScript/Reference/Global_Objects/Object/isFrozen +tags: + - ECMAScript 5 + - JavaScript + - Method + - Object + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Object/isFrozen +--- +<div>{{JSRef}}</div> + +<p><code><strong>Object.isFrozen()</strong></code>은 객체가 {{jsxref("Object.freeze()", "동결", "", 1)}}됐는지 판별합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/object-isfrozen.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code>Object.isFrozen(<var>obj</var>)</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>판별할 객체.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>객체의 동결 여부를 나타내는 {{jsxref("Boolean")}}.</p> + +<h2 id="설명">설명</h2> + +<p>객체는 {{jsxref("Object.isExtensible()", "확장 불가", "", 1)}}이며 모든 속성이 설정 불가 및 모든 데이터 속성(즉, getter 또는 setter 요소가 있는 접근자 속성이 아닌 속성)이 쓰기 불가인 경우에만 동결됩니다.</p> + +<h2 id="예제">예제</h2> + +<pre class="brush: js">// 새로운 객체는 확장 가능해서 동결되지 않습니다. +Object.isFrozen({}); // === false + +// 확장 불가인 빈 객체는 빈 채로 동결됩니다. +var vacuouslyFrozen = Object.preventExtensions({}); +Object.isFrozen(vacuouslyFrozen); // === true + +// 속성이 하나 있는 새 객체도 확장 가능하므로 동결되지 않습니다. +var oneProp = { p: 42 }; +Object.isFrozen(oneProp); // === false + +// 객체 확장을 막아도 여전히 동결되지 않습니다, +// 속성이 여전히 설정 가능(및 쓰기 가능)하기에. +Object.preventExtensions(oneProp); +Object.isFrozen(oneProp); // === false + +// ...그렇지만 그 속성 삭제는 객체를 빈 채로 동결되게 합니다. +delete oneProp.p; +Object.isFrozen(oneProp); // === true + +// 쓰기 불가지만 여전히 설정 가능한 속성이 있는 확장 불가 객체는 동결되지 않습니다. +var nonWritable = { e: 'plep' }; +Object.preventExtensions(nonWritable); +Object.defineProperty(nonWritable, 'e', { writable: false }); // 쓰기 불가로 함 +Object.isFrozen(nonWritable); // === false + +// 그 속성을 설정 불가로 바꾸면 객체를 동결되게 합니다. +Object.defineProperty(nonWritable, 'e', { configurable: false }); // 설정 불가로 함 +Object.isFrozen(nonWritable); // === true + +// 설정 불가지만 여전히 쓰기 가능 속성이 있는 확장 불가 객체도 동결되지 않습니다. +var nonConfigurable = { release: 'the kraken!' }; +Object.preventExtensions(nonConfigurable); +Object.defineProperty(nonConfigurable, 'release', { configurable: false }); +Object.isFrozen(nonConfigurable); // === false + +// 그 속성을 쓰기 불가로 바꾸면 객체를 동결되게 합니다. +Object.defineProperty(nonConfigurable, 'release', { writable: false }); +Object.isFrozen(nonConfigurable); // === true + +// 설정 가능 접근자 속성이 있는 확장 불가 객체는 동결되지 않습니다. +var accessor = { get food() { return 'yum'; } }; +Object.preventExtensions(accessor); +Object.isFrozen(accessor); // === false + +// ...하지만 그 속성을 설정 불가로 하면 동결됩니다. +Object.defineProperty(accessor, 'food', { configurable: false }); +Object.isFrozen(accessor); // === true + +// 하지만 동결되는 객체를 위한 가장 쉬운 방법은 객체에 Object.freeze가 호출된 경우입니다. +var frozen = { 1: 81 }; +Object.isFrozen(frozen); // === false +Object.freeze(frozen); +Object.isFrozen(frozen); // === true + +// 정의에 의해, 동결된 객체는 확장 불가입니다. +Object.isExtensible(frozen); // === false + +// 또한 정의에 의해, 동결된 객체는 봉인됩니다. +Object.isSealed(frozen); // === true +</pre> + +<h2 id="주의">주의</h2> + +<p>ES5에서, 이 메서드의 인수가 비객체(원시형)인 경우, 그러면 {{jsxref("TypeError")}}가 발생합니다. ES6에서, 비객체 인수는 마치 동결된 보통 객체였던 것처럼 취급됩니다, 그저 <code>true</code>를 반환하는.</p> + +<pre class="brush: js">Object.isFrozen(1); +// TypeError: 1은 객체가 아닙니다 (ES5 코드) + +Object.isFrozen(1); +// true (ES6 코드) +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.12', 'Object.isFrozen')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>초기 정의. JavaScript 1.8.5에서 구현됨.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.isfrozen', 'Object.isFrozen')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.isfrozen', 'Object.isFrozen')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Object.isFrozen")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Object.freeze()")}}</li> + <li>{{jsxref("Object.preventExtensions()")}}</li> + <li>{{jsxref("Object.isExtensible()")}}</li> + <li>{{jsxref("Object.seal()")}}</li> + <li>{{jsxref("Object.isSealed()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/object/isprototypeof/index.html b/files/ko/web/javascript/reference/global_objects/object/isprototypeof/index.html new file mode 100644 index 0000000000..0e9de96b41 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/isprototypeof/index.html @@ -0,0 +1,111 @@ +--- +title: Object.prototype.isPrototypeOf() +slug: Web/JavaScript/Reference/Global_Objects/Object/isPrototypeOf +tags: + - JavaScript + - Method + - Object + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Object/isPrototypeOf +--- +<div>{{JSRef}}</div> + +<p><code><strong>isPrototypeOf()</strong></code> 메소드는 해당 객체가 다른 객체의 프로토타입 체인에 속한 객체인지 확인하기 위해 사용됩니다.</p> + +<div class="note"> +<p><strong>Note:</strong> <code>isPrototypeOf</code> 는 {{jsxref("Operators/instanceof", "instanceof")}} 연산자와 다릅니다. "<code>object instanceof AFunction</code>"표현식에서는 <code>object</code>의 프로토타입 체인을 AFunction 자체가 아니라 <code>AFunction.prototype에 대해 </code>확인을 합니다.</p> +</div> + +<h2 id="Syntax" name="Syntax">구문</h2> + +<pre class="syntaxbox"><var>prototypeObj</var>.isPrototypeOf(<var>obj</var>)</pre> + +<h3 id="Parameters" name="Parameters">매개변수</h3> + +<dl> + <dt><code>object</code></dt> + <dd>프로토타입 체인을 가지고 있는 객체가 검색될 것 입니다.</dd> +</dl> + +<h2 id="Description" name="Description">설명</h2> + +<p><code>isPrototypeOf</code> 메소드는 또 다른 객체의 프로토타입 체인에 해당 객체가 존재하는지 여부를 확인할수 있습니다.</p> + +<p>예를들어, 다음의 프로토타입체인을 고려해봅시다.</p> + +<pre class="brush: js">function Fee() { + // ... +} + +function Fi() { + // ... +} +Fi.prototype = new Fee(); + +function Fo() { + // ... +} +Fo.prototype = new Fi(); + +function Fum() { + // ... +} +Fum.prototype = new Fo(); +</pre> + +<p>실행되고 나면 <strong>Fum</strong> 인스턴스의 프로토타입체인이 <strong>Fi</strong>의 프로토타입과 연결되어있는지를 확인할 필요가 있습니다. 다음과 같은 방법으로 확인할 수 있습니다:</p> + +<pre class="brush: js">var fum = new Fum(); +// ... + +if (Fi.prototype.isPrototypeOf(fum)) { + // do something safe +} +</pre> + +<p>이 메소드는 {{jsxref("Operators/instanceof", "instanceof")}} 연산자와 함께 특정 프로토타입으로부터 상속된 객체만 작동하게 하려는(예를 들어 특정 메소드나 속성이 객체에 있다는걸 보장하려는 때) 코드에서 특히 쓸모가 많다.</p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>ECMAScript 3rd Edition.</td> + <td>Standard</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.4.5', 'Object.prototype.hasOwnProperty')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.prototype.hasownproperty', 'Object.prototype.hasOwnProperty')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Object.isPrototypeOf")}}</p> + +<h2 id="See_also" name="See_also">같이 보기</h2> + +<ul> + <li>{{jsxref("Operators/instanceof", "instanceof")}}</li> + <li>{{jsxref("Object.getPrototypeOf()")}}</li> + <li> + <div><span style="font-size: 14px; line-height: 1.5;">{{jsxref("Object.setPrototypeOf()")}}</span></div> + </li> + <li>{{jsxref("Object.prototype.__proto__")}} </li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/object/issealed/index.html b/files/ko/web/javascript/reference/global_objects/object/issealed/index.html new file mode 100644 index 0000000000..38fc953828 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/issealed/index.html @@ -0,0 +1,128 @@ +--- +title: Object.isSealed() +slug: Web/JavaScript/Reference/Global_Objects/Object/isSealed +tags: + - ECMAScript 5 + - JavaScript + - Method + - Object + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Object/isSealed +--- +<div>{{JSRef}}</div> + +<p><code><strong>Object.isSealed()</strong></code> 메서드는 객체가 봉인됐는지 판별합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/object-issealed.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code>Object.isSealed(<var>obj</var>)</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>판별할 객체.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>객체의 봉인 여부를 나타내는 {{jsxref("Boolean")}}.</p> + +<h2 id="설명">설명</h2> + +<p>객체가 봉인된 경우 <code>true</code>를 반환하고, 그렇지 않으면 <code>false</code>. 객체는 {{jsxref("Object.isExtensible", "확장 불가", "", 1)}}이고 모든 속성이 설정 불가이며 따라서 삭제할 수 없(지만 반드시 쓰기 불가일 필요는 없)는 경우 봉인됩니다.</p> + +<h2 id="예제">예제</h2> + +<pre class="brush: js">// 객체는 기본으로 봉인되지 않습니다. +var empty = {}; +Object.isSealed(empty); // === false + +// 빈 객체를 확장 불가하게 한 경우, 빈 채로 봉인됩니다. +Object.preventExtensions(empty); +Object.isSealed(empty); // === true + +// 비어 있지 않은 객체는 다릅니다, 그 속성이 모두 설정 불가가 아닌 한. +var hasProp = { fee: 'fie foe fum' }; +Object.preventExtensions(hasProp); +Object.isSealed(hasProp); // === false + +// 그러나 모두 설정 불가하게 하면 객체는 봉인됩니다. +Object.defineProperty(hasProp, 'fee', { configurable: false }); +Object.isSealed(hasProp); // === true + +// 객체를 봉인하는 가장 쉬운 방법은 물론 Object.seal 입니다. +var sealed = {}; +Object.seal(sealed); +Object.isSealed(sealed); // === true + +// 봉인된 객체는 정의에 의해 확장 불가입니다. +Object.isExtensible(sealed); // === false + +// 봉인된 객체는 동결될 수 있지만 꼭 그럴 필요는 없습니다. +Object.isFrozen(sealed); // === true (모든 속성도 쓰기 불가) + +var s2 = Object.seal({ p: 3 }); +Object.isFrozen(s2); // === false ('p'는 여전히 쓰기 가능) + +var s3 = Object.seal({ get p() { return 0; } }); +Object.isFrozen(s3); // === true (설정 가능성만이 접근자 속성에게 중요함) +</pre> + +<h2 id="주의">주의</h2> + +<p>ES5에서, 이 메서드의 인수가 비객체(원시형)인 경우, 그러면 {{jsxref("TypeError")}}가 발생합니다. ES6에서, 비객체 인수는 마치 봉인된 보통 객체였던 것처럼 취급됩니다, 그저 <code>true</code>를 반환하는.</p> + +<pre class="brush: js">Object.isSealed(1); +// TypeError: 1은 객체가 아닙니다 (ES5 코드) + +Object.isSealed(1); +// true (ES6 코드) +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.11', 'Object.isSealed')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>초기 정의. JavaScript 1.8.5에서 구현됨.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.issealed', 'Object.isSealed')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.issealed', 'Object.isSealed')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Object.isSealed")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Object.seal()")}}</li> + <li>{{jsxref("Object.preventExtensions()")}}</li> + <li>{{jsxref("Object.isExtensible()")}}</li> + <li>{{jsxref("Object.freeze()")}}</li> + <li>{{jsxref("Object.isFrozen()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/object/observe/index.html b/files/ko/web/javascript/reference/global_objects/object/observe/index.html new file mode 100644 index 0000000000..bf3b004d8c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/observe/index.html @@ -0,0 +1,193 @@ +--- +title: Object.observe() +slug: Web/JavaScript/Reference/Global_Objects/Object/observe +tags: + - 감시 객체 +translation_of: Archive/Web/JavaScript/Object.observe +--- +<div>{{JSRef}}</div> + +<p><strong><code>Object.observe()</code></strong> 메소드는 객체의 변화를 비동기로 감시하는데에 사용된다. 이 메소드는 변화들이 발생한 순서대로 그 흐름을 제공한다.</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox"><code>Object.observe(<var>obj</var>, <var>callback</var>[, <var>acceptList</var>])</code></pre> + +<h3 id="파라미터">파라미터</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>감시될 객체입니다.</dd> + <dt><code>callback</code></dt> + <dd><code>obj</code>의 변경이 일어났을 때마다 호출될 함수입니다. 다음과 같은 인자를 갖습니다. + <dl> + <dt><code>changes</code></dt> + <dd>변경 사항을 나타내는 객체의 배열입니다. 그 객체의 프로퍼티는 다음과 같습니다. + <ul> + <li><strong><code>name</code></strong>: 변경된 프로퍼티의 이름입니다.</li> + <li><strong><code>object</code></strong>: 변경이 일어난 뒤의 객체입니다.</li> + <li><strong><code>type</code></strong>: 변경의 종류를 의미하는 string입니다. <code>"add"</code>, <code>"update"</code>, <code>"delete"</code> 중 하나입니다.</li> + <li><strong><code>oldValue</code></strong>: 변경되기 이전의 값입니다. <code>"update"와</code> <code>"delete"</code> 타입에만 존재합니다.</li> + </ul> + </dd> + </dl> + </dd> + <dt><code>acceptList</code></dt> + <dd>감시할 변경의 종류를 의미하는 리스트입니다. 주어지지 않은 경우, 배열 <code>["add", "update", "delete", "reconfigure", "setPrototype", "preventExtensions"]</code> 이 이용될 것입니다.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p><code>callback</code>은 <code>obj</code>에 변경이 있을 때마다 실행되며, 모든 변경 사항이 일어난 순서대로 담긴 배열이 전달됩니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="Logging_all_six_different_types">Logging all six different types</h3> + +<pre class="brush: js">var obj = { + foo: 0, + bar: 1 +}; + +Object.observe(obj, function(changes) { + console.log(changes); +}); + +obj.baz = 2; +// [{name: 'baz', object: <obj>, type: 'add'}] + +obj.foo = 'hello'; +// [{name: 'foo', object: <obj>, type: 'update', oldValue: 0}] + +delete obj.baz; +// [{name: 'baz', object: <obj>, type: 'delete', oldValue: 2}] + +Object.defineProperty(obj, 'foo', {writable: false}); +// [{name: 'foo', object: <obj>, type: 'reconfigure'}] + +Object.setPrototypeOf(obj, {}); +// [{name: '__proto__', object: <obj>, type: 'setPrototype', oldValue: <prototype>}] + +Object.seal(obj); +// [ +// {name: 'foo', object: <obj>, type: 'reconfigure'}, +// {name: 'bar', object: <obj>, type: 'reconfigure'}, +// {object: <obj>, type: 'preventExtensions'} +// ] +</pre> + +<h3 id="데이터_바인딩">데이터 바인딩</h3> + +<pre class="brush: js">// A user model +var user = { + id: 0, + name: 'Brendan Eich', + title: 'Mr.' +}; + +// Create a greeting for the user +function updateGreeting() { + user.greeting = 'Hello, ' + user.title + ' ' + user.name + '!'; +} +updateGreeting(); + +Object.observe(user, function(changes) { + changes.forEach(function(change) { + // Any time name or title change, update the greeting + if (change.name === 'name' || change.name === 'title') { + updateGreeting(); + } + }); +}); +</pre> + +<h3 id="Custom_change_type">Custom change type</h3> + +<pre class="brush: js">// A point on a 2D plane +var point = {x: 0, y: 0, distance: 0}; + +function setPosition(pt, x, y) { + // Performing a custom change + Object.getNotifier(pt).performChange('reposition', function() { + var oldDistance = pt.distance; + pt.x = x; + pt.y = y; + pt.distance = Math.sqrt(x * x + y * y); + return {oldDistance: oldDistance}; + }); +} + +Object.observe(point, function(changes) { + console.log('Distance change: ' + (point.distance - changes[0].oldDistance)); +}, ['reposition']); + +setPosition(point, 3, 4); +// Distance change: 5 +</pre> + +<h2 id="Specifications">Specifications</h2> + +<p><a href="https://github.com/arv/ecmascript-object-observe">Strawman proposal for ECMAScript 7</a>.</p> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("36")}}</td> + <td>{{CompatNo}} [1]</td> + <td>{{CompatNo}} [2]</td> + <td>{{CompatOpera("23")}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome("36")}}</td> + <td>{{CompatNo}} [1]</td> + <td>{{CompatNo}} [2]</td> + <td>{{CompatOpera("23")}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1]: See {{bug(800355)}}</p> + +<p>[2]: See relevant <a href="https://dev.modern.ie/platform/status/objectobserve/">MS Edge platform status entry</a></p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Object.unobserve()")}} {{experimental_inline}}</li> + <li>{{jsxref("Array.observe()")}} {{experimental_inline}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/object/preventextensions/index.html b/files/ko/web/javascript/reference/global_objects/object/preventextensions/index.html new file mode 100644 index 0000000000..b23c6f33e6 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/preventextensions/index.html @@ -0,0 +1,126 @@ +--- +title: Object.preventExtensions() +slug: Web/JavaScript/Reference/Global_Objects/Object/preventExtensions +tags: + - ECMAScript 5 + - JavaScript + - Method + - Object + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Object/preventExtensions +--- +<div>{{JSRef}}</div> + +<p><code><strong>Object.preventExtensions()</strong></code> 메서드는 새로운 속성이 이제까지 객체에 추가되는 것을 방지합니다 (즉 객체의 장래 확장을 막습니다).</p> + +<div>{{EmbedInteractiveExample("pages/js/object-preventextensions.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">Object.preventExtensions(<var>obj</var>)</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>확장 불가로 해야 할 객체.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p>객체는 새로운 속성이 추가될 수 있는 경우 확장 가능입니다. <code>Object.preventExtensions()</code>는 객체를 이제 확장 불가로 표시하므로 표시된 그 시점에 있던 것 이외의 속성을 갖지 않습니다. 보통 확장 불가인 객체의 속성은 여전히 <em>삭제될</em> 수 있음을 주의하세요. 확장 불가인 객체에 새로운 속성을 추가하려는 시도는 실패합니다, 조용히든 {{jsxref("TypeError")}}가 발생해서든 (가장 흔하나 오로지 {{jsxref("Functions_and_function_scope/Strict_mode", "엄격 모드", "", 1)}}인 경우에서만은 아님).</p> + +<p><code>Object.preventExtensions()</code>는 자신의 속성 추가만을 방지합니다. 속성은 여전히 객체의 프로토타입에 추가될 수 있습니다. 그러나, 객체에 <code>Object.preventExtensions()</code>를 호출하면 그 {{jsxref("Object.proto", "__proto__")}} {{deprecated_inline}} 속성의 확장 또한 막습니다.</p> + +<p>ECMAScript 5에서 확장 가능 객체를 확장 불가로 바꾸는 법이 있더라도, 반대로 하는 법은 없습니다.</p> + +<h2 id="예제">예제</h2> + +<pre class="brush: js">// Object.preventExtensions는 확장 불가된 객체를 반환합니다. +var obj = {}; +var obj2 = Object.preventExtensions(obj); +obj === obj2; // true + +// 객체는 기본으로 확장 가능입니다. +var empty = {}; +Object.isExtensible(empty); // === true + +// ...하지만 바뀔 수 있습니다. +Object.preventExtensions(empty); +Object.isExtensible(empty); // === false + +// Object.defineProperty는 확장 불가 객체에 새 속성을 추가할 때 오류가 발생합니다. +var nonExtensible = { removable: true }; +Object.preventExtensions(nonExtensible); +Object.defineProperty(nonExtensible, 'new', { value: 8675309 }); // TypeError 발생 + +// 엄격 모드에서, 확장 불가 객체에 새 속성을 추가하려는 시도는 TypeError가 발생합니다. +function fail() { + 'use strict'; + nonExtensible.newProperty = 'FAIL'; // TypeError 발생 +} +fail(); + +// 확장 (__proto__(는 사라집니다. 대신 Object.getPrototypeOf를 쓰세요)를 +// 지원하는 엔진에서만 동작합니다): +// 확장 불가 객체의 프로토타입은 불변합니다. +var fixed = Object.preventExtensions({}); +fixed.__proto__ = { oh: 'hai' }; // TypeError 발생 +</pre> + +<h2 id="참고">참고</h2> + +<p>ES5에서, 이 메서드의 인수가 비객체(원시형)인 경우, 그러면 {{jsxref("TypeError")}}가 발생합니다. ES6에서, 비객체 인수는 마치 확장 불가인 보통 객체였던 것처럼 취급됩니다, 그저 자신을 반환하는.</p> + +<pre class="brush: js">Object.preventExtensions(1); +// TypeError: 1은 객체가 아닙니다 (ES5 코드) + +Object.preventExtensions(1); +// 1 (ES6 코드) +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.10', 'Object.preventExtensions')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>초기 정의. JavaScript 1.8.5에서 구현됨.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.preventextensions', 'Object.preventExtensions')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.preventextensions', 'Object.preventExtensions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Object.preventExtensions")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Object.isExtensible()")}}</li> + <li>{{jsxref("Object.seal()")}}</li> + <li>{{jsxref("Object.isSealed()")}}</li> + <li>{{jsxref("Object.freeze()")}}</li> + <li>{{jsxref("Object.isFrozen()")}}</li> + <li>{{jsxref("Reflect.preventExtensions()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/object/propertyisenumerable/index.html b/files/ko/web/javascript/reference/global_objects/object/propertyisenumerable/index.html new file mode 100644 index 0000000000..fde6780ffd --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/propertyisenumerable/index.html @@ -0,0 +1,146 @@ +--- +title: Object.prototype.propertyIsEnumerable() +slug: Web/JavaScript/Reference/Global_Objects/Object/propertyIsEnumerable +tags: + - JavaScript + - Method + - Object + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Object/propertyIsEnumerable +--- +<div>{{JSRef}}</div> + +<p><code><strong>propertyIsEnumerable()</strong></code> 메서드는 특정 속성이 열거가능한지 여부를 나타내는 불리언 값을 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/object-prototype-propertyisenumerable.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>obj</var>.propertyIsEnumerable(<var>prop</var>)</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>prop</code></dt> + <dd>테스트 할 속성의 이름.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>특정 속성이 열거가능한지 여부를 나타내는 {{jsxref("Boolean")}}.</p> + +<h2 id="설명">설명</h2> + +<p>모든 객체는 <code>propertyIsEnumerable</code> 메소드를 가지고 있습니다. 이 메소드는 프로토타입 체인을 통해 상속된 특성을 제외하고 개체에 지정된 속성을 {{jsxref("Statements/for...in", "for...in")}} 루프로 열거할 수 있는지 여부를 확인할 수 있습니다. 개체에 지정된 속성이 없으면 이 메소드는 <code>false</code>를 반환합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="A_basic_use_of_propertyIsEnumerable">A basic use of <code>propertyIsEnumerable</code></h3> + +<p>The following example shows the use of <code>propertyIsEnumerable</code> on objects and arrays:</p> + +<pre class="brush: js">var o = {}; +var a = []; +o.prop = 'is enumerable'; +a[0] = 'is enumerable'; + +o.propertyIsEnumerable('prop'); // returns true +a.propertyIsEnumerable(0); // returns true +</pre> + +<h3 id="User-defined_versus_built-in_objects">User-defined versus built-in objects</h3> + +<p>The following example demonstrates the enumerability of user-defined versus built-in properties:</p> + +<pre class="brush: js">var a = ['is enumerable']; + +a.propertyIsEnumerable(0); // returns true +a.propertyIsEnumerable('length'); // returns false + +Math.propertyIsEnumerable('random'); // returns false +this.propertyIsEnumerable('Math'); // returns false +</pre> + +<h3 id="Direct_versus_inherited_properties">Direct versus inherited properties</h3> + +<pre class="brush: js">var a = []; +a.propertyIsEnumerable('constructor'); // returns false + +function firstConstructor() { + this.property = 'is not enumerable'; +} + +firstConstructor.prototype.firstMethod = function() {}; + +function secondConstructor() { + this.method = function method() { return 'is enumerable'; }; +} + +secondConstructor.prototype = new firstConstructor; +secondConstructor.prototype.constructor = secondConstructor; + +var o = new secondConstructor(); +o.arbitraryProperty = 'is enumerable'; + +o.propertyIsEnumerable('arbitraryProperty'); // returns true +o.propertyIsEnumerable('method'); // returns true +o.propertyIsEnumerable('property'); // returns false + +o.property = 'is enumerable'; + +o.propertyIsEnumerable('property'); // returns true + +// These return false as they are on the prototype which +// propertyIsEnumerable does not consider (even though the last two +// are iteratable with for-in) +o.propertyIsEnumerable('prototype'); // returns false (as of JS 1.8.1/FF3.6) +o.propertyIsEnumerable('constructor'); // returns false +o.propertyIsEnumerable('firstMethod'); // returns false +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.4.7', 'Object.prototype.propertyIsEnumerable')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.prototype.propertyisenumerable', 'Object.prototype.propertyIsEnumerable')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.prototype.propertyisenumerable', 'Object.prototype.propertyIsEnumerable')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.Object.propertyIsEnumerable")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/en-US/docs/Enumerability_and_ownership_of_properties">Enumerability and ownership of properties</a></li> + <li>{{jsxref("Statements/for...in", "for...in")}}</li> + <li>{{jsxref("Object.keys()")}}</li> + <li>{{jsxref("Object.defineProperty()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/object/prototype/index.html b/files/ko/web/javascript/reference/global_objects/object/prototype/index.html new file mode 100644 index 0000000000..4fdc17bc49 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/prototype/index.html @@ -0,0 +1,218 @@ +--- +title: Object.prototype +slug: Web/JavaScript/Reference/Global_Objects/Object/prototype +tags: + - JavaScript + - Object + - Property + - Reference + - 프로토타입 +translation_of: Web/JavaScript/Reference/Global_Objects/Object +--- +<div>{{JSRef}}</div> + +<p><code><strong>Object.prototype</strong></code> 속성은 {{jsxref("Object")}} 프로토타입(원형) 객체를<br> + 나타냅니다.</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="설명">설명</h2> + +<p>JavaScript에서 거의 모든 객체는 {{jsxref("Object")}}의 인스턴스입니다. 일반적인 객체는 <code>Object.prototype</code> 에서 속성과 메서드를 상속받으며, 그 중 일부는 (오버라이드 등으로 인해) 숨겨질 수 있습니다. 그러나, 의도적으로 <code>Object</code>를 생성할 때 ({{jsxref("Object.create", "Object.create(null)")}} 처럼) 이를 피할 수도 있고, {{jsxref("Object.setPrototypeOf")}} 등을 통해 나중에 무효화할 수도 있습니다.</p> + +<p><code>Object</code> 프로토타입에 가하는 변경은 프로토타입 체인을 통해, 더 아래쪽 체인에서 덮어 쓴 경우가 아니라면 <strong>모든</strong> 객체에서 관측할 수 있습니다. 이는 객체를 확장하거나 행동을 바꿀 수 있는 매우 강력하면서도 위험한 방법을 제공합니다.</p> + + + +<h2 id="속성">속성</h2> + +<dl> + <dt>{{jsxref("Object.prototype.constructor")}}</dt> + <dd>객체의 프로토타입을 생성하는 함수를 지정합니다.</dd> + <dt>{{jsxref("Object.prototype.__proto__")}} {{non-standard_inline}}</dt> + <dd>객체가 초기화될 때 프로토타입으로 사용된 객체를 가리킵니다.</dd> + <dt><s class="obsoleteElement">{{jsxref("Object.prototype.__noSuchMethod__")}} {{obsolete_inline}}</s></dt> + <dd><s class="obsoleteElement">정의되지 않은 객체 멤버가 메소드로서 호출될 때 실행되는 함수를 정의하는 데 쓰였지만 제거되었습니다.</s></dd> + <dt><s class="obsoleteElement">{{jsxref("Object.prototype.count","Object.prototype.__count__")}} {{obsolete_inline}}</s></dt> + <dd><s class="obsoleteElement">사용자 정의 객체 상에 직접 있는 열거가능 속성의 수를 반환하는 데 쓰였지만 제거되었습니다.</s></dd> + <dt><s class="obsoleteElement">{{jsxref("Object.prototype.parent","Object.prototype.__parent__")}} {{obsolete_inline}}</s></dt> + <dd><s class="obsoleteElement">객체 문맥을 가리키는 데 쓰였지만 제거되었습니다.</s></dd> +</dl> + +<h2 id="메서드">메서드</h2> + +<dl> + <dt>{{jsxref("Object.prototype.__defineGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}</dt> + <dd>함수를 속성에 연결합니다, 접근했을 때 그 함수를 실행해 그 결과값을 반환하는.</dd> + <dt>{{jsxref("Object.prototype.__defineSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}</dt> + <dd>함수를 속성에 연결합니다, 설정했을 때 그 속성을 수정하는 함수를 실행하는.</dd> + <dt>{{jsxref("Object.prototype.__lookupGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}</dt> + <dd>{{jsxref("Object.prototype.__defineGetter__()", "__defineGetter__()")}} 메소드에 의해 지정된 속성과 관련된 함수를 반환합니다.</dd> + <dt>{{jsxref("Object.prototype.__lookupSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}</dt> + <dd>{{jsxref("Object.prototype.__defineSetter__()", "__defineSetter__()")}} 메소드에 의해 지정된 속성과 관련된 함수를 반환합니다.</dd> + <dt>{{jsxref("Object.prototype.hasOwnProperty()")}}</dt> + <dd>객체가 지정된 속성을 프로토타입 체인을 통해 상속되지 않은 그 객체의 직접 속성으로 포함하는지를 나타내는 boolean을 반환합니다.</dd> + <dt>{{jsxref("Object.prototype.isPrototypeOf()")}}</dt> + <dd>지정된 객체가 이 메소드가 호출된 객체의 프로토타입 체인 내에 있는지를 나타내는 boolean을 반환합니다.</dd> + <dt>{{jsxref("Object.prototype.propertyIsEnumerable()")}}</dt> + <dd>내부 <a href="/ko/docs/Web/JavaScript/Data_structures#Properties">ECMAScript [[Enumerable]] attribute</a>가 설정된 경우를 나타내는 boolean을 반환합니다.</dd> + <dt>{{jsxref("Object.prototype.toSource()")}} {{non-standard_inline}}</dt> + <dd>이 메소드가 호출된 객체를 나타내는 객체 리터럴의 출처를 포함하는 문자열을 반환합니다; 새로운 객체를 만들기 위해 이 값을 쓸 수 있습니다.</dd> + <dt>{{jsxref("Object.prototype.toLocaleString()")}}</dt> + <dd>{{jsxref("Object.toString", "toString()")}}을 호출합니다.</dd> + <dt>{{jsxref("Object.prototype.toString()")}}</dt> + <dd>객체의 문자열 표현을 반환합니다.</dd> + <dt>{{jsxref("Object.prototype.unwatch()")}} {{non-standard_inline}}</dt> + <dd>객체 속성에서 감시점을 제거합니다.</dd> + <dt>{{jsxref("Object.prototype.valueOf()")}}</dt> + <dd>지정된 객체의 원시값을 반환합니다.</dd> + <dt>{{jsxref("Object.prototype.watch()")}} {{non-standard_inline}}</dt> + <dd>객체 속성에 감시점을 추가합니다.</dd> + <dt><s class="obsoleteElement">{{jsxref("Object.prototype.eval()")}} {{obsolete_inline}}</s></dt> + <dd><s class="obsoleteElement">지정된 객체의 문맥에서 JavaScript 코드 문자열을 평가하는 데 쓰였지만 제거되었습니다.</s></dd> +</dl> + +<h2 id="예제">예제</h2> + +<p><code>Object.prototype</code>의 기본 메서드를 변경할 때, 기존 조직의 앞 또는 후에 확장(extension) 을 포장하여 코드를 주입시키는 것을 고려하자. 예를 들어서, 이 (시험받지<br> + 않은) 코드는 내장된 로직 또는 어떤 다른 확장이 실행되기 전에 커스텀 로직을 전제조건적으로 실행시킬 것이다.</p> + +<p>함수가 호출되었을 때, 불러온 매개변수들은 배열과 같은 형태로 '변수' <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a>에 보관된다. 예를 들어 myFn(a, b, c) 라는 함수를 부를 때, 이 함수 내부에 배열형태로 매개변수 (a, b, c) 를 담게 된다. prototype을 훅을 이용해 수정할 때, 함수에서 apply()를 호출하여 단순하게 this와 arguments(호출 상태)에 현재 동작을 전달하면 된다. 이 패턴은 Node.prototype, Function.prototype등 prototype에도 사용할 수 있다.</p> + +<pre class="brush: js line-numbers language-js notranslate"><code class="language-js"><span class="keyword token">var</span> current <span class="operator token">=</span> Object<span class="punctuation token">.</span>prototype<span class="punctuation token">.</span>valueOf<span class="punctuation token">;</span> + +<span class="comment token">// 현재 설정한 "-prop-value" 속성은 cross-cutting 이고 </span> +<span class="comment token">// 항상 같은 prototype chain이 아니기 때문에, 이 Object.prototype을 바꾸고 싶다.</span> +Object<span class="punctuation token">.</span>prototype<span class="punctuation token">.</span>valueOf <span class="operator token">=</span> <span class="keyword token">function</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">if</span> <span class="punctuation token">(</span><span class="keyword token">this</span><span class="punctuation token">.</span><span class="function token">hasOwnProperty</span><span class="punctuation token">(</span><span class="string token">'-prop-value'</span><span class="punctuation token">)</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">return</span> <span class="keyword token">this</span><span class="punctuation token">[</span><span class="string token">'-prop-value'</span><span class="punctuation token">]</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> <span class="keyword token">else</span> <span class="punctuation token">{</span> + <span class="comment token">// 이 객체 내 속성(property)이 하나가 아니라면, 현재 동작을 재구성한 것으로부터 + // 기본 동작으로 되돌리자(복구). </span> + <span class="comment token">// apply 동작은 다른 언어에서의 "super"와 유사하다.</span> + <span class="comment token">// 비록 valueOf()가 매개변수를 받지못하더라도, 다른 훅에서 있을 것이다.</span> + <span class="keyword token">return</span> current<span class="punctuation token">.</span><span class="function token">apply</span><span class="punctuation token">(</span><span class="keyword token">this</span><span class="punctuation token">,</span> arguments<span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> +<span class="punctuation token">}</span></code> +</pre> + +<p>JavaScript는 엄밀히 말해서 하위클래스(sub-class) 객체가 없기에, prototype은 객체 역할을 하는 특정 함수의 "기반 클래스" 객체를 만드는 유용한 차선책입니다. 예를 들어:</p> + +<pre class="brush: js notranslate">var Person = function() { + this.canTalk = true; +}; + +Person.prototype.greet = function() { + if (this.canTalk) { + console.log('Hi, I am ' + this.name); + } +}; + +var Employee = function(name, title) { + Person.call(this); + this.name = name; + this.title = title; +}; + +Employee.prototype = Object.create(Person.prototype); +Employee.prototype.constructor = Employee; + +Employee.prototype.greet = function() { + if (this.canTalk) { + console.log('Hi, I am ' + this.name + ', the ' + this.title); + } +}; + +var Customer = function(name) { + Person.call(this); + this.name = name; +}; + +Customer.prototype = Object.create(Person.prototype); +Customer.prototype.constructor = Customer; + +var Mime = function(name) { + Person.call(this); + this.name = name; + this.canTalk = false; +}; + +Mime.prototype = Object.create(Person.prototype); +Mime.prototype.constructor = Mime; + +var bob = new Employee('Bob', 'Builder'); +var joe = new Customer('Joe'); +var rg = new Employee('Red Green', 'Handyman'); +var mike = new Customer('Mike'); +var mime = new Mime('Mime'); + +bob.greet(); +// Hi, I am Bob, the Builder + +joe.greet(); +// Hi, I am Joe + +rg.greet(); +// Hi, I am Red Green, the Handyman + +mike.greet(); +// Hi, I am Mike + +mime.greet(); +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>초기 정의. JavaScript 1.0에서 구현됨.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.1', 'Object.prototype')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.prototype', 'Object.prototype')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.prototype', 'Object.prototype')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.Object.prototype")}}</p> + +<h2 id="참조">참조</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript">객체지향 JavaScript 소개</a></li> +</ul> + +<div id="dicLayer" style=""> +<div id="dicLayerContents"><dicword style="user-select: text;">Even though valueOf() doesn't take arguments, some other hook may.</dicword><dicword style="user-select: text;"><dicimg id="play" style="background-image: url(chrome-extension://bmbdcffdhebhecemcchbkfnjlmdiiepe/play.gif);"></dicimg> <input>Eng<dicimg id="copy" style="background-image: url(chrome-extension://bmbdcffdhebhecemcchbkfnjlmdiiepe/copy.png);" title="copy"></dicimg></dicword><br> +<br> +<br> +<br> +valueOf ()가 인수를받지 않더라도 다른 후크가있을 수 있습니다.</div> + +<div id="dicLayerSub"></div> +</div> + +<div id="dicRawData" style="display: none;">{"mean":["take<br/><br/>[동사]\n\t\t ~ sth (with you) | ~ sth (to sb) | ~ (sb) sth\n\t\t \t\t(어떤 것을 한 곳에서 다른 곳으로) 가지고 가다[이동시키다]","though<br/><br/>[접속사]\n\t\t \t\t(비록) …이긴 하지만[…인데도/…일지라도]\n\n\t\t\t\t\t\t\t\t유의어 although","value<br/><br/>[명사]\n\t\t \t\t(경제적인) 가치\n\n\t\t 참조 market value, street value","other<br/><br/>[형용사, 대명사]\n\t\t \t\t(그 밖의) 다른; 다른 사람[것]\n\n\t\t 참조 another","may<br/><br/>[법조동사]\n\t\t \t\t(가능성을 나타내어) …일지도 모른다[…일 수도 있다]"],"word":"\n\t\t\t\t\t\ttake\n \t\t\t\n\t \t\n\t ","soundUrl":"https://dict-dn.pstatic.net/v?_lsu_sa_=3cd8f6567dcc35f67a9d216930e402fa1d2763157705ff3d60620d707b1d60814356971c64e54c7e792964a50a21103d6cc3ad8a5c30e6d7e9205e93c8517e38f8e5b191d1700b6773822766eee45672523cb75822e10196643a3baf5d3dabb04974f799e77e47c4f2db9476dbfb3e4bf612100b4fa8e918f972d80a449bc79c","phoneticSymbol":"[teɪk]"}</div> + +<div id="dicLayerLoader" style="top: 3322px; left: 514px;"></div> diff --git a/files/ko/web/javascript/reference/global_objects/object/seal/index.html b/files/ko/web/javascript/reference/global_objects/object/seal/index.html new file mode 100644 index 0000000000..c97f71c26d --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/seal/index.html @@ -0,0 +1,135 @@ +--- +title: Object.seal() +slug: Web/JavaScript/Reference/Global_Objects/Object/seal +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Object + - Reference + - 봉인 +translation_of: Web/JavaScript/Reference/Global_Objects/Object/seal +--- +<div>{{JSRef}}</div> + +<p><code><strong>Object.seal()</strong></code> 메서드는 객체를 밀봉합니다. 객체를 밀봉하면 그 객체에는 새로운 속성을 추가할 수 없고, 현재 존재하는 모든 속성을 설정 불가능 상태로 만들어줍니다. 하지만 쓰기 가능한 속성의 값은 밀봉 후에도 변경할 수 있습니다(역자 주 : 바로 이 점이 <code>Object.freeze()</code>와의 차이라고 할 수 있습니다).</p> + +<div>{{EmbedInteractiveExample("pages/js/object-prototype-seal.html")}}</div> + + + +<h2 id="Syntax" name="Syntax">구문</h2> + +<pre class="syntaxbox">Object.seal(<var>obj</var>)</pre> + +<h3 id="Parameters" name="Parameters">매개변수</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>봉인할 객체.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>봉인한 객체.</p> + +<h2 id="Description" name="Description">설명</h2> + +<p>객체는 기본적으로 확장이 가능(<span style="line-height: 16.7999992370605px;">{{jsxref("Object.isExtensible()", "extensible", "", 1)}}</span>)합니다. 즉, 새로운 속성을 추가할 수 있습니다. 하지만 객체를 밀봉하면 그 객체에 새로운 속성을 추가할 수 없게되고, 그 객체 내에 존재하는 모든 속성이 설정 불가능(non-configurable)해 집니다. 객체를 밀봉하면 객체의 속성을 고정된 불변의 상태로 만듭니다. 모든 속성을 설정 불가능한 상태로 만드는 것은 데이터 속성(data properties)을 접근자 속성(accessor properties)으로, 또는 접근자 속성을 데이터 속성으로 변경할 수 없게 만듭니다. 하지만 객체를 완전히 얼려서 데이터 속성의 값도 변경할 수 없게 만드는 <code>Object.freeze()</code>와 달리, <code><strong>Object.seal()</strong></code>은 객체를 밀봉한 후에도 그 객체의 데이터 속성의 값은 여전히 변경할 수 있게 해줍니다. 다만, 밀봉한 후에는 객체를 얼리는 것과 마찬가지로 속성의 추가/삭제나 데이터 속성과 접근자 속성 사이의 전환은 암묵적이든, 아니면 <span style="line-height: 16.7999992370605px;">{{jsxref("Strict_mode", "strict mode", "", 1)}} 에서와 같이 명시적으로 {{jsxref("Global_Objects/TypeError", "TypeError")}} 예외를 발생시키든 모두 실패로 끝납니다.</span></p> + +<p>프로토타입 체인은 밀봉 전이나 후나 달라지지 않습니다. 하지만 <span style="line-height: 16.7999992370605px;">{{jsxref("Object.proto", "__proto__")}} {{deprecated_inline}} 속성은 함께 밀봉됩니다.</span></p> + +<h2 id="Examples" name="Examples">예제</h2> + +<pre class="brush: js">var obj = { + prop: function() {}, + foo: 'bar' +}; + +// 새 속성이 추가되고, 기존 속성은 변경되거나 제거될 수 있음 +obj.foo = 'baz'; +obj.lumpy = 'woof'; +delete obj.prop; + +var o = Object.seal(obj); + +assert(o === obj); +assert(Object.isSealed(obj) === true); + +// 밀봉한 객체의 속성값은 밀봉 전과 마찬가지로 변경할 수 있음 +obj.foo = 'quux'; +obj.foo // 'quux' 가 출력됨 + +// 데이터 속성과 접근자 속성 사이의 전환은 불가 +Object.defineProperty(obj, 'foo', { get: function() { return 'g'; } }); // TypeError 발생 + +// 속성값의 변경을 제외한 어떤 변경도 적용되지 않음 +obj.quaxxor = 'the friendly duck'; // 에러가 나지는 않지만 속성은 추가되지 않음 +delete obj.foo; // 에러가 나지는 않지만 속성이 삭제되지 않음 + +// strict mode 에서는 속성값의 변경을 제외한 모든 변경은 TypeError 발생 +function fail() { + 'use strict'; + delete obj.foo; // TypeError 발생 + obj.sparky = 'arf'; // TypeEror 발생 +} +fail(); + +// Object.defineProperty() 메서드를 이용한 속성의 추가도 TypeError 발생 +Object.defineProperty(obj, 'ohai', { value: 17 }); // TypeErorr 발생 +Object.defineProperty(obj, 'foo', { value: 'eit' }); // 속성값의 변경은 가능함 +</pre> + +<h2 id="Notes" name="Notes">참고</h2> + +<p>ES5에서는 <code><strong>Object.seal()</strong></code> 메서드의 인자가 객체가 아닐 때(즉, 원시형일 때)는 <span style="line-height: 16.7999992370605px;">{{jsxref("Global_Objects/TypeError", "TypeError")}}가 발생합니다. ES6에서는 원시형 인자도 밀봉된 객체라고 취급해서 {{jsxref("Global_Objects/TypeError", "TypeError")}}를 발생시키지 않고 원시형 인자를 그대로 반환합니다.</span></p> + +<pre class="brush: js">> Object.seal(1) +TypeError: 1 is not an object // ES5 code + +> Object.seal(1) +1 // ES6 code +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.8', 'Object.seal')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.8.5.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.seal', 'Object.seal')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.seal', 'Object.seal')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Object.seal")}}</p> + +<h2 id="See_also" name="See_also">같이 보기</h2> + +<ul> + <li>{{jsxref("Object.isSealed()")}}</li> + <li>{{jsxref("Object.preventExtensions()")}}</li> + <li>{{jsxref("Object.isExtensible()")}}</li> + <li>{{jsxref("Object.freeze()")}}</li> + <li>{{jsxref("Object.isFrozen()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/object/setprototypeof/index.html b/files/ko/web/javascript/reference/global_objects/object/setprototypeof/index.html new file mode 100644 index 0000000000..332f857361 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/setprototypeof/index.html @@ -0,0 +1,242 @@ +--- +title: Object.setPrototypeOf() +slug: Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf +translation_of: Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf +--- +<p>{{JSRef}}</p> + +<p>Object.setPrototypeOf() 메소드는 지정된 객체의 프로토타입 (즉, 내부 [[Prototype]] 프로퍼티)을 다른 객체 또는 {{jsxref("null")}} 로 설정합니다.</p> + +<div class="warning"> +<p><strong>Warning:</strong> Changing the <code>[[Prototype]]</code> of an object is, by the nature of how modern JavaScript engines optimize property accesses, a very slow operation, in <strong><em>every</em></strong> browser and JavaScript engine. The effects on performance of altering inheritance are subtle and far-flung, and are not limited to simply the time spent in <code>obj.__proto__ = ...</code> statement, but may extend to <strong><em>any</em></strong> code that has access to <strong><em>any</em></strong> object whose <code>[[Prototype]]</code> has been altered. If you care about performance you should avoid setting the <code>[[Prototype]]</code> of an object. Instead, create a new object with the desired <code>[[Prototype]]</code> using {{jsxref("Object.create()")}}.</p> +</div> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox notranslate"><code>Object.setPrototypeOf(<var>obj</var>, <var>prototype</var>);</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>프로토타입을 설정을 가지는 객체</dd> + <dt><code>prototype</code></dt> + <dd>객체의 새로운 프로토 타입 (객체 or {{jsxref("null")}}).</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>지정된 객체 </p> + +<h2 id="Description">Description</h2> + +<p>만일 프로토타입이 변경될 객체가 {{jsxref("Object.isExtensible()")}} 에 의해서 non-extensible 하다면, {{jsxref("TypeError")}} 예외처리를 해라. 만일 프로토타입 파라미터가 객체가 아니거나 {{jsxref("null")}} (i.e., number, string, boolean, {{jsxref("undefined")}}) 인 경우가 아니라면 어떠한 작업도 하지마라. 이 방법을 통해서 객제의 프로토타입이 새로운 값으로 변경될 것이다.</p> + +<p>Object.setPrototypeOf는 ECMAScript 2015 스펙으로 규정되어 있다. 해당 메소드는 일반적으로 객체의 프로토타입과 논쟁이 되는 {{jsxref("Object.prototype.__proto__")}} 프로퍼티를 설정하는 적절한 방법으로 고려된다. </p> + +<p>Examples</p> + +<pre class="brush: js notranslate">var dict = Object.setPrototypeOf({}, null); +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>예전 버전의 프로퍼티 {{jsxref("Object.prototype.__proto__")}} 를 사용한다면, 우리는 쉽게 Object.setPrototypeOf 가 쉽게 정의 할수 있다.</p> + +<pre class="brush: js notranslate">// Only works in Chrome and FireFox, does not work in IE: +Object.setPrototypeOf = Object.setPrototypeOf || function(obj, proto) { + obj.__proto__ = proto; + return obj; +} +</pre> + +<h2 id="Appending_Prototype_Chains">Appending Prototype Chains</h2> + +<p><code>Object.getPrototypeOf()</code> and {{jsxref("Object.proto", "Object.prototype.__proto__")}} 의 결합은 새로운 프로토타입 오브젝트에 전반적인 프로토타입 Chain을 설정하도록 할수 있다.</p> + +<pre class="brush: js notranslate">/** +*** Object.appendChain(@object, @prototype) +* +* Appends the first non-native prototype of a chain to a new prototype. +* Returns @object (if it was a primitive value it will transformed into an object). +* +*** Object.appendChain(@object [, "@arg_name_1", "@arg_name_2", "@arg_name_3", "..."], "@function_body") +*** Object.appendChain(@object [, "@arg_name_1, @arg_name_2, @arg_name_3, ..."], "@function_body") +* +* Appends the first non-native prototype of a chain to the native Function.prototype object, then appends a +* new Function(["@arg"(s)], "@function_body") to that chain. +* Returns the function. +* +**/ + +Object.appendChain = function(oChain, oProto) { + if (arguments.length < 2) { + throw new TypeError('Object.appendChain - Not enough arguments'); + } + if (typeof oProto !== 'object' && typeof oProto !== 'string') { + throw new TypeError('second argument to Object.appendChain must be an object or a string'); + } + + var oNewProto = oProto, + oReturn = o2nd = oLast = oChain instanceof this ? oChain : new oChain.constructor(oChain); + + for (var o1st = this.getPrototypeOf(o2nd); + o1st !== Object.prototype && o1st !== Function.prototype; + o1st = this.getPrototypeOf(o2nd) + ) { + o2nd = o1st; + } + + if (oProto.constructor === String) { + oNewProto = Function.prototype; + oReturn = Function.apply(null, Array.prototype.slice.call(arguments, 1)); + this.setPrototypeOf(oReturn, oLast); + } + + this.setPrototypeOf(o2nd, oNewProto); + return oReturn; +} +</pre> + +<h3 id="Usage">Usage</h3> + +<h4 id="First_example_프로토타입에_Chain_설정하기">First example: 프로토타입에 Chain 설정하기</h4> + +<pre class="brush: js notranslate">function Mammal() { + this.isMammal = 'yes'; +} + +function MammalSpecies(sMammalSpecies) { + this.species = sMammalSpecies; +} + +MammalSpecies.prototype = new Mammal(); +MammalSpecies.prototype.constructor = MammalSpecies; + +var oCat = new MammalSpecies('Felis'); + +console.log(oCat.isMammal); // 'yes' + +function Animal() { + this.breathing = 'yes'; +} + +Object.appendChain(oCat, new Animal()); + +console.log(oCat.breathing); // 'yes' +</pre> + +<h4 id="Second_example_객체_Constructor의_인스턴스에_존재하는_원래_값을_변경_및_해당_객체_프로토타입에_Chain_설정하기">Second example: 객체 Constructor의 인스턴스에 존재하는 원래 값을 변경 및 해당 객체 프로토타입에 Chain 설정하기</h4> + +<pre class="brush: js notranslate">function MySymbol() { + this.isSymbol = 'yes'; +} + +var nPrime = 17; + +console.log(typeof nPrime); // 'number' + +var oPrime = Object.appendChain(nPrime, new MySymbol()); + +console.log(oPrime); // '17' +console.log(oPrime.isSymbol); // 'yes' +console.log(typeof oPrime); // 'object' +</pre> + +<h4 id="Third_example_Function.prototype객체에_Chain을_설정하고_그_Chain에_새로운_함수를_설정하기">Third example: Function.prototype객체에 Chain을 설정하고 그 Chain에 새로운 함수를 설정하기</h4> + +<pre class="brush: js notranslate">function Person(sName) { + this.identity = sName; +} + +var george = Object.appendChain(new Person('George'), + 'console.log("Hello guys!!");'); + +console.log(george.identity); // 'George' +george(); // 'Hello guys!!' +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-object.setprototypeof', 'Object.setProtoypeOf')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.setprototypeof', 'Object.setProtoypeOf')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("34")}}</td> + <td>{{CompatGeckoDesktop("31")}}</td> + <td>{{CompatIE("11")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatSafari("9")}}</td> + </tr> + </tbody> +</table> + + +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile("31")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatSafari("9")}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Reflect.setPrototypeOf()")}}</li> + <li>{{jsxref("Object.prototype.isPrototypeOf()")}}</li> + <li>{{jsxref("Object.getPrototypeOf()")}}</li> + <li>{{jsxref("Object.prototype.__proto__")}} </li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/object/tolocalestring/index.html b/files/ko/web/javascript/reference/global_objects/object/tolocalestring/index.html new file mode 100644 index 0000000000..809daad824 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/tolocalestring/index.html @@ -0,0 +1,86 @@ +--- +title: Object.prototype.toLocaleString() +slug: Web/JavaScript/Reference/Global_Objects/Object/toLocaleString +tags: + - JavaScript + - Method + - Object + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Object/toLocaleString +--- +<div>{{JSRef}}</div> + +<p><code><strong>toLocaleString()</strong></code> 메서드는 객체로 된 문자열을 반환합니다. 이 메서드는 지역별로 다른 객체로 재정의되어 표시됩니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/object-prototype-tolocalestring.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>obj</var>.toLocaleString()</pre> + +<h3 id="반환_값">반환 값</h3> + +<p>객체를 나타내는 문자열.</p> + +<h2 id="설명">설명</h2> + +<p>{{jsxref("Object")}}의 <code>toLocaleString</code>은 {{jsxref("Object.toString", "toString()")}}을 호출 한 결과를 반환합니다.</p> + +<p>이 함수는 모든 객체가 사용할 수는 없지만 객체에 일반 <code>toLocaleString</code> 메소드를 제공하기 위해 제공됩니다. 아래 목록을 참조하십시오.</p> + +<h3 id="toLocaleString()을_재정의하는_객체"><code>toLocaleString()</code>을 재정의하는 객체</h3> + +<ul> + <li>{{jsxref("Array")}}: {{jsxref("Array.prototype.toLocaleString()")}}</li> + <li>{{jsxref("Number")}}: {{jsxref("Number.prototype.toLocaleString()")}}</li> + <li>{{jsxref("Date")}}: {{jsxref("Date.prototype.toLocaleString()")}}</li> +</ul> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.4.3', 'Object.prototype.toLocaleString')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.prototype.tolocalestring', 'Object.prototype.toLocaleString')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.prototype.tolocalestring', 'Object.prototype.toLocaleString')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Object.toLocaleString")}}</p> +</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Object.prototype.toString()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/object/tostring/index.html b/files/ko/web/javascript/reference/global_objects/object/tostring/index.html new file mode 100644 index 0000000000..77e4284ff7 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/tostring/index.html @@ -0,0 +1,134 @@ +--- +title: Object.prototype.toString() +slug: Web/JavaScript/Reference/Global_Objects/Object/toString +tags: + - JavaScript + - Method + - Object + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Object/toString +--- +<div></div> + +<div>{{JSRef}}</div> + +<p>The <code><strong>toString()</strong></code> 은 문자열을 반환하는 object의 대표적인 방법이다</p> + +<div>{{EmbedInteractiveExample("pages/js/object-prototype-tostring.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>obj</var>.toString()</code></pre> + +<h2 id="Description">Description</h2> + +<p>모든 객체에는 객체가 텍스트 값으로 표시되거나 객체가 문자열이 예상되는 방식으로 참조 될 때 자동으로 호출되는 <code>toString()</code> 메서드가 있습니다. 기본적으로 <code>toString()</code> 메서드는 Object에서 비롯된 모든 객체에 상속됩니다. 이 메서드가 사용자 지정 개체에서 재정의되지 않으면 <code>toString()</code>은 "<code>[object type]</code>"을 반환합니다. 여기서 <code>type</code>은 object type입니다. 다음 코드는 이것을 설명합니다</p> + +<pre class="brush: js">var o = new Object(); +o.toString(); // returns [object Object] +</pre> + +<div class="note"> +<p><strong>Note:</strong> 자바스크립트 1.8.5부터 {{jsxref("null")}}의 <code>toString()</code>을 호출하는 경우 <code>[object <em>Null</em>]</code>을 반환하며, {{jsxref("undefined")}}는 <code>[object <em>Undefined</em>]</code>를 반환합니다. 이는 ECMAScript 제 5판과 후속 정오표에 정의되어 있습니다. See {{anch("toString으로_객체_클래스_검사", "toString으로_객체_클래스_검사")}}.</p> +</div> + +<h2 id="Examples">Examples</h2> + +<h3 id="기본_toString_메소드_재정의">기본 <code>toString</code> 메소드 재정의</h3> + +<p>기본 <code>toString()</code> 메서드 대신에 호출될 함수를 정의할 수 있습니다. <code>toString()</code> 메서드는 인자를 취하지 않고 문자열을 반환합니다. 직접 생성한 <code>toString()</code> 메서드는 원하는 어떤 값이든 될 수 있지만 해당 객체에 대한 정보를 전달하고 있을 때 가장 유용할 것입니다.</p> + +<p>다음 코드는 <code>Dog</code> 객체 타입을 정의하고 <code>Dog</code> 타입을 따르는 <code>theDog</code>를 생성합니다:</p> + +<pre class="brush: js">function Dog(name, breed, color, sex) { + this.name = name; + this.breed = breed; + this.color = color; + this.sex = sex; +} + +theDog = new Dog('Gabby', 'Lab', 'chocolate', 'female'); +</pre> + +<p>커스텀 객체의 <code>toString()</code> 메서드를 호출하는 경우 {{jsxref("Object")}}로부터 상속받은 기본 값을 반환하게 됩니다:</p> + +<pre class="brush: js">theDog.toString(); // returns [object Object] +</pre> + +<p>다음 코드는 기본 <code>toString()</code> 메서드를 재정의하는 <code>dogToString()</code>을 생성하고 할당합니다. 이 함수는 객체의 name, breed, color, sex를 포함하는 문자열을 "<code>property = value;</code>"의 형태로 만들어냅니다.</p> + +<pre class="brush: js">Dog.prototype.toString = function dogToString() { + var ret = 'Dog ' + this.name + ' is a ' + this.sex + ' ' + this.color + ' ' + this.breed; + return ret; +} +</pre> + +<p>앞선 코드를 사용하면 문자열 컨텍스트에서 <code>theDog</code>가 사용될 때마다 자바스크립트는 자동으로 <code>dogToString() </code>함수를 호출하여 다음 문자열을 반환합니다:</p> + +<pre class="brush: js">"Dog Gabby is a female chocolate Lab" +</pre> + +<h3 id="toString으로_객체_클래스_검사"><code>toString()</code>으로 객체 클래스 검사</h3> + +<p><code>toString()</code>은 모든 객체에 사용되어 해당 객체의 클래스를 가져올 수 있습니다. Object.prototype.toString()을 모든 객체에 사용하기 위해서는 {{jsxref("Function.prototype.call()")}} 나 {{jsxref("Function.prototype.apply()")}}를 사용해서 검사하고자 하는 객체를 <code>thisArg</code>로 불리는 첫번째 파라미터로 넘겨야 합니다.</p> + +<pre class="brush: js">var toString = Object.prototype.toString; + +toString.call(new Date); // [object Date] +toString.call(new String); // [object String] +toString.call(Math); // [object Math] + +// Since JavaScript 1.8.5 +toString.call(undefined); // [object Undefined] +toString.call(null); // [object Null] +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.4.2', 'Object.prototype.toString')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Call on {{jsxref("null")}} returns <code>[object <em>Null</em>]</code>, and {{jsxref("undefined")}} returns <code>[object <em>Undefined</em>]</code></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.prototype.tostring', 'Object.prototype.toString')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.prototype.tostring', 'Object.prototype.toString')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Object.toString")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Object.prototype.toSource()")}}</li> + <li>{{jsxref("Object.prototype.valueOf()")}}</li> + <li>{{jsxref("Number.prototype.toString()")}}</li> + <li>{{jsxref("Symbol.toPrimitive")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/object/valueof/index.html b/files/ko/web/javascript/reference/global_objects/object/valueof/index.html new file mode 100644 index 0000000000..7bef3bd48c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/valueof/index.html @@ -0,0 +1,118 @@ +--- +title: Object.prototype.valueOf() +slug: Web/JavaScript/Reference/Global_Objects/Object/valueOf +tags: + - JavaScript + - Method + - Object + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Object/valueOf +--- +<div>{{JSRef}}</div> + +<p><code><strong>valueOf()</strong></code> 메서드는 특정 객체의 원시 값을 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/object-prototype-valueof.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox notranslate"><code><var>object</var>.valueOf()</code></pre> + +<h3 id="반환_값">반환 값</h3> + +<p>객체의 원시 값.</p> + +<div class="blockIndicator note"> +<p> <a href="https://wiki.developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators#단항_연산자">(단항) 더하기 기호</a> 는 가끔 <code>valueOf</code> 의 단축 표현으로 사용됩니다. 예를 들면, 다음과 같은 표현을 보세요. <code>+new Number()</code>. <a href="https://wiki.developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf#단항_더하기_사용하기">단항 더하기 사용하기</a>.도 참조 하세요.</p> +</div> + +<h2 id="설명">설명</h2> + +<p>JavaScript는 객체를 원시 값으로 변환할 때 <code>valueOf</code> 메서드를 호출합니다. 보통 원시 값을 필요로 할 때 알아서 사용하므로 직접 호출해야 하는 경우는 매우 드뭅니다.</p> + +<p>기본적으로 {{jsxref("Object")}}의 모든 후손 객체는 <code>valueOf</code>를 상속받습니다. 내장된 핵심 객체는 모두 <code>valueOf</code>를 재정의<sup>override</sup>해 적합한 값을 반환합니다. 어떤 객체가 원시 값을 가지고 있지 않다면, <code>valueOf</code>는 객체 스스로를 반환합니다.</p> + +<p>여러분의 코드에서 <code>valueOf</code>를 호출해 내장 객체를 원시 값으로 변환할 수 있습니다. 사용자 정의 객체를 만들 땐 <code>valueOf</code>를 재정의해 {{jsxref("Object")}}의 메서드 대신 다른 행동을 부여할 수도 있습니다.</p> + +<h3 id="사용자_정의_객체의_valueOf_오버라이딩">사용자 정의 객체의 valueOf 오버라이딩</h3> + +<p>기본 <code>valueOf</code> 메서드 대신 사용할 함수를 생성할 수 있습니다. 이 때 함수는 매개변수를 받지 않아야 합니다.</p> + +<p><code>MyNumberType</code>이라는 객체 형태가 존재하고, 이 객체의 <code>valueOf</code> 메서드를 만들고 싶다고 가정하겠습니다. 다음의 코드는 객체의 <code>valueOf</code> 메서드에 사용자 정의 함수를 할당합니다.</p> + +<pre class="brush: js notranslate">MyNumberType.prototype.valueOf = function() { return customPrimitiveValue; };</pre> + +<p>위의 코드가 활성화된 상태에서 어떤 <code>MyNumberType</code> 객체를 원시 값으로 표현해야 하면 JavaScript가 자동으로 저 함수를 실행합니다.</p> + +<p>이 객체의 <code>valueOf</code> 메서드는 보통 JavaScript가 호출하겠지만 다음처럼 직접 호출할 수도 있습니다.</p> + +<pre class="brush: js notranslate">myNumberType.valueOf()</pre> + +<div class="note"> +<p><strong>참고:</strong> 문자열 문맥에서 객체-문자열 변환은 {{jsxref("Object.toString", "toString()")}} 메서드를 사용하며, {{jsxref("String")}} 객체의 <code>valueOf</code>를 사용해 원시 문자열로 변환하는 것과는 다릅니다. 모든 객체는, 비록 결과가 "<code>[object type]</code>" 뿐이라도 문자열 변환 기능을 가지고 있습니다. 그러나 대다수의 객체는 숫자, 불리언, 함수 등으로 변환되지 않습니다.</p> +</div> + +<h2 id="예제">예제</h2> + +<h3 id="커스텀_타입에_valueOf_사용하기">커스텀 타입에 valueOf 사용하기</h3> + +<pre class="brush: js notranslate">function MyNumberType(n) { + this.number = n; +} + +MyNumberType.prototype.valueOf = function() { + return this.number; +}; + +var myObj = new MyNumberType(4); +myObj + 3; // 7</pre> + +<h3 id="단항_더하기_사용하기"><a name="Details_of_unary_plus">단항 더하기 사용하기</a></h3> + +<pre class="notranslate">+"5" // 5 (string to number) ++"" // 0 (string to number) ++"1 + 2" // NaN (doesn't evaluate) ++new Date() // same as (new Date()).getTime() ++"foo" // NaN (string to number) ++{} // NaN ++[] // 0 (toString() returns an empty string list) ++[1] // 1 ++[1,2] // NaN ++new Set([1]) // NaN ++BigInt(1) // Uncaught TypeError: Cannot convert a BigInt value to a number ++undefined // NaN ++null // 0 ++true // 1 ++false // 0</pre> + +<h2 id="명세">명세</h2> + +<table> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.prototype.valueof', 'Object.prototype.valueOf')}}</td> + </tr> + </tbody> +</table> + +<h2 id="라우저_호환성">라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Object.valueOf")}}</p> + +<h2 id="함께_보기">함께 보기</h2> + +<ul> + <li>{{jsxref("Object.prototype.toString()")}}</li> + <li>{{jsxref("parseInt", "parseInt()")}}</li> + <li>{{jsxref("Symbol.toPrimitive()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/object/values/index.html b/files/ko/web/javascript/reference/global_objects/object/values/index.html new file mode 100644 index 0000000000..af8f159a53 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/values/index.html @@ -0,0 +1,98 @@ +--- +title: Object.values() +slug: Web/JavaScript/Reference/Global_Objects/Object/values +translation_of: Web/JavaScript/Reference/Global_Objects/Object/values +--- +<div>{{JSRef}}</div> + +<p><code><strong>Object.values()</strong></code> 메소드는 전달된 파라미터 객체가 가지는 (열거 가능한) 속성의 값들로 이루어진 배열을 리턴합니다. 이 배열은 {{jsxref("Statements/for...in", "for...in")}} 구문과 동일한 순서를 가집니다. (for in 반복문은 프로토타입 체인 또한 열거한다는 점에서 차이가 있습니다.)</p> + +<div>{{EmbedInteractiveExample("pages/js/object-values.html")}}</div> + +<p class="hidden">샘플 소스는 GitHub에 저장되어 있습니다. 샘플 소스에 대해서 컨트리뷰트하고 싶다면, <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> 프로젝트를 클론하고, 풀 리퀘스트를 보내주세요. </p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">Object.values(<var>obj</var>)</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>배열로 변환할 열거 가능한 속성을 가지는 객체</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>전달된 객체의 속성 값들을 포함하는 배열</p> + +<h2 id="Description">Description</h2> + +<p><code>Object.values()</code> 는 파라매터로 전달된 객체가 가지는 열거 가능한 속성의 값들로 구성된 배열을 반환합니다. 배열의 값들이 순서는 오브젝트의 속성을 for in 구문등으로 반복한 결과와 동일합니다. (참고로 for in 구문은 순서를 보장하지 않습니다)</p> + +<h2 id="Examples">Examples</h2> + +<pre class="brush: js">var obj = { foo: 'bar', baz: 42 }; +console.log(Object.values(obj)); // ['bar', 42] + +// 유사 배열 (숫자를 속성으로 사용하는 객체) +var obj = { 0: 'a', 1: 'b', 2: 'c' }; +console.log(Object.values(obj)); // ['a', 'b', 'c'] + +// 유사 배열의 경의 속성으로 사용한 숫자의 크기 순으로 정렬되어 반환됩니다. +var an_obj = { 100: 'a', 2: 'b', 7: 'c' }; +console.log(Object.values(an_obj)); // ['b', 'c', 'a'] + +// getFoo는 열거 가능한 속성이 아니라서 배열에 포함되지 않습니다. +var my_obj = Object.create({}, { getFoo: { value: function() { return this.foo; } } }); +my_obj.foo = 'bar'; +console.log(Object.values(my_obj)); // ['bar'] + +// 객체가 아닌 경우에는 객체로 강제로 변환되어 적용됩니다. +console.log(Object.values('foo')); // ['f', 'o', 'o'] +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p><code>Object.values</code> 메소드는 구형 브라우저에서 지원하지 않습니다. 구형 브라우저와의 호환성을 고려하기 위해 폴리필을 찾아 볼 수 있습니다. <a href="https://github.com/tc39/proposal-object-values-entries">tc39/proposal-object-values-entries</a> 혹은 <a href="https://github.com/es-shims/Object.values">es-shims/Object.values</a> 를 참조해보세요.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.values', 'Object.values')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES8', '#sec-object.values', 'Object.values')}}</td> + <td>{{Spec2('ES8')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Object.values")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties">Enumerability and ownership of properties</a></li> + <li>{{jsxref("Object.keys()")}}</li> + <li>{{jsxref("Object.entries()")}}</li> + <li>{{jsxref("Object.prototype.propertyIsEnumerable()")}}</li> + <li>{{jsxref("Object.create()")}}</li> + <li>{{jsxref("Object.getOwnPropertyNames()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/parsefloat/index.html b/files/ko/web/javascript/reference/global_objects/parsefloat/index.html new file mode 100644 index 0000000000..bfc5b2d41e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/parsefloat/index.html @@ -0,0 +1,120 @@ +--- +title: parseFloat() +slug: Web/JavaScript/Reference/Global_Objects/parseFloat +tags: + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/parseFloat +--- +<div>{{jsSidebar("Objects")}}</div> + +<p><code><strong>parseFloat()</strong></code> 함수는 문자열을 분석해 부동소수점 실수로 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/globalprops-parsefloat.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">parseFloat(<em>value</em>)</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>value</code></dt> + <dd>변환할 값.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 값에서 분석한 부동소수점 수. 분석할 수 없으면 {{jsxref("NaN")}}.</p> + +<h2 id="설명">설명</h2> + +<p><code>parseFloat()</code>은 최상위 함수로 어떠한 객체와도 연결되어 있지 않습니다.</p> + +<p><code>parseFloat()</code>은 매개변수로 주어진 값 분석하고 부동소수점 수를 반환합니다. 기호(+, -), 숫자(0-9), 소수점 또는 지수 이외의 문자를 발견하면, 그 전까지의 결과만 반환하고 문제의 문자와 그 이후는 모두 무시합니다. 위치에 상관하지 않고, 그런 문자를 발견하면 {{jsxref("NaN")}}을 반환하는 더 엄격한 방법이 필요하면 {{jsxref("Number", "Number(value)")}}를 고려하세요.</p> + +<p>값이 문자열인데 첫 번째 문자를 숫자로 변환할 수 없는 경우 <code>parseFloat()</code>도 <code>NaN</code>을 반환합니다.</p> + +<p>수학적으로 <code>NaN</code>은 어떤 진법에도 속하지 않습니다. {{jsxref("isNaN", "isNaN()")}} 함수를 사용해 결과 값이 <code>NaN</code>인지 확인할 수 있습니다. <code>NaN</code>을 다른 값과의 수학 연산에 사용하면 그 결과도 언제나 <code>NaN</code>이 됩니다.</p> + +<p><code>parseFloat()</code>은 {{jsxref("Infinity")}}도 분석 및 반환할 수 있습니다. {{jsxref("isFinite", "isFinite()")}} 함수를 사용해 결과 값이 유한수(<code>Infinity</code>, <code>-Infinity</code>, <code>NaN</code>이 아닌 수)인지 알 수 있습니다.</p> + +<p><code>parseFloat()</code>은 <code>toString</code>이나 <code>valueOf</code> 메서드를 구현한 객체도 분석할 수 있습니다. 이 때의 결과는 객체의 <code>toString()</code>, <code>valueOf()</code>의 반환 값을 <code>parseFloat()</code>에 전달한 것과 동일합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="숫자를_반환하는_경우">숫자를 반환하는 경우</h3> + +<p>아래 예제는 모두 <code>3.14</code>를 반환합니다.</p> + +<pre class="brush: js">parseFloat(3.14); +parseFloat('3.14'); +parseFloat('314e-2'); +parseFloat('0.0314E+2'); +parseFloat('3.14와 숫자가 아닌 문자들'); + +var foo = Object.create(null); +foo.toString = function () { return "3.14"; }; +parseFloat(foo); + +var foo = Object.create(null); +foo.valueOf = function () { return "3.14"; }; +parseFloat(foo); +</pre> + +<h3 id="NaN을_반환하는_경우"><code>NaN</code>을 반환하는 경우</h3> + +<p>다음 예제는 {{jsxref("NaN")}}을 반환합니다.</p> + +<pre class="brush: js">parseFloat('FF2'); +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.1.2.3', 'parseFloat')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-parsefloat-string', 'parseFloat')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-parsefloat-string', 'parseFloat')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.parseFloat")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Global_Objects/parseInt", "parseInt()")}}</li> + <li>{{jsxref("Number.parseFloat()")}}</li> + <li>{{jsxref("Number.parseInt()")}}</li> + <li>{{jsxref("Number.toFixed()")}}</li> + <li>{{jsxref("Global_Objects/isNaN", "isNaN()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/parseint/index.html b/files/ko/web/javascript/reference/global_objects/parseint/index.html new file mode 100644 index 0000000000..0539e1ba53 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/parseint/index.html @@ -0,0 +1,220 @@ +--- +title: parseInt() +slug: Web/JavaScript/Reference/Global_Objects/parseInt +tags: + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/parseInt +--- +<div>{{jsSidebar("Objects")}}</div> + +<p><code><strong>parseInt()</strong></code> 함수는 문자열 인자를 구문분석하여 특정 진수(수의 진법 체계에 기준이 되는 값)의 정수를 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/globalprops-parseint.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox notranslate">parseInt(<em>string</em>, <em>radix</em>);</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>string</code></dt> + <dd>분석할 값. 만약 <code>string</code>이 문자열이 아니면 문자열로 변환(<code><a href="http://www.ecma-international.org/ecma-262/6.0/#sec-tostring">ToString</a></code> 추상 연산을 사용)합니다. 문자열의 선행 공백은 무시합니다.</dd> +</dl> + +<dl> + <dt><code>radix</code>{{optional_inline}}</dt> + <dd><code>string</code>이 표현하는 정수를 나타내는 2와 36 사이의 진수(수의 진법 체계에 기준이 되는 값). 주의하세요-기본값이 10이 아닙니다!</dd> + <dt></dt> + <dt> + <div class="blockIndicator warning"> + <p><a href="#설명">아래의 설명</a>은 radix가 제공되지 않았을때 무엇이 발생하는지 상세하게 설명하고 있습니다.</p> + </div> + </dt> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 <code>string</code>로부터 분석한 정수.</p> + +<p>또는 아래의 경우에는 {{jsxref("NaN")}}을 반환합니다</p> + +<ul> + <li><code>radix</code>가 2보다 작거나 36보다 큰 경우</li> + <li>첫번째 non-whitespace 문자가 숫자로 변환되지 않는 경우</li> +</ul> + +<h2 id="설명_2"><a id="설명" name="설명">설명</a></h2> + +<p><code>parseInt</code> 함수는 첫 번째 인자를 문자열로 변환하고 파싱하고, 그 문자열을 파싱하여 정수나 <code>NaN</code>을 리턴합니다.</p> + +<p>만약 <code>NaN</code>이 아니면, 첫번째 인자를 특정 <code><var>radix</var></code>(진수) 값으로 표현한 정수가 반환됩니다. (예를 들면, <code><var>radix</var></code>가 <code>10</code>인 경우 십진수로 변환하며, <code>8</code>인 경우는 8진수로, <code>16</code>인 경우 16진수 등등으로 변환합니다.)</p> + +<p><code>radix </code>가 <code>10</code> 이상인 경우, <code>9</code>보다 큰 숫자들은 알파벳 문자로 나타내집니다. 예를 들면, 16 진수의 경우, A부터 F가 사용됩니다.</p> + +<p>만약 <code>parseInt</code> 함수가 특정 진수를 나타내는 숫자가 아닌 글자를 마주치게 되면, 이 글자와 계속되는 글자들은 전부 무시되며, 파싱된 정수값을 리턴합니다. <code>parseInt</code> 함수는 정수값으로 숫자를 잘라버립니다. 맨 앞의 공백과 그 뒤의 공백들은 허용됩니다.</p> + +<p>일부 숫자들은 문자열 표현에 e 문자를 사용하기 때문에(예: 6.022 × 10<sup>23</sup>의 경우 <code>6.022e23</code> ) 숫자를 자르기 위하여 <code>parseInt</code>를 사용하는 것은 매우 크거나 매우 작은 숫자에 사용하는 경우 예기치 않은 결과가 발생합니다. <code>parseInt</code>는 {{jsxref("Math.floor()")}}의 대체품으로 사용해서는 안 됩니다.</p> + +<p><code>parseInt</code>는 양수를 의미하는 <code>+ </code>기호와 음수를 나타내는 <code>-</code> 기호를 정확히 이해합니다(ECMAScript 1 이후). 공백이 제거된 후 구문 분석의 초기 단계로 수행됩니다. 기호를 찾을 수 없으면 알고리즘이 다음 단계로 이동하고, 그렇지 않으면 기호를 제거하고 문자열의 나머지 부분에서 숫자 파싱을 실행합니다.</p> + +<p>만약 <var>radix</var> 가 <code>undefined</code> 이거나 0이라면, (또는 없다면), JavaScript 는 아래와 같이 임의 처리합니다. :</p> + +<ol> + <li>인풋 값 <code>string</code> 이 "0x" 나 "0X"로 시작한다면, <var>radix</var> 는 16(16진)이며, 나머지 문자열은 파싱됩니다.</li> + <li>인풋 값 <code>string</code> 이 "0"으로 시작한다면, <var>radix</var> 는 8(8진)이거나, 10(십진)입니다. 정확히 이 선택된 radix 는 구현 의존적적입니다. ECMAScript 5 는 10(십진)이 사용되는 것을 명시하지만, 모든 브라우저가 아직 이렇게 되지 않습니다. 이러한 이유로 <strong>항상 <code>parseInt</code>를 사용할 때는 radix 값을 명시해야 합니다.</strong></li> + <li>인풋 값 <code>string</code> 이 다른 값으로 시작 된다면, radix 는 10(십진)입니다.</li> +</ol> + +<p>첫 번째 글자가 숫자로 변환될 수 없다면, <code>parseInt</code> 는 <code>NaN</code>을 리턴할 것입니다.</p> + +<p>연산의 경우, <code>NaN</code> 값은 어떠한 radix 숫자도 아닙니다. <code>parseInt</code> 값이 <code>NaN</code>인지 알아내기 위해 {{jsxref("isNaN")}} 함수를 호출할 수 있습니다. 만약 <code>NaN</code>이 산술 연산으로 넘겨진다면, 이 연산의 결과 또한 NaN이 될 것입니다.</p> + +<p>특정 진수의 스트링 리터럴로 숫자를 변환하는 것은 <code>intValue.toString(radix)</code>를 사용합니다.</p> + +<div class="blockIndicator warning"> +<p>{{jsxref("BigInt")}} 주의: <code>parseInt</code>는 {{jsxref("BigInt")}}를 {{jsxref("Number")}}으로 변환하여 정확성을 떨어뜨립니다. 이는 "n"을 포함한 숫자가 아닌 값은 삭제되기 때문입니다.</p> +</div> + +<h2 id="radix가_없는_8진_해석">radix가 없는 8진 해석</h2> + +<p>비록 ECMAScript 3 에서 권장되지 않고, ECMAScript 5 에서 금지되었지만, 많은 구현들은 <code>0</code>으로 시작하는 8진수 문자열을 해석합니다. 다음의 코드는 8진 결과를 가질 수도 있으며, 10진의 결과를 가질 수도 있습니다. <strong>항상 이러한 명확하지 않은 표현은 피하고 <code>radix</code>를 명시하도록 합니다.</strong></p> + +<pre class="brush: js notranslate">parseInt("0e0"); // 0 +parseInt("08"); // 0, '8' 은 8진수가 아니다. +</pre> + +<h3 id="ECMAScript_5는_8진수_해석을_삭제하였습니다.">ECMAScript 5는 8진수 해석을 삭제하였습니다.</h3> + +<p>ECMAScript 5의 <code>parseInt</code> 함수 스펙은 더 이상 <code>0</code> 으로 시작하는 8진수 값의 문자열을 다루는 구현을 허용하지 않습니다. ECMAScript 5는 다음을 발표했습니다. :</p> + +<p><code>parseInt</code> 함수는 특정 radix(진수)값에 따라 문자열 아규먼트 내용의 해석을 하고, 그 영향을 받은 정수 값을 생성합니다. 문자열 내에서 시작되는 부분에 위치한 공백은 무시됩니다. 만약 radix 값이 정의되지 않거나, <code>0</code>이라면, 이것은 10진수로 여겨집니다. <code>0x</code> 이나 <code>0X</code> 으로 시작되는 숫자 일 때는 16진수로 여겨집니다.</p> + +<p>ECMAScript 3 와의 차이는 8진수의 해석을 허용하고 있느냐의 차이입니다.</p> + +<p>많은 구현들이 2013부터 이 방식을 채택하고 있지 않아 왔습니다. 오래된 브라우저는 지원되어야 하기 때문에 <strong>항상 radix 값을 명시 해야합니다. </strong></p> + +<h2 id="더_엄격한_파싱_함수">더 엄격한 파싱 함수</h2> + +<p>가끔은 int 값을 파싱할 때 더 엄격한 방식을 이용하는 것이유용합니다. 정규 표현식이 도움이 될 것입니다. :</p> + +<pre class="brush: js notranslate">filterInt = function (value) { + if(/^(\-|\+)?([0-9]+|Infinity)$/.test(value)) + return Number(value); + return NaN; +} + +console.log(filterInt('421')); // 421 +console.log(filterInt('-421')); // -421 +console.log(filterInt('+421')); // 421 +console.log(filterInt('Infinity')); // Infinity +console.log(filterInt('421e+0')); // NaN +console.log(filterInt('421hop')); // NaN +console.log(filterInt('hop1.61803398875')); // NaN +console.log(filterInt('1.61803398875')); // NaN +</pre> + +<h2 id="예제">예제</h2> + +<h3 id="parseInt_사용하기"><code>parseInt()</code> 사용하기</h3> + +<p>다음의 예제는 모두 <code>15</code>를 리턴합니다.</p> + +<pre class="brush: js notranslate">parseInt(" 0xF", 16); +parseInt(" F", 16); +parseInt("17", 8); +parseInt(021, 8); +parseInt("015", 10); // parseInt(015, 10); 13이 리턴될 것입니다. +parseInt(15.99, 10); +parseInt("15,123", 10); +parseInt("FXX123", 16); +parseInt("1111", 2); +parseInt("15*3", 10); +parseInt("15e2", 10); +parseInt("15px", 10); +parseInt("12", 13); +</pre> + +<p>다음의 예제는 모두 <code>NaN</code>을 리턴합니다.</p> + +<pre class="brush: js notranslate">parseInt("Hello", 8); // 전부 숫자가 아님. +parseInt("546", 2); // 숫자는 2진법 표현이 불가능함. +</pre> + +<p>다음의 예제는 모두 <code>-15</code>을 리턴합니다. :</p> + +<pre class="brush: js notranslate">parseInt("-F", 16); +parseInt("-0F", 16); +parseInt("-0XF", 16); +parseInt(-15.1, 10) +parseInt(" -17", 8); +parseInt(" -15", 10); +parseInt("-1111", 2); +parseInt("-15e1", 10); +parseInt("-12", 13); +</pre> + +<p>다음의 예제는 모두 <code>4</code>를 리턴합니다.</p> + +<pre class="notranslate">parseInt(4.7, 10) +parseInt(4.7 * 1e22, 10) // 매우 큰 숫자가 4가 됨 +parseInt(0.00000000000434, 10) // 매우 작은 숫자가 4가 됨 +</pre> + +<p>만약 숫자가 <code>1e+21</code>과 같거나 큰 경우, 또는 <code>1e-7</code>과 같거나 작은 경우, <code>1</code>을 리턴합니다.(radix가 <code>10</code>인 경우)</p> + +<pre class="notranslate">parseInt(0.0000001,10); +parseInt(0.000000123,10); +parseInt(1e-7,10); +parseInt(1000000000000000000000,10); +parseInt(123000000000000000000000,10); +parseInt(1e+21,10); +</pre> + +<p>다음의 예제는 모두 <strong><code>224</code></strong>를 리턴합니다.</p> + +<pre class="brush: js notranslate">parseInt("0e0", 16); +</pre> + +<p>{{jsxref("BigInt")}} 는 정확성을 잃습니다.</p> + +<pre class="notranslate">parseInt('900719925474099267n') +// 900719925474099300</pre> + +<p><code>parseInt</code> 는 숫자구분자와 같이 작동하지 않습니다.</p> + +<pre class="notranslate">parseInt('123_456') +// 123</pre> + +<h2 id="명세">명세</h2> + +<table> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-parseint-string-radix', 'parseInt')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div id="compat-mobile">{{Compat("javascript.builtins.parseInt")}}</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Global_Objects/parseFloat", "parseFloat()")}}</li> + <li>{{jsxref("Number.parseFloat()")}}</li> + <li>{{jsxref("Number.parseInt()")}}</li> + <li>{{jsxref("Global_Objects/isNaN", "isNaN()")}}</li> + <li>{{jsxref("Number.toString()")}}</li> + <li>{{jsxref("Object.valueOf")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/promise/all/index.html b/files/ko/web/javascript/reference/global_objects/promise/all/index.html new file mode 100644 index 0000000000..c8a458a665 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/promise/all/index.html @@ -0,0 +1,239 @@ +--- +title: Promise.all() +slug: Web/JavaScript/Reference/Global_Objects/Promise/all +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Promise +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/all +--- +<div>{{JSRef}}</div> + +<p><code><strong>Promise.all()</strong></code> 메서드는 순회 가능한 객체에 주어진 모든 프로미스가 이행한 후, 혹은 프로미스가 주어지지 않았을 때 이행하는 {{jsxref("Promise")}}를 반환합니다. 주어진 프로미스 중 하나가 거부하는 경우, 첫 번째로 거절한 프로미스의 이유를 사용해 자신도 거부합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/promise-all.html")}}</div> + +<p class="hidden">해당 예제의 소스 코드는 GitHub 리포지토리에 저장되어 있습니다. 인터랙티브 데모 프로젝트에 기여하고 싶다면 <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> 를 클론하고 pull request를 보내 주세요.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">Promise.all(<var>iterable</var>); +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>iterable</code></dt> + <dd>{{jsxref("Array")}}와 같이 <a href="/ko/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol">순회 가능</a>한(iterable) 객체.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<ul> + <li>매개변수로 주어진 순회 가능한 객체가 비어 있으면 <strong>이미 이행한</strong> {{jsxref("Promise")}}.</li> + <li>객체에 프로미스가 없으면, <strong>비동기적으로 이행하는</strong> {{jsxref("Promise")}}. 단, 구글 크롬 58은 <strong>이미 이행한</strong> 프로미스를 반환합니다.</li> + <li>그렇지 않은 경우, <strong>대기 중</strong>인 {{jsxref("Promise")}}. 결과로 반환하는 프로미스는 인자의 모든 프로미스가 이행하거나 어떤 프로미스가 거부할 때 (호출 스택이 비는 즉시) <strong>비동기적으로</strong> 이행/거부합니다. "<code>Promise.all</code>의 동기성/비동기성" 예제를 참고하세요. 반환하는 프로미스의 이행 값은 매개변수로 주어진 프로미스의 순서와 일치하며, 완료 순서에 영향을 받지 않습니다.</li> +</ul> + +<h2 id="설명">설명</h2> + +<p><code>Promise.all</code>은 여러 프로미스의 결과를 집계할 때 유용하게 사용할 수 있습니다.</p> + +<h3 id="이행">이행</h3> + +<p>반환한 프로미스의 이행 결과값은 (프로미스가 아닌 값을 포함하여) 매개변수로 주어진 순회 가능한 객체에 포함된 <strong>모든</strong> 값을 담은 배열입니다.</p> + +<ul> + <li>빈 객체를 전달한 경우, (동기적으로) 이미 이행한 프로미스를 반환합니다.</li> + <li>전달받은 모든 프로미스가 이미 이행되어 있거나 프로미스가 없는 경우, 비동기적으로 이행하는 프로미스를 반환합니다.</li> +</ul> + +<h3 id="거부">거부</h3> + +<p>주어진 프로미스 중 하나라도 거부하면, 다른 프로미스의 이행 여부에 상관없이 첫 번째 거부 이유를 사용해 거부합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="Promise.all_사용하기"><code>Promise.all</code> 사용하기</h3> + +<p><code>Promise.all</code>은 배열 내 모든 값의 이행(또는 첫 번째 거부)을 기다립니다.</p> + +<pre class="brush: js">var p1 = Promise.resolve(3); +var p2 = 1337; +var p3 = new Promise((resolve, reject) => { + setTimeout(() => { + resolve("foo"); + }, 100); +}); + +Promise.all([p1, p2, p3]).then(values => { + console.log(values); // [3, 1337, "foo"] +});</pre> + +<p>순회 가능한 객체에 프로미스가 아닌 값이 들어있다면 무시하지만, 이행 시 결과 배열에는 포함합니다.</p> + +<pre class="brush: js">// 매개변수 배열이 빈 것과 동일하게 취급하므로 이행함 +var p = Promise.all([1,2,3]); +// 444로 이행하는 프로미스 하나만 제공한 것과 동일하게 취급하므로 이행함 +var p2 = Promise.all([1,2,3, Promise.resolve(444)]); +// 555로 거부하는 프로미스 하나만 제공한 것과 동일하게 취급하므로 거부함 +var p3 = Promise.all([1,2,3, Promise.reject(555)]); + +// setTimeout()을 사용해 스택이 빈 후에 출력할 수 있음 +setTimeout(function() { + console.log(p); + console.log(p2); + console.log(p3); +}); + +// 출력 +// Promise { <state>: "fulfilled", <value>: Array[3] } +// Promise { <state>: "fulfilled", <value>: Array[4] } +// Promise { <state>: "rejected", <reason>: 555 }</pre> + +<h3 id="Promise.all의_동기성비동기성"><code>Promise.all</code>의 동기성/비동기성</h3> + +<p>다음 예제는 <code>Promise.all</code>의 비동기성(주어진 인자가 빈 경우엔 동기성)을 보입니다.</p> + +<pre class="brush: js">// Promise.all을 최대한 빨리 완료시키기 위해 +// 이미 이행된 프로미스로 배열을 만들어 인자로 전달 +var resolvedPromisesArray = [Promise.resolve(33), Promise.resolve(44)]; + +var p = Promise.all(resolvedPromisesArray); +// 실행 즉시 p의 값을 기록 +console.log(p); + +// 호출 스택을 비운 다음 실행하기 위해 setTimeout을 사용 +setTimeout(function() { + console.log('the stack is now empty'); + console.log(p); +}); + +// 로그 출력 결과 (순서대로): +// Promise { <state>: "pending" } +// the stack is now empty +// Promise { <state>: "fulfilled", <value>: Array[2] } +</pre> + +<p><code>Promise.all()</code>이 거부하는 경우에도 동일한 일이 발생합니다:</p> + +<pre class="brush: js">var mixedPromisesArray = [Promise.resolve(33), Promise.reject(44)]; +var p = Promise.all(mixedPromisesArray); +console.log(p); +setTimeout(function() { + console.log('the stack is now empty'); + console.log(p); +}); + +// 출력 +// Promise { <state>: "pending" } +// the stack is now empty +// Promise { <state>: "rejected", <reason>: 44 } +</pre> + +<p>그러나, <code>Promise.all</code>은 주어진 순회 가능한 객체가 비어있는 경우에만 동기적으로 이행됩니다.</p> + +<pre class="brush: js">var p = Promise.all([]); // 즉시 이행함 +var p2 = Promise.all([1337, "hi"]); // 프로미스가 아닌 값은 무시하지만 비동기적으로 실행됨 +console.log(p); +console.log(p2); +setTimeout(function() { + console.log('the stack is now empty'); + console.log(p2); +}); + +// 출력 +// Promise { <state>: "fulfilled", <value>: Array[0] } +// Promise { <state>: "pending" } +// the stack is now empty +// Promise { <state>: "fulfilled", <value>: Array[2] } +</pre> + +<h3 id="Promise.all()_실패_우선성"><code>Promise.all()</code> 실패 우선성</h3> + +<p><code>Promise.all()</code>은 배열 내 요소 중 어느 하나라도 거부하면 즉시 거부합니다. 예를 들어, 일정 시간이 지난 이후 이행하는 네 개의 프로미스와, 즉시 거부하는 하나의 프로미스를 전달한다면 <code>Promise.all()</code>도 즉시 거부합니다.</p> + +<pre class="brush: js">var p1 = new Promise((resolve, reject) => { + setTimeout(() => resolve('하나'), 1000); +}); +var p2 = new Promise((resolve, reject) => { + setTimeout(() => resolve('둘'), 2000); +}); +var p3 = new Promise((resolve, reject) => { + setTimeout(() => resolve('셋'), 3000); +}); +var p4 = new Promise((resolve, reject) => { + setTimeout(() => resolve('넷'), 4000); +}); +var p5 = new Promise((resolve, reject) => { + reject(new Error('거부')); +}); + + +// .catch 사용: +Promise.all([p1, p2, p3, p4, p5]) +.then(values => { + console.log(values); +}) +.catch(error => { + console.log(error.message) +}); + +// 콘솔 출력값: +// "거부" +</pre> + +<p>발생할 수 있는 거부를 사전에 처리해 동작 방식을 바꿀 수 있습니다.</p> + +<pre class="brush: js">var p1 = new Promise((resolve, reject) => { + setTimeout(() => resolve('p1_지연_이행'), 1000); +}); + +var p2 = new Promise((resolve, reject) => { + reject(new Error('p2_즉시_거부')); +}); + +Promise.all([ + p1.catch(error => { return error }), + p2.catch(error => { return error }), +]).then(values => { + console.log(values[0]) // "p1_지연_이행" + console.log(values[1]) // "Error: p2_즉시_거부" +}) +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-promise.all', 'Promise.all')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition in an ECMA standard.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-promise.all', 'Promise.all')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div class="hidden">To contribute to this compatibility data, please write a pull request against this repository: <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>.</div> + +<p>{{Compat("javascript.builtins.Promise.all")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Promise")}}</li> + <li>{{jsxref("Promise.race()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/promise/allsettled/index.html b/files/ko/web/javascript/reference/global_objects/promise/allsettled/index.html new file mode 100644 index 0000000000..a063f29c7c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/promise/allsettled/index.html @@ -0,0 +1,66 @@ +--- +title: Promise.allSettled() +slug: Web/JavaScript/Reference/Global_Objects/Promise/allSettled +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/allSettled +--- +<p>{{JSRef}}</p> + +<p><code><strong>Promise.allSettled()</strong></code> 메소드는 배열이나 별도의 나열 가능한 객체를 통해 나열된 Promise모음이 모두 이행하거나 거부했을 때에 대한 대응을 할 수 있는 Promise 객체를 반환한다.</p> + +<div>{{EmbedInteractiveExample("pages/js/promise-allsettled.html")}}</div> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox"><em>Promise</em>.allSettled(<em>iterable</em>);</pre> + +<h3 id="인자">인자</h3> + +<dl> + <dt><code>iterable</code></dt> + <dd><a href="/en-US/docs/Web/JavaScript/Guide/iterable">iterable</a> 객체로, 주로 배열({{jsxref("Array")}})을 사용하며, 이들의 요소들은 모두 <code>Promise</code> 객체.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p><strong>실행할</strong> {{jsxref("Promise")}} 객체로 <strong>비동기</strong> 방식으로 이행(Resolved) 및 거부(Rejected)된 결과의 모음을 담아 인자로 전달된다. 이 때 반환된 Promise 객체의 핸들러는 각 본래 Promise 객체가 담긴 배열을 전달할 것이다.</p> + +<p>각 출력 객체는 <code>status</code> 속성을 통해, <code>fulfilled</code>,상태로 전달되면 <code>value</code> 속성이 전달되고, <code>rejected</code> 상태로 전달 시 <code>reason</code> 속성으로 전달된다. 각 Promise가 어떻게 이행(또는 거부)됐는지 value 속성 및 reason 속성을 통해 알 수 있다.</p> + +<h2 id="문서_표준">문서 표준</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td><a href="https://tc39.es/proposal-promise-allSettled/#sec-promise.allsettled"><code>Promise.allSettled()</code> (TC39 Stage 4 Draft)</a></td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="지원_브라우저">지원 브라우저</h2> + +<p class="hidden">To contribute to this compatibility data, please write a pull request against this repository: <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>.</p> + +<p>{{Compat("javascript.builtins.Promise.allSettled")}}</p> + +<h3 id="구현_진행_상태">구현 진행 상태</h3> + +<p>The following table provides a daily implementation status for this feature, because this feature has not yet reached cross-browser stability. The data is generated by running the relevant feature tests in <a href="https://github.com/tc39/test262">Test262</a>, the standard test suite of JavaScript, in the nightly build, or latest release of each browser's JavaScript engine.</p> + +<div>{{EmbedTest262ReportResultsTable("Promise.allSettled")}}</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/en-US/docs/Archive/Add-ons/Techniques/Promises">Promises</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Using_promises">Using promises</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/Asynchronous/Promises">Graceful asynchronous programming with promises</a></li> + <li>{{jsxref("Promise")}}</li> + <li>{{jsxref("Promise.all()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/promise/finally/index.html b/files/ko/web/javascript/reference/global_objects/promise/finally/index.html new file mode 100644 index 0000000000..c75d73ab06 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/promise/finally/index.html @@ -0,0 +1,100 @@ +--- +title: Promise.prototype.finally() +slug: Web/JavaScript/Reference/Global_Objects/Promise/finally +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/finally +--- +<div>{{JSRef}}</div> + +<p><code><strong>finally()</strong></code> 메소드는 {{jsxref("Promise")}} 객체를 반환합니다. Promise가 처리되면 충족되거나 거부되는지 여부에 관계없이 지정된 콜백 함수가 실행됩니다. 이것은 Promise가 성공적으로 수행 되었는지 거절되었는지에 관계없이 <code>Promise</code>가 처리 된 후에 코드가 무조건 한 번은 실행되는 것을 제공합니다.</p> + +<p>이것은 Promise의 {{jsxref("Promise.then", "then()")}}과 {{jsxref("Promise.catch", "catch()")}} 핸들러에서의 코드 중복을 피하게 합니다.</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox"><var>p.finally(onFinally)</var>; + +p.finally(function() { + // settled (fulfilled or rejected) +}); +</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>onFinally</code></dt> + <dd><code>Promise</code>가 처리된 후 {{jsxref("Function")}} 이 호출됩니다.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p><code>finally</code> 핸들러는 <code>onFinally</code> 라는 지정된 함수의 {{jsxref("Promise")}}가 반환됩니다.</p> + +<h2 id="설명">설명</h2> + +<p> </p> + +<p><code>finally()</code> 메서드는 결과에 관계없이 promise가 처리되면 무언가를 프로세싱 또는 정리를 수행하려는 경우에 유용합니다.</p> + +<p><code>finally()</code> 메서드는 <code>.then(onFinally, onFinally)</code> 를 호출하는 것과 매우 비슷하지만 몇 가지 차이점이 있습니다:</p> + +<p> </p> + +<ul> + <li>함수를 인라인으로 만들 때, 두 번 선언해야 하지 않고 한 번만 전달하거나 그것을 위한 변수를 만들 수 있습니다.</li> + <li><code>finally</code> 콜백은 어떠한 인수도 전달받지 않습니다, 왜냐하면 promise가 이행되었는지 또는 거부되었는지를 판단할 수 없기 때문입니다. promise의 왜 거부되었는지 또는 이행되었을때 반환되는 값이 필요하지 않거나 제공할 필요가 없을 때 활용합니다.</li> + <li>Promise.reject (3) .finally (() => {}) Promise.reject (3) .finally (() => {}) (약속 안 함) )는 3으로 거부됩니다.</li> + <li><code>Promise.resolve(2).then(() => {}, () => {})</code>(<code>undefined</code>로 해결될) 와 달리, <code>Promise.resolve(2).finally(() => {})</code> 는 값 <code>2</code>로 해결됩니다.</li> + <li>유사하게 <code>Promise.reject(3).then(() => {}, () => {})</code> (<code>undefined</code>로 거부될)와는 달리 <code>Promise.reject(3).finally(() => {})</code> 는 값 <code>3</code>로 거부됩니다.</li> +</ul> + +<div class="note"> +<p><strong>Note:</strong> <code>finally</code> 콜백에서 <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5); font-size: 16px;">throw</span></font> (또는 거부된 promise를 반환)하면 <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5); font-size: 16px;">throw()</span></font>를 호출 할 때 지정된 거부 이유로 새롭게 만들어진 promise를 반환합니다.</p> +</div> + +<h2 id="예제">예제</h2> + +<pre class="brush: js">let isLoading = true; + +fetch(myRequest).then(function(response) { + var contentType = response.headers.get("content-type"); + if(contentType && contentType.includes("application/json")) { + return response.json(); + } + throw new TypeError("Oops, we haven't got JSON!"); + }) + .then(function(json) { /* process your JSON further */ }) + .catch(function(error) { console.log(error); }) + .finally(function() { isLoading = false; }); + +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td><a href="https://github.com/tc39/proposal-promise-finally">TC39 proposal</a></td> + <td>Stage 4</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">To contribute to this compatibility data, please write a pull request against this repository: <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>.</p> + +<p>{{Compat("javascript.builtins.Promise.finally")}}</p> + +<h2 id="더보기">더보기</h2> + +<ul> + <li>{{jsxref("Promise")}}</li> + <li>{{jsxref("Promise.prototype.then()")}}</li> + <li>{{jsxref("Promise.prototype.catch()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/promise/index.html b/files/ko/web/javascript/reference/global_objects/promise/index.html new file mode 100644 index 0000000000..d3dbf076c5 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/promise/index.html @@ -0,0 +1,226 @@ +--- +title: Promise +slug: Web/JavaScript/Reference/Global_Objects/Promise +tags: + - ECMAScript 2015 + - JavaScript + - Promise + - Reference + - 프로미스 +translation_of: Web/JavaScript/Reference/Global_Objects/Promise +--- +<div>{{JSRef}}</div> + +<p><strong><code>Promise</code></strong> 객체는 비동기 작업이 맞이할 미래의 완료 또는 실패와 그 결과 값을 나타냅니다.</p> + +<p>Promise의 작동 방식과 Promise 사용 방법에 대해 알아보려면 먼저 <a href="https://wiki.developer.mozilla.org/ko/docs/Web/JavaScript/Guide/Using_promises">Promise 사용 방법</a>을 읽어 보십시오.</p> + +<h2 id="설명">설명</h2> + +<p><code>Promise</code>는 프로미스가 생성될 때 꼭 알 수 있지는 않은 값을 위한 대리자로, 비동기 연산이 종료된 이후의 결과값이나 실패 이유를 처리하기 위한 처리기를 연결할 수 있도록 합니다. 프로미스를 사용하면 비동기 메서드에서 마치 동기 메서드처럼 값을 반환할 수 있습니다. 다만 최종 결과를 반환하지는 않고, 대신 프로미스를 반환해서 미래의 어떤 시점에 결과를 제공합니다.</p> + +<p><code>Promise</code>는 다음 중 하나의 상태를 가집니다.</p> + +<ul> + <li>대기(<em>pending)</em>: 이행하거나 거부되지 않은 초기 상태.</li> + <li>이행(<em>fulfilled)</em>: 연산이 성공적으로 완료됨.</li> + <li>거부(<em>rejected)</em>: 연산이 실패함.</li> +</ul> + +<p>대기 중인 프로미스는 값과 함께 <em>이행할</em> 수도, 어떤 이유(오류)로 인해 <em>거부</em>될 수 있습니다. 이행이나 거부될 때, 프로미스에 연결한 처리기는 그 프로미스의 <code>then</code> 메서드에 의해 대기열에 오릅니다. 이미 이행했거나 거부된 프로미스에 연결한 처리기도 호출하므로, 비동기 연산과 처리기 연결 사이에 경합 조건<sup>race condition</sup>은 없습니다.</p> + +<p>{{jsxref("Promise.prototype.then()")}} 및 {{jsxref("Promise.prototype.catch()")}} 메서드의 반환 값은 다른 프로미스이므로, 서로 연결할 수 있습니다.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/8633/promises.png"></p> + +<div class="note"> +<p><strong>혼동 주의:</strong> 느긋한 계산법 및 연산 연기를 위한 방법을 프로미스라고 부르는 다른 언어(예: Scheme)가 여럿 있습니다. 반면 JavaScript에서 프로미스는 콜백 함수를 연결할 수 있는 이미 진행 중인 프로세스를 나타냅니다. 표현식을 느긋하게 평가하려면 인수 없는 <a href="/ko/docs/Web/JavaScript/Reference/Functions/애로우_펑션">화살표 함수</a> <code>f = () => <em>expression</em></code>를 사용하고, <code>f()</code>를 사용해 평가하세요.</p> +</div> + +<div class="note"> +<p><strong>참고</strong>: 프로미스는 대기 중이지 않으며 이행 또는 거부됐을 때 처리(settled)됐다고 말합니다. 프로미스와 함께 쓰이는 단어 resolved는 프로미스가 다른 프로미스의 상태에 맞춰 처리됨, 또는 상태가 "잠김"되었다는 의미입니다. 용어에 관한 더 자세한 설명은 Domenic Denicola의 글 <a href="https://github.com/domenic/promises-unwrapping/blob/master/docs/states-and-fates.md" title="States and fates">States and fates</a>에서 볼 수 있습니다.</p> +</div> + +<h2 id="생성자">생성자</h2> + +<dl> + <dt>{{jsxref("Promise.Promise", "Promise()")}}</dt> + <dd>이미 프로미스를 지원하지 않는 함수를 감쌀 때 주로 사용합니다.</dd> +</dl> + +<h2 id="속성">속성</h2> + +<dl> + <dt><code>Promise.length</code></dt> + <dd>값이 언제나 1인 길이 속성입니다. (생성자 인수의 수)</dd> + <dt>{{jsxref("Promise.prototype")}}</dt> + <dd><code>Promise</code> 생성자의 프로토타입을 나타냅니다.</dd> +</dl> + +<h2 id="메서드">메서드</h2> + +<dl> + <dt>{{jsxref("Promise.all", "Promise.all(iterable)")}}</dt> + <dd><code>iterable</code> 내의 모든 프로미스가 이행한 뒤 이행하고, 어떤 프로미스가 거부하면 즉시 거부하는 프로미스를 반환합니다. 반환된 프로미스가 이행하는 경우 <code>iterable</code> 내의 프로미스가 결정한 값을 모은 배열이 이행 값입니다. 반환된 프로미스가 거부하는 경우 <code>iterable</code> 내의 거부한 프로미스의 이유를 그대로 사용합니다. 이 메서드는 여러 프로미스의 결과를 모을 때 유용합니다.</dd> + <dt>{{jsxref("Promise.race", "Promise.race(iterable)")}}</dt> + <dd><code>iterable</code> 내의 어떤 프로미스가 이행하거나 거부하는 즉시 스스로 이행하거나 거부하는 프로미스를 반환합니다. 이행 값이나 거부 이유는 원 프로미스의 값이나 이유를 그대로 사용합니다.</dd> +</dl> + +<dl> + <dt>{{jsxref("Promise.reject()")}}</dt> + <dd>주어진 이유로 거부하는 <code>Promise</code> 객체를 반환합니다.</dd> +</dl> + +<dl> + <dt>{{jsxref("Promise.resolve()")}}</dt> + <dd>주어진 값으로 이행하는 <code>Promise</code> 객체를 반환합니다. 값이 <code>then</code> 가능한 (즉, <code>then</code> 메서드가 있는) 경우, 반환된 프로미스는 <code>then</code> 메서드를 따라가고 마지막 상태를 취합니다. 그렇지 않은 경우 반환된 프로미스는 주어진 값으로 이행합니다. 어떤 값이 프로미스인지 아닌지 알 수 없는 경우, {{jsxref("Promise.resolve", "Promise.resolve(value)")}} 후 반환값을 프로미스로 처리할 수 있습니다.</dd> +</dl> + +<h2 id="Promise_프로토타입"><code>Promise</code> 프로토타입</h2> + +<h3 id="속성_2">속성</h3> + +<p>{{page('ko/docs/Web/JavaScript/Reference/Global_Objects/Promise/prototype','속성')}}</p> + +<h3 id="메서드_2">메서드</h3> + +<p>{{page('ko/docs/Web/JavaScript/Reference/Global_Objects/Promise/prototype','메서드')}}</p> + +<h2 id="예제">예제</h2> + +<h3 id="기본_예제">기본 예제</h3> + +<pre class="brush: js notranslate">let myFirstPromise = new Promise((resolve, reject) => { + // We call resolve(...) when what we were doing asynchronously was successful, and reject(...) when it failed. + // In this example, we use setTimeout(...) to simulate async code. + // In reality, you will probably be using something like XHR or an HTML5 API. + setTimeout(function(){ + resolve("Success!"); // Yay! Everything went well! + }, 250); +}); + +myFirstPromise.then((successMessage) => { + // successMessage is whatever we passed in the resolve(...) function above. + // It doesn't have to be a string, but if it is only a succeed message, it probably will be. + console.log("Yay! " + successMessage); +});</pre> + +<h3 id="고급_예제">고급 예제</h3> + +<div class="hidden"> +<pre class="brush: html notranslate"><button id="btn">프로미스 만들기!</button> +<div id="log"></div></pre> +</div> + +<p>다음의 작은 예제는 <code>Promise</code>의 동작 방식을 보여줍니다. <code>testPromise()</code> 함수는 {{HTMLElement("button")}}을 클릭할 때마다 호출되며, {{domxref("window.setTimeout()")}}을 사용해 1~3초의 무작위 간격 이후 프로미스 횟수(1부터 시작하는 숫자)로 이행하는 프로미스를 생성합니다. <code>Promise()</code> 생성자는 프로미스를 만드는 데 쓰입니다.</p> + +<p>프로미스 이행은 {{jsxref("Promise.prototype.then()","p1.then()")}}을 사용하는 이행 콜백 세트를 통해 단순히 로그에 남습니다. 약간의 로그를 통해, 함수의 동기 부분이 비동기적 프로미스의 완료와 어떻게 분리되어 있는지 확인할 수 있습니다.</p> + +<pre class="brush: js notranslate">'use strict'; +var promiseCount = 0; + +function testPromise() { + var thisPromiseCount = ++promiseCount; + + var log = document.getElementById('log'); + log.insertAdjacentHTML('beforeend', thisPromiseCount + + ') 시작 (<small>동기적 코드 시작</small>)<br/>'); + + // 새 프로미스 생성 - 프로미스의 생성 순서를 전달하겠다는 약속을 함 (3초 기다린 후) + var p1 = new Promise( + // 실행 함수는 프로미스를 이행(resolve)하거나 + // 거부(reject)할 수 있음 + function(resolve, reject) { + log.insertAdjacentHTML('beforeend', thisPromiseCount + + ') 프로미스 시작 (<small>비동기적 코드 시작</small>)<br/>'); + // setTimeout은 비동기적 코드를 만드는 예제에 불과 + window.setTimeout( + function() { + // 프로미스 이행 ! + resolve(thisPromiseCount); + }, Math.random() * 2000 + 1000); + } + ); + + // 프로미스를 이행했을 때 할 일은 then() 호출로 정의하고, + // 거부됐을 때 할 일은 catch() 호출로 정의 + p1.then( + // 이행 값 기록 + function(val) { + log.insertAdjacentHTML('beforeend', val + + ') 프로미스 이행 (<small>비동기적 코드 종료</small>)<br/>'); + }) + .catch( + // 거부 이유 기록 + function(reason) { + console.log('여기서 거부된 프로미스(' + reason + ')를 처리하세요.'); + }); + + log.insertAdjacentHTML('beforeend', thisPromiseCount + + ') 프로미스 생성 (<small>동기적 코드 종료</small>)<br/>'); +} +</pre> + +<div class="hidden"> +<pre class="brush: js notranslate">if ("Promise" in window) { + var btn = document.getElementById("btn"); + btn.addEventListener("click", testPromise); +} else { + log = document.getElementById('log'); + log.innerHTML = "Live example not available as your browser doesn't support the <code>Promise<code> interface."; +}</pre> +</div> + +<p>이 예제는 버튼을 클릭하면 실행됩니다. <code>Promise</code>를 지원하는 브라우저가 필요합니다. 짧은 시간 안에 버튼을 여러 번 클릭하여, 서로 다른 프로미스가 번갈아 이행되는 것을 볼 수도 있습니다.</p> + +<p>{{EmbedLiveSample("고급_예제", "500", "200")}}</p> + +<h2 id="XHR로_이미지_불러오기">XHR로 이미지 불러오기</h2> + +<p>이미지를 로드하기 위해 <code>Promise</code> 및 {{domxref("XMLHttpRequest")}}를 사용하는 또 다른 간단한 예는 MDN GitHub <a href="https://github.com/mdn/js-examples/tree/master/promises-test">js-examples</a> 저장소에서 이용할 수 있습니다. <a href="http://mdn.github.io/promises-test/">실제 예</a>를 볼 수도 있습니다. 각 단계에 주석이 붙어있어, 프로미스 및 XHR 구조를 차근차근 따라갈 수 있습니다.</p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-promise-objects', 'Promise')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>ECMA 표준에서 초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-promise-objects', 'Promise')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Promise")}}</p> +</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/Using_promises">프로미스 사용하기</a></li> + <li><a href="http://promisesaplus.com/">Promises/A+ 스펙</a></li> + <li><a href="https://medium.com/@ramsunvtech/promises-of-promise-part-1-53f769245a53">Venkatraman.R - JS Promise (Part 1, Basics)</a></li> + <li><a href="https://medium.com/@ramsunvtech/js-promise-part-2-q-js-when-js-and-rsvp-js-af596232525c#.dzlqh6ski">Venkatraman.R - JS Promise (Part 2 - Using Q.js, When.js and RSVP.js)</a></li> + <li><a href="https://tech.io/playgrounds/11107/tools-for-promises-unittesting/introduction">Venkatraman.R - Tools for Promises Unit Testing</a></li> + <li><a href="http://www.html5rocks.com/en/tutorials/es6/promises/">Jake Archibald: JavaScript Promises: There and Back Again</a></li> + <li><a href="http://de.slideshare.net/domenicdenicola/callbacks-promises-and-coroutines-oh-my-the-evolution-of-asynchronicity-in-javascript">Domenic Denicola: Callbacks, Promises, and Coroutines – Asynchronous Programming Patterns in JavaScript</a></li> + <li><a href="http://www.mattgreer.org/articles/promises-in-wicked-detail/">Matt Greer: JavaScript Promises ... In Wicked Detail</a></li> + <li><a href="https://www.promisejs.org/">Forbes Lindesay: promisejs.org</a></li> + <li><a href="https://github.com/jakearchibald/es6-promise/">Promise polyfill</a></li> + <li><a href="https://www.udacity.com/course/javascript-promises--ud898">Udacity: JavaScript Promises</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/promise/promise/index.html b/files/ko/web/javascript/reference/global_objects/promise/promise/index.html new file mode 100644 index 0000000000..531b82dbca --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/promise/promise/index.html @@ -0,0 +1,78 @@ +--- +title: Promise() 생성자 +slug: Web/JavaScript/Reference/Global_Objects/Promise/Promise +tags: + - Constructor + - JavaScript + - Promise + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/Promise +--- +<div>{{JSRef}}</div> + +<p><strong><code>Promise</code></strong> 생성자는 주로 프로미스를 지원하지 않는 함수를 감쌀 때 사용합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/promise-constructor.html")}}</div> + +<p class="hidden">The source for this interactive demo is stored in a GitHub repository. If you'd like to contribute to the interactive demo project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">new Promise(<var>executor</var>)</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>executor</code></dt> + <dd><code>resolve</code> 및 <code>reject</code> 인수를 전달할 실행 함수. 실행 함수는 프로미스 구현에 의해 <code>resolve</code>와 <code>reject</code> 함수를 받아 즉시 실행됩니다(실행 함수는 <code>Promise</code> 생성자가 생성한 객체를 반환하기도 전에 호출됩니다). <code>resolve</code> 및 <code>reject</code> 함수는 호출할 때 각각 프로미스를 이행하거나 거부합니다. 실행 함수는 보통 어떤 비동기 작업을 시작한 후 모든 작업을 끝내면 <code>resolve</code>를 호출해 프로미스를 이행하고, 오류가 발생한 경우 <code>reject</code>를 호출해 거부합니다. 실행 함수에서 오류를 던지면 프로미스는 거부됩니다. 실행 함수의 반환값은 무시됩니다.</dd> +</dl> + +<h2 id="예제">예제</h2> + +<p><code>Promise</code> 객체는 <code>new</code> 키워드와 생성자를 사용해 만듭니다. 생성자는 매개변수로 "실행 함수"를 받습니다. 이 함수는 매개 변수로 두 가지 함수를 받아야 하는데, 첫 번째 함수(<code>resolve</code>)는 비동기 작업을 성공적으로 완료해 결과를 값으로 반환할 때 호출해야 하고, 두 번째 함수(<code>reject</code>)는 작업이 실패하여 오류의 원인을 반환할 때 호출하면 됩니다. 두 번째 함수는 주로 오류 객체를 받습니다.</p> + +<pre class="brush: js;">const myFirstPromise = new Promise((resolve, reject) => { + // do something asynchronous which eventually calls either: + // + // resolve(someValue) // fulfilled + // or + // reject("failure reason") // rejected +}); +</pre> + +<p>함수에 프로미스 기능을 추가하려면, 간단하게 프로미스를 반환하도록 하면 됩니다.</p> + +<pre class="brush: js;">function myAsyncFunction(url) { + return new Promise((resolve, reject) => { + const xhr = new XMLHttpRequest() + xhr.open("GET", url) + xhr.onload = () => resolve(xhr.responseText) + xhr.onerror = () => reject(xhr.statusText) + xhr.send() + }); +}</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-promise-constructor', 'Promise constructor')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div class="hidden">To contribute to this compatibility data, please write a pull request against this repository: <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>.</div> + +<p>{{Compat("javascript.builtins.Promise.Promise")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Guide/Using_promises">프로미스 사용하기</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/promise/prototype/index.html b/files/ko/web/javascript/reference/global_objects/promise/prototype/index.html new file mode 100644 index 0000000000..4569b4d26a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/promise/prototype/index.html @@ -0,0 +1,71 @@ +--- +title: Promise.prototype +slug: Web/JavaScript/Reference/Global_Objects/Promise/prototype +tags: + - JavaScript + - Promise + - Property + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Promise +--- +<div>{{JSRef}}</div> + +<p><strong><code>Promise.prototype</code></strong> 속성은 {{jsxref("Promise")}} 생성자의 프로토타입을 나타냅니다.</p> + +<div>{{js_property_attributes(0,0,0)}}</div> + +<h2 id="설명">설명</h2> + +<p>{{jsxref("Promise")}} 인스턴스는 {{jsxref("Promise.prototype")}}을 상속합니다. 모든 <code>Promise</code> 인스턴스에 속성 또는 메서드를 추가하기 위해 생성자의 프로토타입 객체를 사용할 수 있습니다.</p> + +<h2 id="속성">속성</h2> + +<dl> + <dt><code>Promise.prototype.constructor</code></dt> + <dd>인스턴스의 프로토타입을 만드는 함수를 반환합니다. 기본값은 {{jsxref("Promise")}} 함수입니다.</dd> +</dl> + +<h2 id="메서드">메서드</h2> + +<dl> + <dt>{{jsxref("Promise.prototype.catch()")}}</dt> + <dd>프로미스(promise)에 거부 처리기 콜백을 추가하고 호출된 경우 콜백의 반환값 또는 프로미스가 대신 이행된 경우 그 원래 이행(fulfillment)값으로 결정하는(resolving) 새 프로미스를 반환합니다.</dd> + <dt>{{jsxref("Promise.prototype.then()")}}</dt> + <dd>프로미스에 이행 또는 거부 처리기를 추가하고 호출된 처리기의 반환값 또는 프로미스가 처리되지 않은 경우 그 원래 처리된(settled) 값으로 결정하는 새 프로미스를 반환합니다 (즉 관련 처리기 <code>onFulfilled</code> 또는 <code>onRejected</code>가 <code>undefined</code>인 경우).</dd> + <dt>{{jsxref("Promise.prototype.finally()")}}</dt> + <dd>Appends a handler to the promise, and returns a new promise which is resolved when the original promise is resolved. The handler is called when the promise is settled, whether fulfilled or rejected.</dd> +</dl> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-promise.prototype', 'Promise.prototype')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-promise.prototype', 'Promise.prototype')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Promise.prototype")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Promise")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/promise/race/index.html b/files/ko/web/javascript/reference/global_objects/promise/race/index.html new file mode 100644 index 0000000000..0874d619dd --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/promise/race/index.html @@ -0,0 +1,187 @@ +--- +title: Promise.race() +slug: Web/JavaScript/Reference/Global_Objects/Promise/race +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Promise + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/race +--- +<div>{{JSRef}}</div> + +<p><code><strong>Promise.race()</strong></code> 메소드는 Promise 객체를 반환합니다. 이 프로미스 객체는 iterable 안에 있는 프로미스 중에 가장 먼저 완료된 것의 결과값으로 그대로 이행하거나 거부합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/promise-race.html")}}</div> + +<p class="hidden">해당 예제의 소스 코드는 GitHub 리포지토리에 저장되어 있습니다. 인터랙티브 데모 프로젝트에 기여하고 싶다면 <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> 를 클론하고 pull request를 보내 주세요.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">Promise.race(<em>iterable</em>);</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>iterable</code></dt> + <dd>{{jsxref("Array")}}와 같은 iterable 객체. <a href="/ko/docs/Web/JavaScript/Reference/Iteration_protocols">iterable</a>을 참고하세요.</dd> +</dl> + +<h3 id="반환값">반환값</h3> + +<p>주어진 iterable에서 처음으로 이행하거나 거부한 프로미스의 값을 <strong>비동기적으로</strong> 전달받는 <strong>대기 중</strong>인 {{jsxref("Promise")}}.</p> + +<h2 id="설명">설명</h2> + +<p><code>race</code> 함수는 인자로 주어진 iterable의 프로미스 중 가장 먼저 완료(settle)되는 것과 같은 방식으로 완료(이행/거부)되고, 같은 결과값을 전달하는 <code>Promise</code>를 반환합니다.</p> + +<p>전달받은 iterable이 비어 있을 경우, 반환한 프로미스는 영원히 대기 상태가 됩니다.</p> + +<p>Iterable에 프로미스가 아닌 값이나 이미 완료된 프로미스가 포함되어 있을 경우, <code>Promise.race</code>는 전달받은 iterable에서 처음으로 등장하는 이러한 값을 결과값으로 이행합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="Promise.race의_비동기성"><font face="consolas, Liberation Mono, courier, monospace"><code>Promise.race</code>의 비동기성</font></h3> + +<p>다음 예제에서 <code>Promise.race</code>의 비동기성을 확인할 수 있습니다.</p> + +<pre class="brush: js">// Promise.race를 최대한 빨리 완료시키기 위해 +// 이미 이행된 프로미스로 배열을 만들어 인자로 전달 +var resolvedPromisesArray = [Promise.resolve(33), Promise.resolve(44)]; + +var p = Promise.race(resolvedPromisesArray); +// 실행 즉시 p의 값을 기록 +console.log(p); + +// 호출 스택을 비운 다음 실행하기 위해 setTimeout을 사용 +setTimeout(function(){ + console.log('the stack is now empty'); + console.log(p); +}); + +// 로그 출력 결과 (순서대로): +// Promise { <state>: "pending" } +// the stack is now empty +// Promise { <state>: "fulfilled", <value>: 33 }</pre> + +<p>비어 있는 iterable을 전달하면 반환한 프로미스는 영원히 대기 상태가 됩니다.</p> + +<pre class="brush: js">var foreverPendingPromise = Promise.race([]); +console.log(foreverPendingPromise); +setTimeout(function(){ + console.log('the stack is now empty'); + console.log(foreverPendingPromise); +}); + +// 로그 출력 결과 (순서대로): +// Promise { <state>: "pending" } +// the stack is now empty +// Promise { <state>: "pending" } +</pre> + +<p>Iterable에 프로미스가 아닌 값이나 이미 완료된 프로미스가 포함되어 있을 경우, <code>Promise.race</code>는 전달받은 iterable에서 처음으로 등장하는 이러한 값을 결과값으로 이행합니다.</p> + +<pre class="brush: js">var foreverPendingPromise = Promise.race([]); +var alreadyFulfilledProm = Promise.resolve(666); + +var arr = [foreverPendingPromise, alreadyFulfilledProm, "프로미스 아님"]; +var arr2 = [foreverPendingPromise, "프로미스 아님", Promise.resolve(666)]; +var p = Promise.race(arr); +var p2 = Promise.race(arr2); + +console.log(p); +console.log(p2); +setTimeout(function(){ + console.log('the stack is now empty'); + console.log(p); + console.log(p2); +}); + +// 로그 출력 결과 (순서대로): +// Promise { <state>: "pending" } +// Promise { <state>: "pending" } +// the stack is now empty +// Promise { <state>: "fulfilled", <value>: 666 } +// Promise { <state>: "fulfilled", <value>: "프로미스 아님" } +</pre> + +<h3 id="setTimeout과_함께_Promise.race_사용_예"><code>setTimeout</code>과 함께 <code>Promise.race</code> 사용 예</h3> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">var</span> p1 <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Promise</span><span class="punctuation token">(</span><span class="keyword token">function</span><span class="punctuation token">(</span><span class="parameter token">resolve<span class="punctuation token">,</span> reject</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="function token">setTimeout</span><span class="punctuation token">(</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="operator token">=></span> <span class="function token">resolve</span><span class="punctuation token">(</span><span class="string token">'하나'</span><span class="punctuation token">)</span><span class="punctuation token">,</span> <span class="number token">500</span><span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="keyword token">var</span> p2 <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Promise</span><span class="punctuation token">(</span><span class="keyword token">function</span><span class="punctuation token">(</span><span class="parameter token">resolve<span class="punctuation token">,</span> reject</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="function token">setTimeout</span><span class="punctuation token">(</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="operator token">=></span> <span class="function token">resolve</span><span class="punctuation token">(</span><span class="string token">'둘'</span><span class="punctuation token">)</span><span class="punctuation token">,</span> <span class="number token">100</span><span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + +Promise<span class="punctuation token">.</span><span class="function token">race</span><span class="punctuation token">(</span><span class="punctuation token">[</span>p1<span class="punctuation token">,</span> p2<span class="punctuation token">]</span><span class="punctuation token">)</span> +<span class="punctuation token">.</span><span class="function token">then</span><span class="punctuation token">(</span><span class="keyword token">function</span><span class="punctuation token">(</span><span class="parameter token">value</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span>value<span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// "둘"</span> + <span class="comment token">// 둘 다 이행하지만 p2가 더 빠르므로</span> +<span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + +<span class="keyword token">var</span> p3 <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Promise</span><span class="punctuation token">(</span><span class="keyword token">function</span><span class="punctuation token">(</span><span class="parameter token">resolve<span class="punctuation token">,</span> reject</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="function token">setTimeout</span><span class="punctuation token">(</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="operator token">=></span> <span class="function token">resolve</span><span class="punctuation token">(</span><span class="string token">'셋'</span><span class="punctuation token">)</span><span class="punctuation token">,</span> <span class="number token">100</span><span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="keyword token">var</span> p4 <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Promise</span><span class="punctuation token">(</span><span class="keyword token">function</span><span class="punctuation token">(</span><span class="parameter token">resolve<span class="punctuation token">,</span> reject</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="function token">setTimeout</span><span class="punctuation token">(</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="operator token">=></span> <span class="function token">reject</span><span class="punctuation token">(</span><span class="keyword token">new</span> <span class="class-name token">Error</span><span class="punctuation token">(</span><span class="string token">'넷'</span><span class="punctuation token">)</span><span class="punctuation token">)</span><span class="punctuation token">,</span> <span class="number token">500</span><span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + +Promise<span class="punctuation token">.</span><span class="function token">race</span><span class="punctuation token">(</span><span class="punctuation token">[</span>p3<span class="punctuation token">,</span> p4<span class="punctuation token">]</span><span class="punctuation token">)</span> +<span class="punctuation token">.</span><span class="function token">then</span><span class="punctuation token">(</span><span class="keyword token">function</span><span class="punctuation token">(</span><span class="parameter token">value</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span>value<span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// "셋"</span> + <span class="comment token">// p3이 더 빠르므로 이행함</span> +<span class="punctuation token">}</span><span class="punctuation token">,</span> <span class="keyword token">function</span><span class="punctuation token">(</span><span class="parameter token">reason</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="comment token">// 실행되지 않음</span> +<span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + +<span class="keyword token">var</span> p5 <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Promise</span><span class="punctuation token">(</span><span class="keyword token">function</span><span class="punctuation token">(</span><span class="parameter token">resolve<span class="punctuation token">,</span> reject</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="function token">setTimeout</span><span class="punctuation token">(</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="operator token">=></span> <span class="function token">resolve</span><span class="punctuation token">(</span><span class="string token">'다섯'</span><span class="punctuation token">)</span><span class="punctuation token">,</span> <span class="number token">500</span><span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="keyword token">var</span> p6 <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Promise</span><span class="punctuation token">(</span><span class="keyword token">function</span><span class="punctuation token">(</span><span class="parameter token">resolve<span class="punctuation token">,</span> reject</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="function token">setTimeout</span><span class="punctuation token">(</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="operator token">=></span> <span class="function token">reject</span><span class="punctuation token">(</span><span class="keyword token">new</span> <span class="class-name token">Error</span><span class="punctuation token">(</span><span class="string token">'여섯'</span><span class="punctuation token">)</span><span class="punctuation token">)</span><span class="punctuation token">,</span> <span class="number token">100</span><span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + +Promise<span class="punctuation token">.</span><span class="function token">race</span><span class="punctuation token">(</span><span class="punctuation token">[</span>p5<span class="punctuation token">,</span> p6<span class="punctuation token">]</span><span class="punctuation token">)</span> +<span class="punctuation token">.</span><span class="function token">then</span><span class="punctuation token">(</span><span class="keyword token">function</span><span class="punctuation token">(</span><span class="parameter token">value</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="comment token">// 실행되지 않음</span> +<span class="punctuation token">}</span><span class="punctuation token">,</span> <span class="keyword token">function</span><span class="punctuation token">(</span><span class="parameter token">error</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span>error<span class="punctuation token">.</span>message<span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// "여섯"</span> + <span class="comment token">// p6이 더 빠르므로 거부함</span> +<span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-promise.race', 'Promise.race')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>ECMA 표준에서 초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-promise.race', 'Promise.race')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Promise.race")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Promise")}}</li> + <li>{{jsxref("Promise.all()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/promise/reject/index.html b/files/ko/web/javascript/reference/global_objects/promise/reject/index.html new file mode 100644 index 0000000000..a376940d7e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/promise/reject/index.html @@ -0,0 +1,81 @@ +--- +title: Promise.reject() +slug: Web/JavaScript/Reference/Global_Objects/Promise/reject +tags: + - ECMAScript6 + - JavaScript + - Method + - Promise +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/reject +--- +<div>{{JSRef}}</div> + +<p><code><strong>Promise.reject(reason)</strong></code> 메서드는 주어진 이유(reason)로 거부된 <code>Promise</code> 객체를 반환합니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>Promise.reject(reason)</var>;</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt>reason</dt> + <dd>이 <code>Promise</code>를 거부한 이유.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p>정적 <code>Promise.reject</code> 함수는 거부된 <code>Promise</code>를 반환합니다. 디버깅 목적 및 선택된 오류를 잡기 위해, <code>reason</code>을 <code>instanceof</code> {{jsxref("Error")}} 이게 하는데 유용합니다.</p> + +<h2 id="예">예</h2> + +<h3 id="정적_Promise.reject()_메서드_사용">정적 Promise.reject() 메서드 사용</h3> + +<pre class="brush: js">Promise.reject("Testing static reject").then(function(reason) { + // 호출되지 않음 +}, function(reason) { + console.log(reason); // "Testing static reject" +}); + +Promise.reject(new Error("fail")).then(function(error) { + // 호출되지 않음 +}, function(error) { + console.log(error); // Stacktrace +});</pre> + +<h2 id="스펙">스펙</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-promise.reject', 'Promise.reject')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>ECMA 표준에서 초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-promise.reject', 'Promise.reject')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Promise.reject")}}</p> + +<p> </p> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("Promise")}}</li> + <li><a href="https://github.com/petkaantonov/bluebird#error-handling">BlueBird Promise 라이브러리를 사용해 선택된 오류 잡기</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/promise/resolve/index.html b/files/ko/web/javascript/reference/global_objects/promise/resolve/index.html new file mode 100644 index 0000000000..64180ef2bf --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/promise/resolve/index.html @@ -0,0 +1,162 @@ +--- +title: Promise.resolve() +slug: Web/JavaScript/Reference/Global_Objects/Promise/resolve +tags: + - ECMAScript6 + - JavaScript + - Method + - Promise + - 레퍼런스 +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/resolve +--- +<div>{{JSRef}}</div> + +<p><code><strong>Promise.resolve(value)</strong></code> 메서드는 주어진 값으로 이행하는 {{jsxref("Promise.then")}} 객체를 반환합니다. 그 값이 프로미스인 경우, 해당 프로미스가 반환됩니다. 그 값이 thenable(예, {{jsxref("Promise.then", "\"then\" 메소드")}} 가 있음)인 경우, 반환된 프로미스는 그 thenable을 "따르며", 그 최종 상태를 취합니다. 그렇지 않으면 반환된 프로미스는 그 값으로 이행합니다. 이 함수는 프로미스형의 객체(무언가를 결정하는 프로미스를 결정하는 프로미스 등)의 중첩된 레이어를 단일 레이어로 펼칩니다.</p> + +<div class="blockIndicator warning"> +<p><strong>주의</strong>: 스스로를 결정하는 thenable 에서 <code>Promise.resolve</code> 를 호출하면 안됩니다. 이는 무한히 중첩된 프로미스를 펼치려고하므로 무한 재귀를 유발할 것입니다. Angular 에서 <code>async</code> Pipe 를 함께 사용한 <a href="https://stackblitz.com/edit/angular-promiseresovle-with-async-pipe?file=src/app/app.component.ts">예제</a>입니다. 자세한 내용은<a href="https://angular.io/guide/template-syntax#avoid-side-effects"> 여기</a>에서 확인하세요.</p> +</div> + +<div>{{EmbedInteractiveExample("pages/js/promise-resolve.html")}}</div> + +<div class="hidden"> +<p>The source for this interactive demo is stored in a GitHub repository. If you'd like to contribute to the interactive demo project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p> +</div> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>Promise.resolve(value)</var>; +</pre> + +<h3 id="파라미터">파라미터</h3> + +<dl> + <dt>value</dt> + <dd>이 <code>Promise</code>에 의해 결정되는 인수. <code>Promise</code> 또는 이행할 thenable 일수도 있습니다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<dl> + <dd> + <p>주어진 값으로 이행된 {{jsxref("Promise")}} 또는 값이 promise 객체인 경우, 값으로 전달된 promise. </p> + </dd> +</dl> + +<h2 id="설명">설명</h2> + +<p>정적 <code>Promise.resolve</code> 함수는 이행된 <code>Promise</code> 를 반환합니다.</p> + +<h2 id="예시">예시</h2> + +<h3 id="정적_Promise.resolve_메소드_사용">정적 <code>Promise.resolve</code> 메소드 사용</h3> + +<pre class="brush: js">Promise.resolve("Success").then(function(value) { + console.log(value); // "Success" +}, function(value) { + // 호출되지 않음 +}); +</pre> + +<h3 id="배열_이행">배열 이행</h3> + +<pre class="brush: js">var p = Promise.resolve([1,2,3]); +p.then(function(v) { + console.log(v[0]); // 1 +}); +</pre> + +<h3 id="또_다른_Promise_이행">또 다른 <code>Promise</code> 이행</h3> + +<pre class="brush: js">var original = Promise.resolve(33); +var cast = Promise.resolve(original); +cast.then(function(value) { + console.log('value: ' + value); +}); +<code>console.log('original === cast ? ' + (original === cast)); +</code> +<code>// 로그 순서: +// original === cast ? true +// value: 33</code> +</pre> + +<p>로그의 순서가 반대인 이유는 <code>then</code> 핸들러가 비동기로 호출되기 때문입니다. <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Promise/then#then_%EB%A9%94%EC%84%9C%EB%93%9C_%EC%82%AC%EC%9A%A9">여기</a>에서 <code>then</code> 이 동작하는 방식에 대해 확인하세요.</p> + +<h3 id="thenable_이행_및_오류_발생">thenable 이행 및 오류 발생</h3> + +<pre class="brush: js">// thenable 객체 이행 +var p1 = Promise.resolve({ + then: function(onFulfill, onReject) { onFulfill("fulfilled!"); } +}); +console.log(p1 instanceof Promise) // true, 객체는 Promise 로 변환됨 + +p1.then(function(v) { + console.log(v); // "fulfilled!" + }, function(e) { + // 호출되지 않음 +}); + +// thenable 이 콜백 이전에 오류를 throw +// Promise 거부 +var thenable = { then: function(resolve) { + throw new TypeError("Throwing"); + resolve("Resolving"); +}}; + +var p2 = Promise.resolve(thenable); +p2.then(function(v) { + // 호출되지 않음 +}, function(e) { + console.log(e); // TypeError: Throwing +}); + +// thenable 이 콜백 이후에 오류를 throw +// Promise 이행 +var thenable = { then: function(resolve) { + resolve("Resolving"); + throw new TypeError("Throwing"); +}}; + +var p3 = Promise.resolve(thenable); +p3.then(function(v) { + console.log(v); // "Resolving" +}, function(e) { + // 호출되지 않음 +}); +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">코멘트</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-promise.resolve', 'Promise.resolve')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>ECMA 표준에서 초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-promise.resolve', 'Promise.resolve')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div class="hidden"> +<p>To contribute to this compatibility data, please write a pull request against this repository: <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>.</p> +</div> + +<p>{{Compat("javascript.builtins.Promise.resolve")}}</p> + +<h2 id="함께_보기">함께 보기</h2> + +<ul> + <li>{{jsxref("Promise")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/promise/then/index.html b/files/ko/web/javascript/reference/global_objects/promise/then/index.html new file mode 100644 index 0000000000..b7f79eee9c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/promise/then/index.html @@ -0,0 +1,308 @@ +--- +title: Promise.prototype.then() +slug: Web/JavaScript/Reference/Global_Objects/Promise/then +tags: + - ECMAScript6 + - JavaScript + - Method + - Promise + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/then +--- +<div>{{JSRef}}</div> + +<p><code><strong>then()</strong></code> 메서드는 {{domxref("Promise")}}를 리턴하고 두 개의 콜백 함수를 인수로 받습니다. 하나는 <code>Promise</code>가 <strong>이행</strong>했을 때, 다른 하나는 <strong>거부</strong>했을 때를 위한 콜백 함수입니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/promise-then.html")}}</div> + +<p class="hidden">해당 예제의 소스 코드는 GitHub 리포지토리에 저장되어 있습니다. 인터랙티브 데모 프로젝트에 기여하고 싶다면 <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> 를 클론하고 pull request를 보내 주세요.</p> + +<div class="note"> +<p>매개변수 중 하나 이상을 생략했거나 함수가 아닌 값을 전달한 경우, <code>then</code>은 핸들러가 없는 것이 되지만 오류를 발생하지는 않습니다. <code>then</code> 바로 이전의 <code>Promise</code>가 <code>then</code>에 핸들러가 없는 상태로 완료(이행이나 거부)했을 경우, 추가 핸들러가 없는 <code>Promise</code>가 생성되며, 원래 <code>Promise</code>의 마지막 상태를 그대로 물려받습니다.</p> +</div> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>p.then(onFulfilled, onRejected)</var>; + +p.then(function(value) { + // 이행 +}, function(reason) { + // 거부 +}); +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>onFulfilled</code></dt> + <dd><code>Promise</code>가 수행될 때 호출되는 {{jsxref("Function")}}으로, <strong>이행 값(fulfillment value)</strong> 하나를 인수로 받습니다.</dd> + <dt><code>onRejected</code></dt> + <dd><code>Promise</code>가 거부될 때 호출되는 {{jsxref("Function")}}으로, <strong>거부 이유(rejection reason)</strong> 하나를 인수로 받습니다.</dd> +</dl> + +<h3 id="반환값">반환값</h3> + +<p>{{jsxref("Promise")}}가 이행하거나 거부했을 때, 각각에 해당하는 핸들러 함수(<code style="font-style: normal; font-weight: normal;">onFulfilled</code>나 <code style="font-style: normal; font-weight: normal;">onRejected</code>)가 <strong>비동기적으로</strong> 실행됩니다. 핸들러 함수는 다음 규칙을 따라 실행됩니다.</p> + +<ul> + <li>함수가 값을 반환할 경우, <code>then</code>에서 반환한 프로미스는 그 반환값을 자신의 결과값으로 하여 이행합니다.</li> + <li>값을 반환하지 않을 경우, <code>then</code>에서 반환한 프로미스는 <code>undefined</code>를 결과값으로 하여 이행합니다.</li> + <li>오류가 발생할 경우, <code>then</code>에서 반환한 프로미스는 그 오류를 자신의 결과값으로 하여 거부합니다.</li> + <li>이미 이행한 프로미스를 반환할 경우, <code>then</code>에서 반환한 프로미스는 그 프로미스의 결과값을 자신의 결과값으로 하여 이행합니다.</li> + <li>이미 거부한 프로미스를 반환할 경우, <code>then</code>에서 반환한 프로미스는 그 프로미스의 결과값을 자신의 결과값으로 하여 거부합니다.</li> + <li><strong>대기 중</strong>인 프로미스를 반환할 경우, <code>then</code>에서 반환한 프로미스는 그 프로미스의 이행 여부와 결과값을 따릅니다.</li> +</ul> + +<p>다음 예제에서 <code>then</code> 메서드의 비동기성을 확인할 수 있습니다.</p> + +<pre class="brush: js">// 이행한 프로미스를 받으면 'then' 블록도 바로 실행되지만, +// 핸들러는 아래 console.log에서와 같이 비동기적으로 실행됨 +const resolvedProm = Promise.resolve(33); + +let thenProm = resolvedProm.then(value => { + console.log("이 부분은 호출 스택 이후에 실행됩니다. 전달받은 값이자 반환값은 " + value + "입니다."); + return value; +}); +// thenProm의 값을 즉시 기록 +console.log(thenProm); + +// setTimeout으로 함수 실행을 호출 스택이 빌 때까지 미룰 수 있음 +setTimeout(() => { + console.log(thenProm); +}); + + +// 로그 출력 결과 (순서대로): +// Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined} +// "이 부분은 호출 스택 이후에 실행됩니다. 전달받은 값이자 반환값은 33입니다." +// Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: 33}</pre> + +<h2 id="설명">설명</h2> + +<p><code>then</code>과 {{jsxref("Promise.prototype.catch()")}} 메서드는 프로미스를 반환하기 때문에, 체이닝이 가능합니다. 이를 <em>합성</em>이라고도 합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="then_메서드_사용"><code>then</code> 메서드 사용</h3> + +<pre class="brush: js">var p1 = new Promise(function(resolve, reject) { + resolve("성공!"); + // 또는 + // reject("오류!"); +}); + +p1.then(function(value) { + console.log(value); // 성공! +}, function(reason) { + console.log(reason); // 오류! +}); +</pre> + +<h3 id="체이닝">체이닝</h3> + +<p><code>then</code> 메서드는 <code>Promise</code>를 리턴하기 때문에, 이어지는 <code>then</code> 호출들을 손쉽게 연결할 수 있습니다.</p> + +<p><code>then</code>에 핸들러로 전달된 함수가 프로미스를 반환할 경우, 이와 동등한 프로미스가 메서드 체인의 그다음 <code>then</code>에 노출됩니다. 아래 예제에서는 <code>setTimeout</code> 함수로 비동기 코드를 흉내냅니다.</p> + +<pre class="brush: js">Promise.resolve('foo') + // 1. "foo"를 받고 "bar"를 추가한 다음 그 값으로 이행하여 다음 then에 넘겨줌 + .then(function(string) { + return new Promise(function(resolve, reject) { + setTimeout(function() { + string += 'bar'; + resolve(string); + }, 1); + }); + }) + // 2. "foobar"를 받고 그대로 다음 then에 넘겨준 뒤, + // 나중에 콜백 함수에서 가공하고 콘솔에 출력 + .then(function(string) { + setTimeout(function() { + string += 'baz'; + console.log(string); + }, 1) + return string; + }) + // 3. 이 부분의 코드는 이전의 then 블록 안의 (가짜) 비동기 코드에서 + // 실제로 문자열을 가공하기 전에 실행됨 + .then(function(string) { + console.log("마지막 Then: 앗... 방금 then에서 프로미스 만들고 반환하는 걸 까먹어서 " + + "출력 순서가 좀 이상할지도 몰라요"); + + // 'baz' 부분은 setTimeout 함수로 비동기적으로 실행되기 때문에 + // 이곳의 string에는 아직 'baz' 부분이 없음 + console.log(string); + }); + +// 로그 출력 결과 (순서대로): +// 마지막 Then: 앗... 방금 then에서 프로미스 만들고 반환하는 걸 까먹어서 출력 순서가 좀 이상할지도 몰라요 +// foobar +// foobarbaz</pre> + +<p><code>then</code> 핸들러에서 값을 그대로 반환한 경우에는 <code>Promise.resolve(<핸들러에서 반환한 값>)</code>을 반환하는 것과 같습니다.</p> + +<pre class="brush: js">var p2 = new Promise(function(resolve, reject) { + resolve(1); +}); + +p2.then(function(value) { + console.log(value); // 1 + return value + 1; +}).then(function(value) { + console.log(value + ' - 동기적으로 짜도 돌아감'); +}); + +p2.then(function(value) { + console.log(value); // 1 +}); +</pre> + +<p>함수에서 오류가 발생하거나 거부한 프로미스를 반환한 경우 <code>then</code>에서는 거부한 프로미스를 반환합니다.</p> + +<pre class="brush: js">Promise.resolve() + .then(() => { + // .then()에서 거부한 프로미스를 반환함 + throw new Error('으악!'); + }) + .then(() => { + console.log('실행되지 않는 코드'); + }, error => { + console.error('onRejected 함수가 실행됨: ' + error.message); + });</pre> + +<p>이외의 모든 경우에는 곧 이행할(비동기적으로 실행되는) 프로미스를 반환합니다. 다음 예제에서는 바로 이전의 프로미스가 거부했음에도 첫 번째 <code>then</code>에서는 <code>42</code>의 값을 갖는 곧 이행할 프로미스를 반환합니다.</p> + +<pre class="brush: js">Promise.reject() + .then(() => 99, () => 42) // onRejected에서는 42를 곧 이행할 프로미스로 감싸서 반환함 + .then(solution => console.log(solution + '로 이행함')); // 42로 이행함</pre> + +<p>실제 개발 시에는 아래와 같이 거부한 프로미스를 <code>then</code>의 2단 핸들러보다는 <code>catch</code>를 사용해 처리하는 경우가 많습니다.</p> + +<pre class="brush: js">Promise.resolve() + .then(() => { + // .then()에서 거부한 프로미스를 반환함 + throw new Error('으악!'); + }) + .catch(error => { + console.error('onRejected 함수가 실행됨: ' + error.message); + }) + .then(() => { + console.log("처음 then의 프로미스가 거부했지만 그래도 이 코드는 실행됨"); + });</pre> + +<p><br> + 체이닝을 이용해 프로미스 기반 함수 위에 다른 프로미스 기반 함수를 구현할 수도 있습니다.</p> + +<pre class="brush: js">function fetch_current_data() { + // fetch() API는 프로미스를 반환합니다. 이 함수도 + // API가 비슷하지만, 이 함수의 프로미스는 + // 추가 작업을 거친 이후에 이행값을 반환합니다. + return fetch('current-data.json').then(response => { + if (response.headers.get('content-type') != 'application/json') { + throw new TypeError(); + } + var j = response.json(); + // j 가공하기 + return j; // fetch_current_data().then()을 통해 + // 이행값을 사용할 수 있음 + }); +} +</pre> + +<p><code>onFulfilled</code>가 프로미스를 반환할 경우, <code>then</code>의 반환값 역시 그 프로미스에 의해 이행/거부합니다.</p> + +<pre class="brush: js">function resolveLater(resolve, reject) { + setTimeout(function() { + resolve(10); + }, 1000); +} +function rejectLater(resolve, reject) { + setTimeout(function() { + reject(new Error('오류')); + }, 1000); +} + +var p1 = Promise.resolve('foo'); +var p2 = p1.then(function() { + // 1초 뒤에 10으로 이행할 프로미스 반환 + return new Promise(resolveLater); +}); +p2.then(function(v) { + console.log('이행', v); // "이행", 10 +}, function(e) { + // 실행되지 않음 + console.log('거부', e); +}); + +var p3 = p1.then(function() { + // 1초 뒤에 '오류'로 거부할 프로미스 반환 + return new Promise(rejectLater); +}); +p3.then(function(v) { + // 실행되지 않음 + console.log('이행', v); +}, function(e) { + console.log('거부', e); // "거부", '오류' +}); +</pre> + +<h3 id="domxref(window.setImmediate)의_프로미스_기반_폴리필">{{domxref("window.setImmediate")}}의 프로미스 기반 폴리필</h3> + +<p>{{jsxref("Function.prototype.bind()")}} <code>Reflect.apply</code> ({{jsxref("Reflect.apply()")}}) 메서드를 사용하여 (취소할 수 없는) setImmedate와 비슷한 함수를 생성합니다.</p> + +<pre class="brush: js">const nextTick = (() => { + const noop = () => {}; // literally + const nextTickPromise = () => Promise.resolve().then(noop); + + const rfab = Reflect.apply.bind; // (thisArg, fn, thisArg, [...args]) + const nextTick = (fn, ...args) => ( + fn !== undefined + ? Promise.resolve(args).then(rfab(null, fn, null)) + : nextTickPromise(), + undefined + ); + nextTick.ntp = nextTickPromise; + + return nextTick; +})(); +</pre> + +<h2 id="스펙">스펙</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-promise.prototype.then', 'Promise.prototype.then')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>ECMA 표준에서 초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-promise.prototype.then', 'Promise.prototype.then')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Promise.then")}}</p> + + + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("Promise")}}</li> + <li>{{jsxref("Promise.prototype.catch()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/proxy/handler/apply/index.html b/files/ko/web/javascript/reference/global_objects/proxy/handler/apply/index.html new file mode 100644 index 0000000000..b4928da1d8 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/proxy/handler/apply/index.html @@ -0,0 +1,154 @@ +--- +title: handler.apply() +slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/apply +tags: + - apply트랩 + - 트랩 + - 프록시 +translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/apply +--- +<div>{{JSRef}}</div> + +<p><strong><code>handler.apply()</code></strong> 메소드는 함수호출 시를 위한 트랩(trap)이다.</p> + +<h2 id="문법">문법</h2> + +<pre class="brush: js">var p = new Proxy(target, { + apply: function(target, thisArg, argumentsList) { + } +}); +</pre> + +<h3 id="인자">인자</h3> + +<p>apply 메소드에는 다음과 같은 인자가 들어온다.. <code>this는 </code>handler를 가리킨다.</p> + +<dl> + <dt><code>target</code></dt> + <dd>대상이 되는 객체(함수)</dd> + <dt><code>thisArg</code></dt> + <dd>호출 시 바인딩 된 this</dd> + <dt><code>argumentsList</code></dt> + <dd>호출 시 전달된 인자목록.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p><code>apply</code> 메소드는 어떤 값이든 반환할 수 있다.</p> + +<h2 id="설명">설명</h2> + +<p><code><strong>handler.apply</strong></code> 메소드는 함수호출 시를 위한 트랩이다.</p> + +<h3 id="가로채기">가로채기</h3> + +<p>이 트랩은 다음과 같은 것들을 가로챌 수 있다:</p> + +<ul> + <li><code>proxy(...args)</code></li> + <li>{{jsxref("Function.prototype.apply()")}} 와 {{jsxref("Function.prototype.call()")}}</li> + <li>{{jsxref("Reflect.apply()")}}</li> +</ul> + +<h3 id="기본(불변)조건">기본(불변)조건</h3> + +<p><code>handler.apply</code> 메소드에 대한 특별히 지켜야 할 기본조건은 없다.</p> + +<h2 id="예제">예제</h2> + +<p>다음의 코드는 함수 호출 시에 트랩을 건다.</p> + +<pre class="brush: js">var p = new Proxy(function() {}, { + apply: function(target, thisArg, argumentsList) { + console.log('호출됨: ' + argumentsList.join(', ')); + return argumentsList[0] + argumentsList[1] + argumentsList[2]; + } +}); + +console.log(p(1, 2, 3)); // "호출됨: 1, 2, 3" + // 6 +</pre> + +<h2 id="관련_명세">관련 명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-proxy-object-internal-methods-and-internal-slots-call-thisargument-argumentslist', '[[Call]]')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots-call-thisargument-argumentslist', '[[Call]]')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저별_호환성">브라우저별 호환성</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("18")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("18")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="관련_내용">관련 내용</h2> + +<ul> + <li>{{jsxref("Proxy")}}</li> + <li>{{jsxref("Proxy.handler", "handler")}}</li> + <li>{{jsxref("Function.prototype.apply")}}</li> + <li>{{jsxref("Function.prototype.call")}}</li> + <li>{{jsxref("Reflect.apply()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/proxy/handler/index.html b/files/ko/web/javascript/reference/global_objects/proxy/handler/index.html new file mode 100644 index 0000000000..9eebe33b2f --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/proxy/handler/index.html @@ -0,0 +1,81 @@ +--- +title: Proxy handler +slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler +tags: + - ECMAScript 2015 + - JavaScript + - Proxy +translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy +--- +<div>{{JSRef}}</div> + +<p>The proxy's handler object is a placeholder object which contains traps for {{jsxref("Proxy", "proxies", "", 1)}}.</p> + +<h2 id="Methods">Methods</h2> + +<p>All traps are optional. If a trap has not been defined, the default behavior is to forward the operation to the target.</p> + +<dl> + <dt>{{jsxref("Global_Objects/Proxy/handler/getPrototypeOf", "handler.getPrototypeOf()")}}</dt> + <dd>A trap for {{jsxref("Object.getPrototypeOf")}}.</dd> + <dt>{{jsxref("Global_Objects/Proxy/handler/setPrototypeOf", "handler.setPrototypeOf()")}}</dt> + <dd>A trap for {{jsxref("Object.setPrototypeOf")}}.</dd> + <dt>{{jsxref("Global_Objects/Proxy/handler/isExtensible", "handler.isExtensible()")}}</dt> + <dd>A trap for {{jsxref("Object.isExtensible")}}.</dd> + <dt>{{jsxref("Global_Objects/Proxy/handler/preventExtensions", "handler.preventExtensions()")}}</dt> + <dd>A trap for {{jsxref("Object.preventExtensions")}}.</dd> + <dt>{{jsxref("Global_Objects/Proxy/handler/getOwnPropertyDescriptor", "handler.getOwnPropertyDescriptor()")}}</dt> + <dd>A trap for {{jsxref("Object.getOwnPropertyDescriptor")}}.</dd> + <dt>{{jsxref("Global_Objects/Proxy/handler/defineProperty", "handler.defineProperty()")}}</dt> + <dd>A trap for {{jsxref("Object.defineProperty")}}.</dd> + <dt>{{jsxref("Global_Objects/Proxy/handler/has", "handler.has()")}}</dt> + <dd>A trap for the {{jsxref("Operators/in", "in")}} operator.</dd> + <dt>{{jsxref("Global_Objects/Proxy/handler/get", "handler.get()")}}</dt> + <dd>A trap for getting property values.</dd> + <dt>{{jsxref("Global_Objects/Proxy/handler/set", "handler.set()")}}</dt> + <dd>A trap for setting property values.</dd> + <dt>{{jsxref("Global_Objects/Proxy/handler/deleteProperty", "handler.deleteProperty()")}}</dt> + <dd>A trap for the {{jsxref("Operators/delete", "delete")}} operator.</dd> + <dt>{{jsxref("Global_Objects/Proxy/handler/ownKeys", "handler.ownKeys()")}}</dt> + <dd>A trap for {{jsxref("Object.getOwnPropertyNames")}} and {{jsxref("Object.getOwnPropertySymbols")}}.</dd> + <dt>{{jsxref("Global_Objects/Proxy/handler/apply", "handler.apply()")}}</dt> + <dd>A trap for a function call.</dd> + <dt>{{jsxref("Global_Objects/Proxy/handler/construct", "handler.construct()")}}</dt> + <dd>A trap for the {{jsxref("Operators/new", "new")}} operator.</dd> +</dl> + +<p>Some non-standard traps are <a href="/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#Proxy">obsolete and have been removed</a>.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-proxy-object-internal-methods-and-internal-slots', 'Proxy Object Internal Methods and Internal Slots')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots', 'Proxy Object Internal Methods and Internal Slots')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>The <code>enumerate</code> handler has been removed.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.builtins.Proxy.handler")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Proxy")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/proxy/index.html b/files/ko/web/javascript/reference/global_objects/proxy/index.html new file mode 100644 index 0000000000..777b4648d0 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/proxy/index.html @@ -0,0 +1,394 @@ +--- +title: Proxy +slug: Web/JavaScript/Reference/Global_Objects/Proxy +tags: + - ECMAScript 2015 + - JavaScript + - Proxy + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Proxy +--- +<div>{{JSRef}}</div> + +<p><code><strong>Proxy</strong></code> 객체는 기본적인 동작(속성 접근, 할당, 순회, 열거, 함수 호출 등)의 새로운 행동을 정의할 때 사용합니다.</p> + +<h2 id="용어">용어</h2> + +<dl> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler">handler</a></dt> + <dd>trap들을 가지고 있는 Placeholder 객체.</dd> + <dt>traps</dt> + <dd>프로퍼티에 접근할 수 있는 메소드. 운영체제에서 trap 이라는 컨셉과 유사하다.</dd> + <dt>target</dt> + <dd>proxy가 가상화하는 실제 객체. 이것은 proxy를 위한 backend 저장소로 사용된다. Invariants (semantics that remain unchanged) regarding object non-extensibility or non-configurable properties are verified against the target.</dd> +</dl> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">new Proxy(target, handler); +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>target</code></dt> + <dd>proxy와 함께 감싸진 target 객체 (native array, function, 다른 proxy을 포함한 객체)</dd> + <dt><code>handler</code></dt> + <dd>프로퍼티들이 function 인 객체이다. 동작이 수행될 때, handler는 proxy의 행동을 정의한다.</dd> +</dl> + +<h2 id="메서드">메서드</h2> + +<dl> + <dt>{{jsxref("Proxy.revocable()")}}</dt> + <dd>폐기할 수 있는(revocable) Proxy 객체를 생성.</dd> +</dl> + +<h2 id="Methods_of_the_handler_object">Methods of the handler object</h2> + +<p>handler객체는 <code>Proxy를 위한 trap들을 포함하고 있는 </code>placeholder 객체이다.</p> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler', 'Methods') }}</div> + +<h2 id="예제">예제</h2> + +<h3 id="Basic_example">Basic example</h3> + +<p>프로퍼티 이름이 객체에 없을때, 기본값을 숫자 37로 리턴받는 간단한 예제이다. 이것은 <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/get"><code>get</code></a> handler 를 사용하였다. </p> + +<pre class="brush: js">var handler = { + get: function(target, name){ + return name in target? + target[name] : + 37; + } +}; + +var p = new Proxy({}, handler); +p.a = 1; +p.b = undefined; + +console.log(p.a, p.b); // 1, undefined +console.log('c' in p, p.c); // false, 37 +</pre> + +<h3 id="No-op_forwarding_proxy">No-op forwarding proxy</h3> + +<p>이 예제에서는, native JavaScript를 사용하겠다. proxy는 적용된 모든 동작으로 보낼 것이다.</p> + +<pre class="brush: js">var target = {}; +var p = new Proxy(target, {}); + +p.a = 37; // target으로 동작이 전달 + +console.log(target.a); // 37. 동작이 제대로 전달됨 +</pre> + +<h3 id="Validation_(검증)">Validation (검증)</h3> + +<p>Proxy에서, 객체에 전달된 값을 쉽게 검증할 수 있다. 이 예제는 <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/set"><code>set</code></a> handler 를 사용하였다.</p> + +<pre class="brush: js">let validator = { + set: function(obj, prop, value) { + if (prop === 'age') { + if (!Number.isInteger(value)) { + throw new TypeError('The age is not an integer'); + } + if (value > 200) { + throw new RangeError('The age seems invalid'); + } + } + + // The default behavior to store the value + obj[prop] = value; + } +}; + +let person = new Proxy({}, validator); + +person.age = 100; +console.log(person.age); // 100 +person.age = 'young'; // Throws an exception +person.age = 300; // Throws an exception +</pre> + +<h3 id="Extending_constructor_(생성자_확장)">Extending constructor (생성자 확장)</h3> + +<p>function proxy는 쉽게 새로운 생성자와 함께 생성자를 확장할 수 있다. 이 예제에서는 <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/construct">construct</a> 와</code> <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/apply"><code>apply</code></a> handlers 를 사용하였다.</p> + +<pre class="brush: js">function extend(sup,base) { + var descriptor = Object.getOwnPropertyDescriptor( + base.prototype,"constructor" + ); + base.prototype = Object.create(sup.prototype); + var handler = { + construct: function(target, args) { + var obj = Object.create(base.prototype); + this.apply(target,obj,args); + return obj; + }, + apply: function(target, that, args) { + sup.apply(that,args); + base.apply(that,args); + } + }; + var proxy = new Proxy(base,handler); + descriptor.value = proxy; + Object.defineProperty(base.prototype, "constructor", descriptor); + return proxy; +} + +var Person = function(name){ + this.name = name; +}; + +var Boy = extend(Person, function(name, age) { + this.age = age; +}); + +Boy.prototype.sex = "M"; + +var Peter = new Boy("Peter", 13); +console.log(Peter.sex); // "M" +console.log(Peter.name); // "Peter" +console.log(Peter.age); // 13</pre> + +<h3 id="Manipulating_DOM_nodes_(DOM_nodes_조작)">Manipulating DOM nodes (DOM nodes 조작)</h3> + +<p>가끔씩, 두 개의 다른 element의 속성이나 클래스 이름을 바꾸고 싶을 것이다. 아래는 <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/set"><code>set</code></a> handler 를 사용하였다.</p> + +<pre class="brush: js">let view = new Proxy({ + selected: null +}, +{ + set: function(obj, prop, newval) { + let oldval = obj[prop]; + + if (prop === 'selected') { + if (oldval) { + oldval.setAttribute('aria-selected', 'false'); + } + if (newval) { + newval.setAttribute('aria-selected', 'true'); + } + } + + // The default behavior to store the value + obj[prop] = newval; + } +}); + +let i1 = view.selected = document.getElementById('item-1'); +console.log(i1.getAttribute('aria-selected')); // 'true' + +let i2 = view.selected = document.getElementById('item-2'); +console.log(i1.getAttribute('aria-selected')); // 'false' +console.log(i2.getAttribute('aria-selected')); // 'true' +</pre> + +<h3 id="Value_correction_and_an_extra_property_(값_정정과_추가적인_property)">Value correction and an extra property (값 정정과 추가적인 property)</h3> + +<p><code>products</code> 라는 proxy 객체는 전달된 값을 평가하고, 필요할 때 배열로 변환한다. 이 객체는 <code>latestBrowser</code> 라는 추가적인 property를 지원하는데, getter와 setter 모두 지원한다. </p> + +<pre class="brush: js">let products = new Proxy({ + browsers: ['Internet Explorer', 'Netscape'] +}, +{ + get: function(obj, prop) { + // An extra property + if (prop === 'latestBrowser') { + return obj.browsers[obj.browsers.length - 1]; + } + + // The default behavior to return the value + return obj[prop]; + }, + set: function(obj, prop, value) { + // An extra property + if (prop === 'latestBrowser') { + obj.browsers.push(value); + return; + } + + // Convert the value if it is not an array + if (typeof value === 'string') { + value = [value]; + } + + // The default behavior to store the value + obj[prop] = value; + } +}); + +console.log(products.browsers); // ['Internet Explorer', 'Netscape'] +products.browsers = 'Firefox'; // pass a string (by mistake) +console.log(products.browsers); // ['Firefox'] <- no problem, the value is an array + +products.latestBrowser = 'Chrome'; +console.log(products.browsers); // ['Firefox', 'Chrome'] +console.log(products.latestBrowser); // 'Chrome' +</pre> + +<h3 id="Finding_an_array_item_object_by_its_property_(property로_배열의_객체를_찾기)">Finding an array item object by its property (property로 배열의 객체를 찾기)</h3> + +<p>proxy 는 유용한 특성을 가진 배열로 확장할 것이다. <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties">Object.defineProperties</a>를 사용하지 않고, </code>유연하게 property들을 유연하게 "정의"할 수 있다. 이 예제는 테이블의 cell을 이용해서 row(열)을 찾는데 적용할 수 있다. 이 경우, target은 <code><a href="/en-US/docs/DOM/table.rows">table.rows</a>가 될 것이다.</code></p> + +<pre class="brush: js">let products = new Proxy([ + { name: 'Firefox', type: 'browser' }, + { name: 'SeaMonkey', type: 'browser' }, + { name: 'Thunderbird', type: 'mailer' } +], +{ + get: function(obj, prop) { + // The default behavior to return the value; prop is usually an integer + if (prop in obj) { + return obj[prop]; + } + + // Get the number of products; an alias of products.length + if (prop === 'number') { + return obj.length; + } + + let result, types = {}; + + for (let product of obj) { + if (product.name === prop) { + result = product; + } + if (types[product.type]) { + types[product.type].push(product); + } else { + types[product.type] = [product]; + } + } + + // Get a product by name + if (result) { + return result; + } + + // Get products by type + if (prop in types) { + return types[prop]; + } + + // Get product types + if (prop === 'types') { + return Object.keys(types); + } + + return undefined; + } +}); + +console.log(products[0]); // { name: 'Firefox', type: 'browser' } +console.log(products['Firefox']); // { name: 'Firefox', type: 'browser' } +console.log(products['Chrome']); // undefined +console.log(products.browser); // [{ name: 'Firefox', type: 'browser' }, { name: 'SeaMonkey', type: 'browser' }] +console.log(products.types); // ['browser', 'mailer'] +console.log(products.number); // 3 +</pre> + +<h3 id="A_complete_traps_list_example_(완벽한_traps_리스트_예제)">A complete <code>traps</code> list example (완벽한 <code>traps</code> 리스트 예제)</h3> + +<p>이제 완벽한 traps 리스트를 생성하기 위해서, <em>non native</em> 객체를 프록시화 할 것이다. 이것은 특히, 다음과 같은 동작에 적합하다 : <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie/Simple_document.cookie_framework" title="https://developer.mozilla.org/en-US/docs/DOM/document.cookie#A_little_framework.3A_a_complete_cookies_reader.2Fwriter_with_full_unicode_support">the "little framework" published on the <code>document.cookie</code> page</a> 에 의해 생성된 <code>docCookies</code> 는 글로벌 객체</p> + +<pre class="brush: js">/* + var docCookies = ... get the "docCookies" object here: + https://developer.mozilla.org/en-US/docs/DOM/document.cookie#A_little_framework.3A_a_complete_cookies_reader.2Fwriter_with_full_unicode_support +*/ + +var docCookies = new Proxy(docCookies, { + get: function (oTarget, sKey) { + return oTarget[sKey] || oTarget.getItem(sKey) || undefined; + }, + set: function (oTarget, sKey, vValue) { + if (sKey in oTarget) { return false; } + return oTarget.setItem(sKey, vValue); + }, + deleteProperty: function (oTarget, sKey) { + if (sKey in oTarget) { return false; } + return oTarget.removeItem(sKey); + }, + enumerate: function (oTarget, sKey) { + return oTarget.keys(); + }, + ownKeys: function (oTarget, sKey) { + return oTarget.keys(); + }, + has: function (oTarget, sKey) { + return sKey in oTarget || oTarget.hasItem(sKey); + }, + defineProperty: function (oTarget, sKey, oDesc) { + if (oDesc && "value" in oDesc) { oTarget.setItem(sKey, oDesc.value); } + return oTarget; + }, + getOwnPropertyDescriptor: function (oTarget, sKey) { + var vValue = oTarget.getItem(sKey); + return vValue ? { + value: vValue, + writable: true, + enumerable: true, + configurable: false + } : undefined; + }, +}); + +/* Cookies test */ + +console.log(docCookies.my_cookie1 = "First value"); +console.log(docCookies.getItem("my_cookie1")); + +docCookies.setItem("my_cookie1", "Changed value"); +console.log(docCookies.my_cookie1);</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-proxy-objects', 'Proxy')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES2016', '#sec-proxy-objects', 'Proxy')}}</td> + <td>{{Spec2('ES2016')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES2017', '#sec-proxy-objects', 'Proxy')}}</td> + <td>{{Spec2('ES2017')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-proxy-objects', 'Proxy')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.Proxy", 2)}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a class="external" href="https://www.youtube.com/watch?v=sClk6aB_CPk">"Proxies are awesome" Brendan Eich presentation at JSConf</a> (<a class="external" href="http://www.slideshare.net/BrendanEich/metaprog-5303821">slides</a>)</li> + <li><a class="external" href="http://wiki.ecmascript.org/doku.php?id=harmony:proxies">ECMAScript Harmony Proxy proposal page</a> and <a class="external" href="http://wiki.ecmascript.org/doku.php?id=harmony:proxies_semantics">ECMAScript Harmony proxy semantics page</a></li> + <li><a class="external" href="http://soft.vub.ac.be/~tvcutsem/proxies/">Tutorial on proxies</a></li> + <li><a href="/en-US/docs/JavaScript/Old_Proxy_API" title="/en-US/docs/JavaScript/Old_Proxy_API">SpiderMonkey specific Old Proxy API</a></li> + <li>{{jsxref("Object.watch()")}} is a non-standard feature but has been supported in Gecko for a long time.</li> +</ul> + +<h2 id="라이센스_참고사항">라이센스 참고사항</h2> + +<p>Some content (text, examples) in this page has been copied or adapted from the <a class="external" href="http://wiki.ecmascript.org/doku.php">ECMAScript wiki</a> which content is licensed <a class="external" href="http://creativecommons.org/licenses/by-nc-sa/2.0/">CC 2.0 BY-NC-SA</a>.</p> diff --git a/files/ko/web/javascript/reference/global_objects/rangeerror/index.html b/files/ko/web/javascript/reference/global_objects/rangeerror/index.html new file mode 100644 index 0000000000..7413433c34 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/rangeerror/index.html @@ -0,0 +1,163 @@ +--- +title: RangeError +slug: Web/JavaScript/Reference/Global_Objects/RangeError +translation_of: Web/JavaScript/Reference/Global_Objects/RangeError +--- +<div>{{JSRef}}</div> + +<p><code><strong>RangeError</strong></code> 객체는 값이 집합에 없거나 허용되지 않은 값의 범위일 때 에러를 나타냅니다.</p> + +<h2 id="구문">구문 </h2> + +<pre class="syntaxbox"><code>new RangeError([<var>message</var>[, <var>fileName</var>[, <var>lineNumber</var>]]])</code></pre> + +<h3 id="파라메터">파라메터</h3> + +<dl> + <dt><code>message</code></dt> + <dd>선택적 파라메터. 에러에 대한 설명.</dd> + <dt><code>fileName</code> {{non-standard_inline}}</dt> + <dd>선택적 파라메터. 예외(exception)가 발생한 코드를 포함하고 있는 파일의 이름.</dd> + <dt><code>lineNumber</code> {{non-standard_inline}}</dt> + <dd>선택적 파라메터. 예외(exception)가 발생한 코드의 라인 넘버.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p><code>RangeError</code> 는 허용되지 않은 범위의 수를 포함한 아규먼트를 함수에 넘기려고 할 때 던져집니다. {{jsxref("Array")}} 생성자로 허용범위를 초과한 길이의 배열 생성을 시도하려 하거나, 적절하지 않은 값을 numeric method({{jsxref("Number.toExponential()")}}, {{jsxref("Number.toFixed()")}} 또는 {{jsxref("Number.toPrecision()")}})에 넘기려 할 때, 이 에러를 만날 수 있을 것입니다. </p> + +<h2 id="속성">속성</h2> + +<dl> + <dt>{{jsxref("RangeError.prototype")}}</dt> + <dd><code>RangeError</code> 객체에 속성을 추가하도록 해준다. </dd> +</dl> + +<h2 id="메소드">메소드</h2> + +<p>전역(global)의 <code>RangeError</code>는 자신의 메소드를 가지고 있지 않습니다. 하지만, 몇 가지의 메소드를 프로토타입 체인을 통해 상속받습니다.</p> + +<h2 id="RangeError_인스턴스"><code>RangeError</code> 인스턴스</h2> + +<h3 id="속성_2">속성</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError/prototype', 'Properties')}}</div> + +<h3 id="메소드_2">메소드</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError/prototype', 'Methods')}}</div> + +<h2 id="예">예</h2> + +<h3 id="RangeError_사용하기"><code>RangeError </code>사용하기</h3> + +<pre class="brush: js">var check = function(num) { + if (num < MIN || num > MAX) { + throw new RangeError('Parameter must be between ' + MIN + ' and ' + MAX); + } +}; + +try { + check(500); +} +catch (e) { + if (e instanceof RangeError) { + // Handle range error + } +} +</pre> + +<h2 id="스펙">스펙</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.11.6.2', 'RangeError')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-native-error-types-used-in-this-standard-rangeerror', 'RangeError')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-native-error-types-used-in-this-standard-rangeerror', 'RangeError')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("Error")}}</li> + <li>{{jsxref("RangeError.prototype")}}</li> + <li>{{jsxref("Array")}}</li> + <li>{{jsxref("Number.toExponential()")}}</li> + <li>{{jsxref("Number.toFixed()")}}</li> + <li>{{jsxref("Number.toPrecision()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/referenceerror/index.html b/files/ko/web/javascript/reference/global_objects/referenceerror/index.html new file mode 100644 index 0000000000..ed5fee8c48 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/referenceerror/index.html @@ -0,0 +1,129 @@ +--- +title: ReferenceError +slug: Web/JavaScript/Reference/Global_Objects/ReferenceError +translation_of: Web/JavaScript/Reference/Global_Objects/ReferenceError +--- +<div>{{JSRef}}</div> + +<div> +<p><code><strong>ReferenceError</strong></code> 객체는 존재하지 않는 변수를 참조했을 때 발생하는 에러를 나타냅니다.</p> +</div> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox"><code>new ReferenceError([<var>message</var>[, <var>fileName</var>[, <var>lineNumber</var>]]])</code></pre> + +<h3 id="파라미터">파라미터</h3> + +<dl> + <dt><code>message</code></dt> + <dd>선택사항. 에러에 대한 설명문</dd> + <dt><code>fileName</code> {{non-standard_inline}}</dt> + <dd>선택사항. 예외가 발생한 코드를 포함하는 파일의 이름</dd> + <dt><code>lineNumber</code> {{non-standard_inline}}</dt> + <dd>선택사항. 예외가 발생한 코드의 줄 번호</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p><strong><code>ReferenceError</code></strong>는 선언된 적이 없는 변수를 참조하려고 할 때 발생합니다.</p> + +<h2 id="프로퍼티">프로퍼티</h2> + +<dl> + <dt>{{jsxref("ReferenceError.prototype")}}</dt> + <dd>ReferenceError 객체에 프로퍼티를 추가할 수 있습니다.</dd> +</dl> + +<h2 id="메서드">메서드</h2> + +<p>전역 ReferenceError는 메서드를 가지고 있지 않습니다. 그러나 상속 관계에서 프로토타입 체인을 통해 일부 메서드를 가질 수 있습니다.</p> + +<h2 id="ReferenceError_인스턴스"><code>ReferenceError</code> 인스턴스</h2> + +<h3 id="프로퍼티_2">프로퍼티</h3> + +<div>{{page('/ko-KR/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError/prototype', 'Properties')}}</div> + +<h3 id="메서드_2">메서드</h3> + +<div>{{page('/ko-KR/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError/prototype', 'Methods')}}</div> + +<h2 id="예제">예제</h2> + +<h3 id="ReferenceError_처리하기"><code>ReferenceError</code> 처리하기</h3> + +<pre class="brush: js">try { + var a = undefinedVariable; +} catch (e) { + console.log(e instanceof ReferenceError); // true + console.log(e.message); // "undefinedVariable is not defined" + console.log(e.name); // "ReferenceError" + console.log(e.fileName); // "Scratchpad/1" + console.log(e.lineNumber); // 2 + console.log(e.columnNumber); // 6 + console.log(e.stack); // "@Scratchpad/2:2:7\n" +} +</pre> + +<h3 id="ReferenceError_생성하기"><code>ReferenceError</code> 생성하기</h3> + +<pre class="brush: js">try { + throw new ReferenceError('Hello', 'someFile.js', 10); +} catch (e) { + console.log(e instanceof ReferenceError); // true + console.log(e.message); // "Hello" + console.log(e.name); // "ReferenceError" + console.log(e.fileName); // "someFile.js" + console.log(e.lineNumber); // 10 + console.log(e.columnNumber); // 0 + console.log(e.stack); // "@Scratchpad/2:2:9\n" +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.11.6.3', 'ReferenceError')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-native-error-types-used-in-this-standard-referenceerror', 'ReferenceError')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-native-error-types-used-in-this-standard-referenceerror', 'ReferenceError')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div> +<div class="hidden">이 페이지의 호환성 테이블은 구조화된 데이터로부터 생성됩니다. 해당 데이터를 개선하고 싶다면 <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>을 체크아웃하고 저희에게 풀 리퀘스트를 보내주십시오.</div> + +<p>{{Compat("javascript.builtins.ReferenceError")}}</p> +</div> + +<h2 id="참고">참고</h2> + +<ul> + <li>{{jsxref("Error")}}</li> + <li>{{jsxref("ReferenceError.prototype")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/reflect/apply/index.html b/files/ko/web/javascript/reference/global_objects/reflect/apply/index.html new file mode 100644 index 0000000000..a9146a0952 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/reflect/apply/index.html @@ -0,0 +1,93 @@ +--- +title: Reflect.apply() +slug: Web/JavaScript/Reference/Global_Objects/Reflect/apply +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Reference + - Reflect +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/apply +--- +<div>{{JSRef}}</div> + +<p><code><strong>Reflect</strong></code><strong><code>.apply()</code></strong> 정적 메서드는 대상 함수를 주어진 매개변수로 호출합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/reflect-apply.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">Reflect.apply(<em>target</em>, <em>thisArgument</em>, <em>argumentsList</em>) +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>target</code></dt> + <dd>호출할 대상 함수.</dd> + <dt><code>thisArgument</code></dt> + <dd>호출에서 <code>target</code>의 <code>this</code>로 사용할 값.</dd> + <dt><code>argumentsList</code></dt> + <dd><code>target</code>을 호출할 때 매개변수로 전달할 배열형 객체.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 <code>this</code> 값과 매개변수로 대상 함수를 호출한 결과.</p> + +<h3 id="예외">예외</h3> + +<p><code>target</code>이 호출 가능한 객체가 아니면 {{jsxref("TypeError")}}.</p> + +<h2 id="설명">설명</h2> + +<p>ES5에서는 {{jsxref("Function.prototype.apply()")}} 메서드를 사용해, 함수를 호출할 때 <code>this</code> 값을 지정하거나 매개변수를 배열(또는 배열형 객체)에서 넘겨줄 수 있었습니다.</p> + +<pre class="brush: js">Function.prototype.apply.call(Math.floor, undefined, [1.75]);</pre> + +<p><code>Reflect.apply()</code> 메서드를 사용해 같은 작업을 더 쉽고 유려하게 수행할 수 있습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="Reflect.apply_사용하기"><code>Reflect.apply()</code> 사용하기</h3> + +<pre class="brush: js">Reflect.apply(Math.floor, undefined, [1.75]); +// 1; + +Reflect.apply(String.fromCharCode, undefined, [104, 101, 108, 108, 111]); +// "hello" + +Reflect.apply(RegExp.prototype.exec, /ab/, ['confabulation']).index; +// 4 + +Reflect.apply(''.charAt, 'ponies', [3]); +// "i" +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-reflect.apply', 'Reflect.apply')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Reflect.apply")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Reflect")}}</li> + <li>{{jsxref("Function.prototype.apply()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/reflect/construct/index.html b/files/ko/web/javascript/reference/global_objects/reflect/construct/index.html new file mode 100644 index 0000000000..e98f3204de --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/reflect/construct/index.html @@ -0,0 +1,154 @@ +--- +title: Reflect.construct() +slug: Web/JavaScript/Reference/Global_Objects/Reflect/construct +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Reference + - Reflect +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/construct +--- +<div>{{JSRef}}</div> + +<p><code><strong>Reflect</strong></code><strong><code>.construct()</code></strong> 정적 메서드는 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new"><code>new</code> 연산자</a>처럼 동작하는 함수입니다. <code>new target(...args)</code>를 호출하는 것과 같습니다. 추가 기능으로 다른 프로토타입을 지정할 수도 있습니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/reflect-construct.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">Reflect.construct(<em>target</em>, <em>argumentsList</em>[, <em>newTarget</em>]) +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>target</code></dt> + <dd>호출할 대상 함수.</dd> + <dt><code>argumentsList</code></dt> + <dd><code>target</code>의 매개변수로 전달할 배열형 객체.</dd> + <dt><code>newTarget</code> {{optional_inline}}</dt> + <dd>프로토타입으로 사용할 생성자. <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/new.target">new.target</a></code> 연산자도 확인하세요. <code>newTarget</code>이 주어지지 않았을 땐 <code>target</code>을 사용합니다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p><code>target</code>을 생성자로 하고 주어진 매개변수를 전달해 생성한 <code>target</code>(또는, 지정했다면 <code>newTarget</code>)의 새로운 인스턴스.</p> + +<h3 id="예외">예외</h3> + +<p><code>target</code> 또는 <code>newTarget</code>이 생성자가 아니면 {{jsxref("TypeError")}}.</p> + +<h2 id="설명">설명</h2> + +<p><code>Reflect.construct()</code>는 생성자를 가변 길이의 매개변수로 호출할 수 있습니다. (<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new"><code>new</code> 연산자</a>와 <a href="/ko/docs/Web/JavaScript/Reference/Operators/Spread_syntax">전개 구문</a>을 사용해도 가능합니다)</p> + +<pre class="brush: js">var obj = new Foo(...args); +var obj = Reflect.construct(Foo, args); +</pre> + +<h3 id="Reflect.construct()_vs_Object.create()"><code>Reflect.construct()</code> vs <code>Object.create()</code></h3> + +<p><code>Reflect</code>의 도입 이전에는 임의의 생성자와 프로토타입에 {{jsxref("Object.create()")}}를 사용해 객체를 생성할 수 있었습니다.</p> + +<pre class="brush: js">function OneClass() { + this.name = 'one'; +} + +function OtherClass() { + this.name = 'other'; +} + +// Calling this: +var obj1 = Reflect.construct(OneClass, args, OtherClass); + +// ...has the same result as this: +var obj2 = Object.create(OtherClass.prototype); +OneClass.apply(obj2, args); + +console.log(obj1.name); // 'one' +console.log(obj2.name); // 'one' + +console.log(obj1 instanceof OneClass); // false +console.log(obj2 instanceof OneClass); // false + +console.log(obj1 instanceof OtherClass); // true +console.log(obj2 instanceof OtherClass); // true +</pre> + +<p>그러나, 결과는 동일하더라도 과정에는 중요한 차이가 하나 존재합니다. <code>Object.create()</code>와 {{jsxref("Function.prototype.apply()")}}를 사용할 땐, 객체 생성에 <code>new</code> 키워드가 관여하지 않으므로 <code>new.target</code> 연산자가 <code>undefined</code>를 가리킵니다.</p> + +<p>반면 <code>Reflect.construct()</code>를 호출하면, <code>newTarget</code>이 존재하면 <code>new.target</code> 연산자가 <code>newTarget</code>을, 아니면 <code>target</code>을 가리킵니다.</p> + +<pre class="brush: js">function OneClass() { + console.log('OneClass'); + console.log(new.target); +} +function OtherClass() { + console.log('OtherClass'); + console.log(new.target); +} + +var obj1 = Reflect.construct(OneClass, args); +// Output: +// OneClass +// function OneClass { ... } + +var obj2 = Reflect.construct(OneClass, args, OtherClass); +// Output: +// OneClass +// function OtherClass { ... } + +var obj3 = Object.create(OtherClass.prototype); +OneClass.apply(obj3, args); +// Output: +// OneClass +// undefined +</pre> + +<h2 id="예제">예제</h2> + +<h3 id="Reflect.construct()_사용하기"><code>Reflect.construct()</code> 사용하기</h3> + +<pre class="brush: js">var d = Reflect.construct(Date, [1776, 6, 4]); +d instanceof Date; // true +d.getFullYear(); // 1776 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-reflect.construct', 'Reflect.construct')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-reflect.construct', 'Reflect.construct')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Reflect.construct")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Reflect")}}</li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new"><code>new</code></a></li> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/new.target">new.target</a></code></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/reflect/defineproperty/index.html b/files/ko/web/javascript/reference/global_objects/reflect/defineproperty/index.html new file mode 100644 index 0000000000..a88d2bd722 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/reflect/defineproperty/index.html @@ -0,0 +1,100 @@ +--- +title: Reflect.defineProperty() +slug: Web/JavaScript/Reference/Global_Objects/Reflect/defineProperty +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Reference + - Reflect +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/defineProperty +--- +<div>{{JSRef}}</div> + +<p><code><strong>Reflect</strong></code><strong><code>.defineProperty()</code></strong> 정적 메서드는 {{jsxref("Object.defineProperty()")}}와 같은 동작을 하지만 {{jsxref("Boolean")}}을 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/reflect-defineproperty.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">Reflect.defineProperty(<em>target</em>, <em>propertyKey</em>, <em>attributes</em>) +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>target</code></dt> + <dd>속성을 정의할 대상 객체.</dd> + <dt><code>propertyKey</code></dt> + <dd>정의하거나 수정할 속성의 이름.</dd> + <dt><code>attributes</code></dt> + <dd>정의하거나 수정하는 속성을 기술하는 객체.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>속성이 성공적으로 정의됐는지 나타내는 {{jsxref("Boolean")}}.</p> + +<h3 id="예외">예외</h3> + +<p><code>target</code>이 {{jsxref("Object")}}가 아니면 {{jsxref("TypeError")}}.</p> + +<h2 id="설명">설명</h2> + +<p><code>Reflect.defineProperty</code> 메서드는 객체에 속성을 정교하게 추가하거나 수정할 수 있습니다. 자세한 내용은 유사한 메서드인 {{jsxref("Object.defineProperty")}}를 참고하세요. <code>Object.defineProperty</code>는 성공 시 대상 객체를 반환하고 실패하면 {{jsxref("TypeError")}}를 던지지만, <code>Reflect.defineProperty</code>는 성공 여부를 나타내는 {{jsxref("Boolean")}}을 반환합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="Reflect.defineProperty()_사용하기"><code>Reflect.defineProperty()</code> 사용하기</h3> + +<pre class="brush: js">var obj = {}; +Reflect.defineProperty(obj, 'x', {value: 7}); // true +obj.x; // 7 +</pre> + +<h3 id="속성_정의의_성공_여부_알아내기">속성 정의의 성공 여부 알아내기</h3> + +<p>{{jsxref("Object.defineProperty")}}는 성공 시 객체를 반환하고, 실패 시 {{jsxref("TypeError")}}를 던지므로 속성 정의 과정에 발생할 수 있는 오류를 <code><a href="/ko/docs/Web/JavaScript/Reference/Statements/try...catch">try...catch</a></code> 블록으로 잡아야 합니다. 반면 <code>Reflect.defineProperty</code>는 성공 여부를 나타내는 {{jsxref("Boolean")}}을 반환하므로, 간단하게 <code><a href="/ko/docs/Web/JavaScript/Reference/Statements/if...else">if...else</a></code> 블록만 사용하면 됩니다.</p> + +<pre class="brush: js">if (Reflect.defineProperty(target, property, attributes)) { + // 성공 +} else { + // 실패 +}</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-reflect.defineproperty', 'Reflect.defineProperty')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-reflect.defineproperty', 'Reflect.defineProperty')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Reflect.defineProperty")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Reflect")}}</li> + <li>{{jsxref("Object.defineProperty()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/reflect/deleteproperty/index.html b/files/ko/web/javascript/reference/global_objects/reflect/deleteproperty/index.html new file mode 100644 index 0000000000..de3b8f8ed8 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/reflect/deleteproperty/index.html @@ -0,0 +1,98 @@ +--- +title: Reflect.deleteProperty() +slug: Web/JavaScript/Reference/Global_Objects/Reflect/deleteProperty +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Reference + - Reflect +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/deleteProperty +--- +<div>{{JSRef}}</div> + +<p><code><strong>Reflect</strong></code><strong><code>.deleteProperty()</code></strong> 정적 메서드는 속성을 제거할 수 있습니다. <a href="/ko/docs/Web/JavaScript/Reference/Operators/delete"><code>delete</code> 연산자</a>의 함수판이라고 할 수 있습니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/reflect-deleteproperty.html", "taller")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">Reflect.deleteProperty(<em>target</em>, <em>propertyKey</em>) +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>target</code></dt> + <dd>속성을 제거할 대상 객체.</dd> + <dt><code>propertyKey</code></dt> + <dd>제거할 속성의 이름.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>속성이 성공적으로 제거됐는지 나타내는 {{jsxref("Boolean")}}.</p> + +<h3 id="Exceptions">Exceptions</h3> + +<p><code>target</code>이 {{jsxref("Object")}}가 아니면 {{jsxref("TypeError")}}.</p> + +<h2 id="설명">설명</h2> + +<p><code>Reflect.deleteProperty</code> 메서드는 객체의 속성을 제거할 수 있습니다. 반환값은 속성의 제거 성공 여부를 나타내는 {{jsxref("Boolean")}}입니다. 비엄격 모드의 <a href="/ko/docs/Web/JavaScript/Reference/Operators/delete"><code>delete</code> 연산자</a>와 거의 동일합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="Reflect.deleteProperty()_사용하기"><code>Reflect.deleteProperty()</code> 사용하기</h3> + +<pre class="brush: js">var obj = { x: 1, y: 2 }; +Reflect.deleteProperty(obj, 'x'); // true +obj; // { y: 2 } + +var arr = [1, 2, 3, 4, 5]; +Reflect.deleteProperty(arr, '3'); // true +arr; // [1, 2, 3, , 5] + +// 주어진 속성이 존재하지 않으면 true 반환 +Reflect.deleteProperty({}, 'foo'); // true + +// 주어진 속성이 설정 불가능하면 false 반환 +Reflect.deleteProperty(Object.freeze({foo: 1}), 'foo'); // false +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-reflect.deleteproperty', 'Reflect.deleteProperty')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-reflect.deleteproperty', 'Reflect.deleteProperty')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Reflect.deleteProperty")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Reflect")}}</li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Operators/delete"><code>delete</code> 연산자</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/reflect/get/index.html b/files/ko/web/javascript/reference/global_objects/reflect/get/index.html new file mode 100644 index 0000000000..2d5007b113 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/reflect/get/index.html @@ -0,0 +1,100 @@ +--- +title: Reflect.get() +slug: Web/JavaScript/Reference/Global_Objects/Reflect/get +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Reference + - Reflect +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/get +--- +<div>{{JSRef}}</div> + +<p><strong><code>Reflect.get()</code></strong> 정적 메서드는 객체의 속성을 가져오는 함수입니다. <code>target[propertyKey]</code>와 비슷합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/reflect-get.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">Reflect.get(<em>target</em>, <em>propertyKey</em>[, <em>receiver</em>]) +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>target</code></dt> + <dd>속성을 가져올 대상 객체.</dd> + <dt><code>propertyKey</code></dt> + <dd>가져올 속성의 이름.</dd> + <dt><code>receiver</code> {{optional_inline}}</dt> + <dd>대상 속성이 접근자라면 <code>this</code>의 값으로 사용할 값. {{jsxref("Proxy")}}와 함께 사용하면, 대상을 상속하는 객체를 사용할 수 있습니다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>속성의 값.</p> + +<h3 id="예외">예외</h3> + +<p><code>target</code>이 {{jsxref("Object")}}가 아니면 {{jsxref("TypeError")}}.</p> + +<h2 id="설명">설명</h2> + +<p><code>Reflect.get</code> 메서드는 객체 속성의 값을 가져올 수 있습니다. <a href="/ko/docs/Web/JavaScript/Reference/Operators/Property_Accessors">속성 접근자</a>의 함수판이라고 할 수 있습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="Reflect.get()_사용하기"><code>Reflect.get()</code> 사용하기</h3> + +<pre class="brush: js">// Object +var obj = { x: 1, y: 2 }; +Reflect.get(obj, 'x'); // 1 + +// Array +Reflect.get(['zero', 'one'], 1); // "one" + +// handler 매개변수와 Proxy +var x = {p: 1}; +var obj = new Proxy(x, { + get(t, k, r) { return k + 'bar'; } +}); +Reflect.get(obj, 'foo'); // "foobar" +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-reflect.get', 'Reflect.get')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-reflect.get', 'Reflect.get')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Reflect.get")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Reflect")}}</li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Operators/Property_Accessors">속성 접근자</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/reflect/getownpropertydescriptor/index.html b/files/ko/web/javascript/reference/global_objects/reflect/getownpropertydescriptor/index.html new file mode 100644 index 0000000000..273f5b7011 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/reflect/getownpropertydescriptor/index.html @@ -0,0 +1,103 @@ +--- +title: Reflect.getOwnPropertyDescriptor() +slug: Web/JavaScript/Reference/Global_Objects/Reflect/getOwnPropertyDescriptor +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Reference + - Reflect +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/getOwnPropertyDescriptor +--- +<div>{{JSRef}}</div> + +<p><code><strong>Reflect</strong></code><strong><code>.getOwnPropertyDescriptor()</code></strong> 정적 메서드는 객체에 주어진 속성이 존재하면, 해당 속성의 서술자를 반환합니다. {{jsxref("Object.getOwnPropertyDescriptor()")}}와 유사합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/reflect-getownpropertydescriptor.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">Reflect.getOwnPropertyDescriptor(<em>target</em>, <em>propertyKey</em>) +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>target</code></dt> + <dd>속성을 탐색할 객체.</dd> + <dt><code>propertyKey</code></dt> + <dd>자체 속성 서술자를 가져올 속성의 이름.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>대상 속성이 객체에 존재하면, 그 속성의 서술자. 존재하지 않으면 {{jsxref("undefined")}}.</p> + +<h3 id="예제">예제</h3> + +<p><code>target</code>이 {{jsxref("Object")}}가 아니면 {{jsxref("TypeError")}}.</p> + +<h2 id="설명">설명</h2> + +<p><code>Reflect.getOwnPropertyDescriptor</code> 메서드는 객체 속성의 서술자를 반환합니다. 만약 존재하지 않는 속성이라면 {{jsxref("undefined")}}를 대신 반환합니다. {{jsxref("Object.getOwnPropertyDescriptor()")}}와의 유일한 차이는 객체가 아닌 대상의 처리 방법입니다.</p> + +<h2 id="예제_2">예제</h2> + +<h3 id="Reflect.getOwnPropertyDescriptor()_사용하기"><code>Reflect.getOwnPropertyDescriptor()</code> 사용하기</h3> + +<pre class="brush: js">Reflect.getOwnPropertyDescriptor({x: 'hello'}, 'x'); +// {value: "hello", writable: true, enumerable: true, configurable: true} + +Reflect.getOwnPropertyDescriptor({x: 'hello'}, 'y'); +// undefined + +Reflect.getOwnPropertyDescriptor([], 'length'); +// {value: 0, writable: true, enumerable: false, configurable: false} +</pre> + +<h3 id="Object.getOwnPropertyDescriptor()와의_차이점"><code>Object.getOwnPropertyDescriptor()</code>와의 차이점</h3> + +<p><code>Reflect.getOwnPropertyDescriptor()</code>의 첫 번째 매개변수가 객체가 아니고 {{glossary("Primitive", "원시값")}}이라면 {{jsxref("TypeError")}}가 발생합니다. 반면 {{jsxref("Object.getOwnPropertyDescriptor()")}}는 같은 상황에서 값을 우선 객체로 변환합니다.</p> + +<pre class="brush: js">Reflect.getOwnPropertyDescriptor('foo', 0); +// TypeError: "foo" is not non-null object + +Object.getOwnPropertyDescriptor('foo', 0); +// { value: "f", writable: false, enumerable: true, configurable: false }</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-reflect.getownpropertydescriptor', 'Reflect.getOwnPropertyDescriptor')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-reflect.getownpropertydescriptor', 'Reflect.getOwnPropertyDescriptor')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Reflect.getOwnPropertyDescriptor")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Reflect")}}</li> + <li>{{jsxref("Object.getOwnPropertyDescriptor()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/reflect/getprototypeof/index.html b/files/ko/web/javascript/reference/global_objects/reflect/getprototypeof/index.html new file mode 100644 index 0000000000..f0d2f2d19c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/reflect/getprototypeof/index.html @@ -0,0 +1,104 @@ +--- +title: Reflect.getPrototypeOf() +slug: Web/JavaScript/Reference/Global_Objects/Reflect/getPrototypeOf +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Reference + - Reflect +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/getPrototypeOf +--- +<div>{{JSRef}}</div> + +<p><code><strong>Reflect</strong></code><strong><code>.getPrototypeOf()</code></strong> 정적 메서드는 주어진 객체의 프로토타입을 반환합니다. {{jsxref("Object.getPrototypeOf()")}}와 거의 동일합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/reflect-getprototypeof.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">Reflect.getPrototypeOf(<em>target</em>) +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>target</code></dt> + <dd>프로토타입을 가져올 대상 객체.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 객체의 프로토타입. 상속한 속성이 없으면 {{jsxref("null")}}을 반환합니다.</p> + +<h3 id="예외">예외</h3> + +<p><code>target</code>이 {{jsxref("Object")}}가 아니면 {{jsxref("TypeError")}}.</p> + +<h2 id="설명">설명</h2> + +<p><code>Reflect.getPrototypeOf()</code> 메서드는 주어진 객체의 프로토타입(<code>[[Prototype]]</code> 내부 객체의 값 등)을 반환합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="Reflect.getPrototypeOf()_사용하기"><code>Reflect.getPrototypeOf()</code> 사용하기</h3> + +<pre class="brush: js">Reflect.getPrototypeOf({}); // Object.prototype +Reflect.getPrototypeOf(Object.prototype); // null +Reflect.getPrototypeOf(Object.create(null)); // null +</pre> + +<h3 id="Object.getPrototypeOf()와_비교"><code>Object.getPrototypeOf()</code>와 비교</h3> + +<pre class="brush: js">// 객체에는 동일한 결과 +Object.getPrototypeOf({}); // Object.prototype +Reflect.getPrototypeOf({}); // Object.prototype + +// ES5에서는 비객체 대상에서 모두 오류 +Object.getPrototypeOf('foo'); // Throws TypeError +Reflect.getPrototypeOf('foo'); // Throws TypeError + +// ES2015에서는 Reflect만 오류, Object는 객체로 변환 +Object.getPrototypeOf('foo'); // String.prototype +Reflect.getPrototypeOf('foo'); // Throws TypeError + +// ES2015 Object 동작을 따라하려면 객체 변환과정 필요 +Reflect.getPrototypeOf(Object('foo')); // String.prototype +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-reflect.getprototypeof', 'Reflect.getPrototypeOf')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-reflect.getprototypeof', 'Reflect.getPrototypeOf')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Reflect.getPrototypeOf")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Reflect")}}</li> + <li>{{jsxref("Object.getPrototypeOf()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/reflect/has/index.html b/files/ko/web/javascript/reference/global_objects/reflect/has/index.html new file mode 100644 index 0000000000..363b4d0366 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/reflect/has/index.html @@ -0,0 +1,97 @@ +--- +title: Reflect.has() +slug: Web/JavaScript/Reference/Global_Objects/Reflect/has +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Reference + - Reflect +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/has +--- +<div>{{JSRef}}</div> + +<p><code><strong>Reflect</strong></code><strong><code>.has()</code></strong> 정적 메서드는 <a href="/ko/docs/Web/JavaScript/Reference/Operators/in"><code>in</code> 연산자</a>의 함수판입니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/reflect-has.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">Reflect.has(<em>target</em>, <em>propertyKey</em>) +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>target</code></dt> + <dd>속성을 탐색할 객체.</dd> + <dt><code>propertyKey</code></dt> + <dd>탐색할 속성의 이름.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>객체가 속성을 가지고 있는지 나타내는 {{jsxref("Boolean")}}.</p> + +<h3 id="예외">예외</h3> + +<p><code>target</code>이 {{jsxref("Object")}}가 아니면 {{jsxref("TypeError")}}.</p> + +<h2 id="설명">설명</h2> + +<p><code>Reflect.has()</code> 메서드는 객체에 속성이 존재하는지 판별할 수 있습니다. <a href="/ko/docs/Web/JavaScript/Reference/Operators/in"><code>in</code> 연산자</a>처럼 동작합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="Reflect.has()_사용하기"><code>Reflect.has()</code> 사용하기</h3> + +<pre class="brush: js">Reflect.has({x: 0}, 'x'); // true +Reflect.has({x: 0}, 'y'); // false + +// 프로토타입 체인에 존재하는 속성도 true 반환 +Reflect.has({x: 0}, 'toString'); + +// .has() 처리기 메서드를 가진 Proxy +obj = new Proxy({}, { + has(t, k) { return k.startsWith('door'); } +}); +Reflect.has(obj, 'doorbell'); // true +Reflect.has(obj, 'dormitory'); // false +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-reflect.has', 'Reflect.has')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-reflect.has', 'Reflect.has')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Reflect.has")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Reflect")}}</li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Operators/in"><code>in</code> 연산자</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/reflect/index.html b/files/ko/web/javascript/reference/global_objects/reflect/index.html new file mode 100644 index 0000000000..728dcd74c3 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/reflect/index.html @@ -0,0 +1,106 @@ +--- +title: Reflect +slug: Web/JavaScript/Reference/Global_Objects/Reflect +tags: + - ECMAScript 2015 + - JavaScript + - Reference + - Reflect +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect +--- +<div>{{JSRef}}</div> + +<p><code><strong>Reflect</strong></code>는 중간에서 가로챌 수 있는 JavaScript 작업에 대한 메서드를 제공하는 내장 객체입니다. 메서드의 종류는 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler">프록시 처리기</a>와 동일합니다. <code>Reflect</code>는 함수 객체가 아니므로 생성자로 사용할 수 없습니다.</p> + +<h2 id="설명">설명</h2> + +<p>다른 대부분의 전역 객체와 다르게, <code>Reflect</code>는 생성자가 아닙니다. 따라서 함수처럼 호출하거나 <a href="/ko/docs/Web/JavaScript/Reference/Operators/new"><code>new</code> 연산자</a>로 인스턴스를 만들 수 없습니다. {{jsxref("Math")}} 객체처럼, <code>Reflect</code>의 모든 속성과 메서드는 정적입니다.</p> + +<p><code>Reflect</code> 객체의 정적 메서드 이름은 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler">프록시 처리기 메서드</a>의 이름과 같습니다.</p> + +<p>일부 메서드는 {{jsxref("Object")}}에도 존재하는 메서드이지만 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Reflect/Comparing_Reflect_and_Object_methods">약간의 차이</a>가 있습니다.</p> + +<h2 id="정적_메서드">정적 메서드</h2> + +<dl> + <dt>{{jsxref("Reflect.apply()")}}</dt> + <dd>대상 함수를 주어진 매개변수로 호출합니다. {{jsxref("Function.prototype.apply()")}}도 참고하세요.</dd> + <dt>{{jsxref("Reflect.construct()")}}</dt> + <dd>함수로 사용하는 <a href="/ko/docs/Web/JavaScript/Reference/Operators/new"><code>new</code> 연산자</a>입니다. <code>new target(...args)</code>을 호출하는 것과 같습니다. 다른 프로토타입을 지정하는 추가 기능도 가지고 있습니다.</dd> + <dt>{{jsxref("Reflect.defineProperty()")}}</dt> + <dd>{{jsxref("Object.defineProperty()")}}와 비슷합니다. {{jsxref("Boolean")}}을 반환합니다.</dd> + <dt>{{jsxref("Reflect.deleteProperty()")}}</dt> + <dd>함수로 사용하는 <a href="/ko/docs/Web/JavaScript/Reference/Operators/delete"><code>delete</code> 연산자</a>입니다. <code>delete target[name]</code>을 호출하는 것과 같습니다.</dd> + <dt>{{jsxref("Reflect.get()")}}</dt> + <dd>대상 속성의 값을 반환하는 함수입니다.</dd> + <dt>{{jsxref("Reflect.getOwnPropertyDescriptor()")}}</dt> + <dd>{{jsxref("Object.getOwnPropertyDescriptor()")}}와 비슷합니다. 주어진 속성이 대상 객체에 존재하면, 그 속성의 서술자를 반환합니다. 그렇지 않으면 {{jsxref("undefined")}}를 반환합니다.</dd> + <dt>{{jsxref("Reflect.getPrototypeOf()")}}</dt> + <dd>{{jsxref("Object.getPrototypeOf()")}}와 같습니다.</dd> + <dt>{{jsxref("Reflect.has()")}}</dt> + <dd>함수로 사용하는 <a href="/ko/docs/Web/JavaScript/Reference/Operators/in"><code>in</code> 연산자</a>입니다. 자신의, 혹은 상속한 속성이 존재하는지 나타내는 {{jsxref("Boolean")}}을 반환합니다.</dd> + <dt>{{jsxref("Reflect.isExtensible()")}}</dt> + <dd>{{jsxref("Object.isExtensible()")}}과 같습니다.</dd> + <dt>{{jsxref("Reflect.ownKeys()")}}</dt> + <dd>대상 객체의 자체 키(상속하지 않은 키) 목록을 배열로 반환합니다.</dd> + <dt>{{jsxref("Reflect.preventExtensions()")}}</dt> + <dd>{{jsxref("Object.preventExtensions()")}}와 비슷합니다. {{jsxref("Boolean")}}을 반환합니다.</dd> + <dt>{{jsxref("Reflect.set()")}}</dt> + <dd>속성에 값을 할당하는 함수입니다. 할당 성공 여부를 나타내는 {{jsxref("Boolean")}}을 반환합니다.</dd> + <dt>{{jsxref("Reflect.setPrototypeOf()")}}</dt> + <dd>객체의 프로토타입을 지정하는 함수입니다. 지정 성공 여부를 나타내는 {{jsxref("Boolean")}}을 반환합니다.</dd> +</dl> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-reflect-object', 'Reflect')}}</td> + </tr> + </tbody> +</table> + +<h2 id="예제">예제</h2> + +<h3 id="객체가_특정_속성을_가지고_있는지_검사하기">객체가 특정 속성을 가지고 있는지 검사하기</h3> + +<pre class="brush: js notranslate">const duck = { + name: 'Maurice', + color: 'white', + greeting: function() { + console.log(`Quaaaack! My name is ${this.name}`); + } +} + +Reflect.has(duck, 'color'); +// true +Reflect.has(duck, 'haircut'); +// false</pre> + +<h3 id="객체_자체_키를_반환하기">객체 자체 키를 반환하기</h3> + +<pre class="brush: js notranslate">Reflect.ownKeys(duck); +// [ "name", "color", "greeting" ]</pre> + +<h3 id="객체에_새로운_속성_추가하기">객체에 새로운 속성 추가하기</h3> + +<pre class="brush: js notranslate">Reflect.set(duck, 'eyes', 'black'); +// returns "true" if successful +// "duck" now contains the property "eyes: 'black'"</pre> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Reflect")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Proxy")}} 전역 객체.</li> + <li>{{jsxref("Proxy.handler", "handler")}} 객체.</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/reflect/isextensible/index.html b/files/ko/web/javascript/reference/global_objects/reflect/isextensible/index.html new file mode 100644 index 0000000000..68d168eb65 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/reflect/isextensible/index.html @@ -0,0 +1,111 @@ +--- +title: Reflect.isExtensible() +slug: Web/JavaScript/Reference/Global_Objects/Reflect/isExtensible +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Reference + - Reflect +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/isExtensible +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary"><code><strong>Reflect</strong></code><strong><code>.isExtensible()</code></strong> 정적 메서드는 객체의 확장 가능 여부, 즉 속성을 추가할 수 있는지 판별합니다.</span> {{jsxref("Object.isExtensible()")}}과 유사하지만 {{anch("Object.isExtensible()과의 차이", "차이점")}}도 있습니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/reflect-isextensible.html", "taller")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">Reflect.isExtensible(<em>target</em>) +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>target</code></dt> + <dd>확장 가능 여부를 판별할 대상 객체.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>객체의 확장 가능 여부를 나타내는 {{jsxref("Boolean")}}.</p> + +<h3 id="예외">예외</h3> + +<p><code>target</code>이 {{jsxref("Object")}}가 아니면 {{jsxref("TypeError")}}.</p> + +<h2 id="설명">설명</h2> + +<p><code>Reflect.isExtensible()</code> 메서드는 {{jsxref("Object.isExtensible()")}}와 유사하게, 객체에 새로운 속성을 추가할 수 있는지 판별합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="Reflect.isExtensible()_사용하기"><code>Reflect.isExtensible()</code> 사용하기</h3> + +<p>{{jsxref("Object.isExtensible()")}}도 참고하세요.</p> + +<pre class="brush: js">// 새로운 객체는 확장 가능 +var empty = {}; +Reflect.isExtensible(empty); // === true + +// ...하지만 바꿀 수 있음 +Reflect.preventExtensions(empty); +Reflect.isExtensible(empty); // === false + +// 봉인한 객체는 확장 불가능함 +var sealed = Object.seal({}); +Reflect.isExtensible(sealed); // === false + +// 동결한 객체도 확장 불가능함 +var frozen = Object.freeze({}); +Reflect.isExtensible(frozen); // === false +</pre> + +<h3 id="Object.isExtensible()과의_차이점"><code>Object.isExtensible()</code>과의 차이점</h3> + +<p><code>Reflect.isExtensible()</code>은 첫 번째 매개변수가 {{glossary("Primitive", "원시값")}}이면 {{jsxref("TypeError")}}를 던집니다. 반면 {{jsxref("Object.isExtensible()")}}은 우선 객체로 변환을 시도합니다.</p> + +<pre class="brush: js">Reflect.isExtensible(1); +// TypeError: 1 is not an object + +Object.isExtensible(1); +// false +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-reflect.isextensible', 'Reflect.isExtensible')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-reflect.isextensible', 'Reflect.isExtensible')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Reflect.isExtensible")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Reflect")}}</li> + <li>{{jsxref("Object.isExtensible()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/reflect/ownkeys/index.html b/files/ko/web/javascript/reference/global_objects/reflect/ownkeys/index.html new file mode 100644 index 0000000000..41c350ca60 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/reflect/ownkeys/index.html @@ -0,0 +1,95 @@ +--- +title: Reflect.ownKeys() +slug: Web/JavaScript/Reference/Global_Objects/Reflect/ownKeys +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Reference + - Reflect +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/ownKeys +--- +<div>{{JSRef}}</div> + +<p><code><strong>Reflect.ownKeys()</strong></code> 정적 메서드는 대상 객체의 자체 속성 키를 배열로 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/reflect-ownkeys.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">Reflect.ownKeys(<em>target</em>) +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>target</code></dt> + <dd>자체 키를 가져올 대상 객체.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 객체의 자체 속성 키를 담은 {{jsxref("Array")}}.</p> + +<h3 id="예외">예외</h3> + +<p><code>target</code>이 {{jsxref("Object")}}가 아니면 {{jsxref("TypeError")}}.</p> + +<h2 id="설명">설명</h2> + +<p>The <code>Reflect.ownKeys()</code> 메서드는 대상 객체의 자체 속성 키를 배열로 반환합니다. 반환 값은 <code>{{jsxref("Object.getOwnPropertyNames", "Object.getOwnPropertyNames(target)", "", 1)}}.concat({{jsxref("Object.getOwnPropertySymbols", "Object.getOwnPropertySymbols(target)", "", 1)}})</code>와 동일합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="Reflect.ownKeys()_사용하기"><code>Reflect.ownKeys()</code> 사용하기</h3> + +<pre class="brush: js">Reflect.ownKeys({z: 3, y: 2, x: 1}); // [ "z", "y", "x" ] +Reflect.ownKeys([]); // ["length"] + +var sym = Symbol.for('comet'); +var sym2 = Symbol.for('meteor'); +var obj = {[sym]: 0, 'str': 0, '773': 0, '0': 0, + [sym2]: 0, '-1': 0, '8': 0, 'second str': 0}; +Reflect.ownKeys(obj); +// [ "0", "8", "773", "str", "-1", "second str", Symbol(comet), Symbol(meteor) ] +// Indexes in numeric order, +// strings in insertion order, +// symbols in insertion order +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-reflect.ownkeys', 'Reflect.ownKeys')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-reflect.ownkeys', 'Reflect.ownKeys')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Reflect.ownKeys")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Reflect")}}</li> + <li>{{jsxref("Object.getOwnPropertyNames()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/reflect/preventextensions/index.html b/files/ko/web/javascript/reference/global_objects/reflect/preventextensions/index.html new file mode 100644 index 0000000000..364b46a5fa --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/reflect/preventextensions/index.html @@ -0,0 +1,103 @@ +--- +title: Reflect.preventExtensions() +slug: Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Reference + - Reflect +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary"><code><strong>Reflect.preventExtensions()</strong></code> 정적 메서드는 새로운 속성을 객체에 추가하지 못하도록 완전히 막습니다. 즉, 미래의 객체 확장을 막습니다.</span> {{jsxref("Object.preventExtensions()")}}와 유사하지만 {{anch("Object.preventExtensions()와의 차이점", "차이점")}}도 있습니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/reflect-preventextensions.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">Reflect.preventExtensions(<em>target</em>) +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>target</code></dt> + <dd>확장을 방지할 대상 객체.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>대상의 확장을 성공적으로 방지했는지 나타내는 {{jsxref("Boolean")}}.</p> + +<h3 id="예외">예외</h3> + +<p><code>target</code>이 {{jsxref("Object")}}가 아니면 {{jsxref("TypeError")}}.</p> + +<h2 id="설명">설명</h2> + +<p><code>Reflect.preventExtensions()</code> 메서드는 새로운 속성을 객체에 추가하지 못하도록 완전히 막습니다. 즉, 미래의 객체 확장을 막습니다. {{jsxref("Object.preventExtensions()")}}와 유사합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="Reflect.preventExtensions()_사용하기"><code>Reflect.preventExtensions()</code> 사용하기</h3> + +<p>{{jsxref("Object.preventExtensions()")}}도 참고하세요.</p> + +<pre class="brush: js">// 객체는 기본적으로 확장 가능 +var empty = {}; +Reflect.isExtensible(empty); // === true + +// ...하지만 바꿀 수 있음 +Reflect.preventExtensions(empty); +Reflect.isExtensible(empty); // === false +</pre> + +<h3 id="Object.preventExtensions()와의_차이점"><code>Object.preventExtensions()</code>와의 차이점</h3> + +<p><code>Reflect.preventExtensions()</code>는 첫 번째 매개변수가 {{glossary("Primitive", "원시값")}}이면 {{jsxref("TypeError")}}를 던집니다. 반면 {{jsxref("Object.preventExtensions()")}}는 우선 객체로 변환을 시도합니다.</p> + +<pre class="brush: js">Reflect.preventExtensions(1); +// TypeError: 1 is not an object + +Object.preventExtensions(1); +// 1 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-reflect.preventextensions', 'Reflect.preventExtensions')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-reflect.preventextensions', 'Reflect.preventExtensions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Reflect.preventExtensions")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Reflect")}}</li> + <li>{{jsxref("Object.isExtensible()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/reflect/set/index.html b/files/ko/web/javascript/reference/global_objects/reflect/set/index.html new file mode 100644 index 0000000000..f3cfc3a532 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/reflect/set/index.html @@ -0,0 +1,108 @@ +--- +title: Reflect.set() +slug: Web/JavaScript/Reference/Global_Objects/Reflect/set +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Reference + - Reflect +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/set +--- +<div>{{JSRef}}</div> + +<p><code><strong>Reflect</strong></code><strong><code>.set()</code></strong> 정적 메서드는 객체 속성의 값을 설정합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/reflect-set.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">Reflect.set(<em>target</em>, <em>propertyKey</em>, <em>value</em>[, <em>receiver</em>]) +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>target</code></dt> + <dd>속성의 값을 설정할 대상 객체.</dd> + <dt><code>propertyKey</code></dt> + <dd>값을 설정할 속성의 이름.</dd> + <dt><code>value</code></dt> + <dd>설정할 값.</dd> + <dt><code>receiver</code> {{optional_inline}}</dt> + <dd>속성이 설정자일 경우, <code>this</code>로 사용할 값.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>값 설정의 성공 여부를 나타내는 {{jsxref("Boolean")}}.</p> + +<h3 id="예외">예외</h3> + +<p><code>target</code>이 {{jsxref("Object")}}가 아니면 {{jsxref("TypeError")}}.</p> + +<h2 id="설명">설명</h2> + +<p><code>Reflect.set()</code> 메서드는 객체 속성의 값을 설정할 수 있습니다. 속성 추가도 할 수 있으며, 함수라는 점을 제외하면 동작 방식은 <a href="/ko/docs/Web/JavaScript/Reference/Operators/Property_Accessors">속성 접근자</a>와 같습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="Reflect.set()_사용하기"><code>Reflect.set()</code> 사용하기</h3> + +<pre class="brush: js">// Object +var obj = {}; +Reflect.set(obj, 'prop', 'value'); // true +obj.prop; // "value" + +// Array +var arr = ['duck', 'duck', 'duck']; +Reflect.set(arr, 2, 'goose'); // true +arr[2]; // "goose" + +// 배열 자르기 +Reflect.set(arr, 'length', 1); // true +arr; // ["duck"]; + +// 매개변수를 하나만 제공하면 속성 키 이름은 문자열 "undefined", 값은 undefined +var obj = {}; +Reflect.set(obj); // true +Reflect.getOwnPropertyDescriptor(obj, 'undefined'); +// { value: undefined, writable: true, enumerable: true, configurable: true } +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-reflect.set', 'Reflect.set')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-reflect.set', 'Reflect.set')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Reflect.set")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Reflect")}}</li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Operators/Property_Accessors">속성 접근자</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/reflect/setprototypeof/index.html b/files/ko/web/javascript/reference/global_objects/reflect/setprototypeof/index.html new file mode 100644 index 0000000000..3e97b9b385 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/reflect/setprototypeof/index.html @@ -0,0 +1,88 @@ +--- +title: Reflect.setPrototypeOf() +slug: Web/JavaScript/Reference/Global_Objects/Reflect/setPrototypeOf +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Reference + - Reflect +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/setPrototypeOf +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary"><code><strong>Reflect</strong></code><strong><code>.setPrototypeOf()</code></strong> 정적 메서드는 주어진 객체의 프로토타입(내부 <code>[[Prototype]]</code> 속성)을 다른 객체나 {{jsxref("null")}}로 바꿉니다.</span> 반환 값을 제외하면 {{jsxref("Object.setPrototypeOf()")}} 메서드와 같습니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/reflect-setprototypeof.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">Reflect.setPrototypeOf(<em>target</em>, <em>prototype</em>) +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>target</code></dt> + <dd>프로토타입을 지정할 대상 객체.</dd> + <dt><code>prototype</code></dt> + <dd>대상 객체의 새로운 프로토타입. (객체 또는 {{jsxref("null")}}</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>프로토타입 설정 성공 여부를 나타내는 {{jsxref("Boolean")}}.</p> + +<h3 id="예외">예외</h3> + +<p><code>target</code>이 {{jsxref("Object")}}가 아니거나, <code>prototype</code>이 객체도 {{jsxref("null")}}도 아니면 {{jsxref("TypeError")}}.</p> + +<h2 id="설명">설명</h2> + +<p><code>Reflect.setPrototypeOf()</code> 메서드는 주어진 객체의 프로토타입(즉, 내부 <code>[[Prototype]]</code> 속성)을 변경합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="Reflect.setPrototypeOf_사용하기"><code>Reflect.setPrototypeOf()</code> 사용하기</h3> + +<pre class="brush: js">Reflect.setPrototypeOf({}, Object.prototype); // true + +// It can change an object's [[Prototype]] to null. +Reflect.setPrototypeOf({}, null); // true + +// Returns false if target is not extensible. +Reflect.setPrototypeOf(Object.freeze({}), null); // false + +// Returns false if it cause a prototype chain cycle. +const target = {}; +const proto = Object.create(target); +Reflect.setPrototypeOf(target, proto); // false +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-reflect.setprototypeof', 'Reflect.setPrototypeOf')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Reflect.setPrototypeOf")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Reflect")}}</li> + <li>{{jsxref("Object.setPrototypeOf()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/regexp/exec/index.html b/files/ko/web/javascript/reference/global_objects/regexp/exec/index.html new file mode 100644 index 0000000000..4659688c51 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/regexp/exec/index.html @@ -0,0 +1,188 @@ +--- +title: RegExp.prototype.exec() +slug: Web/JavaScript/Reference/Global_Objects/RegExp/exec +tags: + - JavaScript + - Method + - Prototype + - Reference + - RegExp + - 정규 표현식 +translation_of: Web/JavaScript/Reference/Global_Objects/RegExp/exec +--- +<div>{{JSRef}}</div> + +<p><strong><code>exec()</code></strong> 메서드는 주어진 문자열에서 일치 탐색을 수행한 결과를 배열 혹은 {{jsxref("null")}}로 반환합니다.</p> + +<p>JavaScript {{jsxref("RegExp")}} 객체는 {{jsxref("RegExp.global", "global")}} 또는 {{jsxref("RegExp.sticky", "sticky")}} 플래그를 설정(<code>/foo/g</code>, <code>/foo/y</code> 등)한 경우 이전 일치의 인덱스를 저장하므로 <strong>상태를 가지고</strong>(stateful) 있습니다. 이를 내부적으로 사용하여, {{jsxref("String.prototype.match()")}}와는 다르게 (캡처 그룹을 포함한) 문자열 내의 일치 다수를 반복해 순회할 수 있습니다.</p> + +<p>(캡처 그룹을 포함한) 문자열 내의 다수 일치를 수행할 수 있는 보다 간편한 신규 메서드, {{jsxref("String.prototype.matchAll()")}}이 제안된 상태입니다.</p> + +<p>단순히 <code>true</code>/<code>false</code>가 필요한 경우 {{jsxref("RegExp.prototype.text()")}} 메서드 혹은 {{jsxref("String.prototype.search()")}}를 사용하세요.</p> + +<div>{{EmbedInteractiveExample("pages/js/regexp-prototype-exec.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox notranslate"><var>regexObj</var>.exec(<var>str</var>)</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>str</code></dt> + <dd>정규 표현식 검색을 수행할 대상 문자열.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>정규 표현식이 일치하면, <code>exec()</code> 메서드는 배열(추가 속성 <code>index</code>와 <code>input</code> 포함, 아래 설명을 참고하세요)을 반환하고, 정규 표현식 객체의 {{jsxref("RegExp.lastIndex", "lastIndex")}} 속성을 업데이트합니다. 반환하는 배열은 일치한 텍스트를 첫 번째 원소로, 각각의 괄호 캡처 그룹을 이후 원소로 포함합니다.</p> + +<p>정규표현식 검색에 실패하면, <code>exec()</code> 메서드는 {{jsxref("null")}}을 반환하고 {{jsxref("RegExp.lastIndex", "lastIndex")}}를 <code>0</code>으로 설정합니다.</p> + +<h2 id="설명">설명</h2> + +<p>다음과 같은 예제를 고려해보세요.</p> + +<pre class="brush: js notranslate">// Match "quick brown" followed by "jumps", ignoring characters in between +// Remember "brown" and "jumps" +// Ignore case +let re = /quick\s(brown).+?(jumps)/ig; +let result = re.exec('The Quick Brown Fox Jumps Over The Lazy Dog');</pre> + +<p>다음의 표는 이 스크립트의 결과에 대해 보여줍니다.</p> + +<table class="fullwidth-table standard-table"> + <thead> + <tr> + <th scope="row">객체</th> + <th scope="col">속성/인덱스</th> + <th scope="col">설명</th> + <th scope="col">예제</th> + </tr> + </thead> + <tbody> + <tr> + <th colspan="1" rowspan="4" scope="row" style="vertical-align: top;"><code>result</code></th> + <td><code>[0]</code></td> + <td>일치한 전체 문자.</td> + <td><code>"Quick Brown Fox Jumps"</code></td> + </tr> + <tr> + <td><code>[1], ...[<var>n</var>]</code></td> + <td> + <p>(존재하는 경우) 괄호로 감싼 부분문자열.</p> + + <p>괄호로 감싼 부분문자열 숫자의 제한은 없습니다.</p> + </td> + <td> + <p><code>result[1] === "Brown"</code></p> + + <p><code>result[2] === "Jumps"</code></p> + </td> + </tr> + <tr> + <td><code>index</code></td> + <td>일치가 문자열에서 위치하는 인덱스. (0 시작)</td> + <td><code>4</code></td> + </tr> + <tr> + <td><code>input</code></td> + <td>원본 문자열.</td> + <td><code>"The Quick Brown Fox Jumps Over The Lazy Dog"</code></td> + </tr> + <tr> + <th colspan="1" rowspan="5" scope="row" style="vertical-align: top;"><code>re</code></th> + <td><code>lastIndex</code></td> + <td> + <p>다음 일치를 시작할 인덱스.</p> + + <p><code>g</code>를 누락하면 항상 <code>0</code>입니다.</p> + </td> + <td><code>25</code></td> + </tr> + <tr> + <td><code>ignoreCase</code></td> + <td><code>i</code> 플래그로 대소문자를 무시했는지 여부.</td> + <td><code>true</code></td> + </tr> + <tr> + <td><code>global</code></td> + <td><code>g</code> 플래그로 전역 일치를 수행하는지 여부.</td> + <td><code>true</code></td> + </tr> + <tr> + <td><code>multiline</code></td> + <td><code>m</code> 플래그로 여러 줄에 걸친 탐색을 수행하는지 여부.</td> + <td><code>false</code></td> + </tr> + <tr> + <td><code>source</code></td> + <td>패턴 문자열.</td> + <td><code>"quick\s(brown).+?(jumps)"</code></td> + </tr> + </tbody> +</table> + +<h2 id="예제">예제</h2> + +<h3 id="Finding_successive_matches">Finding successive matches</h3> + +<p>If your regular expression uses the "<code>g</code>" flag, you can use the <code>exec()</code> method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of <code>str</code> specified by the regular expression's {{jsxref("RegExp.lastIndex", "lastIndex")}} property ({{jsxref("RegExp.prototype.test()", "test()")}} will also advance the {{jsxref("RegExp.lastIndex", "lastIndex")}} property). For example, assume you have this script:</p> + +<pre class="brush: js notranslate">var myRe = /ab*/g; +var str = 'abbcdefabh'; +var myArray; +while ((myArray = myRe.exec(str)) !== null) { + var msg = 'Found ' + myArray[0] + '. '; + msg += 'Next match starts at ' + myRe.lastIndex; + console.log(msg); +} +</pre> + +<p>This script displays the following text:</p> + +<pre class="notranslate">Found abb. Next match starts at 3 +Found ab. Next match starts at 9 +</pre> + +<p>Note: Do not place the regular expression literal (or {{jsxref("RegExp")}} constructor) within the <code>while</code> condition or it will create an infinite loop if there is a match due to the {{jsxref("RegExp.lastIndex", "lastIndex")}} property being reset upon each iteration. Also be sure that the global flag is set or a loop will occur here also.</p> + +<h3 id="Using_exec_with_RegExp_literals">Using <code>exec()</code> with <code>RegExp</code> literals</h3> + +<p>You can also use <code>exec()</code> without creating a {{jsxref("RegExp")}} object:</p> + +<pre class="brush: js notranslate">var matches = /(hello \S+)/.exec('This is a hello world!'); +console.log(matches[1]); +</pre> + +<p>This will log a message containing 'hello world!'.</p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-regexp.prototype.exec', 'RegExp.exec')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div> + + +<p>{{Compat("javascript.builtins.RegExp.exec")}}</p> +</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions">Regular Expressions</a> chapter in the <a href="/en-US/docs/Web/JavaScript/Guide">JavaScript Guide</a></li> + <li>{{jsxref("RegExp")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/regexp/index.html b/files/ko/web/javascript/reference/global_objects/regexp/index.html new file mode 100644 index 0000000000..541d3585db --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/regexp/index.html @@ -0,0 +1,233 @@ +--- +title: RegExp +slug: Web/JavaScript/Reference/Global_Objects/RegExp +tags: + - Constructor + - JavaScript + - Reference + - RegExp + - 정규 표현식 + - 정규식 +translation_of: Web/JavaScript/Reference/Global_Objects/RegExp +--- +<div>{{JSRef}}</div> + +<p><strong><code>RegExp</code></strong> 생성자는 패턴을 사용해 텍스트를 판별할 때 사용합니다.</p> + +<p>정규 표현식에 대한 소개는 <a href="/ko/docs/Web/JavaScript/Guide/Regular_Expressions">JavaScript 안내서의 정규 표현식 장</a>을 참고하세요.</p> + +<h2 id="설명">설명</h2> + +<h3 id="리터럴_표기법과_생성자">리터럴 표기법과 생성자</h3> + +<p><code>RegExp</code> 객체는 리터럴 표기법과 생성자로써 생성할 수 있습니다.</p> + +<ul> + <li><strong>리터럴 표기법</strong>의 매개변수는 두 빗금으로 감싸야 하며 따옴표를 사용하지 않습니다.</li> + <li><strong>생성자 함수</strong>의 매개변수는 빗금으로 감싸지 않으나 따옴표를 사용합니다.</li> +</ul> + +<p>다음의 세 표현식은 모두 같은 정규 표현식을 생성합니다.</p> + +<pre class="brush: js notranslate">/ab+c/i +new RegExp(/ab+c/, 'i') // 리터럴 +new RegExp('ab+c', 'i') // 생성자 +</pre> + +<p>리터럴 표기법은 표현식을 평가할 때 정규 표현식을 컴파일합니다. 정규 표현식이 변하지 않으면 리터럴 표기법을 사용하세요. 예를 들어, 반복문 안에서 사용할 정규 표현식을 리터럴 표기법으로 생성하면 정규 표현식을 매번 다시 컴파일하지 않습니다.</p> + +<p>정규 표현식 객체의 생성자(<code>new RegExp('ab+c')</code>)를 사용하면 정규 표현식이 런타임에 컴파일됩니다. 패턴이 변할 가능성이 있거나, 사용자 입력과 같이 알 수 없는 외부 소스에서 가져오는 정규 표현식의 경우 생성자 함수를 사용하세요.</p> + +<h3 id="생성자의_플래그">생성자의 플래그</h3> + +<p>ECMAScript 6부터는 <code>new RegExp(/ab+c/, 'i')</code>처럼, 첫 매개변수가 <code>RegExp</code>이면서 <code>flags</code>를 지정해도 {{jsxref("TypeError")}} (<code>"can't supply flags when constructing one RegExp from another"</code>)가 발생하지 않고, 매개변수로부터 새로운 정규 표현식을 생성합니다.</p> + +<p>생성자 함수를 사용할 경우 보통의 문자열 이스케이프 규칙(특수 문자를 문자열에 사용할 때 앞에 역빗금(<code>\</code>)을 붙이는 것)을 준수해야 합니다.</p> + +<p>예를 들어 다음 두 줄은 동일한 정규 표현식을 생성합니다.</p> + +<pre class="brush: js notranslate">let re = /\w+/ +let re = new RegExp('\\w+')</pre> + +<h3 id="Perl_형태의_RegExp_속성">Perl 형태의 <code>RegExp</code> 속성</h3> + +<p>일부 {{JSxRef("RegExp")}} 속성은 같은 값에 대해 긴 이름과 짧은 (Perl 형태의) 이름 모두 가지고 있습니다. (Perl은 JavaScript가 정규 표현식을 만들 때 참고한 프로그래밍 언어입니다.)<a href="https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#RegExp_Properties"> 사용하지 않는 <code>RegExp</code> 속성</a>을 참고하세요.</p> + +<h2 id="생성자">생성자</h2> + +<dl> + <dt>{{jsxref("RegExp/RegExp", "RegExp()")}}</dt> + <dd>새로운 <code>RegExp</code> 객체를 생성합니다.</dd> +</dl> + +<h2 id="정적_속성">정적 속성</h2> + +<dl> + <dt>{{jsxref("RegExp.@@species", "get RegExp[@@species]")}}</dt> + <dd>파생 객체를 생성할 때 사용하는 생성자입니다.</dd> + <dt>{{jsxref("RegExp.lastIndex")}}</dt> + <dd>다음 판별을 시작할 인덱스입니다.</dd> +</dl> + +<h2 id="인스턴스_속성">인스턴스 속성</h2> + +<dl> + <dt>{{JSxRef("RegExp.prototype.flags")}}</dt> + <dd><code>RegExp</code> 객체의 플래그를 담은 문자열입니다.</dd> + <dt>{{JSxRef("RegExp.prototype.dotAll")}}</dt> + <dd><code>.</code>이 줄 바꿈에 일치하는지 여부를 나타냅니다.</dd> + <dt>{{JSxRef("RegExp.prototype.global")}}</dt> + <dd>정규 표현식이 문자열 내에서 가능한 모든 경우에 일치하는지, 아니면 최초에 대해서만 일치하는지 나타냅니다.</dd> + <dt>{{JSxRef("RegExp.prototype.ignoreCase")}}</dt> + <dd>문자열의 대소문자를 구분하는지 나타냅니다.</dd> + <dt>{{JSxRef("RegExp.prototype.multiline")}}</dt> + <dd>여러 줄에 걸쳐 탐색할 것인지 나타냅니다.</dd> + <dt>{{JSxRef("RegExp.prototype.source")}}</dt> + <dd>패턴을 나타내는 문자열입니다.</dd> + <dt>{{JSxRef("RegExp.prototype.sticky")}}</dt> + <dd>검색이 접착(sticky)되어있는지 나타냅니다.</dd> + <dt>{{JSxRef("RegExp.prototype.unicode")}}</dt> + <dd>Unicode 기능의 활성화 여부입니다.</dd> +</dl> + +<h2 id="인스턴스_메서드">인스턴스 메서드</h2> + +<dl> + <dt>{{JSxRef("RegExp.prototype.compile()")}}</dt> + <dd>스크립트 실행 중 정규 표현식을 (다시) 컴파일합니다.</dd> + <dt>{{JSxRef("RegExp.prototype.exec()")}}</dt> + <dd>문자열 매개변수에 대해 검색을 실행합니다.</dd> + <dt>{{JSxRef("RegExp.prototype.test()")}}</dt> + <dd>문자열 매개변수에 대해 판별을 실행합니다.</dd> + <dt>{{JSxRef("RegExp.prototype.toString()")}}</dt> + <dd>객체의 문자열 표현을 반환합니다. {{JSxRef("Object.prototype.toString()")}} 메서드를 재정의합니다.</dd> + <dt>{{JSxRef("RegExp.prototype.@@match()", "RegExp.prototype[@@match]()")}}</dt> + <dd>주어진 문자열에 대해 일치하는 결과를 반환합니다.</dd> + <dt>{{JSxRef("RegExp.prototype.@@matchAll()", "RegExp.prototype[@@matchAll]()")}}</dt> + <dd>주어진 문자열에 대해 일치하는 모든 결과를 반환합니다.</dd> + <dt>{{JSxRef("RegExp.prototype.@@replace()", "RegExp.prototype[@@replace]()")}}</dt> + <dd>주어진 문자열 내의 일치를 새로운 문자열로 대치합니다.</dd> + <dt>{{JSxRef("RegExp.prototype.@@search()", "RegExp.prototype[@@search]()")}}</dt> + <dd>주어진 문자열에 대해 일치하는 인덱스를 반환합니다.</dd> + <dt>{{JSxRef("RegExp.prototype.@@split()", "RegExp.prototype[@@split]()")}}</dt> + <dd>주어진 문자열을 분할해 배열로 반환합니다.</dd> +</dl> + +<h2 id="예제">예제</h2> + +<h3 id="정규_표현식을_사용해서_데이터_형식_바꾸기">정규 표현식을 사용해서 데이터 형식 바꾸기</h3> + +<p>다음 스크립트에서는 {{jsxref("String")}} 객체의 {{jsxref("String.prototype.replace()", "replace()")}} 메서드를 사용하여 <em>이름 성씨</em> 형태의 이름을 <em>성씨, 이름</em> 형태 바꿔 반환합니다.</p> + +<p>대치 문자열에는 <code>$1</code>과 <code>$2</code>를 사용하여 정규 표현식 패턴의 각 괄호에 일치한 결과를 받아옵니다.</p> + +<pre class="brush: js notranslate">let re = /(\w+)\s(\w+)/ +let str = 'John Smith' +let newstr = str.replace(re, '$2, $1') +console.log(newstr)</pre> + +<p>실행 결과는 <code>"Smith, John"</code>입니다.</p> + +<h3 id="정규_표현식을_사용해서_여러_가지_줄_바꿈_문자가_있는_문자열_나누기">정규 표현식을 사용해서 여러 가지 줄 바꿈 문자가 있는 문자열 나누기</h3> + +<p>기본 줄 바꿈 문자는 플랫폼(Unix, Windows 등)마다 다릅니다. 아래의 분할 스크립트는 모든 플랫폼의 줄 바꿈을 인식합니다.</p> + +<pre class="brush: js notranslate">let text = 'Some text\nAnd some more\r\nAnd yet\rThis is the end' +let lines = text.split(/\r\n|\r|\n/) +console.log(lines) // logs [ 'Some text', 'And some more', 'And yet', 'This is the end' ]</pre> + +<p>정규 표현식 패턴의 순서를 바꾸면 작동하지 않을 수 있습니다.</p> + +<h3 id="여러_줄에서_정규_표현식_사용하기">여러 줄에서 정규 표현식 사용하기</h3> + +<pre class="brush: js notranslate">let s = 'Please yes\nmake my day!' + +s.match(/yes.*day/); +// Returns null + +s.match(/yes[^]*day/); +// Returns ["yes\nmake my day"]</pre> + +<h3 id="접착_플래그와_함께_사용하기">접착 플래그와 함께 사용하기</h3> + +<p>{{JSxRef("Global_Objects/RegExp/sticky", "sticky")}} 플래그는 해당 정규 표현식이 접착 판별, 즉 {{jsxref("RegExp.prototype.lastIndex")}}에서 시작하는 일치만 확인하도록 할 수 있습니다.</p> + +<pre class="brush: js notranslate">let str = '#foo#' +let regex = /foo/y + +regex.lastIndex = 1 +regex.test(str) // true +regex.lastIndex = 5 +regex.test(str) // false (lastIndex is taken into account with sticky flag) +regex.lastIndex // 0 (reset after match failure)</pre> + +<h3 id="접착과_전역_플래그의_차이">접착과 전역 플래그의 차이</h3> + +<p>접착 플래그 <code>y</code>의 일치는 정확히 <code>lastIndex</code> 위치에서만 발생할 수 있으나, 전역 플래그 <code>g</code>의 경우 <code>lastIndex</code> 또는 그 이후에서도 발생할 수 있습니다.</p> + +<pre class="brush: js notranslate">re = /\d/y; +while (r = re.exec("123 456")) console.log(r, "AND re.lastIndex", re.lastIndex); + +// [ '1', index: 0, input: '123 456', groups: undefined ] AND re.lastIndex 1 +// [ '2', index: 1, input: '123 456', groups: undefined ] AND re.lastIndex 2 +// [ '3', index: 2, input: '123 456', groups: undefined ] AND re.lastIndex 3 +// ... and no more match.</pre> + +<p>전역 플래그 <code>g</code>를 사용했다면, 3개가 아니고 6개 숫자 모두 일치했을 것입니다.</p> + +<h3 id="정규_표현식과_Unicode_문자">정규 표현식과 Unicode 문자</h3> + +<p> <code>\w</code>와 <code>\W</code>는 <code>a</code>부터 <code>z</code>, <code>A</code>부터 <code>Z</code>, <code>0</code>부터 <code>9</code> <code>_</code> 등의 {{glossary("ASCII")}} 문자에만 일치합니다.</p> + +<p>러시아어나 히브리어와 같은 다른 언어의 문자까지 일치하려면 <code>\uhhhh</code>(이때 hhhh는 해당 문자의 16진법 Unicode 값) 문법을 사용하세요. 아래 예제에서는 문자열에서 Unicode 문자를 추출합니다.</p> + +<pre class="brush: js notranslate">let text = 'Образец text на русском языке' +let regex = /[\u0400-\u04FF]+/g + +let match = regex.exec(text) +console.log(match[0]) // logs 'Образец' +console.log(regex.lastIndex) // logs '7' + +let match2 = regex.exec(text) +console.log(match2[0]) // logs 'на' [did not log 'text'] +console.log(regex.lastIndex) // logs '15' + +// and so on</pre> + +<p><a href="/ko/docs/Web/JavaScript/Guide/Regular_Expressions/Unicode_Property_Escapes">유니코드 속성 이스케이프</a> 기능을 사용해 <code>\p{scx=Cyrl}</code>과 같은 간단한 구문으로 이 문제를 해결할 수 있습니다.</p> + +<h3 id="URL에서_서브도메인_추출하기">URL에서 서브도메인 추출하기</h3> + +<pre class="brush: js notranslate">let url = 'http://xxx.domain.com' +console.log(/[^.]+/.exec(url)[0].substr(7)) // logs 'xxx'</pre> + +<div class="blockIndicator note"> +<p>이 때는 정규표현식보단 <a href="/ko/docs/Web/API/URL_API">URL API</a>를 통해 브라우저에 내장된 URL 구문 분석기를 사용하는 것이 좋습니다.</p> +</div> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-regexp-regular-expression-objects', 'RegExp')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<div>{{Compat("javascript.builtins.RegExp")}}</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Guide/Regular_Expressions">JavaScript 안내서의 정규 표현식 장</a></li> + <li>{{jsxref("String.prototype.match()")}}</li> + <li>{{jsxref("String.prototype.replace()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/regexp/n/index.html b/files/ko/web/javascript/reference/global_objects/regexp/n/index.html new file mode 100644 index 0000000000..5b6706cad2 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/regexp/n/index.html @@ -0,0 +1,66 @@ +--- +title: RegExp.$1-$9 +slug: Web/JavaScript/Reference/Global_Objects/RegExp/n +translation_of: Web/JavaScript/Reference/Global_Objects/RegExp/n +--- +<div>{{JSRef}} {{non-standard_header}}</div> + +<p>비표준 <strong>$1, $2, $3, $4, $5, $6, $7, $8, $9 </strong>속성들은 정적이며, 괄호로 묶인 하위 문자열 match들을 포함하는 정규 표현식의 읽기 전용 속성들입니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>RegExp</var>.$1 +RegExp.$2</code> +RegExp.$3 +RegExp.$4 +RegExp.$5 +RegExp.$6 +RegExp.$7 +RegExp.$8 +RegExp.$9 +</pre> + +<h2 id="Description">Description</h2> + +<p>$1, ..., $9 properties are static, they are not a property of an individual regular expression object. Instead, you always use them as <code>RegExp.$1</code>, ..., <code>RegExp.$9</code>.</p> + +<p>The values of these properties are read-only and modified whenever successful matches are made.</p> + +<p>The number of possible parenthesized substrings is unlimited, but the <code>RegExp</code> object can only hold the first nine. You can access all parenthesized substrings through the returned array's indexes.</p> + +<p>These properties can be used in the replacement text for the {{jsxref("String.replace")}} method. When used this way, do not prepend them with <code>RegExp</code>. The example below illustrates this. When parentheses are not included in the regular expression, the script interprets <code>$n</code>'s literally (where <code>n</code> is a positive integer).</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_n_with_String.replace">Using <code>$n</code> with <code>String.replace</code></h3> + +<p>아래의 script는 first last 포맷의 이름과 매치하기 위해 {{jsxref("String")}} 인스턴스의 {{jsxref("String.prototype.replace()", "replace()")}} 메소드를 사용하고 그것을 last, first 포맷으로 출력한다. 대체 텍스트에서, 이 script는 정규 표현식 패턴에서 매칭되는 괄호들에 해당하는 결과들을 나타내는 <code>$1</code> 과 <code>$2</code> 를 사용한다.</p> + +<pre class="brush: js">var re = /(\w+)\s(\w+)/; +var str = 'John Smith'; +str.replace(re, '$2, $1'); // "Smith, John" +RegExp.$1; // "John" +RegExp.$2; // "Smith" +</pre> + +<h2 id="Specifications">Specifications</h2> + +<p>Non-standard. Not part of any current specification.</p> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.RegExp.n")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{non-standard_inline}} {{jsxref("RegExp.input", "RegExp.input ($_)")}}</li> + <li>{{non-standard_inline}} {{jsxref("RegExp.lastMatch", "RegExp.lastMatch ($&)")}}</li> + <li>{{non-standard_inline}} {{jsxref("RegExp.lastParen", "RegExp.lastParen ($+)")}}</li> + <li>{{non-standard_inline}} {{jsxref("RegExp.leftContext", "RegExp.leftContext ($`)")}}</li> + <li>{{non-standard_inline}} {{jsxref("RegExp.rightContext", "RegExp.rightContext ($')")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/regexp/regexp/index.html b/files/ko/web/javascript/reference/global_objects/regexp/regexp/index.html new file mode 100644 index 0000000000..387b5bceff --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/regexp/regexp/index.html @@ -0,0 +1,114 @@ +--- +title: RegExp() constructor +slug: Web/JavaScript/Reference/Global_Objects/RegExp/RegExp +tags: + - Constructor + - JavaScript + - Reference + - RegExp +translation_of: Web/JavaScript/Reference/Global_Objects/RegExp/RegExp +--- +<div>{{JSRef}}</div> + +<p><strong><code>RegExp</code></strong> 생성자는 패턴을 사용해 텍스트를 판별할 때 사용하는 정규 표현식 객체를 생성합니다.</p> + +<p>정규 표현식에 대한 소개는 <a href="/ko/docs/Web/JavaScript/Guide/Regular_Expressions">JavaScript 안내서의 정규 표현식 장</a>을 참고하세요.</p> + +<div>{{EmbedInteractiveExample("pages/js/regexp-constructor.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<p>리터럴, 생성자, 팩토리 표기법이 가능합니다.</p> + +<pre class="syntaxbox notranslate">/<var>pattern</var>/<var>flags</var> +new RegExp(<var>pattern</var>[, <var>flags</var>]) +RegExp(<var>pattern</var>[, <var>flags</var>]) +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code><var>pattern</var></code></dt> + <dd>정규 표현식을 나타내는 텍스트.</dd> + <dd>ES5부터는, 생성자 표기법에 한정하여 다른 <code>RegExp</code> 객체 혹은 리터럴을 사용할 수 있습니다. 패턴은 <a href="/ko/docs/Web/JavaScript/Guide/정규식#특수_문자_사용하기">특수 문자</a>를 포함할 수 있어서 일반적인 문자열 리터럴보다 더 넓은 범위의 값을 판별할 수 있습니다.</dd> + <dt><code><var>flags</var></code></dt> + <dd> + <p>정규 표현식에 추가할 플래그.</p> + + <p>정규 표현식 객체를 패턴으로 제공한 경우 <code><var>flags</var></code> 문자열은 제공한 객체의 플래그를 모두 대체하며 <code>lastIndex</code>를 <code>0</code>으로 초기화합니다. (ES2015 이후)</p> + + <p><code><var>flags</var></code>를 지정하지 않았으면서 정규 표현식 객체를 제공한 경우, 해당 객체의 플래그와 <code>lastIndex</code>를 복제합니다.</p> + + <p><code>flags</code>는 다음 문자를 조합하여 지정할 수 있습니다.</p> + + <dl> + <dt><code>g</code> (global, 전역 판별)</dt> + <dd>처음 일치에서 중단하지 않고, 문자열 전체를 판별합니다.</dd> + <dt><code>i</code> (ignore case, 대소문자 무시)</dt> + <dd><code>u</code> 플래그까지 활성화된 경우, Unicode 대소문자 폴딩을 사용합니다.</dd> + <dt><code>m</code> (multiline, 여러 줄)</dt> + <dd>시작과 끝 문자(<code>^</code>과 <code>$</code>)가 여러 줄에 걸쳐 동작합니다. 즉, 전체 입력 문자열의 맨 처음과 맨 끝 뿐만 아니라 (<code>\n</code>이나 <code>\r</code>로 구분되는) <u>각각의</u> 줄의 처음과 끝도 일치합니다.</dd> + <dt><code>s</code> ("dotAll")</dt> + <dd><code>.</code>이 줄 바꿈에도 일치합니다.</dd> + <dt><code>u</code> (unicode)</dt> + <dd><code><var>pattern</var></code>을 Unicode 코드 포인트 시퀀스로 처리합니다. (<a href="/ko/docs/Web/API/DOMString/Binary">이진 문자열</a> 참고)</dd> + <dt><code>y</code> (sticky, 접착)</dt> + <dd>이 정규 표현식의 <code>lastIndex</code> 속성에 명시된 인덱스에서만 판별하고, 이전/이후 인덱스에서 판별을 시도하지 않습니다.</dd> + </dl> + </dd> +</dl> + +<h2 id="예제">예제</h2> + +<h3 id="리터럴_표기법과_생성자">리터럴 표기법과 생성자</h3> + +<p><code>RegExp</code> 객체는 리터럴 표기법과 생성자로써 생성할 수 있습니다.</p> + +<ul> + <li><strong>리터럴 표기법</strong>의 매개변수는 두 빗금으로 감싸야 하며 따옴표를 사용하지 않습니다.</li> + <li><strong>생성자 함수</strong>의 매개변수는 빗금으로 감싸지 않으나 따옴표를 사용합니다.</li> +</ul> + +<p>다음의 세 표현식은 모두 같은 정규 표현식을 생성합니다.</p> + +<pre class="brush: js notranslate">/ab+c/i +new RegExp(/ab+c/, 'i') // 리터럴 +new RegExp('ab+c', 'i') // 생성자 +</pre> + +<p>리터럴 표기법은 표현식을 평가할 때 정규 표현식을 컴파일합니다. 정규 표현식이 변하지 않으면 리터럴 표기법을 사용하세요. 예를 들어, 반복문 안에서 사용할 정규 표현식을 리터럴 표기법으로 생성하면 정규 표현식을 매번 다시 컴파일하지 않습니다.</p> + +<p>정규 표현식 객체의 생성자(<code>new RegExp('ab+c')</code>)를 사용하면 정규 표현식이 런타임에 컴파일됩니다. 패턴이 변할 가능성이 있거나, 사용자 입력과 같이 알 수 없는 외부 소스에서 가져오는 정규 표현식의 경우 생성자 함수를 사용하세요.</p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-regexp-constructor', 'RegExp constructor')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div> + + +<p>{{Compat("javascript.builtins.RegExp.RegExp")}}</p> +</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Guide/Regular_Expressions">JavaScript 안내서의 정규 표현식 장</a></li> + <li>{{jsxref("String.prototype.match()")}}</li> + <li>{{jsxref("String.prototype.replace()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/regexp/test/index.html b/files/ko/web/javascript/reference/global_objects/regexp/test/index.html new file mode 100644 index 0000000000..07569e7eaf --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/regexp/test/index.html @@ -0,0 +1,129 @@ +--- +title: RegExp.prototype.test() +slug: Web/JavaScript/Reference/Global_Objects/RegExp/test +tags: + - JavaScript + - Method + - Prototype + - Reference + - RegExp + - 정규 표현식 + - 정규식 +translation_of: Web/JavaScript/Reference/Global_Objects/RegExp/test +--- +<div>{{JSRef}}</div> + +<p><strong><code>test()</code></strong> 메서드는 주어진 문자열이 정규 표현식을 만족하는지 판별하고, 그 여부를 <code>true</code> 또는 <code>false</code>로 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/regexp-prototype-test.html", "taller")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox notranslate"><var>regexObj</var>.test(<var>str</var>)</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code><var>str</var></code></dt> + <dd>정규 표현식 일치를 수행할 문자열.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 문자열 <code>str</code> 중 정규 표현식이 일치하는 부분이 있으면 <code>true</code>, 아니면, <code>false</code>.</p> + +<h2 id="설명">설명</h2> + +<p>패턴이 문자열 내에 존재하는지에 대한 여부를 알아보고자 할 때 <code>test()</code>를 사용하세요. 일치의 위치 인덱스, 또는 일치하지 않으면 <code>-1</code>을 반환하는 {{jsxref("String.prototype.search()")}}와 달리 <code>test()</code>는 불리언을 반환합니다.</p> + +<p>더 느리지만 더 많은 정보가 필요하면 {{jsxref("RegExp.prototype.exec()", "exec()")}} 메서드를 사용하세요. ({{jsxref("String.prototype.match()")}} 메서드와 비슷합니다.)</p> + +<p><code>exec()</code>처럼, <code>test()</code>도 전역 탐색 플래그를 제공한 정규 표현식에서 여러 번 호출하면 이전 일치 이후부터 탐색합니다. <code>exec()</code>와 <code>test()</code>를 혼용해 사용하는 경우에도 해당됩니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="test_사용하기"><code>test()</code> 사용하기</h3> + +<p>문자열의 맨 처음에 <code>"hello"</code>가 포함됐는지 알아보는 간단한 예제 코드입니다.</p> + +<pre class="brush: js notranslate">const str = 'hello world!'; +const result = /^hello/.test(str); + +console.log(result); // true +</pre> + +<p>다음은 일치 여부에 따라 다른 메시지를 기록하는 예제입니다.</p> + +<pre class="brush: js notranslate">function testInput(re, str) { + let midstring; + if (re.test(str)) { + midstring = 'contains'; + } else { + midstring = 'does not contain'; + } + console.log(`${str} ${midstring} ${re.source}`); +} +</pre> + +<h3 id="전역_플래그와_test">전역 플래그와 <code>test()</code></h3> + +<p>정규 표현식에 <a href="/ko/docs/Web/JavaScript/Guide/Regular_Expressions#플래그를_사용한_고급검색">전역 플래그</a>를 설정한 경우, <code>test()</code> 메서드는 정규 표현식의 {{jsxref("RegExp.lastIndex", "lastIndex")}}를 업데이트합니다. ({{jsxref("RegExp.prototype.exec()")}}도 <code>lastIndex</code> 속성을 업데이트합니다.)</p> + +<p><code>test(<var>str</var>)</code>을 또 호출하면 <code><var>str</var></code> 검색을 <code>lastIndex</code>부터 계속 진행합니다. <code>lastIndex</code> 속성은 매 번 <code>test()</code>가 <code>true</code>를 반환할 때마다 증가하게 됩니다.</p> + +<div class="blockIndicator note"> +<p><strong>참고:</strong> <code>test()</code>가 <code>true</code>를 반환하기만 하면 <code>lastIndex</code>는 초기화되지 않습니다. 심지어 이전과 다른 문자열을 매개변수로 제공해도 그렇습니다!</p> +</div> + +<p><code>test()</code>가 <code>false</code>를 반환할 땐 <code>lastIndex</code> 속성이 <code>0</code>으로 초기화됩니다.</p> + +<p>이 행동에 대한 예제가 다음 코드입니다.</p> + +<pre class="brush: js notranslate">const regex = /foo/g; // the "global" flag is set + +// regex.lastIndex is at 0 +regex.test('foo') // true + +// regex.lastIndex is now at 3 +regex.test('foo') // false + +// regex.lastIndex is at 0 +regex.test('barfoo') // true + +// regex.lastIndex is at 6 +regex.test('foobar') //false + +// regex.lastIndex is at 0 +// (...and so on) +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-regexp.prototype.test', 'RegExp.test')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.RegExp.test")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Guide/Regular_Expressions">JavaScript 안내서의 정규 표현식 장</a></li> + <li>{{jsxref("RegExp")}}</li> + <li>{{jsxref("RegExp.prototype")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/set/add/index.html b/files/ko/web/javascript/reference/global_objects/set/add/index.html new file mode 100644 index 0000000000..622b3d876c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/set/add/index.html @@ -0,0 +1,83 @@ +--- +title: Set.prototype.add() +slug: Web/JavaScript/Reference/Global_Objects/Set/add +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - set +translation_of: Web/JavaScript/Reference/Global_Objects/Set/add +--- +<div>{{JSRef}}</div> + +<p><code><strong>add()</strong></code> 메서드는 <code>Set</code> 개체의 맨 뒤에 주어진 <code>value</code>의 새 요소를 추가합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/set-prototype-add.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><em>mySet</em>.add(<em>value</em>);</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>value</code></dt> + <dd><code>Set</code> 객체에 추가할 요소의 값.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p><code>Set</code> 객체.</p> + +<h2 id="예제">예제</h2> + +<h3 id="add_메서드_사용하기"><code>add</code> 메서드 사용하기</h3> + +<pre class="brush: js">var mySet = new Set(); + +mySet.add(1); +mySet.add(5).add('어떤 문자열'); // 계속 붙일 수 있음 + +console.log(mySet); +// Set [1, 5, "어떤 문자열"] +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">비고</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-set.prototype.add', 'Set.prototype.add')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>최초 정의</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-set.prototype.add', 'Set.prototype.add')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div class="hidden">본 페이지의 호환성 표는 구조화된 데이터로부터 생성되었습니다. 만약 당신이 데이터에 기여를 원한다면 <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>를 체크아웃하고 우리에게 pull request를 보내주세요.</div> + +<p>{{Compat("javascript.builtins.Set.add")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Set")}}</li> + <li>{{jsxref("Set.prototype.delete()")}}</li> + <li>{{jsxref("Set.prototype.has()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/set/clear/index.html b/files/ko/web/javascript/reference/global_objects/set/clear/index.html new file mode 100644 index 0000000000..3ecdb98895 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/set/clear/index.html @@ -0,0 +1,76 @@ +--- +title: Set.prototype.clear() +slug: Web/JavaScript/Reference/Global_Objects/Set/clear +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - set +translation_of: Web/JavaScript/Reference/Global_Objects/Set/clear +--- +<div>{{JSRef}}</div> + +<p><code><strong>clear()</strong></code> 메서드는 <code>Set</code> 객체를 비웁니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/set-prototype-clear.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><em>mySet</em>.clear(); +</pre> + +<h2 id="예제">예제</h2> + +<h3 id="clear()_사용하기"><code>clear()</code> 사용하기</h3> + +<pre class="brush: js">var mySet = new Set(); +mySet.add(1); +mySet.add('foo'); + +mySet.size; // 2 +mySet.has('foo'); // true + +mySet.clear(); + +mySet.size; // 0 +mySet.has('bar') // false +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-set.prototype.clear', 'Set.prototype.clear')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-set.prototype.clear', 'Set.prototype.clear')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Set.clear")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Set")}}</li> + <li>{{jsxref("Set.prototype.delete()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/set/delete/index.html b/files/ko/web/javascript/reference/global_objects/set/delete/index.html new file mode 100644 index 0000000000..a138736b46 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/set/delete/index.html @@ -0,0 +1,98 @@ +--- +title: Set.prototype.delete() +slug: Web/JavaScript/Reference/Global_Objects/Set/delete +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - set +translation_of: Web/JavaScript/Reference/Global_Objects/Set/delete +--- +<div>{{JSRef}}</div> + +<p><code><strong>delete()</strong></code> 메서드는 지정한 요소를 <code>Set</code> 객체에서 제거합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/set-prototype-delete.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><em>mySet</em>.delete(<em>value</em>);</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>value</code></dt> + <dd><code>Set</code> 객체에서 제거할 요소의 값.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>요소를 제거했으면 <code>true</code>, 아니면 <code>false</code>.</p> + +<h2 id="예제">예제</h2> + +<h3 id="delete()_사용하기"><code>delete()</code> 사용하기</h3> + +<pre class="brush: js">var mySet = new Set(); +mySet.add('foo'); + +mySet.delete('bar'); // Returns false. No "bar" element found to be deleted. +mySet.delete('foo'); // Returns true. Successfully removed. + +mySet.has('foo'); // Returns false. The "foo" element is no longer present. +</pre> + +<p>다음 예제는 <code>Set</code>에서 객체를 제거하는 방법을 보입니다.</p> + +<pre class="brush: js">var setObj = new Set(); // Create a New Set. + +setObj.add({x: 10, y: 20}); // Add object in the set. + +setObj.add({x: 20, y: 30}); // Add object in the set. + +// Delete any point with `x > 10`. +setObj.forEach(function(point){ + if(point.x > 10){ + setObj.delete(point) + } +}) +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-set.prototype.delete', 'Set.prototype.delete')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-set.prototype.delete', 'Set.prototype.delete')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Set.delete")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Set")}}</li> + <li>{{jsxref("Set.prototype.clear()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/set/foreach/index.html b/files/ko/web/javascript/reference/global_objects/set/foreach/index.html new file mode 100644 index 0000000000..fbfa4963c5 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/set/foreach/index.html @@ -0,0 +1,117 @@ +--- +title: Set.prototype.forEach() +slug: Web/JavaScript/Reference/Global_Objects/Set/forEach +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - set +translation_of: Web/JavaScript/Reference/Global_Objects/Set/forEach +--- +<div>{{JSRef}}</div> + +<p><code><strong>forEach()</strong></code> 메서드는 주어진 함수를 <code>Set</code> 요소 각각에 대해 삽입 순서대로 실행합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/set-prototype-foreach.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><em>mySet</em>.forEach(<em>callback</em>[, <var>thisArg</var>]<code>)</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>각 요소에 대해 실행할 함수. 다음 세 가지 인수를 받습니다.</dd> + <dd> + <dl> + <dt><code>currentValue</code>, <code>currentKey</code></dt> + <dd>처리할 현재 요소. <code>Set</code>은 키를 갖지 않으므로 두 인수 모두에 값을 전달합니다.</dd> + <dt><code>set</code></dt> + <dd><code>forEach()</code>를 호출한 <code>Set</code>.</dd> + </dl> + </dd> + <dt><code>thisArg</code></dt> + <dd><code>callback</code>을 실행할 때 <code>this</code>로 사용할 값.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>{{jsxref("undefined")}}.</p> + +<h2 id="설명">설명</h2> + +<p><code>forEach()</code> 메서드는 주어진 <code>callback</code>을 <code>Set</code>에 존재하는 요소에 대해 한 번씩 실행합니다. 삭제한 값에 대해선 실행하지 않습니다. 그러나 존재하되 값이 {{jsxref("undefined")}}인 경우엔 실행합니다.</p> + +<p><code>callback</code>은 다음 세 인수와 함께 호출됩니다.</p> + +<ul> + <li><strong>요소 값</strong></li> + <li><strong>요소 키</strong></li> + <li><strong>순회 중인 <code>Set</code> 객체</strong></li> +</ul> + +<p>그러나 <code>Set</code>은 키 값을 사용하지 않으므로, 처음 두 개의 매개변수 모두 <strong>요소 값</strong>을 받습니다. 이는 {{jsxref("Map.foreach", "Map")}}과 {{jsxref("Array.forEach","Array")}}에서 사용하는 <code>forEach()</code>와 동일한 형태를 유지하기 위해서입니다.</p> + +<p><code>thisArg</code> 매개변수를 <code>forEach()</code>에 제공한 경우 <code>callback</code>을 호출할 때 전달해 <code>this</code>의 값으로 쓰입니다. 전달하지 않으면 <code>undefined</code>를 사용하며, 최종 <code>this</code> 값은 {{jsxref("Operators/this", "함수의 <code>this</code>를 결정하는 평소 규칙", "", 0)}}을 따릅니다.</p> + +<p><code>forEach()</code>는 각각의 값을 한 번씩 방문하지만, 순회를 끝내기 전에 제거하고 다시 추가한 값은 예외입니다. 방문하기 전 제거한 값에 대해서는 <code>callback</code>을 호출하지 않습니다. <code>forEach()</code>가 끝나기 전 추가한 요소는 방문합니다.</p> + +<p><code>forEach()</code>는 <code>Set</code> 객체의 요소에 대해 <code>callback</code>을 실행만 하며 값을 반환하지는 않습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="Set의_내용물_기록하기"><code>Set</code>의 내용물 기록하기</h3> + +<p>다음 코드는 <code>Set</code>의 요소 각각을 새로운 줄에 기록합니다.</p> + +<pre class="brush:js">function logSetElements(value1, value2, set) { + console.log('s[' + value1 + '] = ' + value2); +} + +new Set(['foo', 'bar', undefined]).forEach(logSetElements); + +// 콘솔 로그: +// "s[foo] = foo" +// "s[bar] = bar" +// "s[undefined] = undefined" +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-set.prototype.foreach', 'Set.prototype.forEach')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-set.prototype.foreach', 'Set.prototype.forEach')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Set.forEach")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.forEach()")}}</li> + <li>{{jsxref("Map.prototype.forEach()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/set/has/index.html b/files/ko/web/javascript/reference/global_objects/set/has/index.html new file mode 100644 index 0000000000..016da46cfd --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/set/has/index.html @@ -0,0 +1,93 @@ +--- +title: Set.prototype.has() +slug: Web/JavaScript/Reference/Global_Objects/Set/has +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - set +translation_of: Web/JavaScript/Reference/Global_Objects/Set/has +--- +<div>{{JSRef}}</div> + +<p><code><strong>has()</strong></code> 메서드는 <code>Set</code> 객체에 주어진 요소가 존재하는지 여부를 판별해 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/set-prototype-has.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><em>mySet</em>.has(<em>value</em>);</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>value</code></dt> + <dd><code>Set</code> 객체에서 존재 여부를 판별할 값.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p><code>Set</code> 객체에 값이 존재하면 <code>true</code>, 아니면 <code>false</code>.</p> + +<div class="blockIndicator note"> +<p><strong>참고:</strong> 기술적으로, <code>has()</code>는 <a href="/ko/docs/Web/JavaScript/Equality_comparisons_and_sameness#등가0_같음"><code>sameValueZero</code></a> 알고리즘을 사용해 요소의 존재 여부를 판별합니다.</p> +</div> + +<h2 id="예제">예제</h2> + +<h3 id="has()_사용하기"><code>has()</code> 사용하기</h3> + +<pre class="brush: js">var mySet = new Set(); +mySet.add('foo'); + +mySet.has('foo'); // true +mySet.has('bar'); // false + +var set1 = new Set(); +var obj1 = {'key1': 1}; +set1.add(obj1); + +set1.has(obj1); // true +set1.has({'key1': 1}); // false, 형태만 같은 서로 다른 객체의 참조이기 때문 +set1.add({'key1': 1}); // set1의 요소가 2개로 늘어남 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-set.prototype.has', 'Set.prototype.has')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-set.prototype.has', 'Set.prototype.has')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Set.has")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Set")}}</li> + <li>{{jsxref("Set.prototype.add()")}}</li> + <li>{{jsxref("Set.prototype.delete()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/set/index.html b/files/ko/web/javascript/reference/global_objects/set/index.html new file mode 100644 index 0000000000..b8086f89bd --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/set/index.html @@ -0,0 +1,237 @@ +--- +title: Set +slug: Web/JavaScript/Reference/Global_Objects/Set +tags: + - ECMAScript 2015 + - Global Objects + - JavaScript + - Object + - Reference + - set +translation_of: Web/JavaScript/Reference/Global_Objects/Set +--- +<div>{{JSRef}}</div> + +<p><strong><code>Set</code></strong> 객체는 자료형에 관계 없이 {{Glossary("Primitive", "원시 값")}}과 객체 참조 모두 유일한 값을 저장할 수 있습니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/set-prototype-constructor.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">new Set([<em>iterable</em>]);</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>iterable</code></dt> + <dd><a href="/ko/docs/Web/JavaScript/Reference/Statements/for...of">반복 가능한 객체</a>가 전달된 경우, 그 요소는 모두 새로운 <code>Set</code>에 추가됩니다. 만약 매개변수를 명시하지 않거나 <code>null</code>을 전달하면, 새로운 <code>Set</code>은 비어 있는 상태가 됩니다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>새로운 <code>Set</code> 객체.</p> + +<h2 id="설명">설명</h2> + +<p><code>Set</code> 객체는 값 콜렉션으로, 삽입 순서대로 요소를 순회할 수 있습니다. 하나의 <code>Set</code> 내 값은 한 번만 나타날 수 있습니다. 즉, 어떤 값은 그 <code>Set</code> 콜렉션 내에서 유일합니다.</p> + +<h3 id="값_같음">값 같음</h3> + +<p><code>Set</code> 내의 값은 유일해야 하기 때문에 값이 같은지 검사를 수행합니다. 이전 ECMAScript 명세에서는 검사 알고리즘이 <code>===</code> 연산자와는 다른 것이었습니다. 특히, <code>+0 === -0</code>이었지만 <code>Set</code>에서는 <code>+0</code>과 <code>-0</code>이 다른 값이었습니다. 그러나 이는 ECMAScript 2015 명세에서 변경되었습니다. {{anch("브라우저 호환성", "브라우저 호환성")}}의 "Key equality for -0 and 0"을 참고하세요.</p> + +<p>{{jsxref("NaN")}}과 {{jsxref("undefined")}}도 <code>Set</code>에 저장할 수 있습니다. 원래 <code>NaN !== NaN</code>이지만, <code>Set</code>에서 <code>NaN</code>은 <code>NaN</code>과 같은 것으로 간주됩니다.</p> + +<h2 id="속성">속성</h2> + +<dl> + <dt><code>Set.length</code></dt> + <dd>값이 0인 속성입니다.</dd> + <dt>{{jsxref("Set.@@species", "get Set[@@species]")}}</dt> + <dd>파생 객체를 생성하는데 사용하는 생성자 함수입니다.</dd> + <dt>{{jsxref("Set.prototype")}}</dt> + <dd><code>Set</code> 생성자의 프로토타입을 나타냅니다. 모든 <code>Set</code> 객체에 속성을 추가할 수 있습니다.</dd> +</dl> + +<h2 id="Set_인스턴스"><code>Set</code> 인스턴스</h2> + +<p>모든 <code>Set</code> 인스턴스는 {{jsxref("Set.prototype")}}을 상속받습니다.</p> + +<h3 id="속성_2">속성</h3> + +<p>{{page('ko/docs/Web/JavaScript/Reference/Global_Objects/Set/prototype','속성')}}</p> + +<h3 id="메서드">메서드</h3> + +<p>{{page('ko/docs/Web/JavaScript/Reference/Global_Objects/Set/prototype','메서드')}}</p> + +<h2 id="예제">예제</h2> + +<h3 id="Set_객체_사용"><code>Set</code> 객체 사용</h3> + +<pre class="brush: js">var mySet = new Set(); + +mySet.add(1); // Set { 1 } +mySet.add(5); // Set { 1, 5 } +mySet.add(5); // Set { 1, 5 } +mySet.add('some text'); // Set { 1, 5, 'some text' } +var o = {a: 1, b: 2}; +mySet.add(o); + +mySet.add({a: 1, b: 2}); // o와 다른 객체를 참조하므로 괜찮음 + +mySet.has(1); // true +mySet.has(3); // false, 3은 set에 추가되지 않았음 +mySet.has(5); // true +mySet.has(Math.sqrt(25)); // true +mySet.has('Some Text'.toLowerCase()); // true +mySet.has(o); // true + +mySet.size; // 5 + +mySet.delete(5); // set에서 5를 제거함 +mySet.has(5); // false, 5가 제거되었음 + +mySet.size; // 4, 방금 값을 하나 제거했음 +console.log(mySet);// Set {1, "some text", Object {a: 1, b: 2}, Object {a: 1, b: 2}} +</pre> + +<h3 id="Set_반복">Set 반복</h3> + +<pre class="brush: js">// set 내 항목에 대해 반복 +// 순서대로 항목을 (콘솔에) 기록: 1, "some text", {"a": 1, "b": 2} +for (let item of mySet) console.log(item); + +// 순서대로 항목을 기록: 1, "some text", {"a": 1, "b": 2} +for (let item of mySet.keys()) console.log(item); + +// 순서대로 항목을 기록: 1, "some text", {"a": 1, "b": 2} +for (let item of mySet.values()) console.log(item); + +// 순서대로 항목을 기록: 1, "some text", {"a": 1, "b": 2} +// (여기서 key와 value는 같음) +for (let [key, value] of mySet.entries()) console.log(key); + +// Set 객체를 배열 객체로 변환 (<a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/from">Array.from</a>으로) +var myArr = Array.from(mySet); // [1, "some text", {"a": 1, "b": 2}] + +// 다음도 HTML 문서에서 실행하는 경우 작동함 +mySet.add(document.body); +mySet.has(document.querySelector('body')); // true + +// Set과 Array 사이 변환 +mySet2 = new Set([1, 2, 3, 4]); +mySet2.size; // 4 +[...mySet2]; // [1, 2, 3, 4] + +// 교집합은 다음으로 흉내(simulate)낼 수 있음 +var intersection = new Set([...set1].filter(x => set2.has(x))); + +// 차집합은 다음으로 흉내낼 수 있음 +var difference = new Set([...set1].filter(x => !set2.has(x))); + +// forEach로 set 항목 반복 +mySet.forEach(function(value) { + console.log(value); +}); + +// 1 +// 2 +// 3 +// 4</pre> + +<h3 id="기본_집합_연산_구현">기본 집합 연산 구현</h3> + +<pre class="brush: js">Set.prototype.isSuperset = function(subset) { + for (var elem of subset) { + if (!this.has(elem)) { + return false; + } + } + return true; +} + +Set.prototype.union = function(setB) { + var union = new Set(this); + for (var elem of setB) { + union.add(elem); + } + return union; +} + +Set.prototype.intersection = function(setB) { + var intersection = new Set(); + for (var elem of setB) { + if (this.has(elem)) { + intersection.add(elem); + } + } + return intersection; +} + +Set.prototype.difference = function(setB) { + var difference = new Set(this); + for (var elem of setB) { + difference.delete(elem); + } + return difference; +} + +//Examples +var setA = new Set([1, 2, 3, 4]), + setB = new Set([2, 3]), + setC = new Set([3, 4, 5, 6]); + +setA.isSuperset(setB); // => true +setA.union(setC); // => Set [1, 2, 3, 4, 5, 6] +setA.intersection(setC); // => Set [3, 4] +setA.difference(setC); // => Set [1, 2]</pre> + +<h3 id="Array_객체와의_관계"><code>Array</code> 객체와의 관계</h3> + +<pre class="brush: js">var myArray = ['value1', 'value2', 'value3']; + +// Array를 Set으로 변환하기 위해서는 정규 Set 생성자 사용 +var mySet = new Set(myArray); + +mySet.has('value1'); // true 반환 + +// set을 Array로 변환하기 위해 전개 연산자 사용함. +console.log([...mySet]); // myArray와 정확히 같은 배열을 보여줌</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-set-objects', 'Set')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-set-objects', 'Set')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Set")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Map")}}</li> + <li>{{jsxref("WeakMap")}}</li> + <li>{{jsxref("WeakSet")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/set/prototype/index.html b/files/ko/web/javascript/reference/global_objects/set/prototype/index.html new file mode 100644 index 0000000000..ca6e568bed --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/set/prototype/index.html @@ -0,0 +1,86 @@ +--- +title: Set.prototype +slug: Web/JavaScript/Reference/Global_Objects/Set/prototype +tags: + - ECMAScript 2015 + - JavaScript + - Property + - Reference + - set +translation_of: Web/JavaScript/Reference/Global_Objects/Set +--- +<div>{{JSRef}}</div> + +<p><code><strong>Set.prototype</strong></code> 속성은 {{jsxref("Set")}} 생성자의 프로토타입을 나타냅니다.</p> + +<div>{{js_property_attributes(0,0,0)}}</div> + +<h2 id="설명">설명</h2> + +<p>{{jsxref("Set")}} 인스턴스는 {{jsxref("Set.prototype")}}에서 상속합니다. 모든 <code>Set</code> 인스턴스에 속성 또는 메서드를 추가하기 위해 생성자의 프로토타입 객체를 사용할 수 있습니다.</p> + +<h2 id="속성">속성</h2> + +<dl> + <dt><code>Set.prototype.constructor</code></dt> + <dd>인스턴스의 프로토타입을 만든 함수를 반환합니다. 이는 기본으로 {{jsxref("Set")}} 함수입니다.</dd> + <dt>{{jsxref("Set.prototype.size")}}</dt> + <dd><code>Set</code> 객체 내 값의 개수를 반환합니다.</dd> +</dl> + +<h2 id="메서드">메서드</h2> + +<dl> + <dt>{{jsxref("Set.add", "Set.prototype.add(value)")}}</dt> + <dd><code>Set</code> 객체에 주어진 값을 갖는 새로운 요소를 추가합니다. <code>Set</code> 객체를 반환합니다.</dd> + <dt>{{jsxref("Set.prototype.clear()")}}</dt> + <dd><code>Set</code> 객체에서 모든 요소를 제거합니다.</dd> + <dt>{{jsxref("Set.delete", "Set.prototype.delete(value)")}}</dt> + <dd><code>value</code>와 관련된 요소를 제거하고 <code>Set.prototype.has(value)</code>가 이전에 반환했던 값을 반환합니다. <code>Set.prototype.has(value)</code>는 그 뒤에 <code>false</code>를 반환합니다.</dd> + <dt>{{jsxref("Set.prototype.entries()")}}</dt> + <dd>삽입 순으로 <code>Set</code> 객체 내 각 값에 대한 <strong><code>[value, value]</code> 배열</strong>을 포함하는 새로운 <code>Iterator</code> 객체를 반환합니다. 이는 <code>Map</code> 객체와 비슷하게 유지되므로 여기서 각 항목은 그 <em>key</em>와 <em>value</em>에 대해 같은 값을 갖습니다.</dd> + <dt>{{jsxref("Set.forEach", "Set.prototype.forEach(callbackFn[, thisArg])")}}</dt> + <dd>삽입 순으로 <code>Set</code> 객체 내에 있는 각 값에 대해 한 번 <code>callbackFn</code>을 호출합니다. <code>thisArg</code> 매개변수가 <code>forEach</code>에 제공된 경우, 이는 각 콜백에 대해 <code>this</code> 값으로 사용됩니다.</dd> + <dt>{{jsxref("Set.has", "Set.prototype.has(value)")}}</dt> + <dd><code>Set</code> 객체 내 주어진 값을 갖는 요소가 있는지를 주장하는(asserting, 나타내는) boolean을 반환합니다.</dd> + <dt>{{jsxref("Set.prototype.keys()")}}</dt> + <dd><strong><code>values()</code></strong> 함수와 같은 함수로 삽입 순으로 <code>Set</code> 객체 내 각 요소에 대한 값을 포함하는 새로운 <code>Iterator</code> 객체를 반환합니다.</dd> + <dt>{{jsxref("Set.prototype.values()")}}</dt> + <dd>삽입 순으로 <code>Set</code> 객체 내 각 요소에 대한 <strong>값</strong>을 포함하는 새로운 <code>Iterator</code> 객체를 반환합니다.</dd> + <dt>{{jsxref("Set.prototype.@@iterator()", "Set.prototype[@@iterator]()")}}</dt> + <dd>삽입 순으로 <code>Set</code> 객체 내 각 요소에 대한 <strong>값</strong>을 포함하는 새로운 <code>Iterator</code> 객체를 반환합니다.</dd> +</dl> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-set.prototype', 'Set.prototype')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-set.prototype', 'Set.prototype')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Set.prototype")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Map.prototype")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/set/size/index.html b/files/ko/web/javascript/reference/global_objects/set/size/index.html new file mode 100644 index 0000000000..2f437bed4a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/set/size/index.html @@ -0,0 +1,69 @@ +--- +title: Set.prototype.size +slug: Web/JavaScript/Reference/Global_Objects/Set/size +tags: + - ECMAScript 2015 + - JavaScript + - Property + - Prototype + - Reference + - set +translation_of: Web/JavaScript/Reference/Global_Objects/Set/size +--- +<div>{{JSRef}}</div> + +<p><code><strong>size</strong></code> 접근자 속성은 {{jsxref("Set")}} 객체의 원소 수를 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/set-prototype-size.html")}}</div> + + + +<h2 id="설명">설명</h2> + +<p><code>size</code>의 값은 <code>Set</code> 객체가 가진 원소의 수를 나타내는 정수입니다. <code>size</code> 값의 설정자는 {{jsxref("undefined")}}입니다. 즉 값을 직접 바꿀 수는 없습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="size_사용하기"><code>size</code> 사용하기</h3> + +<pre class="brush:js">var mySet = new Set(); +mySet.add(1); +mySet.add(5); +mySet.add('some text') + +mySet.size; // 3 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-get-set.prototype.size', 'Set.prototype.size')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-get-set.prototype.size', 'Set.prototype.size')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Set.size")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Set")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/set/values/index.html b/files/ko/web/javascript/reference/global_objects/set/values/index.html new file mode 100644 index 0000000000..37e019e3da --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/set/values/index.html @@ -0,0 +1,72 @@ +--- +title: Set.prototype.values() +slug: Web/JavaScript/Reference/Global_Objects/Set/values +translation_of: Web/JavaScript/Reference/Global_Objects/Set/values +--- +<div>{{JSRef}}</div> + +<p><code><strong>values()</strong></code> method는 <code>Set<font face="Arial, x-locale-body, sans-serif"><span style="background-color: #ffffff;"> 객체에 요소가 삽입된 순서대로 각 요소의 값을 순환할 수 있는 </span></font></code><code>Iterator</code> 객체를 반환합니다.</p> + +<p>The <strong><code>keys()</code></strong> method is an alias for this method (for similarity with {{jsxref("Map")}} objects); it behaves exactly the same and returns <strong>values</strong> of <code>Set</code> elements.</p> + +<div>{{EmbedInteractiveExample("pages/js/set-prototype-values.html")}}</div> + + + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><em>mySet</em>.values(); +</code></pre> + +<h3 id="Return_value">Return value</h3> + +<p>A new <code><strong>Iterator</strong></code> object containing the values for each element in the given <code>Set</code>, in insertion order.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_values()">Using <code>values()</code></h3> + +<pre class="brush:js">var mySet = new Set(); +mySet.add('foo'); +mySet.add('bar'); +mySet.add('baz'); + +var setIter = mySet.values(); + +console.log(setIter.next().value); // "foo" +console.log(setIter.next().value); // "bar" +console.log(setIter.next().value); // "baz"</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-set.prototype.values', 'Set.prototype.values')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-set.prototype.values', 'Set.prototype.values')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.builtins.Set.values")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Set.prototype.entries()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/sharedarraybuffer/index.html b/files/ko/web/javascript/reference/global_objects/sharedarraybuffer/index.html new file mode 100644 index 0000000000..9919adb447 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/sharedarraybuffer/index.html @@ -0,0 +1,137 @@ +--- +title: SharedArrayBuffer +slug: Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer +tags: + - Constructor + - JavaScript + - Shared Memory + - SharedArrayBuffer + - TypedArrays +translation_of: Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer +--- +<div>{{JSRef}}</div> + +<p><strong><code>SharedArrayBuffer</code></strong> 객체는 제네릭, 고정된 길이의 원시 바이너리 데이터 버퍼를 표현하는데 사용됩니다. {{jsxref("ArrayBuffer")}} 객체와 유사하지만, 공유된 메모리상의 뷰를 생성하는데 사용될 수 있습니다. <code>ArrayBuffer</code> 와는 달리, <code>SharedArrayBuffer</code> 는 분리될 수 없습니다.</p> + +<div class="blockIndicator note"> +<p><a href="https://meltdownattack.com/">Spectre</a> 에대한 응답으로 2018년 1월 5일에 <code>SharedArrayBuffer</code> 는 모든 주요 브라우저에서 기본적으로 비활성화되어있음을 참고하세요. Chrome 은 사이트 격리 기능을 사용하여 Spectre 스타일 취약점으로부터 보호될 수 있는 플랫폼상의 <a href="https://bugs.chromium.org/p/chromium/issues/detail?id=821270">v67 에서 이를 다시 활성화</a>하였습니다.</p> +</div> + +<p>{{EmbedInteractiveExample("pages/js/sharedarraybuffer-constructor.html")}}</p> + +<div class="hidden"> +<p>The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p> +</div> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">new SharedArrayBuffer(length) +</pre> + +<h3 id="파라미터">파라미터</h3> + +<dl> + <dt><code>length</code></dt> + <dd>생성할 array buffer 의 바이트 크기.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>크기가 지정된 새로운 <code>SharedArrayBuffer</code> 객체입니다. 컨텐츠는 0 으로 초기화됩니다.</p> + +<h2 id="설명">설명</h2> + +<h3 id="할당_및_메모리_공유">할당 및 메모리 공유</h3> + +<p>{{jsxref("SharedArrayBuffer")}} 객체를 사용해 메모리를 하나의 agent(agent 는 웹 페이지의 메인 프로그램 또는 웹 워커 중 하나입니다)와 다른 agent 에서 공유하기 위해, <code><a href="https://developer.mozilla.org/ko/docs/Web/API/Worker/postMessage">postMessage</a></code> 와 <a href="https://developer.mozilla.org/ko/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">structured cloning</a> 이 사용됩니다.</p> + +<p>Structured clone 알고리즘은 <code>SharedArrayBuffer</code> 와 <code>SharedArrayBuffer</code> 상에 맵핑된 <code>TypedArray</code> 를 받아들입니다. 이 두 경우에서, <code>SharedArrayBuffer</code> 객체는 수신자(receiver)에게 전달되어 수신 agent(예, {{jsxref("ArrayBuffer")}})의 새로운 비공개의 SharedArrayBuffer 객체를 생성합니다. 하지만, 두 <code>SharedArrayBuffer</code> 에 의해 참조되는 공유 데이터 블록은 같은 블록이며, 부수적인 효과로, 하나의 agent 가 다른 agent 에서 보이게 됩니다.</p> + +<pre class="brush: js">var sab = new SharedArrayBuffer(1024); +worker.postMessage(sab); +</pre> + +<h3 id="Atomic_operation_으로_공유_메모리_수정_및_동기화">Atomic operation 으로 공유 메모리 수정 및 동기화</h3> + +<p>공유 메모리는 워커나 메인 스레드에서 동시에 수정 및 생성할 수 있습니다. 시스템(CPU, OS, 브라우저)에따라 변경사항이 전체 컨텍스트로 전파될때까지 약간의 시간이 필요합니다. 동기화를 위해선, {{jsxref("Atomics", "atomic", "", 1)}} 연산이 필요합니다.</p> + +<h3 id="SharedArrayBuffer_객체를_사용할_수_있는_API"><code>SharedArrayBuffer</code> 객체를 사용할 수 있는 API</h3> + +<ul> + <li>{{domxref("WebGLRenderingContext.bufferData()")}}</li> + <li>{{domxref("WebGLRenderingContext.bufferSubData()")}}</li> + <li>{{domxref("WebGL2RenderingContext.getBufferSubData()")}}</li> +</ul> + +<h3 id="생성자는_new_연산자를_필요로_함">생성자는 <code>new</code> 연산자를 필요로 함</h3> + +<p><code>SharedArrayBuffer</code> 생성자는 생성될 때, {{jsxref("Operators/new", "new")}} 연산자를 필요로 합니다. <code>SharedArrayBuffer</code> 생성자를 new 없이 함수로써 호출하면, {{jsxref("TypeError")}} 를 일으킬 것 입니다.</p> + +<pre class="brush: js example-bad">var sab = SharedArrayBuffer(1024); +// TypeError: calling a builtin SharedArrayBuffer constructor +// without new is forbidden</pre> + +<pre class="brush: js example-good">var sab = new SharedArrayBuffer(1024);</pre> + +<h2 id="속성">속성</h2> + +<dl> + <dt><code>SharedArrayBuffer.length</code></dt> + <dd>값이 1인 <code>SharedArrayBuffer</code> 생성자의 length 속성입니다.</dd> + <dt>{{jsxref("SharedArrayBuffer.prototype")}}</dt> + <dd>모든 <code>SharedArrayBuffer</code> 객체에 프로퍼티 추가를 가능하게 해줍니다.</dd> +</dl> + +<h2 id="SharedArrayBuffer_prototype_객체"><code>SharedArrayBuffer</code> prototype 객체</h2> + +<p>모든 <code>SharedArrayBuffer</code> 인스턴스는 {{jsxref("SharedArrayBuffer.prototype")}} 를 상속합니다.</p> + +<h3 id="속성_2">속성</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/prototype','Properties')}}</p> + +<h3 id="메소드">메소드</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/prototype','Methods')}}</p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">코멘트</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-sharedarraybuffer-objects', 'SharedArrayBuffer')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>ES2017 에서 초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ES8', '#sec-sharedarraybuffer-objects', 'SharedArrayBuffer')}}</td> + <td>{{Spec2('ES8')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.SharedArrayBuffer")}}</p> + +<h2 id="함께_보기">함께 보기</h2> + +<ul> + <li>{{jsxref("Atomics")}}</li> + <li>{{jsxref("ArrayBuffer")}}</li> + <li><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Typed_arrays">JavaScript 형식화 배열</a></li> + <li><a href="https://developer.mozilla.org/ko/docs/Web/API/Web_Workers_API">Web Workers</a></li> + <li><a href="https://github.com/lars-t-hansen/parlib-simple">parlib-simple </a>– 동기화 및 작업 분리 추상화를 제공하는 간단한 라이브러리.</li> + <li><a href="https://github.com/tc39/ecmascript_sharedmem/blob/master/TUTORIAL.md">Shared Memory – 간단한 튜토리얼</a></li> + <li> + <p><a href="https://hacks.mozilla.org/2016/05/a-taste-of-javascripts-new-parallel-primitives/">A Taste of JavaScript’s New Parallel Primitives – Mozilla Hacks</a></p> + </li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/sharedarraybuffer/prototype/index.html b/files/ko/web/javascript/reference/global_objects/sharedarraybuffer/prototype/index.html new file mode 100644 index 0000000000..3499bc77ed --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/sharedarraybuffer/prototype/index.html @@ -0,0 +1,65 @@ +--- +title: SharedArrayBuffer.prototype +slug: Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/prototype +tags: + - JavaScript + - SharedArrayBuffer + - TypedArrays + - 공유 메모리 + - 속성 +translation_of: Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer +--- +<div>{{JSRef}}</div> + +<p><strong><code>SharedArrayBuffer.prototype</code></strong> 속성은 {{jsxref("SharedArrayBuffer")}} 객체를위한 프로토타입을 나타냅니다.</p> + +<div>{{js_property_attributes(0,0,0)}}</div> + +<h2 id="설명">설명</h2> + +<p><code>SharedArrayBuffer</code> 인스턴스는 <code>SharedArrayBuffer.prototype</code> 을 상속합니다. 모든 생성자와 마찬가지로, 생성자의 프로토타입 객체를 변경하여 모든 <code>SharedArrayBuffer</code> 인스턴스에 변화를 줄 수 있습니다.</p> + +<h2 id="속성">속성</h2> + +<dl> + <dt>SharedArrayBuffer.prototype.constructor</dt> + <dd>객체의 프로토타입을 생성하는 함수를 지정합니다. 초기 값은 <code>SharedArrayBuffer</code> 생성자에 내장된 표준입니다.</dd> + <dt>{{jsxref("SharedArrayBuffer.prototype.byteLength")}} {{readonlyInline}}</dt> + <dd>배열의 바이트 크기입니다. 배열이 생성되고 수정이 불가할 때 지정됩니다. <strong>읽기 전용입니다.</strong></dd> +</dl> + +<h2 id="메소드">메소드</h2> + +<dl> + <dt>{{jsxref("SharedArrayBuffer.slice", "SharedArrayBuffer.prototype.slice(begin, end)")}}</dt> + <dd><code>begin</code> 부터 <code>end</code> 까지의 모든 것을 포함하는 <code>SharedArrayBuffer</code> 바이트의 복사본을 컨텐츠로 갖는 새로운 <code>SharedArrayBuffer</code> 를 반환합니다. <code>begin</code> 또는 <code>end</code> 가 음수인 경우, 인덱스는 배열의 끝에서부터이고 반대인 경우 시작부터입니다.</dd> +</dl> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">코멘트</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-sharedarraybuffer.prototype', 'SharedArrayBuffer.prototype')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>ES2017 에서 초기 정의.</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.SharedArrayBuffer.prototype")}}</p> + +<h2 id="함께_보기">함께 보기</h2> + +<ul> + <li>{{jsxref("SharedArrayBuffer")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/charat/index.html b/files/ko/web/javascript/reference/global_objects/string/charat/index.html new file mode 100644 index 0000000000..a5a68c03be --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/charat/index.html @@ -0,0 +1,260 @@ +--- +title: String.prototype.charAt() +slug: Web/JavaScript/Reference/Global_Objects/String/charAt +tags: + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/charAt +--- +<div>{{JSRef}}</div> + +<p><strong>charAt() </strong>함수는 문자열에서 특정 인덱스에 위치하는 유니코드 단일문자를 반환합니다. </p> + +<div>{{EmbedInteractiveExample("pages/js/string-charat.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>str</var>.charAt(<var>index</var>)</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<ul> + <li>0과 문자열의 길이 - 1 사이의 정수값. </li> + <li>인자를 생략하면 기본값으로 0를 설정되고 첫 문자를 반환한다. </li> +</ul> + +<dl> + <dt><code>index</code></dt> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<ul> + <li>지정된 인덱스에 해당하는 유니코드 단일문자를 반환한다.</li> + <li>만약 인덱스가 문자열 길이보다 큰 경우 빈 문자열 (예) " " 을 반환한다. </li> +</ul> + +<h2 id="설명">설명</h2> + +<p>문자열 내의 문자는 왼쪽에서 오른쪽으로 순번(인덱스)이 매겨집니다. 첫 번째 문자의 순번은 0, 그리고 <code>stringName</code> 이라는 이름을 가진 문자열의 마지막 문자 순번은 <code>stringName.length - 1 </code>입니다. <code>index</code>가 문자열 길이를 벗어나면 빈 문자열을 반환하게 됩니다.</p> + +<p><code>index</code>를 제공하지 않으면 기본값은 0입니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="문자열_내의_다른_위치에_있는_문자들을_출력하기">문자열 내의 다른 위치에 있는 문자들을 출력하기</h3> + +<p>아래 예제는 문자열 <code>"Brave new world"</code>의 다른 위치에 있는 문자들을 출력합니다.</p> + +<pre class="brush: js">var anyString = 'Brave new world'; +console.log("The character at index 0 is '" + anyString.charAt() + "'"); +// No index was provided, used 0 as default + +console.log("The character at index 0 is '" + anyString.charAt(0) + "'"); +console.log("The character at index 1 is '" + anyString.charAt(1) + "'"); +console.log("The character at index 2 is '" + anyString.charAt(2) + "'"); +console.log("The character at index 3 is '" + anyString.charAt(3) + "'"); +console.log("The character at index 4 is '" + anyString.charAt(4) + "'"); +console.log("The character at index 999 is '" + anyString.charAt(999) + "'"); +</pre> + +<p>프로그램의 실행 결과는 아래와 같습니다.</p> + +<pre class="brush: js">The character at index 0 is 'B' +The character at index 1 is 'r' +The character at index 2 is 'a' +The character at index 3 is 'v' +The character at index 4 is 'e' +The character at index 999 is '' +</pre> + +<h3 id="문자열_내의_모든_문자_얻기">문자열 내의 모든 문자 얻기</h3> + +<p>아래 예제는 문자열 전체를 순회하며 각 문자가 완전한지 확인하는 프로그램입니다. 심지어 <a href="https://ko.wikipedia.org/wiki/%EC%9C%A0%EB%8B%88%EC%BD%94%EB%93%9C_%ED%8F%89%EB%A9%B4">기본 다국어 평면(Basic Multilingual Plane)</a>에 포함되지 않은 문자들이 포함되어 있다고 하더라도 잘 동작합니다. </p> + +<pre class="brush: js">var str = 'A \uD87E\uDC04 Z'; // 기본 다국어 평면에 포함되지 않는 문자를 사용합니다. +for (var i = 0, chr; i < str.length; i++) { + if ((chr = getWholeChar(str, i)) === false) { + continue; + } + // Adapt this line at the top of each loop, passing in the whole string and + // the current iteration and returning a variable to represent the + // individual character + + console.log(chr); +} + +function getWholeChar(str, i) { + var code = str.charCodeAt(i); + + if (Number.isNaN(code)) { + return ''; // Position not found + } + if (code < 0xD800 || code > 0xDFFF) { + return str.charAt(i); + } + + // High surrogate (could change last hex to 0xDB7F to treat high private + // surrogates as single characters) + if (0xD800 <= code && code <= 0xDBFF) { + if (str.length <= (i + 1)) { + throw 'High surrogate without following low surrogate'; + } + var next = str.charCodeAt(i + 1); + if (0xDC00 > next || next > 0xDFFF) { + throw 'High surrogate without following low surrogate'; + } + return str.charAt(i) + str.charAt(i + 1); + } + // Low surrogate (0xDC00 <= code && code <= 0xDFFF) + if (i === 0) { + throw 'Low surrogate without preceding high surrogate'; + } + var prev = str.charCodeAt(i - 1); + + // (could change last hex to 0xDB7F to treat high private + // surrogates as single characters) + if (0xD800 > prev || prev > 0xDBFF) { + throw 'Low surrogate without preceding high surrogate'; + } + // We can pass over low surrogates now as the second component + // in a pair which we have already processed + return false; +} +</pre> + +<p><a href="/ko/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">비구조화 할당</a>을 허용하는 ECMAScript 2016 환경에서는 아래 예제 코드가 더 간결하고, 문자가 <a href="https://ko.wikipedia.org/wiki/UTF-16">서러게이트 페어</a>가 되는 것을 허용할 때는 증가해야 하는 변수를 자동적으로 증가하기에 위의 코드보다 다소 더 유연합니다.</p> + +<pre class="brush: js">var str = 'A\uD87E\uDC04Z'; // We could also use a non-BMP character directly +for (var i = 0, chr; i < str.length; i++) { + [chr, i] = getWholeCharAndI(str, i); + // Adapt this line at the top of each loop, passing in the whole string and + // the current iteration and returning an array with the individual character + // and 'i' value (only changed if a surrogate pair) + + console.log(chr); +} + +function getWholeCharAndI(str, i) { + var code = str.charCodeAt(i); + + if (Number.isNaN(code)) { + return ''; // Position not found + } + if (code < 0xD800 || code > 0xDFFF) { + return [str.charAt(i), i]; // Normal character, keeping 'i' the same + } + + // High surrogate (could change last hex to 0xDB7F to treat high private + // surrogates as single characters) + if (0xD800 <= code && code <= 0xDBFF) { + if (str.length <= (i + 1)) { + throw 'High surrogate without following low surrogate'; + } + var next = str.charCodeAt(i + 1); + if (0xDC00 > next || next > 0xDFFF) { + throw 'High surrogate without following low surrogate'; + } + return [str.charAt(i) + str.charAt(i + 1), i + 1]; + } + // Low surrogate (0xDC00 <= code && code <= 0xDFFF) + if (i === 0) { + throw 'Low surrogate without preceding high surrogate'; + } + var prev = str.charCodeAt(i - 1); + + // (could change last hex to 0xDB7F to treat high private surrogates + // as single characters) + if (0xD800 > prev || prev > 0xDBFF) { + throw 'Low surrogate without preceding high surrogate'; + } + // Return the next character instead (and increment) + return [str.charAt(i + 1), i + 1]; +} +</pre> + +<h3 id="기본다국어평면(Basic-Multilingual-Plane)이_아닌_문자들을_지원하도록_charAt()_수정하기">기본다국어평면(Basic-Multilingual-Plane)이 아닌 문자들을 지원하도록 <code>charAt()</code> 수정하기</h3> + +<p>어떠한 non-BMP 문자들이 나타났는지 호출자가 알 필요가 없기 때문에 non-BMP 문자들을 지원하도록 하는데는 앞의 예제들이 더 자주 사용되지만, 인덱스로 문자를 선택하는데 있어서 문자열 내에 서로게이트 페어들이 하나의 문자들로 처리되길 원한다면, 아래 예제 코드를 사용하면 됩니다.</p> + +<pre class="brush: js">function fixedCharAt(str, idx) { + var ret = ''; + str += ''; + var end = str.length; + + var surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; + while ((surrogatePairs.exec(str)) != null) { + var li = surrogatePairs.lastIndex; + if (li - 2 < idx) { + idx++; + } else { + break; + } + } + + if (idx >= end || idx < 0) { + return ''; + } + + ret += str.charAt(idx); + + if (/[\uD800-\uDBFF]/.test(ret) && /[\uDC00-\uDFFF]/.test(str.charAt(idx + 1))) { + // Go one further, since one of the "characters" is part of a surrogate pair + ret += str.charAt(idx + 1); + } + return ret; +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.4', 'String.prototype.charAt')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.charat', 'String.prototype.charAt')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.charat', 'String.prototype.charAt')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.String.charAt")}}</p> + +<h2 id="관련문서">관련문서</h2> + +<ul> + <li>{{jsxref("String.prototype.indexOf()")}}</li> + <li>{{jsxref("String.prototype.lastIndexOf()")}}</li> + <li>{{jsxref("String.prototype.charCodeAt()")}}</li> + <li>{{jsxref("String.prototype.codePointAt()")}}</li> + <li>{{jsxref("String.prototype.split()")}}</li> + <li>{{jsxref("String.fromCodePoint()")}}</li> + <li><a href="https://mathiasbynens.be/notes/javascript-unicode">JavaScript has a Unicode problem – Mathias Bynens</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/charcodeat/index.html b/files/ko/web/javascript/reference/global_objects/string/charcodeat/index.html new file mode 100644 index 0000000000..9777130911 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/charcodeat/index.html @@ -0,0 +1,169 @@ +--- +title: String.prototype.charCodeAt() +slug: Web/JavaScript/Reference/Global_Objects/String/charCodeAt +tags: + - JavaScript + - Method + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/charCodeAt +--- +<div>{{JSRef}}</div> + +<p><strong><code>charCodeAt()</code></strong> 메서드는 주어진 인덱스에 대한 UTF-16 코드를 나타내는 0부터 65535 사이의 정수를 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/string-charcodeat.html")}}</div> + + + +<p>전체 코드 값을 원하신다면 {{jsxref("String.prototype.codePointAt()")}}을 사용하세요.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>str</var>.charCodeAt(<var>index</var>)</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>index</code></dt> + <dd>0 이상이고 문자열의 길이보다 작은 정수. 숫자가 아니라면 0을 기본값으로 사용함. </dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 인덱스 대한 문자에 대한 UTF-16 코드를 나타내는 숫자<br> + 범위 밖으로 넘어갔을 경우 {{jsxref("Global_Objects/NaN", "NaN")}}</p> + +<h2 id="설명">설명</h2> + +<p>Unicode code points range from 0 to 1114111 (0x10FFFF). The first 128 Unicode code points are a direct match of the ASCII character encoding. For information on Unicode, see the <a href="/en-US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#Unicode">JavaScript Guide</a>.</p> + +<p>Note that <code>charCodeAt()</code> will always return a value that is less than 65536. This is because the higher code points are represented by a pair of (lower valued) "surrogate" pseudo-characters which are used to comprise the real character. Because of this, in order to examine or reproduce the full character for individual characters of value 65536 and above, for such characters, it is necessary to retrieve not only <code>charCodeAt(i)</code>, but also <code>charCodeAt(i+1)</code> (as if examining/reproducing a string with two letters), or to use codePointAt(i) instead. See example 2 and 3 below.</p> + +<p><code>charCodeAt()</code> returns {{jsxref("Global_Objects/NaN", "NaN")}} if the given index is less than 0 or is equal to or greater than the length of the string.</p> + +<p>Backward compatibilty: In historic versions (like JavaScript 1.2) the <code>charCodeAt()</code> method returns a number indicating the ISO-Latin-1 codeset value of the character at the given index. The ISO-Latin-1 codeset ranges from 0 to 255. The first 0 to 127 are a direct match of the ASCII character set.</p> + +<h2 id="예제">예제</h2> + +<h3 id="Using_charCodeAt()">Using <code>charCodeAt()</code></h3> + +<p>The following example returns 65, the Unicode value for A.</p> + +<pre class="brush: js">'ABC'.charCodeAt(0); // returns 65 +</pre> + +<h3 id="Fixing_charCodeAt()_to_handle_non-Basic-Multilingual-Plane_characters_if_their_presence_earlier_in_the_string_is_unknown">Fixing <code>charCodeAt()</code> to handle non-Basic-Multilingual-Plane characters if their presence earlier in the string is unknown</h3> + +<p>This version might be used in for loops and the like when it is unknown whether non-BMP characters exist before the specified index position.</p> + +<pre class="brush: js">function fixedCharCodeAt(str, idx) { + // ex. fixedCharCodeAt('\uD800\uDC00', 0); // 65536 + // ex. fixedCharCodeAt('\uD800\uDC00', 1); // false + idx = idx || 0; + var code = str.charCodeAt(idx); + var hi, low; + + // High surrogate (could change last hex to 0xDB7F to treat high + // private surrogates as single characters) + if (0xD800 <= code && code <= 0xDBFF) { + hi = code; + low = str.charCodeAt(idx + 1); + if (isNaN(low)) { + throw 'High surrogate not followed by low surrogate in fixedCharCodeAt()'; + } + return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000; + } + if (0xDC00 <= code && code <= 0xDFFF) { // Low surrogate + // We return false to allow loops to skip this iteration since should have + // already handled high surrogate above in the previous iteration + return false; + /*hi = str.charCodeAt(idx - 1); + low = code; + return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;*/ + } + return code; +} +</pre> + +<h3 id="Fixing_charCodeAt()_to_handle_non-Basic-Multilingual-Plane_characters_if_their_presence_earlier_in_the_string_is_known">Fixing <code>charCodeAt()</code> to handle non-Basic-Multilingual-Plane characters if their presence earlier in the string is known</h3> + +<pre class="brush: js">function knownCharCodeAt(str, idx) { + str += ''; + var code, + end = str.length; + + var surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; + while ((surrogatePairs.exec(str)) != null) { + var li = surrogatePairs.lastIndex; + if (li - 2 < idx) { + idx++; + } + else { + break; + } + } + + if (idx >= end || idx < 0) { + return NaN; + } + + code = str.charCodeAt(idx); + + var hi, low; + if (0xD800 <= code && code <= 0xDBFF) { + hi = code; + low = str.charCodeAt(idx + 1); + // Go one further, since one of the "characters" is part of a surrogate pair + return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000; + } + return code; +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.5', 'String.prototype.charCodeAt')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.charcodeat', 'String.prototype.charCodeAt')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.charcodeat', 'String.prototype.charCodeAt')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</div> + +<p>{{Compat("javascript.builtins.String.charCodeAt")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("String.fromCharCode()")}}</li> + <li>{{jsxref("String.prototype.charAt()")}}</li> + <li>{{jsxref("String.fromCodePoint()")}}</li> + <li>{{jsxref("String.prototype.codePointAt()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/concat/index.html b/files/ko/web/javascript/reference/global_objects/string/concat/index.html new file mode 100644 index 0000000000..1d5b4f2cd6 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/concat/index.html @@ -0,0 +1,105 @@ +--- +title: String.prototype.concat() +slug: Web/JavaScript/Reference/Global_Objects/String/concat +tags: + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/concat +--- +<div>{{JSRef}}</div> + +<p><strong><code>concat()</code></strong> 메서드는 매개변수로 전달된 모든 문자열을 호출 문자열에 붙인 새로운 문자열을 반환합니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/string-concat.html")}}</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>str</var>.concat(<var>string2</var>, <var>string3</var>[, ..., <var>stringN</var>])</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>string2...string<em>N</em></code></dt> + <dd>합칠 문자열.</dd> +</dl> + +<h3 id="반환값">반환값</h3> + +<p>주어진 문자열을 모두 붙인 새로운 문자열.</p> + +<h2 id="설명">설명</h2> + +<p><code>concat()</code> 함수는 호출 문자열에 문자열 인수를 이어 붙인 결과를 반환합니다. 원본 문자열과 결과 문자열의 변형은 서로에게 영향을 미치지 않습니다. 인수가 문자열이 아니면 계산 전에 문자열로 변환합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="concat_사용하기"><code>concat()</code> 사용하기</h3> + +<p>아래 예제에서는 문자열을 결합하여 새로운 문자열을 만듭니다.</p> + +<pre><code>var hello = 'Hello, '; +console.log(hello.concat('Kevin', '. Have a nice day.')); +/* Hello, Kevin. Have a nice day. */ + +var greetList = ['Hello', ' ', 'Venkat', '!']; +"".concat(...greetList); // "Hello Venkat!" + +"".concat({}); // [object Object] +"".concat([]); // "" +"".concat(null); // "null" +"".concat(true); // "true" +"".concat(4, 5); // "45"</code></pre> + +<h2 id="성능">성능</h2> + +<p><code>concat()</code> 메서드보다 {{jsxref("Operators/Assignment_Operators", "할당 연산자", "", 1)}} (<code>+</code>, <code>+=</code>)를 사용하는게 더 좋습니다. <a href="https://web.archive.org/web/20170404182053/https://jsperf.com/concat-vs-plus-vs-join">성능 테스트</a> 결과에 따르면 할당 연산자의 속도가 몇 배 빠릅니다.</p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.6', 'String.prototype.concat')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.concat', 'String.prototype.concat')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.concat', 'String.prototype.concat')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.String.concat")}}</p> + +<div></div> + +<div id="compat-mobile"></div> + +<h2 id="관련문서">관련문서</h2> + +<ul> + <li>{{jsxref("Array.prototype.concat()")}}</li> + <li>{{jsxref("Operators/Assignment_Operators", "Assignment operators", "", 1)}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/endswith/index.html b/files/ko/web/javascript/reference/global_objects/string/endswith/index.html new file mode 100644 index 0000000000..d78645e9f3 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/endswith/index.html @@ -0,0 +1,142 @@ +--- +title: String.prototype.endsWith() +slug: Web/JavaScript/Reference/Global_Objects/String/endsWith +translation_of: Web/JavaScript/Reference/Global_Objects/String/endsWith +--- +<div>{{JSRef}}</div> + +<p>The <strong><code>endsWith()</code></strong> 메서드를 사용하여 어떤 문자열에서 특정 문자열로 끝나는지를 확인할 수 있으며, 그 결과를 <code>true</code> 혹은 <code>false</code>로 반환한다. </p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox"><var>str</var>.endsWith(<var>searchString</var>[, <var>length</var>])</pre> + +<h3 id="파라미터들">파라미터들</h3> + +<dl> + <dt><code>searchString</code></dt> + <dd>이 문자열의 끝이 특정 문자열로 끝나는지를 찾기 원하는 문자열입니다.</dd> + <dt><code>length</code></dt> + <dd>옵션입니다. 찾고자 하는 문자열의 길이값이며, 기본값은 문자열 전체 길이입니다. 문자열의 길이값은 문자열 전체 길이 안에서만 존재하여야 합니다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>문자열의 끝이 주어진 문자열로 끝나면 <strong><code>true</code></strong>, 그렇지 않다면 <strong><code>false</code></strong></p> + +<h2 id="설명">설명</h2> + +<p>여러분은 이 메서드를 사용하여 어떤 문자열이 특정 문자열로 끝나는지를 확인할 수 있습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="endsWith_사용하기"><code>endsWith()</code> 사용하기</h3> + +<pre class="brush: js">var str = 'To be, or not to be, that is the question.'; + +console.log(str.endsWith('question.')); // true +console.log(str.endsWith('to be')); // false +console.log(str.endsWith('to be', 19)); // true +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>이 메서드는 ECMAScript 6 규격에 포함되었습니다만 아직까지는 모든 JavaScrpt가 이 기능을 지원하고 있지는 않습니다. 하지만 여러분은 <code>String.prototype.endsWith()</code> 메서드를 다음과 같이 쉽게 <a href="https://en.wikipedia.org/wiki/Polyfill">polyfill</a> 할 수 있습니다:</p> + +<pre class="brush: js">if (!String.prototype.endsWith) { + String.prototype.endsWith = function(searchString, position) { + var subjectString = this.toString(); + if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) { + position = subjectString.length; + } + position -= searchString.length; + var lastIndex = subjectString.indexOf(searchString, position); + return lastIndex !== -1 && lastIndex === position; + }; +} +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.endswith', 'String.prototype.endsWith')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.endswith', 'String.prototype.endsWith')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Edge</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("41")}}</td> + <td>{{CompatGeckoDesktop("17")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatSafari("9")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome("36")}}</td> + <td>{{CompatGeckoMobile("17")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="관련문서">관련문서</h2> + +<ul> + <li>{{jsxref("String.prototype.startsWith()")}}</li> + <li>{{jsxref("String.prototype.includes()")}}</li> + <li>{{jsxref("String.prototype.indexOf()")}}</li> + <li>{{jsxref("String.prototype.lastIndexOf()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/fromcharcode/index.html b/files/ko/web/javascript/reference/global_objects/string/fromcharcode/index.html new file mode 100644 index 0000000000..98b1627666 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/fromcharcode/index.html @@ -0,0 +1,101 @@ +--- +title: String.fromCharCode() +slug: Web/JavaScript/Reference/Global_Objects/String/fromCharCode +tags: + - JavaScript + - Method + - Reference + - String + - Unicode +translation_of: Web/JavaScript/Reference/Global_Objects/String/fromCharCode +--- +<div>{{JSRef}}</div> + +<p><strong><code>String.fromCharCode()</code></strong> 메서드는 UTF-16 코드 유닛의 시퀀스로부터 문자열을 생성해 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/string-fromcharcode.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code>String.fromCharCode(<var>num1</var>[, ...[, <var>numN</var>]])</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>num1, ..., num<em>N</em></code></dt> + <dd>UTF-16 코드 유닛인 숫자 뭉치. 가능한 값의 범위는 0부터 65535(0xFFFF)까지입니다. 0xFFFF를 초과하는 값은 잘립니다. 유효성 검사는 하지 않습니다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 UTF-16 코드 유닛 N개로 이루어진 문자열.</p> + +<h2 id="설명">설명</h2> + +<p>이 메서드는 {{jsxref("String")}} 객체가 아닌 문자열을 반환합니다.</p> + +<p><code>fromCharCode()</code>는 {{jsxref("String")}}의 정적 메서드이기 때문에 <code>String.fromCharCode()</code>로 사용해야 합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="fromCharCode()_사용하기"><code>fromCharCode()</code> 사용하기</h3> + +<p>다음 예제는 문자열 <code>"ABC"</code>를 반환합니다..</p> + +<pre class="brush: js">String.fromCharCode(65, 66, 67); // "ABC" +String.fromCharCode(0x2014) // "—" +String.fromCharCode(0x12014) // 숫자 '1'은 무시해서 "—" +</pre> + +<h2 id="더_큰_값과_사용하기">더 큰 값과 사용하기</h2> + +<p>초기 JavaScript 표준화 과정에서 예상했던 것처럼, 대부분의 흔한 유니코드 값을 16비트 숫자로 표현할 수 있고, <code>fromCharCode()</code>가 많은 흔한 값에서 하나의 문자를 반환할 수 있지만, <strong>모든</strong> 유효한 유니코드 값(최대 21비트)을 처리하려면 <code>fromCharCode()</code>만으로는 부족합니다. 높은 코드 포인트의 문자는 써로게이트<sup>surrogate</sup> 값 두 개를 합쳐 하나의 문자를 표현하므로,{{jsxref("String.fromCodePoint()")}}(ES2015 표준) 메서드는 그러한 쌍을 높은 값의 문자로 변환할 수 있습니다.</p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.3.2', 'StringfromCharCode')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.fromcharcodes', 'String.fromCharCode')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.fromcharcodes', 'String.fromCharCode')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.String.fromCharCode")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("String.fromCodePoint()")}}</li> + <li>{{jsxref("String.prototype.charAt()")}}</li> + <li>{{jsxref("String.prototype.charCodeAt()")}}</li> + <li>{{jsxref("String.prototype.codePointAt()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/includes/index.html b/files/ko/web/javascript/reference/global_objects/string/includes/index.html new file mode 100644 index 0000000000..a3eb79ad16 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/includes/index.html @@ -0,0 +1,125 @@ +--- +title: String.prototype.includes() +slug: Web/JavaScript/Reference/Global_Objects/String/includes +tags: + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/includes +--- +<div>{{JSRef}}</div> + +<p><strong><code>includes()</code></strong> 메서드는 하나의 문자열이 다른 문자열에 포함되어 있는지를 판별하고, 결과를 <code>true</code> 또는 <code>false</code> 로 반환합니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/string-includes.html")}}</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>str</var>.includes(<var>searchString</var>[, <var>position</var>])</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>searchString</code></dt> + <dd>이 문자열에서 찾을 다른 문자열.</dd> + <dt><code>position</code> {{optional_inline}}</dt> + <dd><code>searchString</code>을 찾기 시작할 위치. 기본값 0.</dd> +</dl> + +<h3 id="반환값">반환값</h3> + +<p>문자열을 찾아내면 <code>true</code>. 실패하면 <code>false</code>.</p> + +<h2 id="설명">설명</h2> + +<p><code>includes()</code> 메서드를 사용해 문자열 내에 찾고자 하는 다른 문자열이 있는지 확인할 수 있습니다.</p> + +<h3 id="대소문자_구분">대소문자 구분</h3> + +<p><code>includes()</code> 메서드는 대소문자를 구별합니다. 예를 들어 아래 코드는 <code>false</code>를 반환합니다.</p> + +<pre class="brush: js">'Blue Whale'.includes('blue'); // returns false +</pre> + +<h2 id="예제">예제</h2> + +<h3 id="includes()_사용하기"><code>includes()</code> 사용하기</h3> + +<pre class="brush: js">var str = 'To be, or not to be, that is the question.'; + +console.log(str.includes('To be')); // true +console.log(str.includes('question')); // true +console.log(str.includes('nonexistent')); // false +console.log(str.includes('To be', 1)); // false +console.log(str.includes('TO BE')); // false +</pre> + +<h2 id="폴리필">폴리필</h2> + +<p>이 메서드는 ECMAScript 6 규격에 포함되었습니다만 아직까지는 모든 JavaScrpt가 이 기능을 지원하고 있지는 않습니다. 하지만 여러분은 이 메서드를 다음과 같이 쉽게 <a href="https://en.wikipedia.org/wiki/Polyfill">polyfill</a> 할 수 있습니다.</p> + +<pre class="brush: js">if (!String.prototype.includes) { + String.prototype.includes = function(search, start) { + 'use strict'; + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > this.length) { + return false; + } else { + return this.indexOf(search, start) !== -1; + } + }; +} + +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.includes', 'String.prototype.includes')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.includes', 'String.prototype.includes')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.String.includes")}}</div> + +<h2 id="String.prototype.contains">String.prototype.contains</h2> + +<p>Firefox 18 - 39에서, <code>include()</code> 메서드의 이름은 <code>contains()</code>이었습니다. contains() 함수는 아래와 같은 이유로 {{bug(1102219)}}에서 <code>includes()</code>로 변경되었습니다:</p> + +<p>It's been <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=789036">reported</a> that some websites using MooTools 1.2 broke on Firefox 17. This version of MooTools checks whether <code>String.prototype.contains()</code> exists and, if it doesn't, MooTools adds its own function. With the introduction of this function in Firefox 17, the behavior of that check changed in a way that causes code based on MooTools' <code>String.prototype.contains()</code> implementation to break. As a result, the implementation was <a href="https://hg.mozilla.org/releases/mozilla-aurora/rev/086db97198a8">disabled</a> in Firefox 17 and <code>String.prototype.contains()</code> was available one version later, in Firefox 18, when <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=789036#c32">outreach to MooTools </a>was leading to the <a href="http://mootools.net/blog/2013/02/19/mootools-1-2-6-released">release of MooTools version 1.2.6</a>.</p> + +<p>MooTools 1.3 forces its own version of <code>String.prototype.contains()</code>, so websites relying on it should not break. However, you should note that <a href="http://mootools.net/core/docs/1.3.2/Types/String#String-method:-contains">MooTools 1.3 signature</a> and ECMAScript 6 signatures for this method differ (on the second argument). Later, <a href="https://github.com/mootools/mootools-core/blob/master/Docs/Types/String.md#note">MooTools 1.5+ changed the signature to match the ES6 standard.</a></p> + +<p>Firefox 48에서, <code>String.prototype.contains()</code>은 제거되었습니다. 오직 <code>String.prototype.includes()</code>만 사용할 수 있습니다.</p> + +<h2 id="관련문서">관련문서</h2> + +<ul> + <li>{{jsxref("Array.prototype.includes()")}} {{experimental_inline}}</li> + <li>{{jsxref("TypedArray.prototype.includes()")}} {{experimental_inline}}</li> + <li>{{jsxref("String.prototype.indexOf()")}}</li> + <li>{{jsxref("String.prototype.lastIndexOf()")}}</li> + <li>{{jsxref("String.prototype.startsWith()")}}</li> + <li>{{jsxref("String.prototype.endsWith()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/index.html b/files/ko/web/javascript/reference/global_objects/string/index.html new file mode 100644 index 0000000000..68e9b021e5 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/index.html @@ -0,0 +1,298 @@ +--- +title: String +slug: Web/JavaScript/Reference/Global_Objects/String +tags: + - ECMAScript 2015 + - JavaScript + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String +--- +<div>{{JSRef}}</div> + +<p><strong><code>String</code></strong> 전역 객체는 문자열(문자의 나열)의 생성자입니다.</p> + +<h2 id="Syntax" name="Syntax">구문</h2> + +<p>문자열 리터럴은 다음과 같은 형식을 사용합니다.</p> + +<pre class="syntaxbox">'string text' +"string text" +"中文 español Deutsch English देवनागरी العربية português বাংলা русский 日本語 norsk bokmål ਪੰਜਾਬੀ 한국어 தமிழ் עברית"</pre> + +<p>문자열은 <code>String</code> 전역 객체를 직접 사용하여 생성할 수 있습니다.</p> + +<pre class="syntaxbox">String(<em>thing</em>)</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>thing</code></dt> + <dd>문자열로 변환할 아무 값.</dd> + <dt> + <h3 id="템플릿_리터럴">템플릿 리터럴</h3> + </dt> +</dl> + +<p>ECMAScript 2015 이후, 문자열 리터럴은 소위 <a href="/ko/docs/Web/JavaScript/Reference/Template_literals">템플릿 리터럴</a>이 될 수 있습니다.</p> + +<pre class="language-html"><code class="language-html">`hello world` `hello! world!` `hello ${who}` tag `<span class="tag token"><span class="tag token"><span class="punctuation token"><</span>a</span><span class="punctuation token">></span></span>${who}<span class="tag token"><span class="tag token"><span class="punctuation token"></</span>a</span><span class="punctuation token">></span></span>`</code></pre> + +<h3 id="이스케이프_표현">이스케이프 표현</h3> + +<p>일반적인 출력 문자 외의 특수 문자는 이스케이프 표현을 사용해 적을 수 있습니다.</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">코드</th> + <th scope="col">출력</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>\XXX</code></td> + <td>8진수 Latin-1 문자</td> + </tr> + <tr> + <td><code>\'</code></td> + <td>작은따옴표</td> + </tr> + <tr> + <td><code>\"</code></td> + <td>큰따옴표</td> + </tr> + <tr> + <td><code>\\</code></td> + <td>역슬래시</td> + </tr> + <tr> + <td><code>\n</code></td> + <td>개행</td> + </tr> + <tr> + <td><code>\r</code></td> + <td>캐리지 리턴</td> + </tr> + <tr> + <td><code>\v</code></td> + <td>세로 탭</td> + </tr> + <tr> + <td><code>\t</code></td> + <td>탭</td> + </tr> + <tr> + <td><code>\b</code></td> + <td>백 스페이스</td> + </tr> + <tr> + <td><code>\f</code></td> + <td>폼 피드</td> + </tr> + <tr> + <td><code>\uXXXX</code></td> + <td>유니코드 코드포인트</td> + </tr> + <tr> + <td><code>\u{X}</code> ... <code>\u{XXXXXX}</code></td> + <td>유니코드 코드포인트 {{experimental_inline}}</td> + </tr> + <tr> + <td><code>\xXX</code></td> + <td>Latin-1 문자</td> + </tr> + </tbody> +</table> + +<div class="note"> +<p>일부 다른 프로그래밍 언어와 달리, JavaScript는 작은따옴표와 큰따옴표 문자열을 구분하지 않습니다. 따라서 위의 이스케이프 문자는 작은따옴표나 큰따옴표에서 상관 없이 작동합니다.</p> +</div> + +<h3 id="긴_문자열_리터럴">긴 문자열 리터럴</h3> + +<p>작성한 코드가 매우 긴 문자열을 포함해야 하는 경우, 끝 없이 뻗어나가는 한 줄이나 편집기의 재량에 따라 자동으로 줄을 넘기는 대신 직접 여러 줄로 나누되 내용에는 영향을 주지 않고 싶을 때가 있을겁니다. 이런 상황에는 두 가지 방법을 사용할 수 있습니다.</p> + +<p>우선 다음과 같이 <a href="/ko/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#%EB%8D%94%ED%95%98%EA%B8%B0_()">+</a> 연산자를 사용할 수 있습니다.</p> + +<pre class="brush: js"><code>let longString = "여러 줄에 걸쳐 작성해야 할 정도로 " + + "긴 문자열인데 왜 한 줄에 다 적으면 안되냐면 " + + "코드를 읽기 힘들어지니까요.";</code></pre> + +<p>아니면 역슬래시 문자("\")를 각 줄의 맨 끝에 붙여 문자열이 이어진다는걸 표시할 수도 있습니다. 역슬래시 다음에 공백을 포함한 어떤 문자라도 붙으면 제대로 작동하지 않으므로 주의해야 합니다.</p> + +<pre class="brush: js"><code>let longString = "여러 줄에 걸쳐 작성해야 할 정도로 \ +긴 문자열인데 왜 한 줄에 다 적으면 안되냐면 \ +코드를 읽기 힘들어지니까요.";</code></pre> + +<p>두 예시 모두 동일한 문자열을 생성합니다.</p> + +<h2 id="Description" name="Description">설명</h2> + +<p>문자열은 텍스트 형태로 표현될 수있는 데이터를 보관하는 데 유용합니다. 문자열에서 가장 많이 사용되는 작업들은 문자열의 길이를 확인하는 ({{jsxref("String.length", "length")}}), 문자열을 생성하고 연결하는 <a href="/ko/docs/Web/JavaScript/Reference/Operators/String_Operators" title="JavaScript/Reference/Operators/String_Operators">+ 와 += 문자열 연산자</a>, 서브문자열(substring)이 있는지 확인하고, 있으면 위치를 확인하는 {{jsxref("String.prototype.indexOf()", "indexOf()")}} 메서드, 서브문자열(substring)을 추출해내는 {{jsxref("String.prototype.substring()", "substring()")}} 메서드가 있습니다.</p> + +<h3 id="문자_접근">문자 접근</h3> + +<p>문자열에서 개개의 문자에 접근할 수 있는 방법은 두가지가 있습니다. 첫번째는 {{jsxref("String.prototype.charAt()", "charAt()")}} 메서드를 이용하는 것입니다:</p> + +<pre class="brush: js">return 'cat'.charAt(1); // returns "a" +</pre> + +<p>다른 방법(ECMAScript 5에서 소개하고 있는)은 문자열을 배열과 같은 오브젝트로 취급하여, 문자에 해당하는 숫자 인덱스를 사용하는 방법입니다 :</p> + +<pre class="brush: js">return 'cat'[1]; // returns "a" +</pre> + +<p>브라켓([ ]) 표기법을 사용하여 문자에 접근하는 경우 , 이러한 프로퍼티들에 새로운 값을 할당하거나 삭제할 수는 없습니다. 포함되어 있는 프로퍼티들은 작성할 수도, 수정할 수도 없습니다. (더 자세한 정보는 {{jsxref("Object.defineProperty()")}}를 참고 바랍니다 .)</p> + +<h3 id="Comparing_strings" name="Comparing_strings">문자열 비교</h3> + +<p>C 개발자는 문자열 비교를 위하여 <code><span style="font-family: courier new,andale mono,monospace;">strcmp()</span></code> 함수를 사용합니다. JavaScript에서는 단지 <a href="/ko/docs/Web/JavaScript/Reference/Operators/Comparison_Operators" style="line-height: inherit;" title="JavaScript/Reference/Operators/Comparison_Operators">less-than와 greater-than 연산자</a>만을 사용하여 문자열을 비교할 수 있습니다<span style="line-height: inherit;"> </span><span style="line-height: inherit;">:</span></p> + +<pre class="brush: js">var a = "a"; +var b = "b"; +if (a < b) { // true + console.log(a + " is less than " + b); +} else if (a > b) { + console.log(a + " is greater than " + b); +} else { + console.log(a + " and " + b + " are equal."); +} +</pre> + +<p>비슷한 결과를 얻을 수 있는 방법으로 <span style="font-family: courier new,andale mono,monospace;">String</span> 인스턴스에서 상속된 {{jsxref("String.prototype.localeCompare()", "localeCompare()")}} 메서드를 사용할 수 있습니다.</p> + +<h3 id="문자열_원형과_String_객체의_차이">문자열 원형과 <code>String</code> 객체의 차이</h3> + +<div>JavaScript는 <code>String</code> 오브젝트와 원형의 문자열을 다르게 취급한다는 것에 주의해야 합니다. ({{jsxref("Boolean")}}과 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects" title="JavaScript/Reference/Global_Objects/">숫자</a>의 true도 마찬가지입니다.)</div> + +<div> </div> + +<p>문자열 리터럴(작은 따옴표 또는 큰 따옴표로 생성되는)과 생성자 없이(즉. {{jsxref("Operators/new", "new")}} 키워드를 사용하지 않고) <code>String</code>을 호출하여 반환된 문자열은 원형 문자열(primitive strings)입니다. JavaScript는 자동적으로 원형을 <code>String</code> 오브젝트로 변환하기 때문에, <code>String</code> 오브젝트 메서드를 사용하여 원형문자열을 생성할 수 있습니다. 문맥 안의 메서드에서 프로퍼티 조회 또는 원형의 문자열 호출이 발생하면, JavaScript는 자동으로 문자열 원형을 감싸고 프로퍼티 조회를 수행 하거나 메서드를 호출합니다.</p> + +<pre class="brush: js">var s_prim = "foo"; +var s_obj = new String(s_prim); + +console.log(typeof s_prim); // Logs "string" +console.log(typeof s_obj); // Logs "object" +</pre> + +<p>문자열 원형과 <code>String</code> 오브젝트는 {{jsxref("Global_Objects/eval", "eval()")}}을 사용할 때 다른 결과를 제공합니다. <code>eval</code>에 전달되는 문자열 원형들은 소스 코드 취급을 받습니다; <code>String</code> 오브젝트들은 다른 모든 오브젝트들과 마찬가지로 취급하며, 오브젝트를 반환합니다. 예를 들면:</p> + +<pre class="brush: js">var s1 = '2 + 2'; // creates a string primitive +var s2 = new String('2 + 2'); // creates a String object +console.log(eval(s1)); // returns the number 4 +console.log(eval(s2)); // returns the string "2 + 2" +</pre> + +<p>이러한 이유로, 비록 코드 상에서 원형 문자열을 사용하는 대신에 <code>String</code> 오브젝트를 사용하게 되면 코드가 손상될 수 있지만, 일반적인 개발자는 차이를 걱정할 필요는 없습니다.</p> + +<p><code>String</code><span style="line-height: inherit;"> 오프젝트는 언제든지 </span>{{jsxref("String.prototype.valueOf()", "valueOf()")}} <span style="line-height: inherit;"> 메서드로 원형에 대응하도록 전환할 수 있습니다.</span></p> + +<pre class="brush: js">console.log(eval(s2.valueOf())); // returns the number 4 +</pre> + +<h2 id="Properties" name="Properties">속성</h2> + +<dl> + <dt>{{jsxref("String.prototype")}}</dt> + <dd>String 오브젝트는 프로퍼티의 추가가 가능합니다.</dd> +</dl> + +<h2 id="Methods" name="Methods">메서드</h2> + +<dl> + <dt>{{jsxref("String.fromCharCode()")}}</dt> + <dd>지정된 유니코 값의 순서를 이용하여 만든 문자열을 반환합니다.</dd> + <dt>{{jsxref("String.fromCodePoint()")}} {{experimental_inline}}</dt> + <dd>지정된 코드 포인트 순서를 이용하여 만든 문자열을 반환합니다.</dd> + <dt>{{jsxref("String.raw()")}} {{experimental_inline}}</dt> + <dd>원형 템플릿 문자열(raw template string)에서 생성된 문자열을 반환합니다.</dd> +</dl> + +<h2 id="String_generic_메서드"><code>String</code> generic 메서드</h2> + +<div class="warning"> +<p><strong><code>String</code> generic들은 비표준으로, 가까운 미래에 사라질 것입니다.</strong> 아래에서 제공하고 있는 방식을 사용하지 않으면, 브라우저들간의 호환성은 기대하기 어렵습니다. </p> +</div> + +<p><code>String</code><span style="line-height: inherit;"> 인스턴스 메서드는 JavScript 1.6으로 Firefox에서(ECMAScript 표준에 속하지는 않지만) 어떤 오브젝트라도 String 메서드에 적용하여 String 오브젝트에서 사용가능합니다:</span></p> + +<pre class="brush: js">var num = 15; +console.log(String.replace(num, /5/, '2')); +</pre> + +<p class="brush: js">{{jsxref("Global_Objects/Array", "Generics", "#Array_generic_methods", 1)}}은<span style="line-height: inherit;"> </span>{{jsxref("Global_Objects/Array", "Array")}}<span style="line-height: inherit;"> 메서드에도 사용 가능합니다.</span></p> + +<h2 id="String_instances" name="String_instances"><code>String</code> 인스턴스</h2> + +<h3 id="속성">속성</h3> + +<p>{{ page('ko/docs/JavaScript/Reference/Global_Objects/String/prototype', 'Properties') }}</p> + +<h3 id="메서드">메서드</h3> + +<h4 id="HTML과_관계없는_메서드">HTML과 관계없는 메서드</h4> + +<p>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Methods_unrelated_to_HTML')}}</p> + +<h4 id="HTML_wrapper_methods">HTML wrapper methods</h4> + +<p>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'HTML_wrapper_methods')}}</p> + +<h2 id="예제">예제</h2> + +<h3 id="문자열_변환">문자열 변환</h3> + +<p>비록 일반적으로 toString() 함수를 많이 사용하고 있지만, {{jsxref("String.prototype.toString()", "toString()")}}의 "안전한" 대안으로 String을 사용할 수 있습니다. String은 {{jsxref("Global_Objects/null", "null")}}과 {{jsxref("Global_Objects/undefined", "undefined")}}에 대해서도 잘 동작합니다. 예를 들면: </p> + +<pre class="brush: js">var outputStrings = []; +for (var i = 0, n = inputValues.length; i < n; ++i) { + outputStrings.push(String(inputValues[i])); +} +</pre> + +<h2 id="Browser_Compatibility" name="Browser_Compatibility">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5', 'String')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string-objects', 'String')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string-objects', 'String')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_Compatibility" name="Browser_Compatibility">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.String",2)}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{domxref("DOMString")}}</li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/DOMString/Binary">Binary strings</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/indexof/index.html b/files/ko/web/javascript/reference/global_objects/string/indexof/index.html new file mode 100644 index 0000000000..3e12f74d51 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/indexof/index.html @@ -0,0 +1,159 @@ +--- +title: String.prototype.indexOf() +slug: Web/JavaScript/Reference/Global_Objects/String/indexOf +tags: + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/indexOf +--- +<div>{{JSRef}}</div> + +<p><strong><code>indexOf()</code></strong> 메서드는 호출한 {{jsxref("String")}} 객체에서 주어진 값과 일치하는 첫 번째 인덱스를 반환합니다. 일치하는 값이 없으면 -1을 반환합니다. </p> + +<div>{{EmbedInteractiveExample("pages/js/string-indexof.html")}}</div> + + + +<div class="note"> +<p><strong>참고:</strong> {{jsxref("Array")}}에서는 {{jsxref("Array.prototype.indexOf()")}} 메서드가 같은 역할을 합니다.</p> +</div> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>str</var>.indexOf(<var>searchValue</var>[, <var>fromIndex</var>])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>searchValue</code></dt> + <dd>찾으려는 문자열. 아무 값도 주어지지 않으면 <a href="https://tc39.github.io/ecma262/#sec-tostring">문자열 <code>"undefined"</code>를 찾으려는 문자열로 사용</a>합니다.</dd> + <dt><code>fromIndex</code> {{optional_inline}}</dt> + <dd>문자열에서 찾기 시작하는 위치를 나타내는 인덱스 값입니다. 어떤 정수값이라도 가능합니다. 기본값은 0이며, 문자열 전체를 대상으로 찾게 됩니다. 만약 <code>fromIndex </code>값이 음의 정수이면 전체 문자열을 찾게 됩니다. 만약 <code>fromIndex >= str.length </code>이면, 검색하지 않고 바로 -1을 반환합니다. <code>searchValue</code>가 공백 문자열이 아니라면, <code>str.length</code>를 반환합니다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p><code>searchValue</code>의 첫 번째 등장 인덱스. 찾을 수 없으면 -1.</p> + +<h2 id="설명">설명</h2> + +<p>문자열 내에 있는 문자들은 왼쪽에서 오른쪽 방향으로 순번이 매겨집니다. 제일 처음 문자는 0번째 순번(index)이며, <code>stringName </code>문자열의 마지막 문자의 순번 <code>stringName.length -1</code> 입니다. </p> + +<pre class="brush: js">'Blue Whale'.indexOf('Blue'); // returns 0 +'Blue Whale'.indexOf('Blute'); // returns -1 +'Blue Whale'.indexOf('Whale', 0); // returns 5 +'Blue Whale'.indexOf('Whale', 5); // returns 5 +'Blue Whale'.indexOf('Whale', 7); // returns -1 +'Blue Whale'.indexOf(''); // returns 0 +'Blue Whale'.indexOf('', 9); // returns 9 +'Blue Whale'.indexOf('', 10); // returns 10 +'Blue Whale'.indexOf('', 11); // returns 10</pre> + +<p><code>indexOf()</code> 메서드는 대소문자를 구분합니다. 예를 들면, 아래 예제는 일치하는 문자열이 없으므로 <code>-1</code>을 반환합니다.</p> + +<pre class="brush: js">'Blue Whale'.indexOf('blue'); // returns -1 +</pre> + +<h3 id="존재_여부_확인">존재 여부 확인</h3> + +<p>'0'을 평가했을 때 <code>true</code>가 아니고, -1을 평가했을 때 <code>false</code>가 아닌 것에 주의해야 합니다. 따라서, 임의의 문자열에 특정 문자열이 있는지를 확인하는 올바른 방법은 다음과 같습니다.</p> + +<pre class="brush: js">'Blue Whale'.indexOf('Blue') !== -1; // true +'Blue Whale'.indexOf('Bloe') !== -1; // false +</pre> + +<h2 id="예제">예제</h2> + +<h3 id="indexOf()_사용하기"><code>indexOf()</code> 사용하기</h3> + +<p>아래 예제는 <code>"Brave new world"</code> 문자열의 위치를 확인하기 위해 <code>indexOf()</code>와 {{jsxref("String.prototype.lastIndexOf()", "lastIndexOf()")}} 를 사용하고 있습니다.</p> + +<pre class="brush: js">var anyString = 'Brave new world'; + +console.log('The index of the first w from the beginning is ' + anyString.indexOf('w')); +// 첫번째 w 문자 위치는 8 +console.log('The index of the first w from the end is ' + anyString.lastIndexOf('w')); +// 마지막 w 문자 위치는 10 + +console.log('The index of "new" from the beginning is ' + anyString.indexOf('new')); +// 첫번째 new 문자열 위치는 6 +console.log('The index of "new" from the end is ' + anyString.lastIndexOf('new')); +// 마지막 new 문자열 위치는 6 +</pre> + +<h3 id="indexOf()와_대소문자_구분"><code>indexOf()</code>와 대소문자 구분</h3> + +<p>아래 예제에서는 2개의 문자열 변수를 정의하고 있습니다. 이 변수들 내에 있는 문자열들은 모두 같지만 두 번째 변수에 포함되어 있는 문자열은 대문자를 포함하고 있습니다. 첫 번째 {{domxref("console.log()")}} 메서드의 결과값은 19입니다. 하지만, 두 번째 <code>console.log()</code> 메서드의 결과값은 <code>-1</code>입니다. 왜냐하면, indexOf() 메서드는 대소문자를 구분하기 때문에 <code>myCapString</code>에서 "<code>cheddar</code>" 문자열을 찾을 수 없기 때문입니다. </p> + +<pre class="brush: js">var myString = 'brie, pepper jack, cheddar'; +var myCapString = 'Brie, Pepper Jack, Cheddar'; + +console.log('myString.indexOf("cheddar") is ' + myString.indexOf('cheddar')); +// 로그에 19를 출력합니다. +console.log('myCapString.indexOf("cheddar") is ' + myCapString.indexOf('cheddar')); +// 로그에 -1을 출력합니다. +</pre> + +<h3 id="indexOf()를_사용하여_문자열_내의_특정_문자_숫자_세기"><code>indexOf()</code>를 사용하여 문자열 내의 특정 문자 숫자 세기</h3> + +<p>아래 예제는 <code>str </code>문자열에서 <code>e </code>문자의 총 숫자를 확인하는 프로그램입니다:</p> + +<pre class="brush: js">var str = 'To be, or not to be, that is the question.'; +var count = 0; +var pos = str.indexOf('e'); //pos는 4의 값을 가집니다. + +while (pos !== -1) { + count++; + pos = str.indexOf('e', pos + 1); // 첫 번째 e 이후의 인덱스부터 e를 찾습니다. +} + +console.log(count); // 로그에 4를 출력합니다. +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.7', 'String.prototype.indexOf')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.String.indexOf")}}</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("String.prototype.charAt()")}}</li> + <li>{{jsxref("String.prototype.lastIndexOf()")}}</li> + <li>{{jsxref("String.prototype.split()")}}</li> + <li>{{jsxref("Array.prototype.indexOf()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/lastindexof/index.html b/files/ko/web/javascript/reference/global_objects/string/lastindexof/index.html new file mode 100644 index 0000000000..d2244feee5 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/lastindexof/index.html @@ -0,0 +1,105 @@ +--- +title: String.prototype.lastIndexOf() +slug: Web/JavaScript/Reference/Global_Objects/String/lastIndexOf +tags: + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/lastIndexOf +--- +<div>{{JSRef}}</div> + +<p><strong><code>lastIndexOf()</code></strong> 메서드는 주어진 값과 일치하는 부분을 <code>fromIndex</code>로부터 역순으로 탐색하여, 최초로 마주치는 인덱스를 반환합니다. 일치하는 부분을 찾을 수 없으면 <code>-1</code>을 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/string-lastindexof.html", "shorter")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox notranslate"><var>str</var>.lastIndexOf(<var>searchValue</var>[, <var>fromIndex</var>])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>searchValue</code></dt> + <dd>탐색할 문자열. 빈 값을 제공할 경우 <code>fromIndex</code>를 반환합니다.</dd> + <dt><code>fromIndex</code> {{optional_inline}}</dt> + <dd>탐색의 시작점으로 사용할 인덱스. 기본값은 <code>+Infinity</code>입니다. <code>fromIndex >= str.length</code>인 경우 모든 문자열을 탐색합니다. <code>fromIndex < 0</code>인 경우엔 <code>0</code>을 지정한 것과 동일합니다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>문자열 내에서 searchValue가 마지막으로 등장하는 인덱스. 등장하지 않으면 <code>-1</code>.</p> + +<h2 id="설명">설명</h2> + +<p>문자열의 문자는 왼쪽에서 오른쪽으로 인덱스를 매깁니다. 첫 번째 문자의 인덱스는 <code>0</code>이며, 마지막 문자의 인덱스는 <code>str.length -1</code>입니다.</p> + +<pre class="brush: js notranslate">'canal'.lastIndexOf('a'); // 3 반환 +'canal'.lastIndexOf('a', 2); // 1 반환 +'canal'.lastIndexOf('a', 0); // -1 반환 +'canal'.lastIndexOf('x'); // -1 반환 +'canal'.lastIndexOf('c', -5); // 0 반환 +'canal'.lastIndexOf('c', 0); // 0 반환 +'canal'.lastIndexOf(''); // 5 반환 +'canal'.lastIndexOf('', 2); // 2 반환 +</pre> + +<div class="blockIndicator note"> +<p><strong>참고:</strong> <code>'abab'.lastIndexOf('ab', 2)</code>는 0이 아니고 2를 반환합니다. <code>fromIndex</code>는 탐색의 시작점만 제한하기 때문입니다.</p> +</div> + +<h3 id="대소문자_구분">대소문자 구분</h3> + +<p><code>lastIndexOf()</code> 메서드는 대소문자를 구분합니다. 예를 들어, 아래 예제는 <code>-1</code>을 반환합니다.</p> + +<pre class="brush: js notranslate">'Blue Whale, Killer Whale'.lastIndexOf('blue'); // -1 반환 +</pre> + +<h2 id="예제">예제</h2> + +<h3 id="indexOf와_lastIndexOf_사용하기"><code>indexOf()</code>와 <code>lastIndexOf()</code> 사용하기</h3> + +<p>아래 예제는 문자열 <code>"Brave new world"</code> 내에서 특정 값의 위치를 확인하기 위해 {{jsxref("String.prototype.indexOf()", "indexOf()")}}와 <code>lastIndexOf()</code>를 사용합니다.</p> + +<pre class="brush: js notranslate">let anyString = 'Brave new world'; + +console.log('시작점으로부터 처음 만나는 w의 위치는 ' + anyString.indexOf('w')); +// logs 8 +console.log('끝점으로부터 처음 만나는 w의 위치는 ' + anyString.lastIndexOf('w')); +// logs 10 +console.log('시작점으로부터 처음 만나는 "new"의 위치는 ' + anyString.indexOf('new')); +// logs 6 +console.log('끝점으로부터 처음 만나는 "new"의 위치는 ' + anyString.lastIndexOf('new')); +// logs 6 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.lastindexof', 'String.prototype.lastIndexOf')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.String.lastIndexOf")}}</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("String.prototype.charAt()")}}</li> + <li>{{jsxref("String.prototype.indexOf()")}}</li> + <li>{{jsxref("String.prototype.split()")}}</li> + <li>{{jsxref("Array.prototype.indexOf()")}}</li> + <li>{{jsxref("Array.prototype.lastIndexOf()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/length/index.html b/files/ko/web/javascript/reference/global_objects/string/length/index.html new file mode 100644 index 0000000000..697957aaf9 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/length/index.html @@ -0,0 +1,84 @@ +--- +title: String.length +slug: Web/JavaScript/Reference/Global_Objects/String/length +tags: + - JavaScript + - Property + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/length +--- +<div>{{JSRef}}</div> + +<p><strong><code>length</code></strong> 속성은 UTF-16 코드 유닛을 기준으로 문자열의 길이를 나타냅니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/string-length.html")}}</div> + + + +<h2 id="설명">설명</h2> + +<p><code>length</code> 속성은 문자열 안의 코드 유닛 수를 반환합니다. JavaScript가 사용하는 문자열 형식인 {{interwiki("wikipedia", "UTF-16")}}은 대부분의 일반적인 문자를 표현하기 위해 하나의 16비트 코드 유닛을 사용합니다. 반면, 덜 쓰이는 문자를 표현하기 위해 2개의 코드 유닛을 사용해야 할 때도 있으므로 문자열 내에 있는 문자들의 실제 총 숫자가 <code>length</code> 속성이 반환하는 숫자와 일치하지 않을 수 있습니다.</p> + +<p>ECMAScript 2016 7판은 최대 길이를 <code>2^53 - 1</code>로 설정했습니다. 이전엔 명시된 최대 길이가 없었습니다.</p> + +<p>빈 문자열은 <code>length</code>가 0입니다.</p> + +<p>정적 속성 <code>String.length</code>는 1을 반환합니다. </p> + +<h2 id="예제">예제</h2> + +<h3 id="일반적인_사용법">일반적인 사용법</h3> + +<pre class="brush: js">var x = 'Mozilla'; +var empty = ''; + +console.log('Mozilla는 코드 유닛 ' + x.length + '개의 길이입니다.'); +/* "Mozilla는 코드 유닛 7개의 길이입니다." */ + +console.log('빈 문자열은 ' + empty.length + '의 길이를 가집니다.'); +/* "빈 문자열은 0의 길이를 가집니다." */ +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.5.1', 'String.prototype.length')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-properties-of-string-instances-length', 'String.prototype.length')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-properties-of-string-instances-length', 'String.prototype.length')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.String.length")}}</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="http://developer.teradata.com/blog/jasonstrimpel/2011/11/javascript-string-length-and-internationalizing-web-applications">JavaScript <code>String.length</code> and Internationalizing Web Applications</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/localecompare/index.html b/files/ko/web/javascript/reference/global_objects/string/localecompare/index.html new file mode 100644 index 0000000000..9bd3b19236 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/localecompare/index.html @@ -0,0 +1,159 @@ +--- +title: String.prototype.localeCompare() +slug: Web/JavaScript/Reference/Global_Objects/String/localeCompare +translation_of: Web/JavaScript/Reference/Global_Objects/String/localeCompare +--- +<div>{{JSRef}}</div> + +<p>The <strong><code>localeCompare()</code></strong> 메서드는 기준 문자열과 비교했을 때 비교 대상 문자열이 정렬상 전에 오는지, 후에 오는지 혹은 같은 순서에 배치되는지를 알려주는 숫자를 리턴합니다.</p> + +<p>The new <code>locales</code> and <code>options</code> arguments let applications specify the language whose sort order should be used and customize the behavior of the function. In older implementations, which ignore the <code>locales</code> and <code>options</code> arguments, the locale and sort order used are entirely implementation dependent.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>referenceStr</var>.localeCompare(<var>compareString</var>[, <var>locales</var>[, <var>options</var>]])</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<p>Check the <a href="#Browser_compatibility">Browser compatibility</a> section to see which browsers support the <code>locales</code> and <code>options</code> arguments, and the <a href="#Checking_for_support_for_locales_and_options_arguments">Checking for support for <code>locales</code> and <code>options</code> arguments</a> for feature detection.</p> + +<dl> + <dt><code>compareString</code></dt> + <dd>The string against which the referring string is compared</dd> +</dl> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Collator', 'Parameters')}}</div> + +<h3 id="Return_value">Return value</h3> + +<p>A <strong>negative</strong> number if the reference string occurs before the compare string; <strong>positive</strong> if the reference string occurs after the compare string; <strong>0</strong> if they are equivalent.</p> + +<h2 id="Description">Description</h2> + +<p>Returns an integer indicating whether the <strong>referenceStr</strong> comes before, after or is equivalent to the <strong>compareStr</strong>.</p> + +<ul> + <li>Negative when the <strong>referenceStr</strong> occurs before <strong>compareStr</strong></li> + <li>Positive when the <strong>referenceStr</strong> occurs after <strong>compareStr</strong></li> + <li>Returns 0 if they are equivalent</li> +</ul> + +<p><strong>DO NOT rely on exact return values of -1 or 1. </strong>Negative and positive integer results vary between browsers (as well as between browser versions) because the W3C specification only mandates negative and positive values. Some browsers may return -2 or 2 or even some other negative or positive value.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_localeCompare()">Using <code>localeCompare()</code></h3> + +<pre class="brush: js">// The letter "a" is before "c" yielding a negative value +'a'.localeCompare('c'); // -2 or -1 (or some other negative value) + +// Alphabetically the word "check" comes after "against" yielding a positive value +'check'.localeCompare('against'); // 2 or 1 (or some other positive value) + +// "a" and "a" are equivalent yielding a neutral value of zero +'a'.localeCompare('a'); // 0 +</pre> + +<h3 id="Sort_an_array">Sort an array</h3> + +<p><code>localeCompare</code> enables a case-insensitive sort of an array.</p> + +<pre class="brush: js">var items = ['réservé', 'premier', 'cliché', 'communiqué', 'café', 'adieu']; +items.sort((a, b) => a.localeCompare(b)); // ['adieu', 'café', 'cliché', 'communiqué', 'premier', 'réservé'] +</pre> + +<h3 id="Check_browser_support_for_extended_arguments">Check browser support for extended arguments</h3> + +<p>The <code>locales</code> and <code>options</code> arguments are not supported in all browsers yet. To check whether an implementation supports them, use the "i" argument (a requirement that illegal language tags are rejected) and look for a {{jsxref("RangeError")}} exception:</p> + +<pre class="brush: js">function localeCompareSupportsLocales() { + try { + 'foo'.localeCompare('bar', 'i'); + } catch (e) { + return e.name === 'RangeError'; + } + return false; +} +</pre> + +<h3 id="Using_locales">Using <code>locales</code></h3> + +<p>The results provided by <code>localeCompare()</code> vary between languages. In order to get the sort order of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the <code>locales</code> argument:</p> + +<pre class="brush: js">console.log('ä'.localeCompare('z', 'de')); // a negative value: in German, ä sorts before z +console.log('ä'.localeCompare('z', 'sv')); // a positive value: in Swedish, ä sorts after z +</pre> + +<h3 id="Using_options">Using <code>options</code></h3> + +<p>The results provided by <code>localeCompare()</code> can be customized using the <code>options</code> argument:</p> + +<pre class="brush: js">// in German, ä has a as the base letter +console.log('ä'.localeCompare('a', 'de', { sensitivity: 'base' })); // 0 + +// in Swedish, ä and a are separate base letters +console.log('ä'.localeCompare('a', 'sv', { sensitivity: 'base' })); // a positive value +</pre> + +<h2 id="Performance">Performance</h2> + +<p>When comparing large numbers of strings, such as in sorting large arrays, it is better to create an {{jsxref("Global_Objects/Collator", "Intl.Collator")}} object and use the function provided by its {{jsxref("Collator.prototype.compare", "compare")}} property.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.9', 'String.prototype.localeCompare')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.localecompare', 'String.prototype.localeCompare')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.localecompare', 'String.prototype.localeCompare')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES Int 1.0', '#sec-13.1.1', 'String.prototype.localeCompare')}}</td> + <td>{{Spec2('ES Int 1.0')}}</td> + <td><code>locale</code> and <code>option</code> parameter definitions.</td> + </tr> + <tr> + <td>{{SpecName('ES Int 2.0', '#sec-13.1.1', 'String.prototype.localeCompare')}}</td> + <td>{{Spec2('ES Int 2.0')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES Int Draft', '#sec-String.prototype.localeCompare', 'String.prototype.localeCompare')}}</td> + <td>{{Spec2('ES Int Draft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.localeCompare")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Global_Objects/Collator", "Intl.Collator")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/match/index.html b/files/ko/web/javascript/reference/global_objects/string/match/index.html new file mode 100644 index 0000000000..e1031b8a0e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/match/index.html @@ -0,0 +1,156 @@ +--- +title: String.prototype.match() +slug: Web/JavaScript/Reference/Global_Objects/String/match +translation_of: Web/JavaScript/Reference/Global_Objects/String/match +--- +<div>{{JSRef}}</div> + +<div></div> + +<p><strong><code>match()</code></strong> 메서드는 문자열이 정규식과 매치되는 부분을 검색합니다.</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox"><var>str</var>.match(<var>regexp</var>)</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>regexp</code></dt> + <dd>정규식 개체입니다. RegExp가 아닌 객체 obj가 전달되면, <code>new RegExp(obj)</code>를 사용하여 암묵적으로 {{jsxref("RegExp")}}로 변환됩니다. 매개변수를 전달하지 않고 match()를 사용하면, 빈 문자열:[""]이 있는 {{jsxref("Array")}}가 반환됩니다.</dd> +</dl> + +<h3 id="결과_값">결과 값</h3> + +<p>문자열이 정규식과 일치하면, 일치하는 전체 문자열을 첫 번째 요소로 포함하는 {{jsxref("Array")}}를 반환한 다음 괄호 안에 캡처된 결과가 옵니다. 일치하는 것이 없으면 {{jsxref("null")}}이 반환됩니다.</p> + +<h2 id="설명">설명</h2> + +<p>정규식에 <code>g</code> 플래그가 포함되어있지 않으면, <code>str.match()</code> 는 {{jsxref("RegExp.prototype.exec()", "RegExp.exec()")}}와 같은 결과를 반환합니다. 반환된 {{jsxref("Array")}}는 원래 문자열의 값을 가지는 <code>input</code> 속성을 포함합니다. 그리고 문자열에서 제로 베이스의 인덱스를 나타내는 <code>index</code> 속성 또한 포함합니다.</p> + +<p>정규식에 <code>g</code> 플래그가 포함되어 있으면, 일치는 객체가 아닌 일치하는 하위 문자열을 포함하는 {{jsxref("Array")}}를 반환합니다. 캡처된 그룹은 반환되지 않습니다. 일치하는 것이 없으면 null이 반환됩니다.</p> + +<h3 id="이것도_보세요_RegExp_메서드">이것도 보세요: <code>RegExp</code> 메서드</h3> + +<ul> + <li>문자열이 정규표현식{{jsxref("RegExp")}}과 일치하는지 여부를 알아야할 때, {{jsxref("RegExp.prototype.test()", "RegExp.test()")}}을 이용해보세요.</li> + <li>일치하는 것 중 제일 첫번째 것만 알고싶을 때, {{jsxref("RegExp.prototype.exec()", "RegExp.exec()")}}을 대신에 사용하고 싶을겁니다.</li> + <li>캡처 그룹을 알고 싶고 전역 플래그가 셋팅되어 있다면, {{jsxref("RegExp.prototype.exec()", "RegExp.exec()")}}을 대신에 사용해야합니다.</li> +</ul> + +<h2 id="예제">예제</h2> + +<h3 id="match()_사용하기"><code>match()</code> 사용하기</h3> + +<p>다음 예제에서는, <code>match()</code>를 사용하여 <code>'Chapter'</code> 라는 단어와 그에 이어지는 1 이상의 숫자, 그리고 그에 이어서 소숫점, 숫자 형태가 반복되는 문자열을 찾는다. 이 정규표현식은 i 플래그를 사용함으로써, 대소문자 구분 없이 찾고자 하는 문자열을 찾는다.</p> + +<pre class="brush: js">var str = 'For more information, see Chapter 3.4.5.1'; +var re = /see (chapter \d+(\.\d)*)/i; +var found = str.match(re); + +console.log(found); + +// logs [ 'see Chapter 3.4.5.1', +// 'Chapter 3.4.5.1', +// '.1', +// index: 22, +// input: 'For more information, see Chapter 3.4.5.1' ] + +// 'see Chapter 3.4.5.1'는 완전한 매치 상태임. +// 'Chapter 3.4.5.1'는 '(chapter \d+(\.\d)*)' 부분에 의해 발견된 것임. +// '.1' 는 '(\.\d)'를 통해 매치된 마지막 값임. +// 'index' 요소가 (22)라는 것은 0에서부터 셀 때 22번째 위치부터 완전 매치된 문자열이 나타남을 의미함. +// 'input' 요소는 입력된 원래 문자열을 나타냄.</pre> + +<h3 id="match()와_함께_글로벌(g)_및_대소문자_무시(i)_플래그_사용하기"><code>match()</code>와 함께 글로벌(g) 및 대/소문자 무시(i) 플래그 사용하기</h3> + +<p>다음 예제는 글로벌(g) 및 대/소문자 무시(i) 플래그를 사용하여 <code>match()</code>를 사용하는 방법을 보여준다. A부터 E 까지의 모든 문자와 a부터 e 까지의 모든 문자가 배열의 각 원소를 구성하는 형태로 반환된다.</p> + +<pre class="brush: js">var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; +var regexp = /[A-E]/gi; +var matches_array = str.match(regexp); + +console.log(matches_array); +// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e'] +</pre> + +<h3 id="매개변수_없이_match()_사용하기">매개변수 없이 <code>match()</code> 사용하기</h3> + +<pre class="brush: js">var str = "Nothing will come of nothing."; + +str.match(); // returns [""]</pre> + +<h3 id="정규표현식이_아닌_객체를_매개변수로_사용하기">정규표현식이 아닌 객체를 매개변수로 사용하기</h3> + +<p>매개변수가 문자열이나 숫자(Number)이면, 해당 매개변수는 내부적으로 new RegExp(obj)를 사용하여 {{jsxref("RegExp")}}로 변환된다. 만약 매개변수가 플러스 기호와 이어지는 숫자형이라면, RegExp() 매서드는 플러스 기호를 무시한다. </p> + +<pre class="brush: js">var str1 = "NaN means not a number. Infinity contains -Infinity and +Infinity in JavaScript.", + str2 = "My grandfather is 65 years old and My grandmother is 63 years old.", + str3 = "The contract was declared null and void."; +str1.match("number"); // "number"는 문자열임. ["number"]를 반환함. +str1.match(NaN); // NaN 타입은 숫자형임. ["NaN"]을 반환함. +str1.match(Infinity); // Infinity 타입은 숫자형임. ["Infinity"]를 반환함. +str1.match(+Infinity); // ["Infinity"]를 반환함. +str1.match(-Infinity); // ["-Infinity"]를 반환함. +str2.match(65); // ["65"]를 반환함 +str2.match(+65); // 플러스 기호가 붙은 숫자형. ["65"]를 반환함. +str3.match(null); // ["null"]을 반환함.</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.10', 'String.prototype.match')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.match', 'String.prototype.match')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.match', 'String.prototype.match')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">이 페이지의 호환성 표는 구조화된 데이터를 기반으로 작성하였습니다. 데이터를 제공하고 싶으시다면, <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>를 체크하시고, 풀 리퀘스트를 보내주시기 바랍니다.</p> + +<p>{{Compat("javascript.builtins.String.match")}}</p> + +<h2 id="Firefox-specific_notes">Firefox-specific notes</h2> + +<ul> +</ul> + +<ul> + <li><code>flags</code> was a non standard second argument only available in Gecko : <var>str</var>.match(<var>regexp, flags</var>)</li> + <li>Starting with Gecko 27 {{geckoRelease(27)}}, this method has been adjusted to conform with the ECMAScript specification. When <code>match()</code> is called with a global regular expression, the {{jsxref("RegExp.lastIndex")}} property (if specified) will be reset to <code>0</code> ({{bug(501739)}}).</li> + <li>Starting with Gecko 39 {{geckoRelease(39)}}, the non-standard <code>flags</code> argument is deprecated and throws a console warning ({{bug(1142351)}}).</li> + <li>Starting with Gecko 47 {{geckoRelease(47)}}, the non-standard <code>flags</code> argument is no longer supported in non-release builds and will soon be removed entirely ({{bug(1245801)}}).</li> + <li>Starting with Gecko 49 {{geckoRelease(49)}}, the non-standard <code>flags</code> argument is no longer supported ({{bug(1108382)}}).</li> +</ul> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("RegExp")}}</li> + <li>{{jsxref("RegExp.prototype.exec()")}}</li> + <li>{{jsxref("RegExp.prototype.test()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/normalize/index.html b/files/ko/web/javascript/reference/global_objects/string/normalize/index.html new file mode 100644 index 0000000000..d44f9bec99 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/normalize/index.html @@ -0,0 +1,163 @@ +--- +title: String.prototype.normalize() +slug: Web/JavaScript/Reference/Global_Objects/String/normalize +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - String + - Unicode +translation_of: Web/JavaScript/Reference/Global_Objects/String/normalize +--- +<div>{{JSRef}}</div> + +<p><strong><code>normalize()</code></strong> 메서드는 주어진 문자열을 유니코드 정규화 방식(Unicode Normalization Form)에 따라 정규화된 형태로 반환합니다. 만약 주어진 값이 문자열이 아닐 경우에는 우선 문자열로 변환 후 정규화합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/string-normalize.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>str</var>.normalize([<var>form</var>])</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>form</code></dt> + <dd>유니코드 정규화 방식을 지정합니다. <code>"NFC"</code>, <code>"NFD"</code>, <code>"NFKC"</code>, <code>"NFKD"</code> 중 하나이며, 생략되거나 {{jsxref("undefined")}} 일 경우 <code>"NFC"</code>가 사용됩니다. + <ul> + <li><code>NFC</code> — 정규형 정준 결합(Normalization Form Canonical Composition).</li> + <li><code>NFD</code> — 정규형 정준 분해(Normalization Form Canonical Decomposition).</li> + <li><code>NFKC</code> — 정규형 호환성 결합(Normalization Form Compatibility Composition).</li> + <li><code>NFKD</code> — 정규형 호환성 분해(Normalization Form Compatibility Decomposition).</li> + </ul> + </dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 문자열을 유니코드 정규화 방식에 따라 정규화된 문자열로 반환합니다.</p> + +<h3 id="예외">예외</h3> + +<dl> + <dt>{{jsxref("RangeError")}}</dt> + <dd><code>form</code>이 위에서 명시된 값 중 하나가 아닐 경우 {{jsxref("RangeError")}} 에러가 발생합니다.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p><code>normalize()</code> 메서드는 문자열을 유니코드 정규화 방식에 따라 정규화된 형태로 반환합니다. 문자열의 값 자체에는 영향을 주지 않습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="normalize()_사용하기"><code>normalize()</code> 사용하기</h3> + +<pre class="brush: js">// 원본 문자열 + +// U+1E9B: LATIN SMALL LETTER LONG S WITH DOT ABOVE +// U+0323: COMBINING DOT BELOW +var str = '\u1E9B\u0323'; + + +// 정규형 정준 결합 (NFC) + +// U+1E9B: LATIN SMALL LETTER LONG S WITH DOT ABOVE +// U+0323: COMBINING DOT BELOW +str.normalize('NFC'); // '\u1E9B\u0323' +str.normalize(); // 위와 같은 결과 + + +// 정규형 정준 분해 (NFD) + +// U+017F: LATIN SMALL LETTER LONG S +// U+0323: COMBINING DOT BELOW +// U+0307: COMBINING DOT ABOVE +str.normalize('NFD'); // '\u017F\u0323\u0307' + + +// 정규형 호환성 결합 (NFKC) + +// U+1E69: LATIN SMALL LETTER S WITH DOT BELOW AND DOT ABOVE +str.normalize('NFKC'); // '\u1E69' + + +// 정규형 호환성 분해 (NFKD) + +// U+0073: LATIN SMALL LETTER S +// U+0323: COMBINING DOT BELOW +// U+0307: COMBINING DOT ABOVE +str.normalize('NFKD'); // '\u0073\u0323\u0307' +</pre> + +<h3 id="한글에_normalize()_사용하기">한글에 <code>normalize()</code> 사용하기</h3> + +<pre class="brush: js">// 결합된 한글 문자열 + +// U+D55C: 한(HANGUL SYLLABLE HAN) +// U+AE00: 글(HANGUL SYLLABLE GEUL) +var first = '\uD55C\uAE00'; + + +// 정규형 정준 분해 (NFD) +// 정준 분해 결과 초성, 중성, 종성의 자소분리가 일어납니다. +// 일부 브라우저에서는 결과값 '한글'이 자소분리된 상태로 보여질 수 있습니다. + +// U+1112: ᄒ(HANGUL CHOSEONG HIEUH) +// U+1161: ᅡ(HANGUL JUNGSEONG A) +// U+11AB: ᆫ(HANGUL JONGSEONG NIEUN) +// U+1100: ᄀ(HANGUL CHOSEONG KIYEOK) +// U+1173: ᅳ(HANGUL JUNGSEONG EU) +// U+11AF: ᆯ(HANGUL JONGSEONG RIEUL) +var second = first.normalize('NFD'); // '\u1112\u1161\u11AB\u1100\u1173\u11AF' + + +// 정규형 정준 결합 (NFC) +// 정준 결합 결과 자소분리 되었던 한글이 결합됩니다. + +// U+D55C: 한(HANGUL SYLLABLE HAN) +// U+AE00: 글(HANGUL SYLLABLE GEUL) +var third = second.normalize('NFC'); // '\uD55C\uAE00' + + +console.log(second === third); // 같은 글자처럼 보이지만 false를 출력합니다. +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-string.prototype.normalize', 'String.prototype.normalize')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.normalize', 'String.prototype.normalize')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.normalize")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="http://www.unicode.org/reports/tr15/">Unicode Standard Annex #15, Unicode Normalization Forms</a></li> + <li><a href="http://en.wikipedia.org/wiki/Unicode_equivalence">Unicode equivalence</a></li> + <li><a href="https://ko.wikipedia.org/wiki/%EC%9C%A0%EB%8B%88%EC%BD%94%EB%93%9C_%EC%A0%95%EA%B7%9C%ED%99%94">유니코드 정규화</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/padend/index.html b/files/ko/web/javascript/reference/global_objects/string/padend/index.html new file mode 100644 index 0000000000..1c027c1363 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/padend/index.html @@ -0,0 +1,99 @@ +--- +title: String.prototype.padEnd() +slug: Web/JavaScript/Reference/Global_Objects/String/padEnd +tags: + - JavaScript + - Method + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/padEnd +--- +<div>{{JSRef}}</div> + +<p><strong><code>padEnd()</code></strong> 메서드는 현재 문자열에 다른 문자열을 채워, 주어진 길이를 만족하는 새로운 문자열을 반환합니다. 채워넣기는 대상 문자열의 끝(우측)부터 적용됩니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/string-padend.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>str</var>.padEnd(<var>targetLength</var> [, <var>padString</var>])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>targetLength</code></dt> + <dd>목표 문자열 길이. 현재 문자열의 길이보다 작다면 채워넣지 않고 그대로 반환.</dd> + <dt><code>padString</code> {{optional_inline}}</dt> + <dd>현재 문자열에 채워넣을 다른 문자열. 문자열이 너무 길어 목표 문자열 길이를 초과한다면 좌측 일부를 잘라서 넣음. 기본값은 " ". (U+0020)</dd> +</dl> + +<h3 id="반환값">반환값</h3> + +<p>끝부터 주어진 문자열로 채워 목표 길이를 만족하는 {{jsxref("String")}}</p> + +<h2 id="예시">예시</h2> + +<pre class="brush: js">'abc'.padEnd(10); // "abc " +'abc'.padEnd(10, "foo"); // "abcfoofoof" +'abc'.padEnd(6, "123456"); // "abc123" +'abc'.padEnd(1); // "abc"</pre> + +<h2 id="폴리필">폴리필</h2> + +<p>다른 모든 코드 이전에 아래 코드를 포함하면 지원하지 않는 플랫폼에서도 <code>String.prototype.padStart()</code> 메서드를 사용할 수 있습니다.</p> + +<pre class="brush: js">// https://github.com/uxitten/polyfill/blob/master/string.polyfill.js +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd +if (!String.prototype.padEnd) { + String.prototype.padEnd = function padEnd(targetLength,padString) { + targetLength = targetLength>>0; //floor if number or convert non-number to 0; + padString = String((typeof padString !== 'undefined' ? padString : ' ')); + if (this.length > targetLength) { + return String(this); + } + else { + targetLength = targetLength-this.length; + if (targetLength > padString.length) { + padString += padString.repeat(targetLength/padString.length); //append to original to ensure we are longer than needed + } + return String(this) + padString.slice(0,targetLength); + } + }; +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.padend', 'String.prototype.padEnd')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Initial definition in ECMAScript 2017.</td> + </tr> + <tr> + <td>{{SpecName('ES8', '#sec-string.prototype.padend', 'String.prototype.padEnd')}}</td> + <td>{{Spec2('ES8')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.padEnd")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("String.prototype.padStart()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/padstart/index.html b/files/ko/web/javascript/reference/global_objects/string/padstart/index.html new file mode 100644 index 0000000000..eff03dd4ac --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/padstart/index.html @@ -0,0 +1,104 @@ +--- +title: String.prototype.padStart() +slug: Web/JavaScript/Reference/Global_Objects/String/padStart +tags: + - JavaScript + - Method + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/padStart +--- +<div>{{JSRef}}</div> + +<p><strong><code>padStart()</code></strong> 메서드는 현재 문자열의 시작을 다른 문자열로 채워, 주어진 길이를 만족하는 새로운 문자열을 반환합니다. 채워넣기는 대상 문자열의 시작(좌측)부터 적용됩니다.</p> + +<p> </p> + +<div>{{EmbedInteractiveExample("pages/js/string-padstart.html")}}</div> + + + +<p> </p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>str</var>.padStart(<var>targetLength</var> [, <var>padString</var>])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>targetLength</code></dt> + <dd>목표 문자열 길이. 현재 문자열의 길이보다 작다면 채워넣지 않고 그대로 반환.</dd> + <dt><code>padString</code> {{optional_inline}}</dt> + <dd>현재 문자열에 채워넣을 다른 문자열. 문자열이 너무 길어 목표 문자열 길이를 초과한다면 좌측 일부를 잘라서 넣음. 기본값은 " ". (U+0020)</dd> +</dl> + +<h3 id="반환값">반환값</h3> + +<p>시작점부터 주어진 문자열로 채워 목표 길이를 만족하는 {{jsxref("String")}}.</p> + +<h2 id="예시">예시</h2> + +<pre class="brush: js">'abc'.padStart(10); // " abc" +'abc'.padStart(10, "foo"); // "foofoofabc" +'abc'.padStart(6,"123465"); // "123abc" +'abc'.padStart(8, "0"); // "00000abc" +'abc'.padStart(1); // "abc"</pre> + +<h2 id="폴리필">폴리필</h2> + +<p>다른 모든 코드 이전에 아래 코드를 포함하면 지원하지 않는 플랫폼에서도 <code>String.prototype.padStart()</code> 메서드를 사용할 수 있습니다.</p> + +<pre class="brush: js">// https://github.com/uxitten/polyfill/blob/master/string.polyfill.js +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart +if (!String.prototype.padStart) { + String.prototype.padStart = function padStart(targetLength,padString) { + targetLength = targetLength>>0; //truncate if number or convert non-number to 0; + padString = String((typeof padString !== 'undefined' ? padString : ' ')); + if (this.length > targetLength) { + return String(this); + } + else { + targetLength = targetLength-this.length; + if (targetLength > padString.length) { + padString += padString.repeat(targetLength/padString.length); //append to original to ensure we are longer than needed + } + return padString.slice(0,targetLength) + String(this); + } + }; +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.padstart', 'String.prototype.padStart')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Initial definition in ECMAScript 2017.</td> + </tr> + <tr> + <td>{{SpecName('ES8', '#sec-string.prototype.padstart', 'String.prototype.padStart')}}</td> + <td>{{Spec2('ES8')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.padStart")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("String.prototype.padEnd()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/prototype/index.html b/files/ko/web/javascript/reference/global_objects/string/prototype/index.html new file mode 100644 index 0000000000..707680d3c4 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/prototype/index.html @@ -0,0 +1,218 @@ +--- +title: String.prototype +slug: Web/JavaScript/Reference/Global_Objects/String/prototype +tags: + - JavaScript + - Property + - Prototype + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String +--- +<div>{{JSRef("Global_Objects", "String")}}</div> + +<h2 id="Summary" name="Summary">요약</h2> + +<p><strong><code>String.prototype</code></strong> 프라퍼티는 {{jsxref("Global_Objects/String", "String")}} 프로토타입 오브젝트를 표현하고 있습니다.</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="Description" name="Description">설명</h2> + +<p>모든 {{jsxref("Global_Objects/String", "String")}} 인스턴스들은 <code>String.prototype</code>를 상속합니다. <code>String</code> 프라퍼티 오브젝트를 변경하면, 그 변경은 모든 {{jsxref("Global_Objects/String", "String")}} 인스턴스들에 영향을 주게 됩니다.</p> + +<h2 id="Properties" name="Properties">Properties</h2> + +<dl> + <dt><code>String.prototype.constructor</code></dt> + <dd>오브젝트의 프로토타입을 생성하는 함수를 명세합니다.</dd> + <dt>{{jsxref("String.prototype.length")}}</dt> + <dd>문자열의 길이를 반영합니다.</dd> + <dt><code><em>N</em></code></dt> + <dd><em>N</em>번째 위치에 있는 문자에 접근하기 위해 사용합니다. <em>N</em> 은 0과 {{jsxref("String.length", "length")}}보다 작은 값 사이에 있는 양의 정수입니다. 이 퍼라퍼티들은 읽기 전용(read-only) 속성을 가지고 있습니다. </dd> +</dl> + +<h2 id="Methods" name="Methods">메서드</h2> + +<h3 id="Methods_unrelated_to_HTML" name="Methods_unrelated_to_HTML">HTML과 관련이 없는 메서드</h3> + +<dl> + <dt>{{jsxref("String.prototype.charAt()")}}</dt> + <dd>문자열 내 특정 위치(index)에 있는 문자를 반환합니다.</dd> + <dt>{{jsxref("String.prototype.charCodeAt()")}}</dt> + <dd>문자열 내 주어진 위치(index)에 있는 문자의 유니코드 값을 반환합니다.</dd> + <dt>{{jsxref("String.prototype.codePointAt()")}} {{experimental_inline}}</dt> + <dd>주어진 위치에 있는 UTF-16으로 인코딩된 코드 포인터값인 음수가 아닌 정수값을 반환합니다. </dd> + <dt>{{jsxref("String.prototype.concat()")}}</dt> + <dd>두 문자열의 문자를 합쳐서 새로운 문자열로 만든 다음, 그 새로운 문자열을 반환합니다. </dd> + <dt>{{jsxref("String.prototype.includes()")}} {{experimental_inline}}</dt> + <dd>문자열 내에 찾고자 하는 문자열이 있는지를 확인합니다. </dd> + <dt>{{jsxref("String.prototype.endsWith()")}} {{experimental_inline}}</dt> + <dd>문자열에서 특정 문자열로 끝나는지를 확인할 수 있습니다.</dd> + <dt>{{jsxref("String.prototype.indexOf()")}}</dt> + <dd>{{jsxref("Global_Objects/String", "String")}} 오브젝트에 있는 특정 값이 일치하는 첫 번째 인덱스 값을 반환하며, 일치하는 값이 없을 경우에는 -1을 반환합니다.</dd> + <dt>{{jsxref("String.prototype.lastIndexOf()")}}</dt> + <dd><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String" title="String 글로벌 오브젝트는 문자열의 생성자, 또는 문자열의 순서입니다."><code>String</code></a> 오브젝트에서 <code>fromIndex</code>로부터 반대방향으로 찾기 시작하여 특정 값이 일치하는 마지막 인덱스를 반환합니다. 문자열에서 일치하는 특정 값이 없으면 <code>-1</code>을 리턴합니다.</dd> + <dt>{{jsxref("String.prototype.localeCompare()")}}</dt> + <dd>Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.</dd> + <dt>{{jsxref("String.prototype.match()")}}</dt> + <dd>Used to match a regular expression against a string.</dd> + <dt>{{jsxref("String.prototype.normalize()")}} {{experimental_inline}}</dt> + <dd>Returns the Unicode Normalization Form of the calling string value.</dd> + <dt><s class="obsoleteElement">{{jsxref("String.prototype.quote()")}} {{obsolete_inline}}</s></dt> + <dd><s class="obsoleteElement">Wraps the string in double quotes ("<code>"</code>").</s></dd> + <dt>{{jsxref("String.prototype.repeat()")}} {{experimental_inline}}</dt> + <dd>Returns a string consisting of the elements of the object repeated the given times.</dd> + <dt>{{jsxref("String.prototype.replace()")}}</dt> + <dd>Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.</dd> + <dt>{{jsxref("String.prototype.search()")}}</dt> + <dd>Executes the search for a match between a regular expression and a specified string.</dd> + <dt>{{jsxref("String.prototype.slice()")}}</dt> + <dd>Extracts a section of a string and returns a new string.</dd> + <dt>{{jsxref("String.prototype.split()")}}</dt> + <dd>Splits a {{jsxref("Global_Objects/String", "String")}} object into an array of strings by separating the string into substrings.</dd> + <dt>{{jsxref("String.prototype.startsWith()")}} {{experimental_inline}}</dt> + <dd>Determines whether a string begins with the characters of another string.</dd> + <dt>{{jsxref("String.prototype.substr()")}}</dt> + <dd>Returns the characters in a string beginning at the specified location through the specified number of characters.</dd> + <dt>{{jsxref("String.prototype.substring()")}}</dt> + <dd>Returns the characters in a string between two indexes into the string.</dd> + <dt>{{jsxref("String.prototype.toLocaleLowerCase()")}}</dt> + <dd>The characters within a string are converted to lower case while respecting the current locale. For most languages, this will return the same as {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}}.</dd> + <dt>{{jsxref("String.prototype.toLocaleUpperCase()")}}</dt> + <dd>The characters within a string are converted to upper case while respecting the current locale. For most languages, this will return the same as {{jsxref("String.prototype.toUpperCase()", "toUpperCase()")}}.</dd> + <dt>{{jsxref("String.prototype.toLowerCase()")}}</dt> + <dd>Returns the calling string value converted to lower case.</dd> + <dt>{{jsxref("String.prototype.toSource()")}} {{non-standard_inline}}</dt> + <dd>Returns an object literal representing the specified object; you can use this value to create a new object. Overrides the {{jsxref("Object.prototype.toSource()")}} method.</dd> + <dt>{{jsxref("String.prototype.toString()")}}</dt> + <dd>Returns a string representing the specified object. Overrides the {{jsxref("Object.prototype.toString()")}} method.</dd> + <dt>{{jsxref("String.prototype.toUpperCase()")}}</dt> + <dd>Returns the calling string value converted to uppercase.</dd> + <dt>{{jsxref("String.prototype.trim()")}}</dt> + <dd>Trims whitespace from the beginning and end of the string. Part of the ECMAScript 5 standard.</dd> + <dt>{{jsxref("String.prototype.trimLeft()")}} {{non-standard_inline}}</dt> + <dd>Trims whitespace from the left side of the string.</dd> + <dt>{{jsxref("String.prototype.trimRight()")}} {{non-standard_inline}}</dt> + <dd>Trims whitespace from the right side of the string.</dd> + <dt>{{jsxref("String.prototype.valueOf()")}}</dt> + <dd>Returns the primitive value of the specified object. Overrides the {{jsxref("Object.prototype.valueOf()")}} method.</dd> + <dt>{{jsxref("String.prototype.@@iterator()", "String.prototype[@@iterator]()")}} {{experimental_inline}}</dt> + <dd>Returns a new <code>Iterator</code> object that iterates over the code points of a String value, returning each code point as a String value.</dd> +</dl> + +<h3 id="HTML_wrapper_methods" name="HTML_wrapper_methods">HTML wrapper methods</h3> + +<p>These methods are of limited use, as they provide only a subset of the available HTML tags and attributes.</p> + +<dl> + <dt>{{jsxref("String.prototype.big()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("big")}}</dd> + <dt>{{jsxref("String.prototype.blink()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("blink")}}</dd> + <dt>{{jsxref("String.prototype.bold()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("b")}}</dd> + <dt>{{jsxref("String.prototype.fixed()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("tt")}}</dd> + <dt>{{jsxref("String.prototype.fontcolor()")}} {{deprecated_inline}}</dt> + <dd>{{htmlattrxref("color", "font", "<font color=\"color\">")}}</dd> + <dt>{{jsxref("String.prototype.fontsize()")}} {{deprecated_inline}}</dt> + <dd>{{htmlattrxref("size", "font", "<font size=\"size\">")}}</dd> + <dt>{{jsxref("String.prototype.italics()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("i")}}</dd> + <dt>{{jsxref("String.prototype.link()")}}</dt> + <dd>{{htmlattrxref("href", "a", "<a href=\"rul\">")}} (link to URL)</dd> + <dt>{{jsxref("String.prototype.small()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("small")}}</dd> + <dt>{{jsxref("String.prototype.strike()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("strike")}}</dd> + <dt>{{jsxref("String.prototype.sub()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("sub")}}</dd> + <dt>{{jsxref("String.prototype.sup()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("sup")}}</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>ECMAScript 1st Edition.</td> + <td>Standard</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.3.1', 'String.prototype')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype', 'String.prototype')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also" name="See_also">See also</h2> + +<ul> + <li>{{jsxref("Global_Objects/String", "String")}}</li> + <li>{{jsxref("Function.prototype")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/repeat/index.html b/files/ko/web/javascript/reference/global_objects/string/repeat/index.html new file mode 100644 index 0000000000..8e1d67988b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/repeat/index.html @@ -0,0 +1,113 @@ +--- +title: String.prototype.repeat() +slug: Web/JavaScript/Reference/Global_Objects/String/repeat +translation_of: Web/JavaScript/Reference/Global_Objects/String/repeat +--- +<div>{{JSRef}}</div> + +<p><strong><code>repeat()</code></strong> 메서드는 문자열을 주어진 횟수만큼 반복해 붙인 새로운 문자열을 반환합니다.</p> + +<h2 id="구문">구문</h2> + +<pre><code><var>str</var>.repeat(<var>count</var>);</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>count</code></dt> + <dd>문자열을 반복할 횟수. 0과 양의 무한대 사이의 정수([0, +∞)).</dd> +</dl> + +<h3 id="반환값">반환값</h3> + +<p>현재 문자열을 주어진 횟수만큼 반복해 붙인 새로운 문자열.</p> + +<h3 id="예외">예외</h3> + +<ul> + <li>{{jsxref("Errors/Negative_repetition_count", "RangeError")}}: 반복 횟수는 양의 정수여야 함.</li> + <li>{{jsxref("Errors/Resulting_string_too_large", "RangeError")}}: 반복 횟수는 무한대보다 작아야 하며, 최대 문자열 크기를 넘어선 안됨.</li> +</ul> + +<h2 id="예제">예제</h2> + +<pre class="brush: js">'abc'.repeat(-1); // RangeError +'abc'.repeat(0); // '' +'abc'.repeat(1); // 'abc' +'abc'.repeat(2); // 'abcabc' +'abc'.repeat(3.5); // 'abcabcabc' (count will be converted to integer) +'abc'.repeat(1/0); // RangeError + +({ toString: () => 'abc', repeat: String.prototype.repeat }).repeat(2); +// 'abcabc' (repeat() is a generic method) +</pre> + +<h2 id="폴리필">폴리필</h2> + +<p><code>repeat</code>은 ECMAScript 2015 명세에 추가됐습니다. 따라서 어떤 표준 구현체에서는 사용할 수 없을 수도 있습니다. 그러나 아래 코드를 포함하면 지원하지 않는 플랫폼에서도 <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">repeat</span></font>을 사용할 수 있습니다.</p> + +<pre dir="rtl"><code>if (!String.prototype.repeat) { + String.prototype.repeat = function(count) { + 'use strict'; + if (this == null) { + throw new TypeError('can\'t convert ' + this + ' to object'); + } + var str = '' + this; + count = +count; + if (count != count) { + count = 0; + } + if (count < 0) { + throw new RangeError('repeat count must be non-negative'); + } + if (count == Infinity) { + throw new RangeError('repeat count must be less than infinity'); + } + count = Math.floor(count); + if (str.length == 0 || count == 0) { + return ''; + } + // Ensuring count is a 31-bit integer allows us to heavily optimize the + // main part. But anyway, most current (August 2014) browsers can't handle + // strings 1 << 28 chars or longer, so: + if (str.length * count >= 1 << 28) { + throw new RangeError('repeat count must not overflow maximum string size'); + } + var maxCount = str.length * count; + count = Math.floor(Math.log(count) / Math.log(2)); + while (count) { + str += str; + count--; + } + str += str.substring(0, maxCount - str.length); + return str; + } +}</code></pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-string.prototype.repeat', 'String.prototype.repeat')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.repeat', 'String.prototype.repeat')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.repeat")}}</p> diff --git a/files/ko/web/javascript/reference/global_objects/string/replace/index.html b/files/ko/web/javascript/reference/global_objects/string/replace/index.html new file mode 100644 index 0000000000..3b189bfbf5 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/replace/index.html @@ -0,0 +1,299 @@ +--- +title: String.prototype.replace() +slug: Web/JavaScript/Reference/Global_Objects/String/replace +translation_of: Web/JavaScript/Reference/Global_Objects/String/replace +--- +<div>{{JSRef}}</div> + +<p><strong><code>replace()</code></strong> 메서드는 어떤 패턴에 일치하는 일부 또는 모든 부분이 교체된 새로운 문자열을 반환합니다. 그 패턴은 문자열이나 정규식({{jsxref("RegExp")}})이 될 수 있으며, 교체 문자열은 문자열이나 모든 매치에 대해서 호출된 함수일 수 있습니다.</p> + +<p> </p> + +<p>pattern이 문자열 인 경우, 첫 번째 문자열만 치환이 되며 원래 문자열은 변경되지 않습니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/string-replace.html")}}</p> + +<h2 id="구문">구문</h2> + +<pre><code>var newStr = str.replace(regexp|substr, newSubstr|function)</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>regexp</code> (pattern)</dt> + <dd>정규식({{jsxref ( "RegExp")}}) 객체 또는 리터럴. 일치하는 항목은 <code>newSubStr</code> 또는 지정된 함수(<code>function</code>)가 반환 한 값으로 대체됩니다.</dd> + <dt><code>substr</code> (pattern)</dt> + <dd><code>newSubStr</code>로 대체 될 {{jsxref ( "String")}}. 정규식이 아닌 글자 그대로의 문자열로 처리됩니다. 오직 첫 번째 일치되는 문자열만이 교체됩니다.</dd> + <dt><code>newSubStr</code> (replacement)</dt> + <dd>첫번째 파라미터를 대신할 문자열({{jsxref("String")}}). 여러가지 대체 패턴들이 지원됩니다. 아래의 "<a href="#Specifying_a_string_as_a_parameter">매개변수가 <code>string</code>으로 지정되었을 때</a>" 섹션을 참고하세요.</dd> + <dt><code>function</code> (replacement)</dt> + <dd>주어진 <code>regexp</code> 또는 <code>substr</code>에 일치하는 요소를 대체하는 데 사용될 새 하위 문자열을 생성하기 위해 호출되는 함수. 이 함수에 제공되는 인수는 아래 "<a href="#Specifying_a_function_as_a_parameter">매개변수가 <code>function</code>으로 지정되었을 때</a>"단원에서 설명합니다.</dd> +</dl> + +<h3 id="반환값">반환값</h3> + +<p>어떤 패턴에 일치하는 일부 또는 모든 부분이 교체된 새로운 문자열</p> + +<h2 id="설명">설명</h2> + +<p>이 메서드는 호출된 {{jsxref("String")}} 객체를 바꾸지 않습니다. 단순히 새로운 문자열을 리턴합니다.</p> + +<p>모든 문자열에 대해 검색하고 바꾸려면 정규표현식의 <code>g</code>플래그를 포함하세요.</p> + +<h3 id="매개변수가_string으로_지정되었을_때">매개변수가 <code>string</code>으로 지정되었을 때</h3> + +<p><code>replacement</code> 문자열은 다음과 같은 특수 교체 패턴을 포함할 수 있습니다.</p> + +<table class="fullwidth-table"> + <tbody> + <tr> + <td class="header">Pattern</td> + <td class="header">Inserts</td> + </tr> + <tr> + <td><code>$$</code></td> + <td> "<code>$</code>" 기호를 삽입합니다.</td> + </tr> + <tr> + <td><code>$&</code></td> + <td>매치된 문자열을 삽입합니다.</td> + </tr> + <tr> + <td><code>$`</code></td> + <td>매치된 문자열 앞쪽까지의 문자열을 삽입합니다.</td> + </tr> + <tr> + <td><code>$'</code></td> + <td>매치된 문자열의 문자열을 삽입합니다.</td> + </tr> + <tr> + <td><code>$<em>n</em></code></td> + <td> + <p><em><code>n</code></em>이 1이상 99이하의 정수라면, 첫번째 매개변수로 넘겨진 {{jsxref("RegExp")}}객체에서 소괄호로 묶인 <em><code>n</code></em>번째의 부분 표현식으로 매치된 문자열을 삽입합니다.</p> + </td> + </tr> + </tbody> +</table> + +<h3 id="매개변수가_function으로_지정되었을_때">매개변수가 <code>function</code>으로 지정되었을 때</h3> + +<p>두번째 매개변수로 함수를 지정할 수 있습니다. 이 경우, 함수는 정규표현식 매치가 수행된 후 호출될 것입니다. 함수의 반환값은 교체될 문자열이 됩니다. (참고: 윗쪽에서 언급된 특수 교체 패턴은 반환값에 <em>적용되지 않습니다.</em>) 만약 정규표현식의 플래그로 글로벌(<code>g</code>)이 오는 경우, 함수는 매치될 때마다 계속 호출될 것입니다. </p> + +<p>함수의 매개변수들은 다음과 같습니다.</p> + +<table class="fullwidth-table"> + <tbody> + <tr> + <td class="header">Possible name</td> + <td class="header">Supplied value</td> + </tr> + <tr> + <td><code>match</code></td> + <td>매치된 문자열. (윗쪽의 <code>$& </code>표현식으로 매치된 경우와 동일합니다.)</td> + </tr> + <tr> + <td><code>p1,<br> + p2,<br> + ...</code></td> + <td>윗쪽의 $n 표현식과 동일합니다. (<code>$1</code>은 <code>p1</code>, <code>$2</code>는 <code>p2</code>...) 예를 들어, 만약 정규표현식 <code>/(\a+)(\b+)/</code> 이 주어진다면<code><font face="Open Sans, Arial, sans-serif"> </font></code><code>p1</code>은 <code>\a+</code>와 매치되고 <code>p2</code>는 <code>\b+</code>와 매치됩니다.</td> + </tr> + <tr> + <td><code>offset</code></td> + <td>조사된 전체 문자열 중에서 매치된 문자열의 <code>index.</code>(예를 들어, 조사될 전체 문자열이 <code>abcd</code>이고, 매치된 문자열이 <code>bc</code>면 이 매개변수의 값은 1이 됩니다.)</td> + </tr> + <tr> + <td><code>string</code></td> + <td>조사된 전체 문자열 (<code>replace</code>를 호출한 <code>string</code>)</td> + </tr> + </tbody> +</table> + +<p>인수의 정확한 수는 첫 번째 인수가 {{jsxref ( "RegExp")}} 객체인지 아닌지에 따라 다르며, 소괄호로 묶이는 부분표현식의 갯수에 따라 달라집니다.</p> + +<p> </p> + +<p>다음 예제는 <code>newString</code>을 <code>'abc - 12345 - #$*%'</code>로 교체합니다:</p> + +<pre><code>function replacer(match, p1, p2, p3, offset, string) { + // p1 is nondigits, p2 digits, and p3 non-alphanumerics + return [p1, p2, p3].join(' - '); +} +var newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer); +console.log(newString); // abc - 12345 - #$*%</code></pre> + +<h2 id="예제">예제</h2> + +<h3 id="replace()의_정규표현식_정의"><code>replace()</code>의 정규표현식 정의</h3> + +<p>다음 예제에서, 대소문자를 구분하지 않는 정규표현식을 <code>replace()</code>에 정의했습니다.</p> + +<pre class="brush: js">var str = 'Twas the night before Xmas...'; +var newstr = str.replace(/xmas/i, 'Christmas'); +console.log(newstr); // Twas the night before Christmas... +</pre> + +<p>'Twas the night before Christmas...'로 출력됩니다.</p> + +<h3 id="global과_ignore를_사용한_replace()"><code>global</code>과 <code>ignore</code>를 사용한 <code>replace()</code></h3> + +<p>Global replace는 정규식으로만 수행 할 수 있습니다. 다음 예제에서 정규 표현식은 replace()가 'apples'를 'oranges'로 바꿀 수 있도록 global 및 ignore case 플래그를 포함합니다.</p> + +<pre class="brush: js">var re = /apples/gi; +var str = 'Apples are round, and apples are juicy.'; +var newstr = str.replace(re, 'oranges'); +console.log(newstr); // oranges are round, and oranges are juicy. +</pre> + +<p>'오렌지는 둥글고 오렌지는 맛있습니다.' 가 출력됩니다.</p> + +<p> </p> + +<h3 id="문자열의_단어_치환">문자열의 단어 치환</h3> + +<p>다음 스크립트는 문자열의 단어를 전환합니다. 대체 텍스트의 경우 스크립트는 <code>$1</code> 와 <code>$2</code> 대체 패턴을 사용합니다.</p> + +<pre class="brush: js">var re = /(\w+)\s(\w+)/; +var str = 'John Smith'; +var newstr = str.replace(re, '$2, $1'); +console.log(newstr); // Smith, John +</pre> + +<p>'Smith, John.'이 출력됩니다.</p> + +<h3 id="Using_an_inline_function_that_modifies_the_matched_characters">Using an inline function that modifies the matched characters</h3> + +<p> </p> + +<p>이 예제에서 문자열의 대문자가 모두 소문자로 변환되고 일치되는 위치 바로 앞에 하이픈이 삽입됩니다. 여기에서 중요한 점은 일치되는 항목이 대체 항목으로 다시 반환되기 전에 추가 작업이 필요하다는 것입니다.</p> + +<p>바꾸기 기능은 일치하는 스니펫을 매개 변수로 받고 이를 사용하여 각 케이스별로 변환한후 반환하기 전에 하이픈을 연결합니다.</p> + +<p> </p> + +<pre class="brush: js">function styleHyphenFormat(propertyName) { + function upperToHyphenLower(match) { + return '-' + match.toLowerCase(); + } + return propertyName.replace(/[A-Z]/g, upperToHyphenLower); +} +</pre> + +<p>Given <code>styleHyphenFormat('borderTop')</code>, this returns 'border-top'.</p> + +<p>Because we want to further transform the <em>result</em> of the match before the final substitution is made, we must use a function. This forces the evaluation of the match prior to the {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}} method. If we had tried to do this using the match without a function, the {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}} would have no effect.</p> + +<pre class="brush: js">var newString = propertyName.replace(/[A-Z]/g, '-' + '$&'.toLowerCase()); // won't work +</pre> + +<p>This is because <code>'$&'.toLowerCase()</code> would be evaluated first as a string literal (resulting in the same <code>'$&'</code>) before using the characters as a pattern.</p> + +<h3 id="Replacing_a_Fahrenheit_degree_with_its_Celsius_equivalent">Replacing a Fahrenheit degree with its Celsius equivalent</h3> + +<p>The following example replaces a Fahrenheit degree with its equivalent Celsius degree. The Fahrenheit degree should be a number ending with F. The function returns the Celsius number ending with C. For example, if the input number is 212F, the function returns 100C. If the number is 0F, the function returns -17.77777777777778C.</p> + +<p>The regular expression <code>test</code> checks for any number that ends with F. The number of Fahrenheit degree is accessible to the function through its second parameter, <code>p1</code>. The function sets the Celsius number based on the Fahrenheit degree passed in a string to the <code>f2c()</code> function. <code>f2c()</code> then returns the Celsius number. This function approximates Perl's <code>s///e</code> flag.</p> + +<pre class="brush: js">function f2c(x) { + function convert(str, p1, offset, s) { + return ((p1 - 32) * 5/9) + 'C'; + } + var s = String(x); + var test = /(-?\d+(?:\.\d*)?)F\b/g; + return s.replace(test, convert); +} +</pre> + +<h3 id="Use_an_inline_function_with_a_regular_expression_to_avoid_for_loops">Use an inline function with a regular expression to avoid <code>for</code> loops</h3> + +<p>The following example takes a string pattern and converts it into an array of objects.</p> + +<p><strong>Input:</strong></p> + +<p>A string made out of the characters <code>x</code>, <code>-</code> and <code>_</code></p> + +<pre>x-x_ +x---x---x---x--- +x-xxx-xx-x- +x_x_x___x___x___ +</pre> + +<p><strong>Output:</strong></p> + +<p>An array of objects. An <code>'x'</code> denotes an <code>'on'</code> state, a <code>'-'</code> (hyphen) denotes an <code>'off'</code> state and an <code>'_'</code> (underscore) denotes the length of an <code>'on'</code> state.</p> + +<pre class="brush: json">[ + { on: true, length: 1 }, + { on: false, length: 1 }, + { on: true, length: 2 } + ... +] +</pre> + +<p><strong>Snippet:</strong></p> + +<pre class="brush: js">var str = 'x-x_'; +var retArr = []; +str.replace(/(x_*)|(-)/g, function(match, p1, p2) { + if (p1) { retArr.push({ on: true, length: p1.length }); } + if (p2) { retArr.push({ on: false, length: 1 }); } +}); + +console.log(retArr); +</pre> + +<p>This snippet generates an array of 3 objects in the desired format without using a <code>for</code> loop.</p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.11', 'String.prototype.replace')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.replace', 'String.prototype.replace')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.replace', 'String.prototype.replace')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div> </div> + +<div id="compat-mobile">{{Compat("javascript.builtins.String.replace")}}</div> + +<h2 id="Firefox-specific_notes">Firefox-specific notes</h2> + +<ul> + <li>Starting with Gecko 27 {{geckoRelease(27)}}, this method has been adjusted to conform with the ECMAScript specification. When <code>replace()</code> is called with a global regular expression, the {{jsxref("RegExp.lastIndex")}} property (if specified) will be reset to <code>0</code> ({{bug(501739)}}).</li> + <li>Starting with Gecko 39 {{geckoRelease(39)}}, the non-standard <code>flags</code> argument is deprecated and throws a console warning ({{bug(1142351)}}).</li> + <li>Starting with Gecko 47 {{geckoRelease(47)}}, the non-standard <code>flags</code> argument is no longer supported in non-release builds and will soon be removed entirely ({{bug(1245801)}}).</li> + <li>Starting with Gecko 49 {{geckoRelease(49)}}, the non-standard <code>flags</code> argument is no longer supported ({{bug(1108382)}}).</li> +</ul> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("String.prototype.match()")}}</li> + <li>{{jsxref("RegExp.prototype.exec()")}}</li> + <li>{{jsxref("RegExp.prototype.test()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/search/index.html b/files/ko/web/javascript/reference/global_objects/string/search/index.html new file mode 100644 index 0000000000..3d27d812fc --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/search/index.html @@ -0,0 +1,100 @@ +--- +title: String.prototype.search() +slug: Web/JavaScript/Reference/Global_Objects/String/search +translation_of: Web/JavaScript/Reference/Global_Objects/String/search +--- +<div>{{JSRef}}</div> + +<p><strong><code>search()</code></strong> 메서드는 정규 표현식과 이 {{jsxref("String")}} 객체간에 같은 것을 찾기<br> + 위한 검색을 실행한다.</p> + +<div>{{EmbedInteractiveExample("pages/js/string-search.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>str</var>.search(<var>regexp</var>)</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>regexp</code></dt> + <dd>정규 표현식 객체. non-RegExp 객체 <code>obj</code> 가 전달되면, 그것은 <code>new RegExp(obj)</code> 을 이용하여 {{jsxref("RegExp")}} 으로 암묵적으로 변환된다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>정규표현식과 주어진 스트링간에 첫번째로 매치되는 것의 인덱스를 반환한다.<br> + 찾지 못하면 <strong>-1</strong> 를 반환한다.</p> + +<h2 id="설명">설명</h2> + +<p>When you want to know whether a pattern is found and also its index in a string use <code>search()</code> (if you only want to know if it exists, use the similar {{jsxref("RegExp.prototype.test()", "test()")}} method on the RegExp prototype, which returns a boolean); for more information (but slower execution) use {{jsxref("String.prototype.match()", "match()")}} (similar to the regular expression {{jsxref("RegExp.prototype.exec()", "exec()")}} method).</p> + +<h2 id="예">예</h2> + +<h3 id="search()를_이용하기"><code>search()를 이용하기</code></h3> + +<p>The following example searches a string with 2 different regex objects to show a successful search (positive value) vs. an unsuccessful search (-1)</p> + +<pre class="brush: js">var str = "hey JudE"; +var re = /[A-Z]/g; +var re2 = /[.]/g; +console.log(str.search(re)); // returns 4, which is the index of the first capital letter "J" +console.log(str.search(re2)); // returns -1 cannot find '.' dot punctuation</pre> + +<h2 id="사양">사양</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">사양</th> + <th scope="col">상태</th> + <th scope="col">주석</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.12', 'String.prototype.search')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.search', 'String.prototype.search')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.search', 'String.prototype.search')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.search")}}</p> + +<h2 id="Gecko-specific_notes">Gecko-specific notes</h2> + +<ul> + <li><code>flags</code> was a non standard second argument only available in Gecko : <var>str</var>.search(<var>regexp, flags</var>)</li> + <li>Prior to {{Gecko("8.0")}}, <code>search()</code> was implemented incorrectly; when it was called with no parameters or with {{jsxref("undefined")}}, it would match against the string 'undefined', instead of matching against the empty string. This is fixed; now <code>'a'.search()</code> and <code>'a'.search(undefined)</code> correctly return 0.</li> + <li>Starting with Gecko 39 {{geckoRelease(39)}}, the non-standard <code>flags</code> argument is deprecated and throws a console warning ({{bug(1142351)}}).</li> + <li>Starting with Gecko 47 {{geckoRelease(47)}}, the non-standard <code>flags</code> argument is no longer supported in non-release builds and will soon be removed entirely ({{bug(1245801)}}).</li> + <li>Starting with Gecko 49 {{geckoRelease(49)}}, the non-standard <code>flags</code> argument is no longer supported ({{bug(1108382)}}).</li> +</ul> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("String.prototype.match()")}}</li> + <li>{{jsxref("RegExp.prototype.exec()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/slice/index.html b/files/ko/web/javascript/reference/global_objects/string/slice/index.html new file mode 100644 index 0000000000..3bd23ace3b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/slice/index.html @@ -0,0 +1,129 @@ +--- +title: String.prototype.slice() +slug: Web/JavaScript/Reference/Global_Objects/String/slice +tags: + - 메소드 + - 문자열 + - 자바스크립트 + - 프로토타입 +translation_of: Web/JavaScript/Reference/Global_Objects/String/slice +--- +<div>{{JSRef}}</div> + +<p><strong><code>slice()</code></strong> 메소드는 문자열의 일부를 추출하면서 새로운 문자열을 반환합니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/string-slice.html")}}</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox notranslate"><code><var>str</var>.slice(<var>beginIndex</var>[, <var>endIndex</var>])</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>beginIndex</code></dt> + <dd>추출 시작점인 0부터 시작하는 인덱스입니다. 만약 음수라면, beginIndex는 <code>strLength(문자열 길이) + beginIndex</code>로 취급됩니다. (예를 들어 <code>beginIndex</code>가 -3이면 시작점은 <code>strLength - 3</code>).</dd> + <dd>만약 <code>beginIndex</code>가 <code>strLength</code> 보다 크거나 같은 경우, <code>slice()</code>는 빈 문자열을 반환합니다.</dd> + <dt><code>endIndex</code>{{optional_inline}}</dt> + <dd>0부터 시작하는 추출 종료점 인덱스로 그 직전까지 추출됩니다. 인덱스 위치의 문자는 추출에 포함되지 않습니다.</dd> + <dd>만약 <code>endIndex</code>가 생략된다면, <code>silce()</code>는 문자열 마지막까지 추출합니다. 만약 음수라면, endIndex는 <code>strLength(문자열 길이) + endIndex</code> 로 취급됩니다(예를 들어 <code>endIndex</code>가 -3이면 종료점은 <code>strLength - 3</code>).</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>문자열의 추출된 부분을 담는 새로운 문자열이 반환됩니다.</p> + +<h2 id="설명">설명</h2> + +<p><code>slice()</code>는 문자열로부터 텍스트를 추출하고 새 문자열을 반환합니다. 문자열의 변경은 다른 문자열에 영향을 미치지 않습니다.</p> + +<p><code>slice()</code>는 <code>endIndex</code>를 포함하지 않고 추출합니다. <code>str.slice(1, 4)</code>는 두 번째 문자부터 네 번째 문자까지 추출합니다 (1, 2, 3 인덱스 문자).</p> + +<p><code>str.slice(2, -1)</code>는 세 번째 문자부터 문자열의 마지막에서 두 번째 문자까지 추출합니다.</p> + +<h2 id="예시">예시</h2> + +<h3 id="slice를_사용하여_새_문자열_생성하기"><code>slice()</code>를 사용하여 새 문자열 생성하기</h3> + +<p>아래 예시는 새 문자열을 생성하기 위해 <code>slice()</code>를 사용합니다.</p> + +<pre class="brush: js notranslate">var str1 = 'The morning is upon us.', // the length of str1 is 23. + str2 = str1.slice(1, 8), + str3 = str1.slice(4, -2), + str4 = str1.slice(12), + str5 = str1.slice(30); +console.log(str2); // OUTPUT: he morn +console.log(str3); // OUTPUT: morning is upon u +console.log(str4); // OUTPUT: is upon us. +console.log(str5); // OUTPUT: "" +</pre> + +<h3 id="음수_인덱스로_slice_사용하기">음수 인덱스로 <code>slice()</code> 사용하기</h3> + +<p>아래 예시는 <code>slice()</code>에 음수 인덱스를 사용합니다.</p> + +<pre class="brush: js notranslate">var str = 'The morning is upon us.'; +str.slice(-3); // returns 'us.' +str.slice(-3, -1); // returns 'us' +str.slice(0, -1); // returns 'The morning is upon us' +</pre> + +<p>아래의 예시는 시작 인덱스를 찾기 위해 문자열의 끝에서부터 역방향으로 <code>11</code>개를 세고 끝 인덱스를 찾기 위해 문자열의 시작에서부터 정방향으로 <code>16</code>개를 셉니다.</p> + +<pre class="brush: js notranslate"><code>console.log(str.slice(-11, 16)) // => "is u";</code></pre> + +<p>아래에서는 시작 인덱스를 찾기 위해 문자열의 처음부터 정방향으로 <code>11</code>개를 세고 끝 인덱스를 찾기 위해 끝에서부터 <code>7</code>개를 셉니다.</p> + +<pre class="brush: js notranslate"><code>console.log(str.slice(11, -7)) // => "is u";</code> +</pre> + +<p>이 인수는 끝에서부터 5로 역순으로 계산하여 시작 인덱스를 찾은 다음 끝에서부터 1을 거쳐 끝 인덱스를 찾습니다.</p> + +<pre class="brush: js notranslate"><code>console.log(str.slice(-5, -1)) // => "n us";</code> +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.slice', 'String.prototype.slice')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.slice', 'String.prototype.slice')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.13', 'String.prototype.slice')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{Compat("javascript.builtins.String.slice")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("String.prototype.substr()")}}</li> + <li>{{jsxref("String.prototype.substring()")}}</li> + <li>{{jsxref("Array.prototype.slice()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/split/index.html b/files/ko/web/javascript/reference/global_objects/string/split/index.html new file mode 100644 index 0000000000..7100e55a50 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/split/index.html @@ -0,0 +1,231 @@ +--- +title: String.prototype.split() +slug: Web/JavaScript/Reference/Global_Objects/String/split +tags: + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/split +--- +<div>{{JSRef}}</div> + +<p><strong><code>split()</code></strong> 메서드는 {{jsxref("String")}} 객체를 지정한 구분자를 이용하여 여러 개의 문자열로 나눕니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/string-split.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>str</var>.split([<var>separator</var>[, <var>limit</var>]])</pre> + +<div class="warning"> +<p><strong>주의:</strong> 구분자로 빈 문자열(<code>""</code>)을 제공하면, 사용자가 인식하는 문자 하나(<a href="https://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries">grapheme cluster</a>) 또는 유니코드 문자(코드포인트) 하나씩으로 나누는 것이 아니라, UTF-16 코드유닛으로 나누게 되며 <a href="http://unicode.org/faq/utf_bom.html#utf16-2">써로게이트 페어</a><sup>surrogate pair</sup>가 망가질 수 있습니다. 스택 오버플로우의 <a href="https://stackoverflow.com/a/34717402">How do you get a string to a character array in JavaScript?</a> 질문도 참고해 보세요.</p> +</div> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>separator</code> {{optional_inline}}</dt> + <dd>원본 문자열을 끊어야 할 부분을 나타내는 문자열을 나타냅니다. 실제 문자열이나 {{jsxref("Global_Objects/RegExp", "정규표현식", "", 1)}}을 받을 수 있습니다. 문자열 유형의 <code>separator</code>가 두 글자 이상일 경우 그 부분 문자열 전체가 일치해야 끊어집니다. <code>separator</code>가 생략되거나 <code>str</code>에 등장하지 않을 경우, 반환되는 배열은 원본 문자열을 유일한 원소로 가집니다. <code>separator</code>가 빈 문자열일 경우 <code>str</code>의 각각의 문자가 배열의 원소 하나씩으로 변환됩니다.</dd> + <dt><code>limit</code> {{optional_inline}}</dt> + <dd> + <p>끊어진 문자열의 최대 개수를 나타내는 정수입니다. 이 매개변수를 전달하면 split() 메서드는 주어진 <code>separator</code>가 등장할 때마다 문자열을 끊지만 배열의 원소가 <code>limit</code>개가 되면 멈춥니다. 지정된 한계에 도달하기 전에 문자열의 끝까지 탐색했을 경우 <code>limit</code>개 미만의 원소가 있을 수도 있습니다. 남은 문자열은 새로운 배열에 포함되지 않습니다.</p> + </dd> +</dl> + +<h3 id="반환값">반환값</h3> + +<p>주어진 문자열을 <code>separator</code>마다 끊은 부분 문자열을 담은 {{jsxref("Array")}}.</p> + +<h2 id="설명">설명</h2> + +<p>문자열에서 <code>separator</code>가 등장하면 해당 부분은 삭제되고 남은 문자열이 배열로 반환됩니다. <code>separator</code>가 등장하지 않거나 생략되었을 경우 배열은 원본 문자열을 유일한 원소로 가집니다. <code>separator</code>가 빈 문자열일 경우, <code>str</code>은 문자열의 모든 문자를 원소로 가지는 배열로 변환됩니다. <code>separator</code>가 원본 문자열의 처음이나 끝에 등장할 경우 반환되는 배열도 빈 문자열로 시작하거나 끝납니다. 그러므로 원본 문자열에 <code>separator</code> 하나만이 포함되어 있을 경우 빈 문자열 두 개를 원소로 가지는 배열이 반환됩니다.</p> + +<p><code>separator</code>가 포획 괄호<sup>capturing parentheses</sup>를 포함하는 정규표현식일 경우, <code>separator</code>가 일치할 때마다 포획 괄호의 (정의되지 않은 경우도 포함한) 결과가 배열의 해당 위치에 포함됩니다.</p> + +<p>{{Note("<code>separator</code>가 배열일 경우 분할에 사용하기 전에 우선 문자열로 변환됩니다.")}}</p> + +<h2 id="예제">예제</h2> + +<h3 id="split()_사용하기"><code>split()</code> 사용하기</h3> + +<p>{{Note("빈 문자열이 주어졌을 경우 <code>split()</code>은 빈 배열이 아니라 빈 문자열을 포함한 배열을 반환합니다. 문자열과 <code>separator</code>가 모두 빈 문자열일 때는 빈 배열을 반환합니다.")}}</p> + +<pre class="brush: js">const myString = ''; +const splits = myString.split(); + +console.log(splits); + +// ↪ [""] +</pre> + +<p>다음 예제에서는 문자열을 주어진 구분자로 끊는 함수를 정의합니다. 문자열을 끊은 다음에는 (끊기 이전의) 원본 문자열과 사용한 구분자, 배열의 길이와 각 원소를 로그로 출력합니다.</p> + +<pre class="brush: js">function splitString(stringToSplit, separator) { + var arrayOfStrings = stringToSplit.split(separator); + + console.log('The original string is: "' + stringToSplit + '"'); + console.log('The separator is: "' + separator + '"'); + console.log('The array has ' + arrayOfStrings.length + ' elements: ' + arrayOfStrings.join(' / ')); +} + +var tempestString = 'Oh brave new world that has such people in it.'; +var monthString = 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'; + +var space = ' '; +var comma = ','; + +splitString(tempestString, space); +splitString(tempestString); +splitString(monthString, comma); +</pre> + +<p>위 예제의 출력은 다음과 같습니다.</p> + +<pre>The original string is: "Oh brave new world that has such people in it." +The separator is: " " +The array has 10 elements: Oh / brave / new / world / that / has / such / people / in / it. + +The original string is: "Oh brave new world that has such people in it." +The separator is: "undefined" +The array has 1 elements: Oh brave new world that has such people in it. + +The original string is: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec" +The separator is: "," +The array has 12 elements: Jan / Feb / Mar / Apr / May / Jun / Jul / Aug / Sep / Oct / Nov / Dec +</pre> + +<h3 id="문자열에서_공백_제거하기">문자열에서 공백 제거하기</h3> + +<p>다음 예제에서 <code>split()</code>은 세미콜론 앞뒤에 각각 0개 이상의 공백이 있는 부분 문자열을 찾고, 있을 경우 문자열에서 세미콜론과 공백을 제거합니다. <code>split()</code>의 결과로 반환된 배열은 <code>nameList</code>에 저장됩니다.</p> + +<pre class="brush: js">var names = 'Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand '; + +console.log(names); + +var re = /\s*(?:;|$)\s*/; +var nameList = names.split(re); + +console.log(nameList); +</pre> + +<p>위 예제는 원본 문자열과 반환된 배열을 각각 한 줄씩 로그로 출력합니다.</p> + +<pre>Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand +[ "Harry Trump", "Fred Barney", "Helen Rigby", "Bill Abel", "Chris Hand", "" ] +</pre> + +<h3 id="끊는_횟수_제한하기">끊는 횟수 제한하기</h3> + +<p>다음 예제에서 <code>split()</code>은 문자열을 공백으로 끊고 처음 3개의 문자열을 반환합니다.</p> + +<pre class="brush: js">var myString = 'Hello World. How are you doing?'; +var splits = myString.split(' ', 3); + +console.log(splits); +</pre> + +<p>위 예제의 로그 출력은 다음과 같습니다.</p> + +<pre>["Hello", "World.", "How"] +</pre> + +<h3 id="RegExp를_사용해_구분자도_결과에_포함하기"><code>RegExp</code>를 사용해 구분자도 결과에 포함하기</h3> + +<p><code>separator</code>가 포획 괄호 <code>()</code>를 포함하는 정규표현식일 경우, 포획된 결과도 배열에 포함됩니다.</p> + +<pre class="brush: js">var myString = 'Hello 1 word. Sentence number 2.'; +var splits = myString.split(/(\d)/); + +console.log(splits); +</pre> + +<p>위 예제의 로그 출력은 다음과 같습니다.</p> + +<pre>[ "Hello ", "1", " word. Sentence number ", "2", "." ] +</pre> + +<h3 id="배열을_구분자로_사용하기">배열을 구분자로 사용하기</h3> + +<pre class="brush: js">var myString = 'this|is|a|Test'; +var splits = myString.split(['|']); + +console.log(splits); //["this", "is", "a", "Test"] + +var myString = 'ca,bc,a,bca,bca,bc'; + +var splits = myString.split(['a','b']); +// <em>myString.split(['a','b'])</em>은 <em>myString.split(String(['a','b']))</em>와 같다 + +console.log(splits); //["c", "c,", "c", "c", "c"] +</pre> + +<h3 id="split()으로_문자열_뒤집기"><code>split()</code>으로 문자열 뒤집기</h3> + +<div class="warning"> +<p>이 방법은 문자열 뒤집기에 효과적인 방법이 아닙니다.</p> + +<pre class="brush: js">var str = 'asdfghjkl'; +var strReverse = str.split('').reverse().join(''); // 'lkjhgfdsa' +// split()에서 반환한 배열에는 reverse()와 join()을 사용할 수 있다 +</pre> + +<p>문자열에 grapheme clusters가 있을 경우, 유니코드 플래그를 설정해도 오류를 일으킵니다(<a href="https://github.com/mathiasbynens/esrever">esrever</a> 등의 라이브러리를 대신 사용하세요).</p> + +<pre class="brush: js">var str = 'résumé'; +var strReverse = str.split(/(?:)/u).reverse().join(''); +// => "́emuśer" +</pre> + +<p><strong>추가:</strong> {{jsxref("Operators/Comparison_Operators", "===", "#Identity_strict_equality_(===)")}} 연산자를 사용하면 원본 문자열이 팰린드롬인지 확인할 수 있습니다.</p> +</div> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">비고</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>초기 정의. JavaScript 1.1에 구현되었음.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.14', 'String.prototype.split')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.split', 'String.prototype.split')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.split', 'String.prototype.split')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.split")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("String.prototype.charAt()")}}</li> + <li>{{jsxref("String.prototype.indexOf()")}}</li> + <li>{{jsxref("String.prototype.lastIndexOf()")}}</li> + <li>{{jsxref("Array.prototype.join()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/startswith/index.html b/files/ko/web/javascript/reference/global_objects/string/startswith/index.html new file mode 100644 index 0000000000..41eb064129 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/startswith/index.html @@ -0,0 +1,95 @@ +--- +title: String.prototype.startsWith() +slug: Web/JavaScript/Reference/Global_Objects/String/startsWith +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/startsWith +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary"><strong><code>startsWith()</code></strong></span><span class="seoSummary"> 메소드는 어떤 문자열이 특정 문자로 시작하는지 확인하여 결과를 <code>true</code> 혹은 <code>false</code>로 반환합니다.</span></p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>str</var>.startsWith(<var>searchString</var>[, <var>position</var>])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>searchString</code></dt> + <dd>문자열의 시작 지점에서 탐색할 문자열</dd> + <dt><code>position</code> {{optional_inline}}</dt> + <dd><code>searchString</code>을 탐색할 위치. 기본값 0.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>문자열이 검색 문자열로 시작하면 <code>true</code>, 아니면 <code>false</code>.</p> + +<h2 id="설명"><span style="display: none;"> </span><span style="display: none;"> </span>설명</h2> + +<p><code>startsWith</code> 메소드로 어떤 문자열이 다른 문자열로 시작하는지 확인 할 수 있습니다. 대소문자를 구분합니다.</p> + +<h2 id="예시">예시</h2> + +<h3 id="startsWith()_사용하기"><code>startsWith()</code> 사용하기</h3> + +<pre class="brush: js">//startswith +var str = 'To be, or not to be, that is the question.'; + +console.log(str.startsWith('To be')); // true +console.log(str.startsWith('not to be')); // false +console.log(str.startsWith('not to be', 10)); // true +</pre> + +<h2 id="폴리필">폴리필</h2> + +<p><code>startsWith</code> 메소드는 ECMAScript 2015 명세에 포함됐으며, 아직까지 모든 JavaScrpt 구현체가 지원하지 않을 수 있습니다. 그러나 아래 코드 조각을 사용해 폴리필 할 수 있습니다.</p> + +<pre><code>if (!String.prototype.startsWith) { + String.prototype.startsWith = function(search, pos) { + return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; + }; +}</code></pre> + +<p>ES2015 명세를 모두 만족하지만, 더 무거운 폴리필은 <a href="https://github.com/mathiasbynens/String.prototype.startsWith">Mathias Bynens의 GitHub</a> 에서 확인할 수 있습니다.</p> + +<h2 id="명세서">명세서</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.startswith', 'String.prototype.startsWith')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.startswith', 'String.prototype.startsWith')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.String.startsWith")}}</div> + +<h2 id="관련_문서">관련 문서</h2> + +<ul> + <li>{{jsxref("String.prototype.endsWith()")}}</li> + <li>{{jsxref("String.prototype.includes()")}}</li> + <li>{{jsxref("String.prototype.indexOf()")}}</li> + <li>{{jsxref("String.prototype.lastIndexOf()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/substr/index.html b/files/ko/web/javascript/reference/global_objects/string/substr/index.html new file mode 100644 index 0000000000..39fe5e126b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/substr/index.html @@ -0,0 +1,131 @@ +--- +title: String.prototype.substr() +slug: Web/JavaScript/Reference/Global_Objects/String/substr +tags: + - Deprecated + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/substr +--- +<div>{{JSRef}}</div> + +<div> </div> + +<div class="warning"> +<p>경고: 엄밀히 말해서 <code>String.prototype.substr()</code> 메서드가 더 이상 사용되지 않는, 즉 "웹 표준에서 제거된" 건 아닙니다. 그러나 <code>substr()</code>이 포함된 ECMA-262 표준의 <a href="https://www.ecma-international.org/ecma-262/9.0/index.html#sec-additional-ecmascript-features-for-web-browsers">부록 B</a>는 다음과 같이 명시하고 있습니다.</p> + +<blockquote>… 본 부록이 포함한 모든 언어 기능과 행동은 하나 이상의 바람직하지 않은 특징을 갖고 있으며 사용처가 없어질 경우 명세에서 제거될 것입니다. …<br> +… 프로그래머는 새로운 ECMAScript 코드를 작성할 때 본 부록이 포함한 기능을 사용하거나 존재함을 가정해선 안됩니다. …</blockquote> +</div> + +<p><strong><code>substr()</code></strong> 메서드는 문자열에서 특정 위치에서 시작하여 특정 문자 수 만큼의 문자들을 반환합니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/string-substr.html")}}</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>str</var>.substr(<var>start</var>[, <var>length</var>])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>start</code></dt> + <dd>추출하고자 하는 문자들의 시작위치입니다. 만약 음수가 주어진다면, <code>문자열총길이 + start</code>의 값으로 취급합니다. 예를 들면, <code>start</code>에 -3을 설정하면, 자동적으로 <code>문자열총길이 - 3</code>으로 설정하게 됩니다. </dd> + <dt><code>length</code></dt> + <dd>옵션값. 추출할 문자들의 총 숫자.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p><code>start</code>는 문자 인덱스입니다. 문자열에서 첫 번째 문자의 인덱스는 0이며, 마지막 문자의 인덱스는 문자열 전체 길이에서 1을 뺀 값입니다. <code>substr()</code>는<code> start</code>에서 문자들을 추출을 시작하여 <code>length</code>만큼 문자들을 수집합니다.</p> + +<p>만약 <code>start</code> 값이 양수이고 문자열 전체 길이보다 크거가 같을 경우, <code>substr()</code>은 빈 문자열을 반환합니다. </p> + +<p>만약 <code>start</code>가 음수이면, <code>substr()</code>은 문자열 끝에서 <code>start</code> 숫자만큼 뺀 곳에서 시작하게 됩니다. 만약 <code>start</code>가 음수이고 절대값이 문자열 전체보다 크다면, <code>substr()</code>은 문자열의 0 인덱스부터 시작하게 됩니다. (주의: <code>start</code>의 음수값은 Microsoft JScript에서는 위의 설명과 같이 동작하지 않습니다.)</p> + +<p>만약 <code>length</code>가 0 혹은 음수이면, <code>substr()</code>은 빈 문자열을 반환합니다. 만약 <code>length</code>가 생략되면, <code>substr()</code>은 문자열의 끝까지 추출하여 반환합니다. </p> + +<h2 id="예제">예제</h2> + +<h3 id="substr()_사용하기"><code>substr()</code> 사용하기</h3> + +<pre class="brush: js">var str = 'abcdefghij'; + +console.log('(1, 2): ' + str.substr(1, 2)); // '(1, 2): bc' +console.log('(-3, 2): ' + str.substr(-3, 2)); // '(-3, 2): hi' +console.log('(-3): ' + str.substr(-3)); // '(-3): hij' +console.log('(1): ' + str.substr(1)); // '(1): bcdefghij' +console.log('(-20, 2): ' + str.substr(-20, 2)); // '(-20, 2): ab' +console.log('(20, 2): ' + str.substr(20, 2)); // '(20, 2): ' +</pre> + +<h2 id="폴리필">폴리필</h2> + +<p>Microsoft의 JScript는 시작 인덱스에서 음수값을 지원하지 않습니다. 만약 여러분이 이렇게 동작하길 원한다면, 아래 코드를 사용하여 해결할 수 있습니다: </p> + +<pre class="brush: js">// only run when the substr() function is broken +if ('ab'.substr(-1) != 'b') { + /** + * Get the substring of a string + * @param {integer} start where to start the substring + * @param {integer} length how many characters to return + * @return {string} + */ + String.prototype.substr = function(substr) { + return function(start, length) { + // call the original method + return substr.call(this, + // did we get a negative start, calculate how much it is from the beginning of the string + // adjust the start parameter for negative value + start < 0 ? this.length + start : start, + length) + } + }(String.prototype.substr); +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Defined in the (informative) Compatibility Annex B. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-B.2.3', 'String.prototype.substr')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Defined in the (informative) Compatibility Annex B</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.substr', 'String.prototype.substr')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.substr', 'String.prototype.substr')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.String.substr")}}</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("String.prototype.slice()")}}</li> + <li>{{jsxref("String.prototype.substring()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/substring/index.html b/files/ko/web/javascript/reference/global_objects/string/substring/index.html new file mode 100644 index 0000000000..91d13974c9 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/substring/index.html @@ -0,0 +1,190 @@ +--- +title: String.prototype.substring() +slug: Web/JavaScript/Reference/Global_Objects/String/substring +translation_of: Web/JavaScript/Reference/Global_Objects/String/substring +--- +<div>{{JSRef}}</div> + +<p><strong><code>substring()</code></strong><font><font>메소드는 string 객체의 시작 인덱스로 부터 종료 인덱스 전 까지 문자열의 부분 문자열을 반환합니다. </font></font></p> + +<div>{{EmbedInteractiveExample("pages/js/string-substring.html")}}</div> + + + +<h2 id="사용방법">사용방법 </h2> + +<pre class="syntaxbox"><code><var>str</var>.substring(<var>indexStart</var>[, <var>indexEnd</var>])</code></pre> + +<h3 id="인자값">인자값</h3> + +<dl> + <dt><code><var>indexStart</var></code></dt> + <dd>반환문자열의 시작 인덱스 </dd> + <dt> </dt> + <dt><code><var>indexEnd</var></code></dt> + <dd>옵션. 반환문자열의 마지막 인덱스 (포함하지 않음.)</dd> +</dl> + +<h3 id="반환값">반환값</h3> + +<p>기존문자열의 부분 문자열을 반환합니다. </p> + +<h2 id="Description">Description</h2> + +<p><code>substring()</code> 메서드는 <code><var>indexStart</var></code> 부터 문자를 추출하지만 <code><var>indexEnd</var></code> 가 포함되지 않아도 괜찮습니다. 특징은 아래와 같습니다.</p> + +<ul> + <li>만약 <code><var>indexEnd</var></code> 가 생략된 경우, <code>substring()</code> 문자열의 끝까지 모든 문자를 추출합니다.</li> + <li>만약 <code><var>indexStart</var></code> 가 <code><var>indexEnd</var></code>와 같을 경우, <code>substring()</code> 빈 문자열을 반환합니다.</li> + <li>만약 <code><var>indexStart</var></code> 가 <code><var>indexEnd</var></code>보다 큰 경우, <code>substring()</code> 메서드는 마치 두 개의 인자를 바꾼 듯 작동하게 됩니다. 아래 예제를 보세요.</li> +</ul> + +<p>0보다 작은 인자 값을 가지는 경우에는 0으로, <code>stringName.length</code> 보다 큰 인자 값을 가지는 경우, <code>stringName.length</code> 로 처리됩니다. {{jsxref("NaN")}} 값은 0으로 처리됩니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_substring()">Using <code>substring()</code></h3> + +<p>The following example uses <code>substring()</code> to display characters from the string <code>'Mozilla'</code>:</p> + +<pre class="brush: js">var anyString = 'Mozilla'; + +// Displays 'M' +console.log(anyString.substring(0, 1)); +console.log(anyString.substring(1, 0)); + +// Displays 'Mozill' +console.log(anyString.substring(0, 6)); + +// Displays 'lla' +console.log(anyString.substring(4)); +console.log(anyString.substring(4, 7)); +console.log(anyString.substring(7, 4)); + +// Displays 'Mozilla' +console.log(anyString.substring(0, 7)); +console.log(anyString.substring(0, 10)); +</pre> + +<h3 id="Using_substring()_with_length_property">Using <code>substring()</code> with <code>length</code> property</h3> + +<p>The following example uses the <code>substring()</code> method and {{jsxref("String.length", "length")}} property to extract the last characters of a particular string. This method may be easier to remember, given that you don't need to know the starting and ending indices as you would in the above examples.</p> + +<pre class="brush: js">// Displays 'illa' the last 4 characters +var anyString = 'Mozilla'; +var anyString4 = anyString.substring(anyString.length - 4); +console.log(anyString4); + +// Displays 'zilla' the last 5 characters +var anyString = 'Mozilla'; +var anyString5 = anyString.substring(anyString.length - 5); +console.log(anyString5); +</pre> + +<h3 id="The_difference_between_substring()_and_substr()">The difference between <code>substring()</code> and <code>substr()</code></h3> + +<p>There's a subtle difference between the <code>substring()</code> and {{jsxref("String.substr", "substr()")}} methods, so you should be careful not to get them confused.</p> + +<p>The arguments of <code>substring()</code> represent the starting and ending indexes, while the arguments of <code>substr()</code> represent the starting index and the number of characters to include in the returned string.</p> + +<pre class="brush: js">var text = 'Mozilla'; +console.log(text.substring(2,5)); // => "zil" +console.log(text.substr(2,3)); // => "zil"</pre> + +<h3 id="Differences_between_substring()_and_slice()">Differences between <code>substring()</code> and <code>slice()</code></h3> + +<p>The <code>substring()</code> and {{jsxref("String.slice", "slice()")}} methods are almost identical, but there are a couple of subtle differences between the two, especially in the way negative arguments are dealt with.</p> + +<p>The <code>substring()</code> method swaps its two arguments if <code><var>indexStart</var></code> is greater than <code><var>indexEnd</var></code>, meaning that a string is still returned. The {{jsxref("String.slice", "slice()")}} method returns an empty string if this is the case.</p> + +<pre class="brush: js">var text = 'Mozilla'; +console.log(text.substring(5, 2)); // => "zil" +console.log(text.slice(5, 2)); // => "" +</pre> + +<p>If either or both of the arguments are negative or <code>NaN</code>, the <code>substring()</code> method treats them as if they were <code>0</code>.</p> + +<pre class="brush: js">console.log(text.substring(-5, 2)); // => "Mo" +console.log(text.substring(-5, -2)); // => "" +</pre> + +<p><code>slice()</code> also treats <code>NaN</code> arguments as <code>0</code>, but when it is given negative values it counts backwards from the end of the string to find the indexes.</p> + +<pre class="brush: js">console.log(text.slice(-5, 2)); // => "" +console.log(text.slice(-5, -2)); // => "zil" +</pre> + +<p>See the {{jsxref("String.slice", "slice()")}} page for more examples with negative numbers.</p> + +<h3 id="Replacing_a_substring_within_a_string">Replacing a substring within a string</h3> + +<p>The following example replaces a substring within a string. It will replace both individual characters and substrings. The function call at the end of the example changes the string <code>Brave New World</code> to <code>Brave New Web</code>.</p> + +<pre class="brush: js">// Replaces oldS with newS in the string fullS +function replaceString(oldS, newS, fullS) { + for (var i = 0; i < fullS.length; ++i) { + if (fullS.substring(i, i + oldS.length) == oldS) { + fullS = fullS.substring(0, i) + newS + fullS.substring(i + oldS.length, fullS.length); + } + } + return fullS; +} + +replaceString('World', 'Web', 'Brave New World'); +</pre> + +<p>Note that this can result in an infinite loop if <code>oldS</code> is itself a substring of <code>newS</code> — for example, if you attempted to replace 'World' with 'OtherWorld' here. A better method for replacing strings is as follows:</p> + +<pre class="brush: js">function replaceString(oldS, newS, fullS) { + return fullS.split(oldS).join(newS); +} +</pre> + +<p>The code above serves as an example for substring operations. If you need to replace substrings, most of the time you will want to use {{jsxref("String.prototype.replace()")}}.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.substring', 'String.prototype.substring')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.substring', 'String.prototype.substring')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.15', 'String.prototype.substring')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Implemented in JavaScript 1.0.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.substring")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("String.prototype.substr()")}} {{deprecated_inline}}</li> + <li>{{jsxref("String.prototype.slice()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/tolowercase/index.html b/files/ko/web/javascript/reference/global_objects/string/tolowercase/index.html new file mode 100644 index 0000000000..d91e48729f --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/tolowercase/index.html @@ -0,0 +1,83 @@ +--- +title: String.prototype.toLowerCase() +slug: Web/JavaScript/Reference/Global_Objects/String/toLowerCase +tags: + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/toLowerCase +--- +<div>{{JSRef}}</div> + +<div><strong><code>toLowerCase()</code></strong> 메서드는 문자열을 소문자로 변환해 반환합니다.</div> + +<div> </div> + +<div>{{EmbedInteractiveExample("pages/js/string-tolowercase.html")}}</div> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>str</var>.toLowerCase()</code></pre> + +<h3 id="반환값">반환값</h3> + +<p>호출 문자열을 소문자로 변환한 새로운 문자열</p> + +<h2 id="설명">설명</h2> + +<p><code>toLowerCase()</code> 메서드는 호출 문자열을 소문자로 변환해 반환합니다. <code>toLowerCase()</code> 는 원래의 <code>str</code>에 영향을 주지 않습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="toLowerCase()"> <code>toLowerCase()</code></h3> + +<pre class="brush: js">console.log('ALPHABET'.toLowerCase()); // 'alphabet' +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">표준</th> + <th scope="col">상태</th> + <th scope="col">비고</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.16', 'String.prototype.toLowerCase')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.tolowercase', 'String.prototype.toLowerCase')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.tolowercase', 'String.prototype.toLowerCase')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.toLowerCase")}}</p> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("String.prototype.toLocaleLowerCase()")}}</li> + <li>{{jsxref("String.prototype.toLocaleUpperCase()")}}</li> + <li>{{jsxref("String.prototype.toUpperCase()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/tosource/index.html b/files/ko/web/javascript/reference/global_objects/string/tosource/index.html new file mode 100644 index 0000000000..d08a2a816a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/tosource/index.html @@ -0,0 +1,49 @@ +--- +title: String.prototype.toSource() +slug: Web/JavaScript/Reference/Global_Objects/String/toSource +translation_of: Web/JavaScript/Reference/Global_Objects/String/toSource +--- +<div>{{JSRef}} {{non-standard_header}}</div> + +<p>The <strong><code>toSource()</code></strong> method returns a string representing the source code of the object.</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox"><code>String.toSource() +<var>str</var>.toSource() +</code></pre> + +<h3 id="리턴_값">리턴 값</h3> + +<p>호출한 객체의 소스코드가 <code>string</code>으로 보여집니다.</p> + +<h2 id="설명">설명</h2> + +<p><code>toSource()</code> 메소드는 다음 값을 리턴:</p> + +<p>For the built-in {{jsxref("String")}} object, <code>toSource()</code> returns the following string indicating that the source code is not available:</p> + +<pre class="brush: js">function String() { + [native code] +} +</pre> + +<p>For instances of {{jsxref("String")}} or string literals, <code>toSource()</code> returns a string representing the source code.</p> + +<p>This method is usually called internally by JavaScript and not explicitly in code.</p> + +<h2 id="Specifications">Specifications</h2> + +<p>Not part of any standard. Implemented in JavaScript 1.3.</p> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.toSource")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Object.prototype.toSource()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/tostring/index.html b/files/ko/web/javascript/reference/global_objects/string/tostring/index.html new file mode 100644 index 0000000000..999d5c0c74 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/tostring/index.html @@ -0,0 +1,59 @@ +--- +title: String.prototype.toString() +slug: Web/JavaScript/Reference/Global_Objects/String/toString +translation_of: Web/JavaScript/Reference/Global_Objects/String/toString +--- +<div><font><font>{{JSRef}}</font></font></div> + +<p><font><font>이 </font></font><strong><code>toString()</code></strong><font><font>메소드는 지정된 객체를 나타내는 문자열을 반환합니다.</font></font></p> + +<div><font><font>{{EmbedInteractiveExample ( "pages / js / string-tostring.html")}}</font></font></div> + +<h2 id="통사론"><font><font>통사론</font></font></h2> + +<pre class="syntaxbox"><code><var>str</var>.toString()</code></pre> + +<h3 id="반환_값"><font><font>반환 값</font></font></h3> + +<p><font><font>호출 객체를 나타내는 문자열</font></font></p> + +<h2 id="기술"><font><font>기술</font></font></h2> + +<p><font><font>{{jsxref ( "String")}} 오브젝트 </font></font><code>toString()</code><font><font>는 {{jsxref ( "Object")}} 오브젝트 </font><font>의 </font><font>메소드를 </font><font>대체 </font><font>합니다. </font><font>{{jsxref ( "Object.prototype.toString ()")}}을 상속하지 않습니다. </font><font>{{jsxref ( "String")}} 오브젝트의 경우 </font></font><code>toString()</code><font><font>메소드는 </font><font>오브젝트 </font><font>의 문자열 표시를 리턴하며 {{jsxref ( "String.prototype.valueOf ()")}} 메소드와 동일합니다.</font></font></p> + +<h2 id="예"><font><font>예</font></font></h2> + +<h3 id="사용_toString"><font><font>사용 </font></font><code>toString()</code></h3> + +<p><font><font>다음 예제는 {{jsxref ( "String")}} 오브젝트의 문자열 값을 표시합니다.</font></font></p> + +<pre class="brush: js"><font><font>var x = new String ( 'Hello world');</font></font> +<font><font> +console.log (x.toString ()); </font><font>// 'Hello world'를 기록합니다.</font></font> +</pre> + +<h2 id="명세서"><font><font>명세서</font></font></h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col"><font><font>사양</font></font></th> + </tr> + <tr> + <td><font><font>{{SpecName ( 'ESDraft', '# sec-string.prototype.tostring', 'String.prototype.toString')}}}</font></font></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성"><font><font>브라우저 호환성</font></font></h2> + +<p class="hidden"><font><font>이 페이지의 호환성 표는 구조화 된 데이터에서 생성됩니다. </font><font>데이터에 기여하려면 </font></font><a href="https://github.com/mdn/browser-compat-data"><font><font>https://github.com/mdn/browser-compat-data</font></font></a><font><font> 를 확인하고 </font><font>풀 요청을 보내주십시오.</font></font></p> + +<p><font><font>{{Compat ( "javascript.builtins.String.toString")}}</font></font></p> + +<h2 id="또한보십시오"><font><font>또한보십시오</font></font></h2> + +<ul> + <li><font><font>{{jsxref ( "Object.prototype.toSource ()")}}</font></font></li> + <li><font><font>{{jsxref ( "String.prototype.valueOf ()")}}</font></font></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/touppercase/index.html b/files/ko/web/javascript/reference/global_objects/string/touppercase/index.html new file mode 100644 index 0000000000..f6a0c8f05c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/touppercase/index.html @@ -0,0 +1,105 @@ +--- +title: String.prototype.toUpperCase() +slug: Web/JavaScript/Reference/Global_Objects/String/toUpperCase +tags: + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/toUpperCase +--- +<div>{{JSRef}}</div> + +<p><strong><code>toUpperCase()</code></strong> 메서드는 문자열을 대문자로 변환해 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/string-touppercase.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>str</var>.toUpperCase()</pre> + +<h3 id="반환_값">반환 값</h3> + +<p>대문자로 변환한 새로운 문자열.</p> + +<h3 id="예외">예외</h3> + +<dl> + <dt>{{jsxref("TypeError")}}</dt> + <dd>{{jsxref("Function.prototype.call()")}} 등을 사용해 {{jsxref("null")}}이나 {{jsxref("undefined")}}에서 호출 시.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p><code>toUpperCase()</code> 메서드는 문자열을 대문자로 변환한 값을 반환합니다. JavaScript의 문자열은 불변하므로 원본 문자열에는 영향을 주지 않습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="기본_사용법">기본 사용법</h3> + +<pre class="brush: js">console.log('alphabet'.toUpperCase()); // 'ALPHABET'</pre> + +<h3 id="문자열이_아닌_this의_문자열_변환">문자열이 아닌 <code>this</code>의 문자열 변환</h3> + +<p><code>toUpperCase()</code>의 <code>this</code>가 문자열이 아니고, <code>undefined</code>와 <code>null</code>도 아니면 자동으로 문자열로 변환합니다.</p> + +<pre class="brush: js">const a = String.prototype.toUpperCase.call({ + toString: function toString() { + return 'abcdef'; + } +}); + +const b = String.prototype.toUpperCase.call(true); + +// prints out 'ABCDEF TRUE'. +console.log(a, b); +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">비고</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.18', 'String.prototype.toUpperCase')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.touppercase', 'String.prototype.toUpperCase')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.touppercase', 'String.prototype.toUpperCase')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.String.toUpperCase")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("String.prototype.toLocaleLowerCase()")}}</li> + <li>{{jsxref("String.prototype.toLocaleUpperCase()")}}</li> + <li>{{jsxref("String.prototype.toLowerCase()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/trim/index.html b/files/ko/web/javascript/reference/global_objects/string/trim/index.html new file mode 100644 index 0000000000..0f0b71f548 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/trim/index.html @@ -0,0 +1,97 @@ +--- +title: String.prototype.trim() +slug: Web/JavaScript/Reference/Global_Objects/String/Trim +tags: + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/Trim +--- +<div>{{JSRef}}</div> + +<p><strong><code>trim()</code></strong> 메서드는 문자열 양 끝의 공백을 제거합니다. 공백이란 모든 공백문자(space, tab, NBSP 등)와 모든 개행문자(LF, CR 등)를 의미합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/string-trim.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>str</var>.trim()</pre> + +<h3 id="반환_값">반환 값</h3> + +<p>양 끝에서 공백을 제거한 새로운 문자열.</p> + +<h2 id="설명">설명</h2> + +<p><code>trim()</code> 메서드는 양끝의 공백을 제거한 문자열을 반환합니다. <code>trim()</code>은 원본 문자열에는 영향을 주지 않습니다. </p> + +<h2 id="예제">예제</h2> + +<h3 id="trim()_사용"><code>trim()</code> 사용</h3> + +<p>아래의 예제는 소문자 문자열 <code>'foo'</code>를 표시합니다.</p> + +<pre class="brush: js">var orig = ' foo '; +console.log(orig.trim()); // 'foo' + +// 한 쪽의 공백만 제거하는 .trim() 예제 + +var orig = 'foo '; +console.log(orig.trim()); // 'foo' +</pre> + +<h2 id="폴리필">폴리필</h2> + +<p>다른 코드 전에 아래 코드를 실행하면 지원하지 않는 환경에서도 <code>String.trim()</code> 을 사용할 수 있습니다.</p> + +<pre class="brush: js">if (!String.prototype.trim) { + String.prototype.trim = function () { + return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); + }; +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">표준</th> + <th scope="col">상태</th> + <th scope="col">비고</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.20', 'String.prototype.trim')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.8.1.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.trim', 'String.prototype.trim')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.trim', 'String.prototype.trim')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.trim")}}</p> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("String.prototype.trimLeft()")}} {{non-standard_inline}}</li> + <li>{{jsxref("String.prototype.trimRight()")}} {{non-standard_inline}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/valueof/index.html b/files/ko/web/javascript/reference/global_objects/string/valueof/index.html new file mode 100644 index 0000000000..e8e217d615 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/valueof/index.html @@ -0,0 +1,83 @@ +--- +title: String.prototype.valueOf() +slug: Web/JavaScript/Reference/Global_Objects/String/valueOf +tags: + - 메서드 + - 문자열 + - 자바스크립트 + - 참고 + - 프로토타입 +translation_of: Web/JavaScript/Reference/Global_Objects/String/valueOf +--- +<div>{{JSRef}}</div> + +<p><strong><code>valueOf()</code></strong> 메서드는 {{jsxref("String")}} 객체의 원시값을 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/string-valueof.html")}}</div> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>str</var>.valueOf()</code></pre> + +<h3 id="반환_값">반환 값</h3> + +<p>지정된 {{jsxref("String")}} 객체의 원시 값을 나타내는 문자열.</p> + +<h2 id="설명">설명</h2> + +<p>{{jsxref("String")}} 의 <code>valueOf()</code> 메서드는 {{jsxref("String")}} 객체의 원시 값을 문자열 데이터 타입으로 반환 합니다. 이 값은 {{jsxref("String.prototype.toString()")}}.과 동일합니다.</p> + +<p>이 메서드는 보통 자바스크립트에 의해 내부적으로 호출되며, 코드에서 명시적으로 사용하지는 않습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="valueOf_사용"> <code>valueOf()</code> 사용</h3> + +<pre class="brush: js">var x = new String('Hello world'); +console.log(x.valueOf()); // 'Hello world' 가 보여집니다. +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>초기 정의. JavaScript 1.1 에서 구현.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.3', 'String.prototype.valueOf')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.valueof', 'String.prototype.valueOf')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.valueof', 'String.prototype.valueOf')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">이 페이지의 호환성 표는 구조화된 데이터로부터 생성됩니다. 만약 데이터에 기여하고 싶다면, <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> 을 확인하시고 pull 요청을 보내주세요.</p> + +<p>{{Compat("javascript.builtins.String.valueOf")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("String.prototype.toString()")}}</li> + <li>{{jsxref("Object.prototype.valueOf()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/symbol/for/index.html b/files/ko/web/javascript/reference/global_objects/symbol/for/index.html new file mode 100644 index 0000000000..e489deb27d --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/symbol/for/index.html @@ -0,0 +1,150 @@ +--- +title: Symbol.for() +slug: Web/JavaScript/Reference/Global_Objects/Symbol/for +translation_of: Web/JavaScript/Reference/Global_Objects/Symbol/for +--- +<div>{{JSRef}}</div> + +<p><code><strong>Symbol.for(key)</strong></code> 메소드는 runtime-wide 심볼 레지스트리에서 해당 키로 존재하는 심볼을 찾는다. 없으면 전역 심볼 레지시트리에 해당 키로 새로운 심볼을 만들어 준다. </p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox"><var>Symbol.for(key)</var>;</pre> + +<h3 id="파라미터">파라미터</h3> + +<dl> + <dt>key</dt> + <dd>String, 필수. 심볼의 키 (심볼의 설명을 위해서도 쓰인다).</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>해당 키에 해당하는 심볼이 있다면 반환 없으면 새로운 심볼을 만들고 반환한다.</p> + +<h2 id="설명">설명</h2> + +<p><code>Symbol()과는 다르게</code>, the <code>Symbol.for()</code> 함수는 전역 심볼 레지스트리 리스트에 심볼을 만든다. <code>Symbol.for()는 또한 매 호출마다 새로운 심볼을 만들지 않고 현재 레지스트리에 해당 키를 가진 심볼이 있는지 먼저 검사를 한다. 있다면 그 심볼을 반환한다. 만약 키에 해당하는 심볼이 없다면 </code>Symbol.for()는 새로운 전역 심볼을 만들 것이다.</p> + +<h3 id="전역_심볼_레지스트리">전역 심볼 레지스트리 </h3> + +<p>전역심볼 레지스트리는 다음 레코드 구조를 가진 리스트이고 초기 값은 비어 있다:</p> + +<p>전역심볼 레지스트리의 레코드</p> + +<table class="standard-table"> + <tbody> + <tr> + <th>필드 명</th> + <th>값</th> + </tr> + <tr> + <td>[[key]]</td> + <td>심볼을 구분하기 위해 사용되는 문자열 키</td> + </tr> + <tr> + <td>[[symbol]]</td> + <td>전역으로 저장되는 심볼</td> + </tr> + </tbody> +</table> + +<h2 id="예제">예제</h2> + +<pre class="brush: js">Symbol.for('foo'); // 새로운 전역심볼 생성 +Symbol.for('foo'); // 이미 만들어진 심볼을 검색 + +// 전역심볼은 서로 같고, 지역심볼은 아니다. +Symbol.for('bar') === Symbol.for('bar'); // true +Symbol('bar') === Symbol('bar'); // false + +// 키는 설명하는데 쓰이기도 한다. +var sym = Symbol.for('mario'); +sym.toString(); // "Symbol(mario)" +</pre> + +<p>다른 라이브러리의 전역 심볼들과 당신의 전역 심볼간의 키 충돌을 피하기 위해서는 당신 심볼 앞에 prefix를 두는 것이 좋다:</p> + +<pre class="brush: js">Symbol.for('mdn.foo'); +Symbol.for('mdn.bar'); +</pre> + +<h2 id="명세서">명세서</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-symbol.for', 'Symbol.for')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-symbol.for', 'Symbol.for')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatChrome(40) }}</td> + <td>{{ CompatGeckoDesktop("36.0") }}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>10</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{ CompatGeckoMobile("36.0") }}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("Symbol.keyFor()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/symbol/index.html b/files/ko/web/javascript/reference/global_objects/symbol/index.html new file mode 100644 index 0000000000..05b1fdd25b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/symbol/index.html @@ -0,0 +1,233 @@ +--- +title: Symbol +slug: Web/JavaScript/Reference/Global_Objects/Symbol +tags: + - ECMAScript 2015 + - 심볼 + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Global_Objects/Symbol +--- +<div>{{JSRef}}</div> + +<p><code>Symbol()</code> 함수는 <strong>심볼(symbol)</strong> 형식의 값을 반환하는데, 이 심볼은 내장 객체(built-in objects)의 여러 멤버를 가리키는 정적 프로퍼티와 전역 심볼 레지스트리(global symbol registry)를 가리키는 정적 메서드를 가지며, "<code>new Symbol()</code>" 문법을 지원하지 않아 생성자 측면에서는 불완전한 내장 객체 클래스(built-in object class)와 유사합니다.</p> + +<p><code>Symbol()</code>로부터 반환되는 모든 심볼 값은 고유합니다. 심볼 값은 객체 프로퍼티(object properties)에 대한 식별자로 사용될 수 있습니다; 이것이 심볼 데이터 형식의 유일한 목적입니다. 목적과 용례에 대한 더 자세한 설명은 <a href="https://developer.mozilla.org/en-US/docs/Glossary/Symbol">용어집의 심볼 항목(glossary entry for Symbol)</a>에서 볼 수 있습니다.</p> + +<p><strong>심볼(symbol)</strong> 데이터 형은 원시 데이터 형({{Glossary("Primitive", "primitive data type")}})의 일종입니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/symbol-constructor.html")}}</div> + + + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox"><code>Symbol(<em>[description]</em>)</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>description</code> {{optional_inline}}</dt> + <dd>선택적(optional) 문자열. 디버깅에 사용할 수 있는 심볼에 대한 설명(description)으로 심볼 자체에 접근하는 용도로는 사용할 수 없음.</dd> +</dl> + +<h2 id="설명(Description)">설명(Description)</h2> + +<p>새 원시(primitive) 심볼을 생성하려면, 심볼을 설명하는 선택적(optional) 문자열과 함께 <code>Symbol()</code>을 쓰면됩니다.</p> + +<pre class="brush: js">var sym1 = Symbol(); +var sym2 = Symbol("foo"); +var sym3 = Symbol("foo"); +</pre> + +<p>위의 코드는 세 개의 새 심볼을 생성합니다. <code>Symbol("foo")</code>는 "foo"라는 문자열을 심볼로 강제로 변환시키지 않는다는 점에 유의하시기 바랍니다. 해당 코드는 매 번 새로운 심볼을 생성합니다:</p> + +<pre class="brush: js">Symbol("foo") === Symbol("foo"); // false</pre> + +<p>아래 {{jsxref("Operators/new", "new")}} 연산자를 이용한 문법은 {{jsxref("TypeError")}}를 발생시킬 것입니다:</p> + +<pre class="brush: js">var sym = new Symbol(); // TypeError</pre> + +<p>이는 작성자가 새로운 심볼 값 대신 명시적으로 심볼 래퍼 객체(<code>Symbol</code> wrapper object)를 생성할 수 없게 합니다. 일반적으로 원시 데이터 형에 대한 명시적인 래퍼 객체 생성(예를 들어, <code>new Boolean</code>, <code>new String</code> 또는 <code>new Number</code>와 같은)이 가능하다는 점에 비춰보면 의외일 수 있습니다.</p> + +<p>꼭 심볼 래퍼 객체를 생성하고 싶다면, <code>Object()</code> 함수를 이용할 수 있습니다.</p> + +<pre class="brush: js">var sym = Symbol("foo"); +typeof sym; // "symbol" +var symObj = Object(sym); +typeof symObj; // "object" +</pre> + +<h3 id="전역_심볼_레지스트리_내_공유_심볼">전역 심볼 레지스트리 내 공유 심볼</h3> + +<p><code>Symbol()</code> 함수를 사용한 위의 문법은 코드베이스(codebase) 전체에서 사용 가능한 전역 심볼을 생성하는 것은 아닙니다. 파일 간(across files), 또는 램(realms, 각각이 자체의 전역 범위(scope)를 가지는) 간에도 사용할 수 있는 심볼을 생성하기 위해서는, {{jsxref("Symbol.for()")}}와 {{jsxref("Symbol.keyFor()")}} 메서드를 이용해 전역 심볼 레지스트리에 심볼을 설정하거나 추출해야 합니다.</p> + +<h3 id="객체에서_심볼_속성(symbol_properties)_찾기">객체에서 심볼 속성(symbol properties) 찾기</h3> + +<p>{{jsxref("Object.getOwnPropertySymbols()")}} 메서드는 심볼의 배열을 반환하여 주어진 객체의 심볼 속성을 찾을 수 있게 해줍니다. 모든 객체는 스스로에 대한 심볼 속성이 없는 상태로 초기화되기 때문에 해당 객체에 심볼 속성을 설정하기 전까지는 빈 배열을 반환한다는 점에 유의하시기 바랍니다.</p> + +<h2 id="속성(properties)">속성(properties)</h2> + +<dl> + <dt><code>Symbol.length</code></dt> + <dd>값이 0인 길이 속성</dd> + <dt>{{jsxref("Symbol.prototype")}}</dt> + <dd><code>Symbol</code> 생성자의 프로토타입을 나타냄.</dd> +</dl> + +<h3 id="잘_알려진_심볼들">잘 알려진 심볼들</h3> + +<p>여러분이 정의하는 심볼 외에, 자바스크립트는 ECMAScript 5와 그 이전 버전에서는 개발자에게 제공되지 않았던 언어 내부의 동작을 나타내는 내장(built-in) 심볼을 몇 가지 가지고 있습니다. 다음 속성을 이용해 이들 심볼에 접근할 수 있습니다:</p> + +<h4 id="반복(iteration)_심볼">반복(iteration) 심볼</h4> + +<dl> + <dt>{{jsxref("Symbol.iterator")}}</dt> + <dd>객체의 기본 반복자(default iterator)를 반환하는 메서드.<code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a></code>에서 사용됨.</dd> + <dt>{{jsxref("Symbol.asyncIterator")}} {{experimental_inline}}</dt> + <dd>객체의 기본 비동기 반복자(default AsyncIterator)를 반환하는 메서드. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await-of"><code>for await of</code></a>에서 사용됨.</dd> +</dl> + +<h4 id="정규표현식_심볼">정규표현식 심볼</h4> + +<dl> + <dt>{{jsxref("Symbol.match")}}</dt> + <dd>문자열과 일치하는(match) 메서드로 객체를 정규표현식으로 사용할 수 있는지 확인하는데도 사용. {{jsxref("String.prototype.match()")}}에서 사용됨.</dd> + <dt>{{jsxref("Symbol.replace")}}</dt> + <dd>문자열 중 일치하는 문자열 일부를 대체하는 메소드. {{jsxref("String.prototype.replace()")}}에서 사용됨.</dd> + <dt>{{jsxref("Symbol.search")}}</dt> + <dd>문자열에서 정규표현식과 일치하는 인덱스(index)를 반환하는 메서드. {{jsxref("String.prototype.search()")}}에서 사용됨.</dd> + <dt>{{jsxref("Symbol.split")}}</dt> + <dd>정규표현식과 일치하는 인덱스에서 문자열을 나누는 메서드. {{jsxref("String.prototype.split()")}}에서 사용됨.</dd> +</dl> + +<h4 id="그_외_심볼들">그 외 심볼들</h4> + +<dl> + <dt>{{jsxref("Symbol.hasInstance")}}</dt> + <dd>생성자 객체(constructor object)가 어떤 객체를 자신의 인스턴스로 인식하는지를 확인하는데 사용하는 메소드. {{jsxref("Operators/instanceof", "instanceof")}}에서 사용됨.</dd> + <dt>{{jsxref("Symbol.isConcatSpreadable")}}</dt> + <dd>객체가 자신의 배열 요소를 직렬로(be flattened) 나타낼 수 있는지 여부를 나타내는 부울 값. {{jsxref("Array.prototype.concat()")}}에서 사용됨.</dd> + <dt>{{jsxref("Symbol.unscopables")}}</dt> + <dd>자신의 속성명 또는 상속된 속성명이 연관 객체(the associated objet)의 <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with">with</a></code> 환경 바인딩(envorinment bindings)에서 제외된 객체의 값 (An object value of whose own and inherited property names are excluded from the <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with">with</a></code> environment bindings of the associated object).</dd> + <dt>{{jsxref("Symbol.species")}}</dt> + <dd>파생(derived) 객체를 생성하는데 사용되는 생성자 함수.</dd> + <dt>{{jsxref("Symbol.toPrimitive")}}</dt> + <dd>객체를 원시형(primitive) 값으로 변환하는 메서드.</dd> + <dt>{{jsxref("Symbol.toStringTag")}}</dt> + <dd>객체에 대한 기본 설명(description)으로 사용되는 문자열 값. {{jsxref("Object.prototype.toString()")}}에서 사용됨.</dd> +</dl> + +<h2 id="메서드">메서드</h2> + +<dl> + <dt>{{jsxref("Symbol.for()", "Symbol.for(key)")}}</dt> + <dd>주어진 키(key)로 현재 존재하는 심볼을 검색하고 찾으면 반환합니다. 존재하지 않으면 주어진 키로 전역 심볼 레지스트리에 새로운 심볼을 생성하고 그 심볼을 반환합니다.</dd> + <dt>{{jsxref("Symbol.keyFor", "Symbol.keyFor(sym)")}}</dt> + <dd>전역 심볼 레지스트리로부터 주어진 심볼에 대한 공유 심볼 키(shared symbol key)를 추출합니다.</dd> +</dl> + +<h2 id="심볼(Symbol)_프로토타입"><code>심볼(Symbol)</code> 프로토타입</h2> + +<p>모든 심볼은 {{jsxref("Symbol.prototype")}}을 상속합니다.</p> + +<h3 id="속성(properties)_2">속성(properties)</h3> + +<p>{{page('ko/Web/JavaScript/Reference/Global_Objects/Symbol/prototype','Properties')}}</p> + +<h3 id="메서드_2">메서드</h3> + +<p>{{page('ko/Web/JavaScript/Reference/Global_Objects/Symbol/prototype','Methods')}}</p> + +<h2 id="예제">예제</h2> + +<h3 id="심볼에_typeof_연산자_사용">심볼에 <code>typeof</code> 연산자 사용</h3> + +<p>{{jsxref("Operators/typeof", "typeof")}} 연산자를 이용해 심볼인지 알 수 있습니다.</p> + +<pre class="brush: js">typeof Symbol() === 'symbol' +typeof Symbol('foo') === 'symbol' +typeof Symbol.iterator === 'symbol' +</pre> + +<h3 id="심볼의_형_변환(type_conversions)">심볼의 형 변환(type conversions)</h3> + +<p>심볼의 형 변환(type conversion)할 때 유의해야 할 사항</p> + +<ul> + <li>심볼을 숫자(number)로 변환하고자 할 때, {{jsxref("TypeError")}}가 발생합니다.<br> + (e.g. <code>+sym</code> or <code>sym | 0</code>).</li> + <li>느슨한 동등(loose equality) 연산자를 사용할 때, <code>Object(sym) == sym</code>는 <code>true</code>를 반환합니다.</li> + <li><code>Symbol("foo") + "bar"</code>는 {{jsxref("TypeError")}} (심볼을 문자열로 변환할 수 없는)를 발생시킵니다. 이는 예를 들자면, 심볼에서 암묵적으로 새로운 문자열 속성명을 생성하지 못하게 합니다.</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#String_conversion">"보다 안전한" String(sym) 변환("safer" <code>String(sym)</code> conversion)</a>은 심볼에 대해 {{jsxref("Symbol.prototype.toString()")}}을 호출하는 것과 같이 동작하지만, <code>new String(sym)</code>는 오류(error)를 발생시키는 것을 유의하시기 바랍니다.</li> +</ul> + +<h3 id="심볼과_for...in_반복문">심볼과 <code>for...in</code> 반복문</h3> + +<p>심볼은 <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in"><code>for...in</code></a> 반복문 내에서 하나씩 열거할 수 없습니다. 더구나, {{jsxref("Object.getOwnPropertyNames()")}}는 심볼 객체 속성(symbol object properties)을 반환하지 않습니다. 하지만, {{jsxref("Object.getOwnPropertySymbols()")}}를 이용해 이것들을 가져올 수 있습니다.</p> + +<pre class="brush: js">var obj = {}; + +obj[Symbol("a")] = "a"; +obj[Symbol.for("b")] = "b"; +obj["c"] = "c"; +obj.d = "d"; + +for (var i in obj) { + console.log(i); // logs "c" and "d" +}</pre> + +<h3 id="심볼과_JSON.stringify()">심볼과 <code>JSON.stringify()</code></h3> + +<p>심볼을 키로 사용한 속성(symbol-keyed properties)은 <code>JSON.stringify()</code>을 사용할 때 완전히 무시됩니다:</p> + +<pre class="brush: js">JSON.stringify({[Symbol("foo")]: "foo"}); +// '{}'</pre> + +<p>더 자세한 것은 {{jsxref("JSON.stringify()")}}를 참조하시기 바랍니다.</p> + +<h3 id="속성_키로서의_심볼_래퍼_객체(symbol_wrapper_object)">속성 키로서의 심볼 래퍼 객체(symbol wrapper object)</h3> + +<p>심볼 래퍼 객체를 속성 키로 사용하면, 이 객체는 래핑된 심볼로 강제 변환됩니다(When a Symbol wrapper object is used as a property key, this object will be coerced to its wrapped symbol):</p> + +<pre class="brush: js">var sym = Symbol("foo"); +var obj = {[sym]: 1}; +obj[sym]; // 1 +obj[Object(sym)]; // still 1 +</pre> + +<h2 id="명세서">명세서</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-symbol-objects', 'Symbol')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-symbol-objects', 'Symbol')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.Symbol")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Glossary/Symbol">Glossary: Symbol data type</a></li> + <li>{{jsxref("Operators/typeof", "typeof")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Data_structures">Data types and data structures</a></li> + <li><a href="https://hacks.mozilla.org/2015/06/es6-in-depth-symbols/">"ES6 In Depth: Symbols" on hacks.mozilla.org</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/symbol/iterator/index.html b/files/ko/web/javascript/reference/global_objects/symbol/iterator/index.html new file mode 100644 index 0000000000..820e63d1cb --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/symbol/iterator/index.html @@ -0,0 +1,95 @@ +--- +title: Symbol.iterator +slug: Web/JavaScript/Reference/Global_Objects/Symbol/iterator +translation_of: Web/JavaScript/Reference/Global_Objects/Symbol/iterator +--- +<div>{{JSRef}}</div> + +<p>잘 알려진 <code><strong>Symbol.iterator</strong></code> 심볼은 객체에 대응하는 기본 이터레이터를 지정합니다. <a href="/docs/Web/JavaScript/Reference/Statements/for...of"><code>for...of</code></a>와 같이 사용됩니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/symbol-iterator.html")}}</div> + + + +<div>{{js_property_attributes(0,0,0)}}</div> + +<h2 id="설명">설명</h2> + +<p>(<code>for..of</code> 루프의 시작부분과 같이) 객체가 반환될 필요가 있을때는 언제든지<code>@@iterator</code> 메서드는 인수 없이도 호출 할 수 있습니다. 반환된 <strong>iterator</strong>는 반복할 값을 취득하기 위해 사용됩니다.</p> + +<p>{{jsxref("Object")}}와 같이 반복동작을 내장하고 있는 형태도 있지만 그렇지 않은 경우도 있습니다. <code>@@iterator</code> 메서드를 가지고 있는 내장형 타입은 아래와 같습니다.</p> + +<ul> + <li>{{jsxref("Array.@@iterator", "Array.prototype[@@iterator]()")}}</li> + <li>{{jsxref("TypedArray.@@iterator", "TypedArray.prototype[@@iterator]()")}}</li> + <li>{{jsxref("String.@@iterator", "String.prototype[@@iterator]()")}}</li> + <li>{{jsxref("Map.@@iterator", "Map.prototype[@@iterator]()")}}</li> + <li>{{jsxref("Set.@@iterator", "Set.prototype[@@iterator]()")}}</li> +</ul> + +<p>상세한 내용은 <a href="/ko/docs/Web/JavaScript/Reference/Iteration_protocols">반복처리 프로토콜</a>도 확인 해 주시기 바랍니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="유저_정의_이터레이터">유저 정의 이터레이터</h3> + +<p>앞에서 기술한 바와 같이 독자적으로 이터레이터를 만드는 것이 가능합니다.</p> + +<pre class="brush: js">var myIterable = {} +myIterable[Symbol.iterator] = function* () { + yield 1; + yield 2; + yield 3; +}; +[...myIterable] // [1, 2, 3] +</pre> + +<h3 id="비정형_이터레이터">비정형 이터레이터</h3> + +<p>iterable의 <code>@@iterator</code> 메서드가 이터레이터 객체를 반환하지 않는 경우 비정형 이터레이터입니다. 이와 같이 사용하는 경우 실행시 예외 혹은 예상치 못한 버그를 발생할 가능성이 있습니다.</p> + +<pre class="brush: js">var nonWellFormedIterable = {} +nonWellFormedIterable[Symbol.iterator] = () => 1 +[...nonWellFormedIterable] // TypeError: [] is not a function +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상황</th> + <th scope="col">코멘트</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-symbol.iterator', 'Symbol.iterator')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>초기 정의</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-symbol.iterator', 'Symbol.iterator')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div class="hidden"> +<p>The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> +</div> + +<p>{{Compat("javascript.builtins.Symbol.iterator")}}</p> + +<h2 id="관련_정보">관련 정보</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Reference/Iteration_protocols">반복처리 프로토콜</a></li> + <li>{{jsxref("Array.@@iterator", "Array.prototype[@@iterator]()")}}</li> + <li>{{jsxref("TypedArray.@@iterator", "TypedArray.prototype[@@iterator]()")}}</li> + <li>{{jsxref("String.@@iterator", "String.prototype[@@iterator]()")}}</li> + <li>{{jsxref("Map.@@iterator", "Map.prototype[@@iterator]()")}}</li> + <li>{{jsxref("Set.@@iterator", "Set.prototype[@@iterator]()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/syntaxerror/index.html b/files/ko/web/javascript/reference/global_objects/syntaxerror/index.html new file mode 100644 index 0000000000..84ccc26908 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/syntaxerror/index.html @@ -0,0 +1,123 @@ +--- +title: SyntaxError +slug: Web/JavaScript/Reference/Global_Objects/SyntaxError +translation_of: Web/JavaScript/Reference/Global_Objects/SyntaxError +--- +<div>{{JSRef}}</div> + +<p><code><strong>SyntaxError</strong></code> 객체는 문법적으로 유효하지 않은 코드를 해석하려고 시도할 때 발생하는 오류를 표현합니다.</p> + +<h2 id="설명">설명</h2> + +<p><code>SyntaxError</code>는 JavaScript 엔진이 코드를 분석할 때 문법을 준수하지 않은 코드를 만나면 발생합니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code>new SyntaxError([<var>message</var>[, <var>fileName</var>[, <var>lineNumber</var>]]])</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>message</code><strong> {{optional_inline}}</strong></dt> + <dd>오류에 대한 설명.</dd> + <dt><code>fileName</code><strong> {{optional_inline}}</strong> {{non-standard_inline}}</dt> + <dd>예외가 발생한 코드를 담고 있는 파일의 이름.</dd> + <dt><code>lineNumber</code><strong> {{optional_inline}}</strong> {{non-standard_inline}}</dt> + <dd>예외가 발생한 코드의 라인 넘버.</dd> +</dl> + +<h2 id="속성">속성</h2> + +<dl> + <dt>{{jsxref("SyntaxError.prototype")}}</dt> + <dd><code>SyntaxError</code> 객체에 속성을 추가할 수 있도록 해주고 있습니다.</dd> +</dl> + +<h2 id="메서드">메서드</h2> + +<p>전역(global) <code>SyntaxError</code> 는 고유의 메소드를 가지고 있지 않지만, prototype chain을 통해 몇몇의 메소드를 상속 받습니다.</p> + +<h2 id="SyntaxError_인스턴스"><code>SyntaxError</code> 인스턴스</h2> + +<h3 id="속성_2">속성</h3> + +<div>{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError/prototype', 'Properties')}}</div> + +<h3 id="메소드">메소드</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError/prototype', 'Methods')}}</div> + +<h2 id="예제">예제</h2> + +<h3 id="SyntaxError_잡기"><code>SyntaxError</code> 잡기</h3> + +<pre class="brush: js">try { + eval('hoo bar'); +} catch (e) { + console.log(e instanceof SyntaxError); // true + console.log(e.message); // "missing ; before statement" + console.log(e.name); // "SyntaxError" + console.log(e.fileName); // "Scratchpad/1" + console.log(e.lineNumber); // 1 + console.log(e.columnNumber); // 4 + console.log(e.stack); // "@Scratchpad/1:2:3\n" +} +</pre> + +<h3 id="SyntaxError_생성하기"><code>SyntaxError</code> 생성하기</h3> + +<pre class="brush: js">try { + throw new SyntaxError('Hello', 'someFile.js', 10); +} catch (e) { + console.log(e instanceof SyntaxError); // true + console.log(e.message); // "Hello" + console.log(e.name); // "SyntaxError" + console.log(e.fileName); // "someFile.js" + console.log(e.lineNumber); // 10 + console.log(e.columnNumber); // 0 + console.log(e.stack); // "@Scratchpad/2:11:9\n" +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.11.6.4', 'SyntaxError')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-native-error-types-used-in-this-standard-syntaxerror', 'SyntaxError')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-native-error-types-used-in-this-standard-syntaxerror', 'SyntaxError')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.SyntaxError")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Error")}}</li> + <li>{{jsxref("SyntaxError.prototype")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/syntaxerror/prototype/index.html b/files/ko/web/javascript/reference/global_objects/syntaxerror/prototype/index.html new file mode 100644 index 0000000000..5fda6d61ad --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/syntaxerror/prototype/index.html @@ -0,0 +1,126 @@ +--- +title: SyntaxError.prototype +slug: Web/JavaScript/Reference/Global_Objects/SyntaxError/prototype +translation_of: Web/JavaScript/Reference/Global_Objects/SyntaxError +--- +<div>{{JSRef}}</div> + +<p><code><strong>SyntaxError.prototype </strong></code>속성은 {{jsxref("SyntaxError")}} 객체의 생성자 프로토타입을 표현합니다.</p> + +<h2 id="설명">설명</h2> + +<p>모든 {{jsxref("SyntaxError")}} 인스턴스는 <code>SyntaxError.prototype </code>객체로부터<code> </code>상속 받습니다. 또한, 속성이나 메소드를 추가할 때 모든 인스턴스에 프로토타입을 사용 할 수 있습니다.</p> + +<h2 id="속성">속성</h2> + +<dl> + <dt><code>SyntaxError.prototype.constructor</code></dt> + <dd>인스턴스의 프로토타입을 생성하는 함수를 명시합니다.</dd> + <dt>{{jsxref("Error.prototype.message", "SyntaxError.prototype.message")}}</dt> + <dd>에러 메시지. 비록 ECMA-262는 {{jsxref("SyntaxError")}} 가 고유의 <code>message</code> 속성을 제공해야 한다고 명시하고 있지만, <a href="/en-US/docs/Mozilla/Projects/SpiderMonkey">SpiderMonkey</a> 에서는, {{jsxref("Error.prototype.message")}}를 상속 받습니다. </dd> + <dt>{{jsxref("Error.prototype.name", "SyntaxError.prototype.name")}}</dt> + <dd>에러명. {{jsxref("Error")}}로부터 상속 받습니다.</dd> + <dt>{{jsxref("Error.prototype.fileName", "SyntaxError.prototype.fileName")}}</dt> + <dd>에러를 발생시킨 파일의 경로. {{jsxref("Error")}}로부터 상속 받습니다.</dd> + <dt>{{jsxref("Error.prototype.lineNumber", "SyntaxError.prototype.lineNumber")}}</dt> + <dd>에러가 발생한 파일의 코드 라인 넘버. {{jsxref("Error")}}로부터 상속 받습니다.</dd> + <dt>{{jsxref("Error.prototype.columnNumber", "SyntaxError.prototype.columnNumber")}}</dt> + <dd>에러가 발생된 라인의 컬럼 넘버. {{jsxref("Error")}}로부터 상속 받습니다.</dd> + <dt>{{jsxref("Error.prototype.stack", "SyntaxError.prototype.stack")}}</dt> + <dd>스택 트레이스. {{jsxref("Error")}}로부터 상속 받습니다.</dd> +</dl> + +<h2 id="메소드">메소드</h2> + +<p>비록 {{jsxref("SyntaxError")}} 프로토타입 객체는 고유의 메소드를 가지고 있지는 않지만, {{jsxref("SyntaxError")}} 인스턴스는 몇 가지의 메소드를 프로토타입 체인을 통하여 상속 받습니다.</p> + +<h2 id="스펙">스펙</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.11.7.6', 'NativeError.prototype')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td><code><em>NativeError</em>.prototype</code>로 정의.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-nativeerror.prototype', 'NativeError.prototype')}}</td> + <td>{{Spec2('ES6')}}</td> + <td><code><em>NativeError</em>.prototype</code>로 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-nativeerror.prototype', 'NativeError.prototype')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td><code><em>NativeError</em>.prototype</code>로 정의.</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("Error.prototype")}}</li> + <li>{{jsxref("Function.prototype")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/@@iterator/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/@@iterator/index.html new file mode 100644 index 0000000000..ded3d1c973 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/@@iterator/index.html @@ -0,0 +1,127 @@ +--- +title: 'TypedArray.prototype[@@iterator]()' +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/@@iterator +tags: + - Iterator + - JavaScript + - Method + - Prototype + - TypedArray +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/@@iterator +--- +<div>{{JSRef}}</div> + +<p>@@iterator 속성의 초기값은 {{jsxref("TypedArray.prototype.values()", "values")}} 속성의 초기값과 같은 함수 객체입니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>arr</var>[Symbol.iterator]()</code></pre> + +<h2 id="예">예</h2> + +<h3 id="for...of_루프를_사용하는_반복"><code>for...of</code> 루프를 사용하는 반복</h3> + +<pre class="brush: js">var arr = new Uint8Array([10, 20, 30, 40, 50]); +// 브라우저가 for..of 루프 및 for 루프에서 +// let 스코프인 변수를 지원해야 합니다 +for (let n of arr) { + console.log(n); +} +</pre> + +<h3 id="대안_반복">대안 반복</h3> + +<pre class="brush: js">var arr = new Uint8Array([10, 20, 30, 40, 50]); +var eArr = arr[Symbol.iterator](); +console.log(eArr.next().value); // 10 +console.log(eArr.next().value); // 20 +console.log(eArr.next().value); // 30 +console.log(eArr.next().value); // 40 +console.log(eArr.next().value); // 50 +</pre> + +<h2 id="스펙">스펙</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-%typedarray%.prototype-@@iterator', '%TypedArray%.prototype[@@iterator]()')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-%typedarray%.prototype-@@iterator', '%TypedArray%.prototype[@@iterator]()')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatVersionUnknown }}</td> + <td>{{ CompatGeckoDesktop("36") }} [1]</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{ CompatVersionUnknown }}</td> + <td>{{ CompatGeckoMobile("36") }} [1]</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Gecko 17 (Firefox 17 / Thunderbird 17 / SeaMonkey 2.14)에서 Gecko 26 (Firefox 26 / Thunderbird 26 / SeaMonkey 2.23 / Firefox OS 1.2)까지는 <code>iterator</code> 속성이 쓰였고(<a href="https://bugzilla.mozilla.org/show_bug.cgi?id=907077">bug 907077</a>), Gecko 27에서 Gecko 35까지는 <code>"@@iterator"</code> placeholder가 사용됐습니다. Gecko 36 (Firefox 36 / Thunderbird 36 / SeaMonkey 2.33)에서는, <code>@@iterator</code> <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Symbol">symbol</a>이 구현됐습니다 (<a href="https://bugzilla.mozilla.org/show_bug.cgi?id=918828">bug 918828</a>).</p> + +<h2 id="참조">참조</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Typed_arrays">JavaScript 형식화 배열</a></li> + <li>{{jsxref("TypedArray")}}</li> + <li>{{jsxref("TypedArray.prototype.entries()")}}</li> + <li>{{jsxref("TypedArray.prototype.keys()")}}</li> + <li>{{jsxref("TypedArray.prototype.values()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/buffer/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/buffer/index.html new file mode 100644 index 0000000000..702fe13eb7 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/buffer/index.html @@ -0,0 +1,111 @@ +--- +title: TypedArray.prototype.buffer +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/buffer +tags: + - JavaScript + - Property + - Prototype + - TypedArray +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/buffer +--- +<div>{{JSRef}}</div> + +<p><strong><code>buffer</code></strong> 접근자(accessor) 속성(property)은 생성 시간에 <em>TypedArray</em>에 의해 참조되는 {{jsxref("ArrayBuffer")}}를 나타냅니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>typedArray</var>.buffer</pre> + +<h2 id="설명">설명</h2> + +<p><code>buffer</code> 속성은 set 접근자 함수가 <code>undefined</code>인 접근자 속성입니다, 이 속성을 읽을 수만 있음을 뜻하는. 그 값은 <em>TypedArray</em>가 만들어질 때 수립되어 변경될 수 없습니다. <em>TypedArray</em>는 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#TypedArray_객체">TypedArray 객체 유형</a> 중 하나입니다.</p> + +<h2 id="예">예</h2> + +<h3 id="buffer_속성_사용"><code>buffer</code> 속성 사용</h3> + +<pre class="brush:js">var buffer = new ArrayBuffer(8); +var uint16 = new Uint16Array(buffer); +uint16.buffer; // ArrayBuffer { byteLength: 8 } +</pre> + +<h2 id="스펙">스펙</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-get-%typedarray%.prototype.buffer', 'TypedArray.prototype.buffer')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-get-%typedarray%.prototype.buffer', 'TypedArray.prototype.buffer')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>7.0</td> + <td>{{ CompatGeckoDesktop("2") }}</td> + <td>10</td> + <td>11.6</td> + <td>5.1</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>4.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{ CompatGeckoMobile("2") }}</td> + <td>10</td> + <td>11.6</td> + <td>4.2</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="참조">참조</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Typed_arrays">JavaScript 형식화 배열</a></li> + <li>{{jsxref("TypedArray")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/bytelength/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/bytelength/index.html new file mode 100644 index 0000000000..37a12d927a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/bytelength/index.html @@ -0,0 +1,73 @@ +--- +title: TypedArray.prototype.byteLength +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/byteLength +tags: + - JavaScript + - Property + - Prototype + - Reference + - TypedArray +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/byteLength +--- +<div>{{JSRef}}</div> + +<p><strong><code>byteLength</code></strong> 접근자(accessor) 속성(property)은 형식화 배열의 길이(바이트 단위)를 나타냅니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>typedarray</var>.byteLength</pre> + +<h2 id="설명">설명</h2> + +<p><code>byteLength</code> 속성은 접근자 함수가 <code>undefined</code>인 접근자 속성입니다, 이 속성을 읽을 수만 있음을 뜻하는. 그 값은 <em>TypedArray</em>가 만들어질 때 수립되어 변경될 수 없습니다. <em>TypedArray</em>에 <code>byteOffset</code> 또는 <code>length</code>를 지정하지 않은 경우, 참조되는 <code>ArrayBuffer</code>의 <code>length</code>가 반환됩니다. <em>TypedArray</em>는 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#TypedArray_객체">TypedArray 객체 유형</a> 중 하나입니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="byteLength_속성_사용"><code>byteLength</code> 속성 사용</h3> + +<pre class="brush:js">var buffer = new ArrayBuffer(8); + +var uint8 = new Uint8Array(buffer); +uint8.byteLength; // 8 (버퍼의 byteLength와 일치) + +var uint8 = new Uint8Array(buffer, 1, 5); +uint8.byteLength; // 5 (Uint8Array를 만들 때 지정된 대로) + +var uint8 = new Uint8Array(buffer, 2); +uint8.byteLength; // 6 (만든 Uint8Array의 오프셋으로 인해) +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-get-%typedarray%.prototype.bytelength', 'TypedArray.prototype.byteLength')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-get-%typedarray%.prototype.bytelength', 'TypedArray.prototype.byteLength')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.TypedArray.byteLength")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Typed_arrays">JavaScript 형식화 배열</a></li> + <li>{{jsxref("TypedArray")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/byteoffset/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/byteoffset/index.html new file mode 100644 index 0000000000..3be7af84cd --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/byteoffset/index.html @@ -0,0 +1,69 @@ +--- +title: TypedArray.prototype.byteOffset +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/byteOffset +tags: + - JavaScript + - Property + - Prototype + - TypedArray +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/byteOffset +--- +<div>{{JSRef}}</div> + +<p><strong><code>byteOffset</code></strong> 접근자(accessor) 속성(property)은 그 {{jsxref("ArrayBuffer")}}의 시작점에서 형식화 배열의 오프셋(단위 바이트)을 나타냅니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>typedarray</var>.byteOffset</pre> + +<h2 id="설명">설명</h2> + +<p><code>byteOffset</code> 속성은 set 접근자 함수가 <code>undefined</code>인 접근자 속성입니다, 이 속성을 읽을 수만 있음을 뜻하는. 그 값은 <em>TypedArray</em>가 만들어질 때 수립되어 변경될 수 없습니다. <em>TypedArray</em>는 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#TypedArray_객체">TypedArray 객체 유형</a> 중 하나입니다.</p> + +<h2 id="예">예</h2> + +<h3 id="byteOffset_속성_사용"><code>byteOffset</code> 속성 사용</h3> + +<pre class="brush:js">var buffer = new ArrayBuffer(8); + +var uint8 = new Uint8Array(buffer); +uint8.byteOffset; // 0 (지정된 오프셋이 없음) + +var uint8 = new Uint8Array(buffer, 3); +uint8.byteOffset; // 3 (Uint8Array를 만들 때 지정된 대로) +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-get-%typedarray%.prototype.byteoffset', 'TypedArray.prototype.byteOffset')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-get-%typedarray%.prototype.byteoffset', 'TypedArray.prototype.byteOffset')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.TypedArray.byteOffset")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Typed_arrays">JavaScript 형식화 배열</a></li> + <li>{{jsxref("TypedArray")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/bytes_per_element/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/bytes_per_element/index.html new file mode 100644 index 0000000000..563b7856cc --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/bytes_per_element/index.html @@ -0,0 +1,75 @@ +--- +title: TypedArray.BYTES_PER_ELEMENT +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/BYTES_PER_ELEMENT +tags: + - JavaScript + - Property + - Reference + - TypedArray +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/BYTES_PER_ELEMENT +--- +<div>{{JSRef}}</div> + +<p><code><strong>TypedArray.BYTES_PER_ELEMENT</strong></code> 속성은 각 형식화 배열 요소의 크기를 바이트로 나타냅니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/typedarray-bytes-per-element.html")}}</div> + + + +<div>{{js_property_attributes(0,0,0)}}</div> + +<h2 id="설명">설명</h2> + +<p>TypedArray 객체는 요소 당 바이트 수 및 바이트가 해석되는 방법으로 서로 다릅니다. <code>BYTES_PER_ELEMENT</code> 상수는 주어진 TypedArray의 각 요소가 갖는 바이트 수를 포함합니다.</p> + +<h2 id="예제">예제</h2> + +<pre class="brush:js">Int8Array.BYTES_PER_ELEMENT; // 1 +Uint8Array.BYTES_PER_ELEMENT; // 1 +Uint8ClampedArray.BYTES_PER_ELEMENT; // 1 +Int16Array.BYTES_PER_ELEMENT; // 2 +Uint16Array.BYTES_PER_ELEMENT; // 2 +Int32Array.BYTES_PER_ELEMENT; // 4 +Uint32Array.BYTES_PER_ELEMENT; // 4 +Float32Array.BYTES_PER_ELEMENT; // 4 +Float64Array.BYTES_PER_ELEMENT; // 8</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('Typed Array')}}</td> + <td>{{Spec2('Typed Array')}}</td> + <td>ECMAScript 6로 대체됨.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-typedarray.bytes_per_element', 'TypedArray.BYTES_PER_ELEMENT')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>ECMA 표준에서 초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-typedarray.bytes_per_element', 'TypedArray.BYTES_PER_ELEMENT')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.TypedArray.BYTES_PER_ELEMENT")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Typed_arrays">JavaScript 형식화 배열</a></li> + <li>{{jsxref("TypedArray")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/fill/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/fill/index.html new file mode 100644 index 0000000000..8e315fc201 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/fill/index.html @@ -0,0 +1,75 @@ +--- +title: TypedArray.prototype.fill() +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/fill +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - TypedArray +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/fill +--- +<div>{{JSRef}}</div> + +<p><strong><code>fill()</code></strong> 메서드는 배열의 모든 요소를 지정한 시작 인덱스부터 종료 인덱스까지 정적인 값으로 채웁니다. <code>fill()</code>은 {{jsxref("Array.prototype.fill()")}}과 동일한 알고리즘을 가지고 있습니다. TypedArray 는 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#TypedArray_objects">typed array types</a> 이곳에 있는 것 중 하나 입니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/typedarray-fill.html")}}</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>typedarray</var>.<code>fill(<var>value</var>[, <var>start<var> = 0[, <var>end</var> = this.length]])</var></var></code></code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>value</code></dt> + <dd>배열에 채워넣을 값.</dd> + <dt><code>start</code></dt> + <dd>선택사항. 시작 위치. 기본값은 0.</dd> + <dt><code>end</code></dt> + <dd>선택사항. 종료 위치 (종료위치를 포함하지않습니다. 즉, end -1 까지만 해당됩니다.). 기본값 this.length(배열의 길이).</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p>start 와 end 사이에 요소들을 채웁니다.</p> + +<p><strong><code>fill</code></strong> 메소드는 value, start 그리고 and 3개의 매개변수를 요구합니다. start 와 end 매개변수는 선택사항이며 기본값은 0 과 지정한 배열객체의 길이값 입니다.</p> + +<p>만약 start 매개변수가 음수이면, start 의 값은 배열의 길이값을 합한 결과가 시작지점이 되고, 만약 end 가 음수라면, end 매개변수와 배열의 길이값을 합한 결과가 종료지점이 됩니다.</p> + +<h2 id="예제">예제</h2> + +<pre class="brush: js">new Uint8Array([1, 2, 3]).fill(4); // Uint8Array [4, 4, 4] +new Uint8Array([1, 2, 3]).fill(4, 1); // Uint8Array [1, 4, 4] +new Uint8Array([1, 2, 3]).fill(4, 1, 2); // Uint8Array [1, 4, 3] +new Uint8Array([1, 2, 3]).fill(4, 1, 1); // Uint8Array [1, 2, 3] +new Uint8Array([1, 2, 3]).fill(4, -3, -2); // Uint8Array [4, 2, 3] +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-%typedarray%.prototype.fill', 'TypedArray.prototype.fill')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.TypedArray.fill")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.fill()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/index.html new file mode 100644 index 0000000000..3f4edc9970 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/index.html @@ -0,0 +1,342 @@ +--- +title: TypedArray +slug: Web/JavaScript/Reference/Global_Objects/TypedArray +tags: + - JavaScript + - TypedArray + - TypedArrays +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray +--- +<div>{{JSRef}}</div> + +<p><strong><em>TypedArray</em></strong> 객체는 밑에 깔린 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer">이진 데이터 버퍼</a>의 배열 같은 뷰를 기술합니다. <code>TypedArray</code>인 전역 속성도 눈에 직접 보이는 <code>TypedArray</code> 생성자도 없습니다. 대신 다양한 전역 속성이 있습니다, 그 값이 아래 나열된 특정 요소 유형에 대한 형식화 배열 생성자인. 다음 페이지에서 각 유형 요소를 포함하는 모든 형식화 배열에 쓰일 수 있는 공통 속성 및 메서드를 찾을 수 있습니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">new<em> TypedArray</em>(length); +new <em>TypedArray</em>(typedArray); +new <em>TypedArray</em>(object); +new <em>TypedArray</em>(buffer [, byteOffset [, length]]); + +<em>TypedArray()</em>는 다음 중 하나입니다: + +Int8Array(); +Uint8Array(); +Uint8ClampedArray(); +Int16Array(); +Uint16Array(); +Int32Array(); +Uint32Array(); +Float32Array(); +Float64Array(); +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt>length</dt> + <dd><code>length</code> 인수와 함께 호출하면 메모리상에 길이에 BYTES_PER_ELEMENT bytes(바이트)를 곱한 크기만큼의, 0을 포함한 이진 데이터 버퍼를 생성합니다.</dd> + <dt>typedArray</dt> + <dd><code>typedArray</code> 인수와 함께 호출하면, 모든 형식화 배열 객체 유형(가령 <code>Int32Array</code>)이 될 수 있는, <code>typedArray</code>는 새로운 형식화 배열로 복사됩니다. <code>typedArray</code> 내 각 값은 새로운 배열로 복사되기 전에 해당 유형의 생성자로 변환됩니다.</dd> + <dt>object</dt> + <dd><code>object</code> 인수와 함께 호출하면, 새로운 형식화 배열이 마치 <code><em>TypedArray</em>.from()</code> 메서드에 의해서처럼 생성됩니다.</dd> + <dt>buffer, byteOffset, length</dt> + <dd><code>buffer</code>와 선택 사항으로 <code>byteOffset</code> 및 <code>length</code> 인수와 함께 호출하면, 새로운 형식화 배열 뷰는 지정된 {{jsxref("ArrayBuffer")}} 뷰로 생성됩니다. <code>byteOffset</code> 및 <code>length</code> 매개변수는 형식화 배열 뷰에 의해 노출되는 메모리 범위를 지정합니다. 둘 다 생략된 경우, <code>buffer</code>가 모두 보입니다; <code>length</code>만 생략된 경우, <code>buffer</code>의 나머지가 보입니다.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p>ECMAScript 6는 모든 <em>TypedArray</em> 생성자의 <code>[[Prototype]]</code> 역할을 하는 <em>TypedArray</em> 생성자를 정의합니다. 이 생성자는 직접 노출되지 않습니다: 전역 <code>%TypedArray%</code> 또는 <code>TypedArray</code> 속성은 없습니다. <code>Object.getPrototypeOf(Int8Array.prototype)</code> 및 비슷한 방식을 통해서만 직접 접근할 수 있습니다. 모든 <em>TypedArray</em> 생성자는 <code>%TypedArray%</code> 생성자 함수로부터 공통 속성을 상속합니다. 게다가, 모든 형식화 배열 프로토타입(<em>TypedArray</em><code>.prototype</code>)은 자기 <code>[[Prototype]]</code>으로서 <code>%TypedArray%.prototype</code>이 있습니다.</p> + +<p><code>%TypedArray%</code> 생성자 자체로는 특별히 유용한 것은 아닙니다. 호출하거나 <code>new</code> 식으로 사용하면 <code>TypeError</code>가 발생합니다, 서브클래싱을 지원하는 JS 엔진에서 객체 생성 도중 사용될 때 빼고는. 현재로서는 그러한 엔진이 없기에 <code>%TypedArray%</code>는 모든 <em>TypedArray</em> 생성자에 함수 또는 속성을 폴리필할 때만 유용합니다.</p> + +<h3 id="속성_접근">속성 접근</h3> + +<p>표준 배열 인덱스 구문(즉, 각괄호 표기법)을 써서 배열의 요소를 참조할 수 있습니다. 그러나, 형식화 배열에 인덱스 있는 속성의 읽기(getting) 또는 쓰기(setting)는 이 속성에 대한 프로토타입 체인에서 찾을 수 없습니다, 심지어 인덱스가 범위 밖인 경우라도. 인덱스 있는 속성은 {{jsxref("ArrayBuffer")}}를 조사하고 객체 속성을 조사하지는 않습니다. 여전히 유명 속성을 사용할 수 있습니다, 모든 객체와 마찬가지로.</p> + +<pre class="brush: js">// 표준 배열 구문을 사용해 쓰기 및 읽기 +var int16 = new Int16Array(2); +int16[0] = 42; +console.log(int16[0]); // 42 + +// 프로토타입의 인덱스 있는 속성은 조사되지 않음 (Fx 25) +Int8Array.prototype[20] = "foo"; +(new Int8Array(32))[20]; // 0 +// 비록 범위 밖 또는 +Int8Array.prototype[20] = "foo"; +(new Int8Array(8))[20]; // undefined +// 음의 정수인 경우에도 +Int8Array.prototype[-1] = "foo"; +(new Int8Array(8))[-1]; // undefined + +// 유명(named) 속성은 허용됨, 다만 (Fx 30) 에서지만 +Int8Array.prototype.foo = "bar"; +(new Int8Array(32)).foo; // "bar"</pre> + +<h2 id="TypedArray_객체">TypedArray 객체</h2> + +<table class="standard-table"> + <tbody> + <tr> + <td class="header">유형</td> + <td class="header">크기 (바이트)</td> + <td class="header">설명</td> + <td class="header">Web IDL 형</td> + <td class="header">해당 C 형</td> + </tr> + <tr> + <td>{{jsxref("Int8Array")}}</td> + <td>1</td> + <td>8비트 2의 보수 형식 부호 있는 정수</td> + <td><code>byte</code></td> + <td><code>int8_t</code></td> + </tr> + <tr> + <td>{{jsxref("Uint8Array")}}</td> + <td>1</td> + <td>8비트 부호 없는 정수</td> + <td><code>octet</code></td> + <td><code>uint8_t</code></td> + </tr> + <tr> + <td>{{jsxref("Uint8ClampedArray")}}</td> + <td>1</td> + <td>8비트 부호 없는 정수 (단속됨)</td> + <td><code>octet</code></td> + <td><code>uint8_t</code></td> + </tr> + <tr> + <td>{{jsxref("Int16Array")}}</td> + <td>2</td> + <td>16비트 2의 보수 형식 부호 있는 정수</td> + <td><code>short</code></td> + <td><code>int16_t</code></td> + </tr> + <tr> + <td>{{jsxref("Uint16Array")}}</td> + <td>2</td> + <td>16비트 부호 없는 정수</td> + <td><code>unsigned short</code></td> + <td><code>uint16_t</code></td> + </tr> + <tr> + <td>{{jsxref("Int32Array")}}</td> + <td>4</td> + <td>32비트 2의 보수 형식 부호 있는 정수</td> + <td><code>long</code></td> + <td><code>int32_t</code></td> + </tr> + <tr> + <td>{{jsxref("Uint32Array")}}</td> + <td>4</td> + <td>32비트 부호 없는 정수</td> + <td><code>unsigned long</code></td> + <td><code>uint32_t</code></td> + </tr> + <tr> + <td>{{jsxref("Float32Array")}}</td> + <td>4</td> + <td>32비트 IEEE 부동 소수점 수</td> + <td><code>unrestricted float</code></td> + <td><code>float</code></td> + </tr> + <tr> + <td>{{jsxref("Float64Array")}}</td> + <td>8</td> + <td>64비트 IEEE 부동 소수점 수</td> + <td><code>unrestricted double</code></td> + <td><code>double</code></td> + </tr> + </tbody> +</table> + +<h2 id="속성">속성</h2> + +<dl> + <dt>{{jsxref("TypedArray.BYTES_PER_ELEMENT")}}</dt> + <dd>서로 다른 형식화 배열 객체에 대해 요소 크기의 숫자값을 반환합니다.</dd> + <dt><em>TypedArray</em>.length</dt> + <dd>값이 3인 길이 속성.</dd> + <dt>{{jsxref("TypedArray.name")}}</dt> + <dd>생성자 이름의 문자열 값을 반환합니다. 가령 "Int8Array".</dd> + <dt>{{jsxref("TypedArray.@@species", "get TypedArray[@@species]")}}</dt> + <dd>파생된 객체를 생성하는데 쓰이는 생성자 함수.</dd> + <dt>{{jsxref("TypedArray.prototype")}}</dt> + <dd><em>TypedArray</em> 객체에 대한 프로토타입.</dd> +</dl> + +<h2 id="메서드">메서드</h2> + +<dl> + <dt>{{jsxref("TypedArray.from()")}}</dt> + <dd>배열 같은 또는 반복가능(iterable) 객체로부터 새로운 형식화 배열을 생성합니다. {{jsxref("Array.from()")}}도 참조.</dd> + <dt>{{jsxref("TypedArray.of()")}}</dt> + <dd>가변(variable) 인수로 새로운 형식화 배열을 생성합니다. {{jsxref("Array.of()")}}도 참조.</dd> +</dl> + +<h2 id="TypedArray_프로토타입">TypedArray 프로토타입</h2> + +<p>모든 <em>TypedArray</em>는 {{jsxref("TypedArray.prototype")}}을 상속합니다.</p> + +<h3 id="속성_2">속성</h3> + +<p>{{page('ko/Web/JavaScript/Reference/Global_Objects/TypedArray/prototype','속성')}}</p> + +<h3 id="메서드_2">메서드</h3> + +<p>{{page('ko/Web/JavaScript/Reference/Global_Objects/TypedArray/prototype','메서드')}}</p> + +<h2 id="스펙">스펙</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('Typed Array')}}</td> + <td>{{Spec2('Typed Array')}}</td> + <td>형식화 배열 뷰 유형이 있는 <code>TypedArray</code> 및 <code>ArrayBufferView</code> 인터페이스로 정의됨. ECMAScript 6로 대체됨.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-typedarray-objects', 'TypedArray Objects')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>ECMA 표준에서 초기 정의. 인덱스 있고 유명 속성에 대한 행동이 지정됨. <code>new</code>가 필요함이 지정됨.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-typedarray-objects', 'TypedArray Objects')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(7.0)}}</td> + <td>{{CompatGeckoDesktop("2")}}</td> + <td>10</td> + <td>11.6</td> + <td>5.1</td> + </tr> + <tr> + <td>Indexed properties not consulting prototype</td> + <td>{{CompatVersionUnknown}} [1]</td> + <td>{{CompatGeckoDesktop("25")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Named properties</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("30")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>new</code> is required</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("44")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>4.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{ CompatGeckoMobile("2") }}</td> + <td>10</td> + <td>11.6</td> + <td>4.2</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Indexed properties not consulting prototype</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}} [1]</td> + <td>{{ CompatGeckoMobile("25") }}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}} [1]</td> + </tr> + <tr> + <td>Named properties</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{ CompatGeckoMobile("30") }}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>new</code> is required</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{ CompatGeckoMobile("44") }}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] <code>-1</code>과 비슷한 값은 인덱스 있는 속성으로 여겨지지 않기에 그 프로토타입 속성값을 반환합니다.</p> + +<h2 id="호환성_주의사항">호환성 주의사항</h2> + +<p>ECMAScript 2015 (ES6)를 시작으로, <code>TypedArray</code> 생성자는 {{jsxref("Operators/new", "new")}} 연산자로 생성되어야 합니다. <code>new</code> 없는 함수로서 <code>TypedArray</code> 생성자를 호출하면, 이제부터 {{jsxref("TypeError")}}가 발생합니다.</p> + +<pre class="brush: js example-bad">var dv = Int8Array([1, 2, 3]); +// TypeError: new 없은 내장 Int8Array 생성자 +// 호출은 금지됩니다</pre> + +<pre class="brush: js example-good">var dv = new Int8Array([1, 2, 3]);</pre> + +<h2 id="참조">참조</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Typed_arrays">JavaScript 형식화 배열</a></li> + <li>{{jsxref("ArrayBuffer")}}</li> + <li>{{jsxref("DataView")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/indexof/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/indexof/index.html new file mode 100644 index 0000000000..1ccd923d93 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/indexof/index.html @@ -0,0 +1,80 @@ +--- +title: TypedArray.prototype.indexOf() +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/indexOf +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/indexOf +--- +<div>{{JSRef}}</div> + +<p><strong><code>indexOf()</code></strong> 메소드는 형식화 배열(typed array)에서 주어진 값과 일치하는 첫 번째 인덱스를 반환한다. 일치하는 값이 없으면 -1을 반환한다. 이 메소드는 {{jsxref("Array.prototype.indexOf()")}} 와 동일한 알고리즘을 가지고 있다<em>.</em> <em>TypedArray</em>는 <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#TypedArray_%EA%B0%9D%EC%B2%B4">TypedArray 객체 유형</a> 중 하나이다.</p> + +<div>{{EmbedInteractiveExample("pages/js/typedarray-indexof.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>typedarray</var>.<var>i<code>ndexOf(<var>searchElement</var>[, <var>fromIndex</var> = 0])</code></var></code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>searchElement</code></dt> + <dd>배열에서 검색할 요소.</dd> + <dt><code>fromIndex</code></dt> + <dd>문자열에서 찾기 시작하는 위치를 나타내는 인덱스 값. 만약 인덱스 번호가 배열의 길이와 동일하거나 더 크다면, 해당 요소를 찾을 수 없기 때문에 결과값으로 -1이 반환된다. 만약 인덱스 번호가 음수라면, 배열의 끝에서부터 하나씩 상쇄하며 계산한다. (예. fromIndex로 -1을 준 경우 가장 마지막 배열 요소의 값부터 검색을 시작. -2를 준 경우, 가장 마지막 배열 요소에서 하나 앞 요소부터 검색을 시작). 주의: 주어진 인덱스가 음수인 경우에도 배열은 여전히 앞에서부터 뒤로(왼쪽에서 오른쪽 순서로) 검색 된다. 만약 결과값으로 나온 인덱스가 0보다 작다면, 배열 전체가 찾아진 것이다. 디폴트 값 : 0 (전체 배열이 검색된다).</dd> +</dl> + +<h3 id="반환_결과">반환 결과</h3> + +<p>해당 배열에서 찾으려는 요소가 위치한 첫 번째 인덱스 값. 만약 찾으려는 요소가 없을 경우에는 -1을 반환. </p> + +<h2 id="설명">설명</h2> + +<p><code>indexOf</code> 메소드는 배열의 요소를 <code>searchElement</code> 와 비교할 때, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Using_the_Equality_Operators">strict equality</a>(===, <em>트리플 equals</em>) 를 사용하여 자료형의 일치 여부까지 비교한다. </p> + +<h2 id="예시">예시</h2> + +<pre class="brush: js">var uint8 = new Uint8Array([2, 5, 9]); +uint8.indexOf(2); // 0 +uint8.indexOf(7); // -1 +uint8.indexOf(9, 2); // 2 +uint8.indexOf(2, -1); // -1 +uint8.indexOf(2, -3); // 0 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-%typedarray%.prototype.indexof', 'TypedArray.prototype.indexOf')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-%typedarray%.prototype.indexof', 'TypedArray.prototype.indexOf')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div> + + +<p>{{Compat("javascript.builtins.TypedArray.indexOf")}}</p> +</div> + +<h2 id="참고">참고</h2> + +<ul> + <li>{{jsxref("TypedArray.prototype.lastIndexOf()")}}</li> + <li>{{jsxref("Array.prototype.indexOf()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/length/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/length/index.html new file mode 100644 index 0000000000..0d5091aeb6 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/length/index.html @@ -0,0 +1,68 @@ +--- +title: TypedArray.prototype.length +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/length +tags: + - JavaScript + - Property + - Prototype + - TypedArray +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/length +--- +<div>{{JSRef}}</div> + +<p><strong><code>length</code></strong> 접근자(accessor) 속성(property)은 형식화 배열의 (요소) 길이를 나타냅니다.</p> + +<h2 id="설명">설명</h2> + +<p><code>length</code> 속성은 set 접근자 함수가 <code>undefined</code>인 접근자 속성입니다, 이 속성을 읽을 수만 있음을 뜻하는. 값은 <em>TypedArray</em>가 만들어질 때 수립되어 변경될 수 없습니다. <em>TypedArray</em>가 <code>byteOffset</code> 또는 <code>length</code>를 지정하지 않은 경우, 참조되는 {{jsxref("ArrayBuffer")}}의 길이가 반환됩니다. <em>TypedArray</em>는 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#TypedArray_객체">TypedArray 객체 유형</a> 중 하나입니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="length_속성_사용"><code>length</code> 속성 사용</h3> + +<pre class="brush:js">var buffer = new ArrayBuffer(8); + +var uint8 = new Uint8Array(buffer); +uint8.length; // 8 (버퍼의 길이와 일치) + +var uint8 = new Uint8Array(buffer, 1, 5); +uint8.length; // 5 (Uint8Array를 만들 때 지정된 대로) + +var uint8 = new Uint8Array(buffer, 2); +uint8.length; // 6 (만든 Uint8Array의 오프셋으로 인해) +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-get-%typedarray%.prototype.length', 'TypedArray.prototype.length')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-get-%typedarray%.prototype.length', 'TypedArray.prototype.length')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.TypedArray.length")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Typed_arrays">JavaScript 형식화 배열</a></li> + <li>{{jsxref("TypedArray")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/name/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/name/index.html new file mode 100644 index 0000000000..83b7f47ab1 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/name/index.html @@ -0,0 +1,70 @@ +--- +title: TypedArray.name +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/name +tags: + - JavaScript + - Property + - Reference + - TypedArray +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/name +--- +<div>{{JSRef}}</div> + +<p><code><strong><em>TypedArray</em>.name</strong></code> 속성은 형식화 배열 생성자 이름의 문자열 값을 나타냅니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/typedarray-name.html")}}</div> + + + +<div>{{js_property_attributes(0,0,0)}}</div> + +<h2 id="설명">설명</h2> + +<p>TypedArray 객체는 요소 당 바이트 수 및 바이트가 해석되는 방법으로 서로 다릅니다. <code>name</code> 속성은 어떤 데이터 형이 배열을 구성하는 지를 기술합니다. 첫 번째 부분은 "정수"용 <code>Int</code> 또는 "부호 없는 정수"용 <code>Uint</code>일 수 있습니다, "부동 소수점"용 <code>Float</code>도 쓰입니다 . 두 번째 부분은 배열의 비트 크기를 기술하는 숫자입니다. 끝으로, 객체 형은 <code>Array</code>입니다, 특수한 경우로 <code>ClampedArray</code>가 있는. 자세한 사항은 {{jsxref("Uint8ClampedArray")}}를 참조해 주세요.</p> + +<h2 id="예제">예제</h2> + +<pre class="brush:js">Int8Array.name; // "Int8Array" +Uint8Array.name; // "Uint8Array" +Uint8ClampedArray.name; // "Uint8ClampedArray" +Int16Array.name; // "Int16Array" +Uint16Array.name; // "Uint16Array" +Int32Array.name; // "Int32Array" +Uint32Array.name; // "Uint32Array" +Float32Array.name; // "Float32Array" +Float64Array.name; // "Float64Array"</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-properties-of-the-typedarray-constructors', 'TypedArray.name')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-properties-of-the-typedarray-constructors', 'TypedArray.name')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.TypedArray.name")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Typed_arrays">JavaScript 형식화 배열</a></li> + <li>{{jsxref("TypedArray")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/of/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/of/index.html new file mode 100644 index 0000000000..854c53cedf --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/of/index.html @@ -0,0 +1,92 @@ +--- +title: TypedArray.of() +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/of +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/of +--- +<div>{{JSRef}}</div> + +<div><code><strong><em>TypedArray</em>.of()</strong></code>는 가변적으로 인수를 전달 할수 있는 새로운 형식화 배열(<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#TypedArray_objects">typed array</a>)를 만들어내는 메소드입니다.</div> + +<p>이 메소드는 {{jsxref("Array.of()")}}와 거의 같습니다.</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox"><code><em>TypedArray</em>.of(<var>element0</var>[, <var>element1</var>[, ...[, <var>elementN</var>]]]) +</code> +where <em>TypedArray</em> is one of: + +Int8Array +Uint8Array +Uint8ClampedArray +Int16Array +Uint16Array +Int32Array +Uint32Array +Float32Array +Float64Array</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>element<em>N</em></code></dt> + <dd>형식화 된 배열을 만들 요소입니다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>생성된 {{jsxref("TypedArray")}} 인스턴스</p> + +<h2 id="설명">설명</h2> + +<p>{{jsxref("Array.of()")}}와 <code><em>TypedArray</em>.of()</code> 사이의 약간의 차이점은 다음과 같습니다. </p> + +<ul> + <li><code>TypedArray.of</code>에 전달된 값이 생성자가 아닌 경우 <code>TypedArray.of</code>는 {{jsxref ( "TypeError")}}를 발생시킵니다. <code>Array.of</code>는 기본적으로 새로운 {{jsxref ( "Array")}}를 생성합니다. </li> + <li><code><em>TypedArray</em>.of</code> uses <code>[[Put]]</code> where <code>Array.of</code> uses <code>[[DefineProperty]]</code>. Hence, when working with {{jsxref("Proxy")}} objects, it calls {{jsxref("Global_Objects/Proxy/handler/set", "handler.set")}} to create new elements rather than {{jsxref("Global_Objects/Proxy/handler/defineProperty", "handler.defineProperty")}}.</li> + <li><code>TypedArray.of</code>는 <code>Array.of</code>가 <code>[[DefineProperty]]</code>를 사용하는 것처럼 <code>[[Put]]</code>을 사용합니다. 따라서 {{jsxref("Proxy")}} 객체로 작업 할 때 새로운 요소를 생성하기 위해 {{jsxref("Global_Objects/Proxy/handler/set", "handler.set")}}대신 {{jsxref("Global_Objects/Proxy/handler/defineProperty", "handler.defineProperty")}}를 호출합니다.</li> +</ul> + +<h2 id="예제">예제</h2> + +<pre class="brush: js">Uint8Array.of(1); // Uint8Array [ 1 ] +Int8Array.of('1', '2', '3'); // Int8Array [ 1, 2, 3 ] +Float32Array.of(1, 2, 3); // Float32Array [ 1, 2, 3 ] +Int16Array.of(undefined); // IntArray [ 0 ] +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-%typedarray%.of', '%TypedArray%.of')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-%typedarray%.of', '%TypedArray%.of')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.TypedArray.of")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("TypedArray.from()")}}</li> + <li>{{jsxref("Array.of()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/prototype/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/prototype/index.html new file mode 100644 index 0000000000..9a1b624b3b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/prototype/index.html @@ -0,0 +1,175 @@ +--- +title: TypedArray.prototype +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/prototype +tags: + - JavaScript + - Property + - TypedArray +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray +--- +<div>{{JSRef}}</div> + +<p><code><strong>TypedArray</strong></code><strong><code>.prototype</code></strong> 속성(property)은 {{jsxref("TypedArray")}} 생성자에 대한 프로토타입을 나타냅니다.</p> + +<div>{{js_property_attributes(0,0,0)}}</div> + +<h2 id="설명">설명</h2> + +<p>{{jsxref("TypedArray")}} 인스턴스는 {{jsxref("TypedArray.prototype")}}을 상속합니다. 모든 <em>TypedArray</em> 인스턴스에 속성 또는 메서드를 추가하기 위해 생성자의 프로토타입 객체를 사용할 수 있으며, <em>TypedArray</em>는 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#TypedArray_객체">TypedArray 객체 유형</a> 중 하나입니다.</p> + +<p>상속에 관한 자세한 정보를 위해 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#설명"><em>TypedArray</em></a>에 대한 설명도 참조하세요.</p> + +<h2 id="속성">속성</h2> + +<dl> + <dt><code>TypedArray.prototype.constructor</code></dt> + <dd>인스턴스의 프로토타입을 만든 함수를 반환합니다. 이는 기본으로 해당 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#TypedArray_객체">TypedArray 객체 유형</a> 함수 중 하나입니다.</dd> + <dt>{{jsxref("TypedArray.prototype.buffer")}} {{readonlyInline}}</dt> + <dd>형식화 배열에 의해 참조되는 {{jsxref("ArrayBuffer")}}를 반환합니다. 생성 시에 고정되기에 <strong>읽기 전용</strong>.</dd> + <dt>{{jsxref("TypedArray.prototype.byteLength")}} {{readonlyInline}}</dt> + <dd>{{jsxref("ArrayBuffer")}}의 시작점부터 형식화 배열의 길이(단위 바이트)를 반환합니다. 생성 시에 고정되기에 <strong>읽기 전용</strong>.</dd> + <dt>{{jsxref("TypedArray.prototype.byteOffset")}} {{readonlyInline}}</dt> + <dd>{{jsxref("ArrayBuffer")}}의 시작점부터 형식화 배열의 오프셋(단위 바이트)을 반환합니다. 생성 시에 고정되기에 <strong>읽기 전용</strong>.</dd> + <dt>{{jsxref("TypedArray.prototype.length")}} {{readonlyInline}}</dt> + <dd>형식화 배열 내 보유한 요소의 수를 반환합니다. 생성 시에 고정되기에 <strong>읽기 전용</strong>.</dd> +</dl> + +<h2 id="메서드">메서드</h2> + +<dl> + <dt>{{jsxref("TypedArray.prototype.copyWithin()")}}</dt> + <dd>배열 내부 일련의 배열 요소를 복사합니다. {{jsxref("Array.prototype.copyWithin()")}}도 참조.</dd> + <dt>{{jsxref("TypedArray.prototype.entries()")}}</dt> + <dd>배열 내 각 인덱스에 대한 키/값 쌍을 포함하는 새로운 <code>Array Iterator</code> 객체를 반환합니다. {{jsxref("Array.prototype.entries()")}}도 참조.</dd> + <dt>{{jsxref("TypedArray.prototype.every()")}}</dt> + <dd>배열의 모든 요소가 함수로 제공되는 테스트를 통과하는지를 테스트합니다. {{jsxref("Array.prototype.every()")}}도 참조.</dd> + <dt>{{jsxref("TypedArray.prototype.fill()")}}</dt> + <dd>시작 인덱스부터 끝 인덱스까지 배열의 모든 요소를 고정값으로 채웁니다. {{jsxref("Array.prototype.fill()")}}도 참조.</dd> + <dt>{{jsxref("TypedArray.prototype.filter()")}}</dt> + <dd>제공되는 필터링 함수가 true를 반환하는 이 배열의 모든 요소를 갖는 새로운 배열을 생성합니다. {{jsxref("Array.prototype.filter()")}}도 참조.</dd> + <dt>{{jsxref("TypedArray.prototype.find()")}}</dt> + <dd>배열 내 요소가 제공되는 테스트 함수를 만족하는 경우 배열 내 찾은 값 또는 못 찾은 경우 <code>undefined</code>를 반환합니다. {{jsxref("Array.prototype.find()")}}도 참조.</dd> + <dt>{{jsxref("TypedArray.prototype.findIndex()")}}</dt> + <dd>배열 내 요소가 제공되는 테스트 함수를 만족하는 경우 배열 내 찾은 인덱스 또는 못 찾은 경우 -1을 반환합니다. {{jsxref("Array.prototype.findIndex()")}}도 참조.</dd> + <dt>{{jsxref("TypedArray.prototype.forEach()")}}</dt> + <dd>배열 내 각 요소에 대해 함수를 호출합니다. {{jsxref("Array.prototype.forEach()")}}도 참조.</dd> + <dt>{{jsxref("TypedArray.prototype.includes()")}} {{experimental_inline}}</dt> + <dd>형식화 배열이 특정 요소를 포함하는지를 판단해, 적절히 <code>true</code> 또는 <code>false</code>를 반환합니다. {{jsxref("Array.prototype.includes()")}}도 참조.</dd> + <dt>{{jsxref("TypedArray.prototype.indexOf()")}}</dt> + <dd>지정된 값과 같은 배열 내부 요소의 첫(최소) 인덱스 또는 못 찾은 경우 -1을 반환합니다. {{jsxref("Array.prototype.indexOf()")}}도 참조.</dd> + <dt>{{jsxref("TypedArray.prototype.join()")}}</dt> + <dd>배열의 모든 요소를 문자열로 합칩니다. {{jsxref("Array.prototype.join()")}}도 참조.</dd> + <dt>{{jsxref("TypedArray.prototype.keys()")}}</dt> + <dd>배열의 각 인덱스에 대한 키를 포함하는 새로운 <code>Array Iterator</code>를 반환합니다. {{jsxref("Array.prototype.keys()")}}도 참조.</dd> + <dt>{{jsxref("TypedArray.prototype.lastIndexOf()")}}</dt> + <dd>지정된 값과 같은 배열 내부 요소의 끝(최대) 인덱스 또는 못 찾은 경우 -1을 반환합니다. {{jsxref("Array.prototype.lastIndexOf()")}}도 참조.</dd> + <dt>{{jsxref("TypedArray.prototype.map()")}}</dt> + <dd>이 배열의 모든 요소에 제공된 함수를 호출한 결과를 갖는 새로운 배열을 생성합니다. {{jsxref("Array.prototype.map()")}}도 참조.</dd> + <dt>{{jsxref("TypedArray.prototype.move()")}} {{non-standard_inline}} {{unimplemented_inline}}</dt> + <dd>{{jsxref("TypedArray.prototype.copyWithin()")}}의 이전 비표준 버전.</dd> + <dt>{{jsxref("TypedArray.prototype.reduce()")}}</dt> + <dd>누산기(accumulator) 및 배열의 각 값(좌에서 우로)에 대해 한 값으로 줄도록 함수를 적용합니다. {{jsxref("Array.prototype.reduce()")}}도 참조.</dd> + <dt>{{jsxref("TypedArray.prototype.reduceRight()")}}</dt> + <dd>누산기 및 배열의 각 값(우에서 좌로)에 대해 한 값으로 줄도록 함수를 적용합니다. {{jsxref("Array.prototype.reduceRight()")}}도 참조.</dd> + <dt>{{jsxref("TypedArray.prototype.reverse()")}}</dt> + <dd>배열 요소의 순서를 뒤집습니다 — 처음이 마지막이 되고 마지막이 처음이 됩니다. {{jsxref("Array.prototype.reverse()")}}도 참조.</dd> + <dt>{{jsxref("TypedArray.prototype.set()")}}</dt> + <dd>형식화 배열에 여러 값을 저장합니다, 지정된 배열에서 입력 값을 읽어.</dd> + <dt>{{jsxref("TypedArray.prototype.slice()")}}</dt> + <dd>배열의 한 부분을 추출하여 새로운 배열을 반환합니다. {{jsxref("Array.prototype.slice()")}}도 참조.</dd> + <dt>{{jsxref("TypedArray.prototype.some()")}}</dt> + <dd>이 배열의 적어도 한 요소가 제공된 테스트 함수를 만족하는 경우 true를 반환합니다. {{jsxref("Array.prototype.some()")}}도 참조.</dd> + <dt>{{jsxref("TypedArray.prototype.sort()")}}</dt> + <dd>배열의 요소를 적소에 정렬해 그 배열을 반환합니다. {{jsxref("Array.prototype.sort()")}}도 참조.</dd> + <dt>{{jsxref("TypedArray.prototype.subarray()")}}</dt> + <dd>주어진 시작 및 끝 요소 인덱스로부터 새로운 TypedArray를 반환합니다.</dd> + <dt>{{jsxref("TypedArray.prototype.values()")}}</dt> + <dd>배열의 각 인덱스에 대한 값을 포함하는 새로운 <code>Array Iterator</code> 객체를 반환합니다. {{jsxref("Array.prototype.values()")}}도 참조.</dd> + <dt>{{jsxref("TypedArray.prototype.toLocaleString()")}}</dt> + <dd>배열 및 그 요소를 나타내는 지역화된 문자열을 반환합니다. {{jsxref("Array.prototype.toLocaleString()")}}도 참조.</dd> + <dt>{{jsxref("TypedArray.prototype.toString()")}}</dt> + <dd>배열 및 그 요소를 나타내는 문자열을 반환합니다. {{jsxref("Array.prototype.toString()")}}도 참조.</dd> + <dt>{{jsxref("TypedArray.prototype.@@iterator()", "TypedArray.prototype[@@iterator]()")}}</dt> + <dd>배열의 각 인덱스에 대한 값을 포함하는 새로운 <code>Array Iterator</code> 객체를 반환합니다.</dd> +</dl> + +<h2 id="스펙">스펙</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-properties-of-the-%typedarrayprototype%-object', 'TypedArray prototype')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-properties-of-the-%typedarrayprototype%-object', 'TypedArray prototype')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>7.0</td> + <td>{{ CompatGeckoDesktop("2") }}</td> + <td>10</td> + <td>11.6</td> + <td>5.1</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>4.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{ CompatGeckoMobile("2") }}</td> + <td>10</td> + <td>11.6</td> + <td>4.2</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="참조">참조</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Typed_arrays">JavaScript 형식화 배열</a></li> + <li>{{jsxref("TypedArray")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/reverse/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/reverse/index.html new file mode 100644 index 0000000000..0d7ff7f5e2 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/reverse/index.html @@ -0,0 +1,69 @@ +--- +title: TypedArray.prototype.reverse() +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/reverse +tags: + - ECMAScript6 + - JavaScript + - Method + - Prototype + - TypedArray +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/reverse +--- +<div>{{JSRef}}</div> + +<p><code><strong>reverse()</strong></code> 메서드는 제자리에서 형식화 배열을 뒤집습니다. 형식화 배열 첫 요소는 마지막이 되고 마지막은 첫 요소가 됩니다. 이 메서드는 {{jsxref("Array.prototype.reverse()")}}와 같은 알고리즘입니다. <em>TypedArray</em>는 여기 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#TypedArray_objects">TypedArray 객체 유형</a> 중 하나입니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/typedarray-reverse.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>typedarray</var>.reverse(); +</pre> + +<h3 id="반환_값">반환 값</h3> + +<p>뒤집힌 배열.</p> + +<h2 id="예제">예제</h2> + +<pre class="brush: js">var uint8 = new Uint8Array([1, 2, 3]); +uint8.reverse(); + +console.log(uint8); // Uint8Array [3, 2, 1] +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-%typedarray%.prototype.reverse', 'TypedArray.prototype.reverse')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-%typedarray%.prototype.reverse', 'TypedArray.prototype.reverse')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.TypedArray.reverse")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.reverse()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/set/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/set/index.html new file mode 100644 index 0000000000..3ce518f8cc --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/set/index.html @@ -0,0 +1,95 @@ +--- +title: TypedArray.prototype.set() +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/set +tags: + - JavaScript + - Method + - Prototype + - Reference + - TypedArray +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/set +--- +<div>{{JSRef}}</div> + +<p><strong><code>set()</code></strong> 메서드는 지정된 배열로부터 입력 값을 읽어 형식화 배열 내에 여러 값을 저장합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/typedarray-set.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>typedarr</var>.set(<em>array</em>[, <em>offset</em>]) +typedarr.set(<em>typedarray</em>[, <em>offset</em>]) +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>array</code></dt> + <dd>값을 복사할 배열. 소스 배열로부터 모든 값이 대상 배열로 복사됩니다, 소스 배열의 길이 + 오프셋이 대상 배열의 길이를 초과하지 않는 한, 그 경우에는 예외가 발생됩니다.</dd> + <dt><code>typedarray</code></dt> + <dd>소스 배열이 형식화 배열인 경우, 두 배열은 기본 {{jsxref("ArrayBuffer")}}를 같이 공유할 수 있습니다; 브라우저는 버퍼의 소스 범위를 대상(destination) 범위로 똑똑하게 <strong>복사</strong>합니다.</dd> + <dt><code>offset</code> {{optional_inline}}</dt> + <dd>소스 <code>array</code>에서 값을 쓰기 시작하는 대상 배열의 오프셋. 이 값이 생략된 경우, 0으로 간주됩니다 (즉, 소스 <code>array</code>는 인덱스 0에서 시작하는 대상 배열 내 값을 덮어씁니다).</dd> +</dl> + +<h3 id="예외">예외</h3> + +<dl> + <dt>{{jsxref("RangeError")}}</dt> + <dd><code>offset</code>이 가령 형식화 배열의 끝을 넘어서 저장하려고 설정된 경우 발생.</dd> +</dl> + +<h2 id="예제">예제</h2> + +<h3 id="set()_사용하기"><code>set()</code> 사용하기</h3> + +<pre class="brush:js">var buffer = new ArrayBuffer(8); +var uint8 = new Uint8Array(buffer); + +uint8.set([1,2,3], 3); + +console.log(uint8); // Uint8Array [ 0, 0, 0, 1, 2, 3, 0, 0 ] +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('Typed Array')}}</td> + <td>{{Spec2('Typed Array')}}</td> + <td>ECMAScript 6에 의해 대체됨.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-%typedarray%.prototype.set-array-offset', 'TypedArray.prototype.set')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>ECMA 표준에서 초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-%typedarray%.prototype.set-array-offset', 'TypedArray.prototype.set')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.TypedArray.set")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Typed_arrays">JavaScript 형식화 배열</a></li> + <li>{{jsxref("TypedArray")}}</li> + <li>{{jsxref("ArrayBuffer")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/slice/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/slice/index.html new file mode 100644 index 0000000000..adef23132b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/slice/index.html @@ -0,0 +1,129 @@ +--- +title: TypedArray.prototype.slice() +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/slice +tags: + - ECMAScript6 + - JavaScript + - Method + - Prototype + - TypedArray +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/slice +--- +<div>{{JSRef}}</div> + +<p><code><strong>slice()</strong></code> 메서드는 형식화 배열의 일부를 얕게 복사(shallow copy)한 새로운 형식화 배열 객체를 반환합니다. 이 메서드는 {{jsxref("Array.prototype.slice()")}}와 같은 알고리즘입니다. <em>TypedArray</em>는 여기 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#TypedArray_객체">TypedArray 객체 유형</a> 중 하나입니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>typedarray</var>.slice([<var>begin</var>[, <var>end</var>]])</code></pre> + +<h2 id="매개변수">매개변수</h2> + +<dl> + <dt><code>begin</code> {{optional_inline}}</dt> + <dd>추출을 시작하는 인덱스(0부터 셈).</dd> + <dd>음수 인덱스일 때, <code>begin</code>은 열 끝으로부터 오프셋을 나타냅니다. <code>slice(-2)</code>는 열에서 마지막 두 요소를 추출합니다.</dd> + <dd><code>begin</code>이 생략된 경우, <code>slice</code>는 인덱스 <code>0</code>에서 시작합니다.</dd> + <dt><code>end</code> {{optional_inline}}</dt> + <dd>추출을 끝내는 인덱스(0부터 셈). <code>slice</code>는 <code>end</code>(를 포함하지 않음)까지만 추출합니다.</dd> + <dd><code>slice(1,4)</code>는 2번째부터 4번째 요소까지 추출합니다 (인덱스가 1, 2 및 3인 요소).</dd> + <dd>음수 인덱스일 때, <code>end</code>는 열 끝으로부터 오프셋을 나타냅니다. <code>slice(2,-1)</code>은 열의 3번째부터 끝에서 2번째 요소까지 추출합니다.</dd> + <dd><code>end</code>가 생략된 경우, <code>slice</code>는 열의 끝까지 추출합니다 (<code>arr.length</code>).</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p><code>slice</code> 메서드는 바꾸지 않습니다. 원래 형식화 배열에서 얕게 복사된 요소를 반환합니다.</p> + +<p>새 요소가 어느 형식화 배열에든 추가된 경우, 다른 형식화 배열은 영향을 받지 않습니다.</p> + +<h2 id="예">예</h2> + +<h3 id="기존_형식화_배열의_일부를_반환">기존 형식화 배열의 일부를 반환</h3> + +<pre class="brush: js">var uint8 = new Uint8Array([1,2,3]); +uint8.slice(1); // Uint8Array [ 2, 3 ] +uint8.slice(2); // Uint8Array [ 3 ] +uint8.slice(-2); // Uint8Array [ 2, 3 ] +uint8.slice(0,1); // Uint8Array [ 1 ] +</pre> + +<h2 id="스펙">스펙</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-%typedarray%.prototype.slice', '%TypedArray%.prototype.slice')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-%typedarray%.prototype.slice', '%TypedArray%.prototype.slice')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>45</td> + <td>{{CompatGeckoDesktop("38")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop("38")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("Array.prototype.slice()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/some/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/some/index.html new file mode 100644 index 0000000000..94ce55b40a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/some/index.html @@ -0,0 +1,106 @@ +--- +title: TypedArray.prototype.some() +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/some +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - TypedArray +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/some +--- +<div>{{JSRef}}</div> + +<p><code><strong>some()</strong></code> 메서드는 형식화 배열 내 일부 요소가 제공되는 함수에 의해 구현되는 테스트를 통과하는지 여부를 테스트합니다. 이 메서드는 {{jsxref("Array.prototype.some()")}}과 같은 알고리즘입니다. <em>TypedArray</em>는 여기 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#TypedArray_objects">TypedArray 객체 유형</a> 중 하나입니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/typedarray-some.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>typedarray</var>.some(<var>callback</var>[, <var>thisArg</var>])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>각 요소에 대해 테스트하는 함수, 다음 인수 셋을 취하는: + <dl> + <dt><code>currentValue</code></dt> + <dd>형식화 배열에서 현재 처리 중인 요소.</dd> + <dt><code>index</code></dt> + <dd>형식화 배열에서 현재 처리 중인 요소의 인덱스.</dd> + <dt><code>array</code></dt> + <dd><code>some</code>이 호출한 형식화 배열.</dd> + </dl> + </dd> + <dt><code>thisArg</code></dt> + <dd>선택 사항. <code>callback</code>을 실행할 때 <code>this</code>로서 사용하는 값.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p><code>some</code> 메서드는 <code>callback</code>이 true 값을 반환하는 요소를 찾을 때까지 형식화 배열에 있는 각 요소에 대해 한 번 <code>callback</code> 함수를 실행합니다. 그런 요소가 발견된 경우, <code>some</code>은 즉시 <code>true</code>를 반환합니다. 그렇지 않으면, <code>some</code>은 <code>false</code>를 반환합니다.</p> + +<p><code>callback</code>은 세 인수와 함께 호출됩니다: 요소값, 요소 인덱스 및 순회(traverse)되는 배열 객체.</p> + +<p><code>thisArg</code> 매개변수가 <code>some</code>에 제공되는 경우, 호출될 때 <code>callback</code>에 전달됩니다, 그 <code>this</code> 값으로 사용하기 위해. 그렇지 않으면, <code>undefined</code> 값이 그 <code>this</code> 값으로 사용하기 위해 전달됩니다. <code>callback</code>에 의해 결국 관찰할 수 있는 <code>this</code> 값은 <a href="/ko/docs/Web/JavaScript/Reference/Operators/this">함수에 의해 보이는 <code>this</code>를 결정하는 평소 규칙</a>에 따라 결정됩니다.</p> + +<p><code>some</code>은 호출된 형식화 배열을 변화시키지(mutate) 않습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="모든_형식화_배열_요소의_크기_테스트">모든 형식화 배열 요소의 크기 테스트</h3> + +<p>다음 예는 형식화 배열의 모든 요소가 10보다 더 큰지 테스트합니다.</p> + +<pre class="brush: js language-js">function isBiggerThan10(element, index, array) { + return element > 10; +} +new Uint8Array([2, 5, 8, 1, 4]).some(isBiggerThan10); // false +new Uint8Array([12, 5, 8, 1, 4]).some(isBiggerThan10); // true +</pre> + +<h3 id="화살표_함수를_사용하여_형식화_배열_요소_테스트">화살표 함수를 사용하여 형식화 배열 요소 테스트</h3> + +<p><a href="/ko/docs/Web/JavaScript/Reference/Functions/애로우_펑션">화살표 함수</a>는 같은 테스트에 대해 더 짧은 구문을 제공합니다.</p> + +<pre class="brush: js">new Uint8Array([2, 5, 8, 1, 4]).some(elem => elem > 10); // false +new Uint8Array([12, 5, 8, 1, 4]).some(elem => elem > 10); // true</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-%typedarray%.prototype.some', 'TypedArray.prototype.some')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-%typedarray%.prototype.some', 'TypedArray.prototype.some')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.TypedArray.some")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("TypedArray.prototype.every()")}}</li> + <li>{{jsxref("Array.prototype.some()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/sort/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/sort/index.html new file mode 100644 index 0000000000..ef94943b23 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/sort/index.html @@ -0,0 +1,119 @@ +--- +title: TypedArray.prototype.sort() +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/sort +tags: + - ECMAScript6 + - JavaScript + - Method + - Prototype + - TypedArray +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/sort +--- +<div>{{JSRef}}</div> + +<p><code><strong>sort()</strong></code> 메서드는 <em>적소에</em> 형식화 배열의 요소를 정렬하여 그 형식화 배열을 반환합니다. 이 메서드는 {{jsxref("Array.prototype.sort()")}}<em>와 같은 알고리즘입니다.</em> <em>TypedArray</em>는 여기 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#TypedArray_objects">형식화 배열 유형</a> 중 하나입니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>typedarray</var>.sort([<var>compareFunction</var>])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>compareFunction</code> {{optional_inline}}</dt> + <dd>정렬 순서를 정의하는 함수를 지정합니다.</dd> +</dl> + +<h2 id="예">예</h2> + +<p>더 많은 예는, {{jsxref("Array.prototype.sort()")}} 메서드도 참조하세요.</p> + +<pre class="brush: js">var number = new Uint8Array([40, 1, 5, 200]); + +function compareNumbers(a, b) { + return a - b; +} + +numbers.sort(compareNumbers); +// Uint8Array [ 1, 5, 40, 200 ] +</pre> + +<h2 id="스펙">스펙</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-%typedarray%.prototype.sort', 'TypedArray.prototype.sort')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-%typedarray%.prototype.sort', 'TypedArray.prototype.sort')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(46)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(46)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("Array.prototype.sort()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/values/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/values/index.html new file mode 100644 index 0000000000..863d3c3cbb --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/values/index.html @@ -0,0 +1,127 @@ +--- +title: TypedArray.prototype.values() +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/values +tags: + - ECMAScript6 + - Iterator + - JavaScript + - Method + - Prototype + - TypedArray +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/values +--- +<div>{{JSRef}}</div> + +<p><strong><code>values()</code></strong> 메서드는 배열 내 각 인덱스에 대한 값을 포함하는 새로운 <code>Array Iterator</code> 객체를 반환합니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>arr</var>.values()</code></pre> + +<h2 id="예">예</h2> + +<h3 id="for...of_루프를_사용한_반복"><code>for...of</code> 루프를 사용한 반복</h3> + +<pre class="brush: js">var arr = new Uint8Array([10, 20, 30, 40, 50]); +var eArray = arr.values(); +// 브라우저가 for..of 루프 및 for 루프에서 +// let 스코프인 변수를 지원해야 합니다 +for (let n of eArray) { + console.log(n); +} +</pre> + +<h3 id="대안_반복">대안 반복</h3> + +<pre class="brush: js">var arr = new Uint8Array([10, 20, 30, 40, 50]); +var eArr = arr.values(); +console.log(eArr.next().value); // 10 +console.log(eArr.next().value); // 20 +console.log(eArr.next().value); // 30 +console.log(eArr.next().value); // 40 +console.log(eArr.next().value); // 50 +</pre> + +<h2 id="스펙">스펙</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-%typedarray%.prototype.values', '%TypedArray%.prototype.values()')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-%typedarray%.prototype.values', '%TypedArray%.prototype.values()')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatVersionUnknown }}</td> + <td>{{CompatGeckoDesktop(37)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{ CompatVersionUnknown }}</td> + <td>{{CompatGeckoMobile(37)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="참조">참조</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Typed_arrays">JavaScript 형식화 배열</a></li> + <li>{{jsxref("TypedArray")}}</li> + <li>{{jsxref("TypedArray.prototype.entries()")}}</li> + <li>{{jsxref("TypedArray.prototype.keys()")}}</li> + <li>{{jsxref("TypedArray.prototype.@@iterator()", "TypedArray.prototype[@@iterator]()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/typeerror/index.html b/files/ko/web/javascript/reference/global_objects/typeerror/index.html new file mode 100644 index 0000000000..2a95fc358d --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typeerror/index.html @@ -0,0 +1,123 @@ +--- +title: TypeError +slug: Web/JavaScript/Reference/Global_Objects/TypeError +tags: + - Error + - JavaScript + - Reference + - TypeError +translation_of: Web/JavaScript/Reference/Global_Objects/TypeError +--- +<div>{{JSRef}}</div> + +<p><code><strong>TypeError</strong></code> 객체는 보통 값이 기대하던 자료형이 아니라서 연산을 할 수 없을 때 발생하는 오류입니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code>new TypeError([<var>message</var>[, <var>fileName</var>[, <var>lineNumber</var>]]])</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>message</code> {{optional_inline}}</dt> + <dd>사람이 읽을 수 있는 오류에 대한 설명.</dd> + <dt><code>fileName</code> {{optional_inline}} {{non-standard_inline}}</dt> + <dd>오류가 발생한 코드를 포함한 파일 이름.</dd> + <dt><code>lineNumber</code> {{optional_inline}} {{non-standard_inline}}</dt> + <dd>오류가 발생한 코드의 줄 위치.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p>함수나 연산자의 인자가, 그 함수나 연산자가 예상하던 타입과 호환되지 않을 때 <code>TypeError</code> 오류가 던져집니다.</p> + +<h2 id="속성">속성</h2> + +<dl> + <dt>{{jsxref("TypeError.prototype")}}</dt> + <dd><code>TypeError</code> 객체에 속성을 추가할 수 있습니다.</dd> +</dl> + +<h2 id="메서드">메서드</h2> + +<p>전역 <code>TypeError</code>는 메서드는 자신만의 메서드를 갖지 않지만, 프로토타입 체인을 통해 몇몇 메서드를 상속합니다.</p> + +<h2 id="TypeError_인스턴스"><code>TypeError</code> 인스턴스</h2> + +<h3 id="속성_2">속성</h3> + +<div> +<dl> + <dt><code>TypeError.prototype.constructor</code></dt> + <dd>인스턴스의 프로토타입을 생성한 함수를 나타냅니다.</dd> + <dt>{{jsxref("Error.prototype.message", "TypeError.prototype.message")}}</dt> + <dd>오류의 메시지.</dd> + <dt>{{jsxref("Error.prototype.name", "TypeError.prototype.name")}}</dt> + <dd>오류 이름. {{jsxref("Error")}}에서 상속합니다.</dd> + <dt>{{jsxref("Error.prototype.fileName", "TypeError.prototype.fileName")}}</dt> + <dd>오류가 발생한 파일로의 경로. {{jsxref("Error")}}에서 상속합니다.</dd> + <dt>{{jsxref("Error.prototype.lineNumber", "TypeError.prototype.lineNumber")}}</dt> + <dd>오류가 발생한 곳의 줄 위치. {{jsxref("Error")}}에서 상속합니다.</dd> + <dt>{{jsxref("Error.prototype.columnNumber", "TypeError.prototype.columnNumber")}}</dt> + <dd>오류가 발생한 곳의 행 위치. {{jsxref("Error")}}에서 상속합니다.</dd> + <dt>{{jsxref("Error.prototype.stack", "TypeError.prototype.stack")}}</dt> + <dd>스택 추적. {{jsxref("Error")}}에서 상속합니다.</dd> +</dl> +</div> + +<h2 id="예제">예제</h2> + +<h3 id="TypeError_오류를_잡아내기"><code>TypeError</code> 오류를 잡아내기</h3> + +<pre class="brush: js">try { + null.f(); +} catch (e) { + console.log(e instanceof TypeError); // true + console.log(e.message); // "null has no properties" + console.log(e.name); // "TypeError" + console.log(e.fileName); // "Scratchpad/1" + console.log(e.lineNumber); // 2 + console.log(e.columnNumber); // 2 + console.log(e.stack); // "@Scratchpad/2:2:3\n" +} +</pre> + +<h3 id="TypeError_오류를_생성하기"><code>TypeError</code> 오류를 생성하기</h3> + +<pre class="brush: js">try { + throw new TypeError('Hello', "someFile.js", 10); +} catch (e) { + console.log(e instanceof TypeError); // true + console.log(e.message); // "Hello" + console.log(e.name); // "TypeError" + console.log(e.fileName); // "someFile.js" + console.log(e.lineNumber); // 10 + console.log(e.columnNumber); // 0 + console.log(e.stack); // "@Scratchpad/2:2:9\n" +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-native-error-types-used-in-this-standard-typeerror', 'TypeError')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.TypeError")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Error")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/undefined/index.html b/files/ko/web/javascript/reference/global_objects/undefined/index.html new file mode 100644 index 0000000000..8ff8f09360 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/undefined/index.html @@ -0,0 +1,138 @@ +--- +title: undefined +slug: Web/JavaScript/Reference/Global_Objects/undefined +tags: + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/undefined +--- +<div>{{jsSidebar("Objects")}}</div> + +<p>전역 <code><strong>undefined</strong></code> 속성은 <code>{{Glossary("Undefined", "undefined")}}</code> 원시 값을 나타내며, JavaScript의 {{Glossary("Primitive", "원시 자료형")}} 중 하나입니다.</p> + +<p>{{js_property_attributes(0,0,0)}}</p> + +<div>{{EmbedInteractiveExample("pages/js/globalprops-undefined.html")}}</div> + +<div class="hidden">The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</div> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox notranslate">undefined</pre> + +<h2 id="설명">설명</h2> + +<p><code>undefined</code>는 전역 객체의 속성입니다. 즉, 전역 스코프에서의 변수입니다. <code>undefined</code>의 초기 값은 <code>{{Glossary("Undefined", "undefined")}}</code> 원시 값입니다.</p> + +<p>최신 브라우저에서 <code>undefined</code>는 ECMAScript 5 명세에 따라 설정 불가, 쓰기 불가한 속성입니다. 그렇지 않더라도 덮어쓰는건 피하는게 좋습니다.</p> + +<p>값을 할당하지 않은 변수는 <code>undefined</code> 자료형입니다. 또한 메서드와 선언도 평가할 변수가 값을 할당받지 않은 경우에 <code>undefined</code>를 반환합니다. 함수는 값을 명시적으로 {{jsxref("Statements/return", "반환", "", 1)}}하지 않으면 <code>undefined</code>를 반환합니다.</p> + +<div class="note"> +<p><code>undefined</code>는 <a href="/ko/docs/Web/JavaScript/Reference/Reserved_Words">예약어</a>가 아니기 때문에 전역 범위 외에서 {{Glossary("Identifier", "식별자")}}(변수 이름)로 사용할 수 있습니다. 그러나 유지보수와 디버깅 시 어려움을 낳을 수 있으므로 반드시 피해야 합니다.</p> + +<pre class="brush: js example-bad notranslate">// DON'T DO THIS + +// logs "foo string" +(function() { + var undefined = 'foo'; + console.log(undefined, typeof undefined); +})(); + +// logs "foo string" +(function(undefined) { + console.log(undefined, typeof undefined); +})('foo');</pre> +</div> + +<h2 id="예제">예제</h2> + +<h3 id="일치_연산과_undefined">일치 연산과 <code>undefined</code></h3> + +<p><code>undefined</code>와 일치, 불일치 연산자를 사용해 변수에 값이 할당됐는지 판별할 수 있습니다. 다음 예제에서 변수 <code>x</code>는 초기화되지 않았으므로 <code>if</code>문은 <code>true</code>로 평가됩니다.</p> + +<pre class="brush: js notranslate">var x; +if (x === undefined) { + // 이 문이 실행됨 +} +else { + // 이 문이 실행되지 않음 +} +</pre> + +<div class="note"> +<p><strong>참고</strong>: 동등 연산자가 아니라 일치 연산자를 사용해야 합니다. 동등 연산자일 때 <code>x == undefined</code>는 <code>x</code>가 {{jsxref("null")}}일 때도 참이기 때문입니다. 즉 <code>null</code>은 <code>undefined</code>와 동등하지만, 일치하지는 않습니다.</p> + +<p>자세한 내용은 {{jsxref("Operators/Comparison_Operators", "비교 연산자", "", 1)}} 문서를 확인하세요.</p> +</div> + +<h3 id="typeof_연산자와_undefined"><code>typeof</code> 연산자와 <code>undefined</code></h3> + +<p>위의 예제 대신 {{jsxref("Operators/typeof", "typeof")}}를 사용할 수도 있습니다.</p> + +<pre class="brush: js notranslate">var x; +if (typeof x === 'undefined') { + // 이 문이 실행됨 +} +</pre> + +<p><code>typeof</code>를 사용하는 이유 중 하나는 선언하지 않은 변수를 사용해도 오류를 던지지 않기 때문입니다.</p> + +<pre class="brush: js notranslate">// x를 선언한 적 없음 +if (typeof x === 'undefined') { // 오류 없이 true로 평가 + // 이 문이 실행됨 +} + +if(x === undefined) { // ReferenceError + +} +</pre> + +<p>그러나 다른 방법도 있습니다. JavaScript는 정적 범위를 가지는 언어이므로, 변수의 선언 여부는 현재 맥락의 코드를 읽어 알 수 있습니다.</p> + +<p>전역 범위는 {{jsxref("globalThis", "전역 객체", "", 1)}}에 묶여 있으므로, 전역 맥락에서 변수의 존재 유무는 {{jsxref("Operators/in", "in")}} 연산자를 전역 객체 대상으로 실행해 알 수 있습니다. 즉,</p> + +<pre class="brush: js notranslate">if ('x' in window) { + // x가 전역으로 정의된 경우 이 문이 실행됨 +}</pre> + +<h3 id="void_연산자와_undefined"><code>void</code> 연산자와 <code>undefined</code></h3> + +<p>{{jsxref("Operators/void", "void")}} 연산자를 제 3의 대안으로 사용할 수 있습니다.</p> + +<pre class="brush: js notranslate">var x; +if (x === void 0) { + // 이 문이 실행됨 +} + +// y를 선언한 적 없음 +if (y === void 0) { + // Uncaught Reference Error: y is not defined +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-undefined', 'undefined')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.undefined")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>JavaScript의 {{glossary("Primitive", "원시 값")}}</li> + <li>{{jsxref("null")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/uneval/index.html b/files/ko/web/javascript/reference/global_objects/uneval/index.html new file mode 100644 index 0000000000..54713864f3 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/uneval/index.html @@ -0,0 +1,67 @@ +--- +title: uneval() +slug: Web/JavaScript/Reference/Global_Objects/uneval +tags: + - Function + - JavaScript + - Non-standard + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/uneval +--- +<div>{{jsSidebar("Objects")}}{{Non-standard_header}}</div> + +<p><code><strong>uneval()</strong></code>는 개체의 소스코드에 대한 문자열 표현을 만드는 함수이다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">uneval(<var>object</var>)</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>object</code></dt> + <dd>JavaScript 표현식 혹은 구문.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 개체의 소스코드에 대한 문자열 표현</p> + +<div class="note"><strong>주의:</strong> 인자로 넘긴 개체의 유효한 JSON 표현이 아닐 수 있습니다.</div> + +<h2 id="설명">설명</h2> + +<p><code>uneval()</code>은 최상위 수준의 함수이며 어떠한 개체와도 연관 되어있지 않습니다.</p> + +<h2 id="예제">예제</h2> + +<pre class="brush:js">var a = 1; +uneval(a); // 1을 포함한 문자열을 반환한다 + +var b = '1'; +uneval(b); // "1"을 포함한 문자열을 반환한다 + +uneval(function foo() {}); // "(function foo(){})"를 반환 + + +var a = uneval(function foo() { return 'hi'; }); +var foo = eval(a); +foo(); // "hi"를 반환 +</pre> + +<h2 id="명세">명세</h2> + +<p>어떤 명세에도 속하지 않습니다.</p> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.uneval")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Global_Objects/eval", "eval()")}}</li> + <li>{{jsxref("JSON.stringify")}}</li> + <li>{{jsxref("JSON.parse")}}</li> + <li>{{jsxref("Object.toSource")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/weakmap/delete/index.html b/files/ko/web/javascript/reference/global_objects/weakmap/delete/index.html new file mode 100644 index 0000000000..0c82351679 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/weakmap/delete/index.html @@ -0,0 +1,80 @@ +--- +title: WeakMap.prototype.delete() +slug: Web/JavaScript/Reference/Global_Objects/WeakMap/delete +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - WeakMap +translation_of: Web/JavaScript/Reference/Global_Objects/WeakMap/delete +--- +<div>{{JSRef}}</div> + +<p><code><strong>delete()</strong></code> 메소드는 <code>WeakMap</code> 객체의 특정 요소를 제거합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/weakmap-prototype-delete.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><em>wm</em>.delete(<em>key</em>);</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>key</code></dt> + <dd><code>WeakMap</code> 객체에서 제거할 요소의 키.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p><code>WeakMap</code> 객체의 요소가 성공적으로 제거되면 <code>true</code>, 키를 찾을 수 없거나 키가 객체가 아닌 경우 <code>false</code>.</p> + +<h2 id="예제">예제</h2> + +<h3 id="delete_메서드_사용하기"><code>delete</code> 메서드 사용하기</h3> + +<pre class="brush: js;highlight:[4]">var wm = new WeakMap(); +wm.set(window, 'foo'); + +wm.delete(window); // Returns true. Successfully removed. + +wm.has(window); // Returns false. The window object is no longer in the WeakMap. +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-weakmap.prototype.delete', 'WeakMap.prototype.delete')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-weakmap.prototype.delete', 'WeakMap.prototype.delete')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.WeakMap.delete")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("WeakMap")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/weakmap/index.html b/files/ko/web/javascript/reference/global_objects/weakmap/index.html new file mode 100644 index 0000000000..392759f523 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/weakmap/index.html @@ -0,0 +1,283 @@ +--- +title: WeakMap +slug: Web/JavaScript/Reference/Global_Objects/WeakMap +tags: + - ECMAScript6 + - JavaScript + - WeakMap +translation_of: Web/JavaScript/Reference/Global_Objects/WeakMap +--- +<div>{{JSRef}}</div> + +<p><strong><code>WeakMap</code></strong> 객체는 키가 약하게 참조되는 키/값 쌍의 컬렉션입니다. 키는 객체여야만 하나 값은 임의 값이 될 수 있습니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">new WeakMap([iterable]) +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>iterable</code></dt> + <dd>iterable은 배열 또는 요소가 키-값 쌍(2-요소 배열)인 다른 iterable 객체입니다. 각 키-값 쌍은 새로운 WeakMap에 추가됩니다. null은 undefined로 취급됩니다.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p>WeakMap의 키는 오직 <code>Object</code>형뿐입니다. 키로 {{Glossary("Primitive", "원시 데이터형")}}은 허용되지 않습니다(가령 {{jsxref("Symbol")}}은 <code>WeakMap</code> 키가 될 수 없습니다).</p> + +<p>WeakMap 내 키는 약하게 유지됩니다. 이게 뜻하는 바는, 다른 강한 키 참조가 없는 경우, 그러면 모든 항목은 가비지 컬렉터에 의해 WeakMap에서 제거됩니다.</p> + +<h3 id="왜_WeakMap인가요">왜 <em>Weak</em>Map인가요?</h3> + +<p>숙련된 JavaScript 프로그래머는 이 API는 네 API 메서드에 의해 공유되는 두 배열(키에 하나, 값에 하나)로 JavaScript에서 구현될 수 있음을 알 수 있습니다. 이러한 구현은 주로 두 가지가 불편했을 겁니다. 첫 번째는 O(n) 검색(n은 map 내 키 개수)입니다. 두 번째는 메모리 누수 문제입니다. 수동으로 작성된 map이면, 키 배열은 키 객체 참조를 유지하려고 합니다, 가비지 컬렉트되는 것을 방지하는. 원래 WeakMap에서는, 키 객체 참조는 "약하게" 유지되고, 이는 다른 객체 참조가 없는 경우 가비지 컬렉션을 막지 않음을 뜻합니다.</p> + +<p>약한 참조로 인해, <code>WeakMap</code> 키는 열거불가입니다(즉 키 목록을 제공하는 메서드가 없습니다). 키가 있다면, 그 목록은 가비지 콜렉션 상태에 달려있습니다, 비결정성(non-determinism, 크기를 결정할 수 없는)을 도입하는. 키 목록을 원하는 경우, {{jsxref("Map")}}을 사용해야 합니다.</p> + +<h2 id="속성">속성</h2> + +<dl> + <dt><code>WeakMap.length</code></dt> + <dd><code>length</code> 속성값은 0.</dd> + <dt>{{jsxref("WeakMap.prototype")}}</dt> + <dd><code>WeakMap</code> 생성자에 대한 프로토타입을 나타냅니다. 모든 <code>WeakMap</code> 객체에 속성을 추가할 수 있습니다.</dd> +</dl> + +<h2 id="WeakMap_인스턴스"><code>WeakMap</code> 인스턴스</h2> + +<p>모든 <code>WeakMap</code> 인스턴스는 {{jsxref("WeakMap.prototype")}}에서 상속합니다.</p> + +<h3 id="속성_2">속성</h3> + +<p>{{page('ko/docs/Web/JavaScript/Reference/Global_Objects/WeakMap/prototype','속성')}}</p> + +<h3 id="메서드">메서드</h3> + +<p>{{page('ko/docs/Web/JavaScript/Reference/Global_Objects/WeakMap/prototype','메서드')}}</p> + +<h2 id="예">예</h2> + +<h3 id="WeakMap_사용"><code>WeakMap</code> 사용</h3> + +<pre class="brush: js">var wm1 = new WeakMap(), + wm2 = new WeakMap(), + wm3 = new WeakMap(); +var o1 = {}, + o2 = function(){}, + o3 = window; + +wm1.set(o1, 37); +wm1.set(o2, "azerty"); +wm2.set(o1, o2); // 값은 무엇이든 될 수 있음, 객체 또는 함수 포함 +wm2.set(o3, undefined); +wm2.set(wm1, wm2); // 키와 값은 어떤 객체든 될 수 있음. 심지어 WeakMap도! + +wm1.get(o2); // "azerty" +wm2.get(o2); // undefined, wm2에 o2에 대한 키가 없기에 +wm2.get(o3); // undefined, 이게 설정값이기에 + +wm1.has(o2); // true +wm2.has(o2); // false +wm2.has(o3); // true (값 자체가 'undefined'이더라도) + +wm3.set(o1, 37); +wm3.get(o1); // 37 + +wm1.has(o1); // true +wm1.delete(o1); +wm1.has(o1); // false +</pre> + +<h3 id=".clear()_메서드로_WeakMap_같은_클래스_구현">.clear() 메서드로 <code>WeakMap</code> 같은 클래스 구현</h3> + +<p>설명을 위해, 다음 예는 새로운 ECMAScript 6 <code>class</code> 구조를 사용합니다, 현재 널리 구현되지 않은.</p> + +<pre class="brush: js">class ClearableWeakMap { + constructor(init) { + this._wm = new WeakMap(init) + } + clear() { + this._wm = new WeakMap() + } + delete(k) { + return this._wm.delete(k) + } + get(k) { + return this._wm.get(k) + } + has(k) { + return this._wm.has(k) + } + set(k, v) { + this._wm.set(k, v) + return this + } +} +</pre> + +<h2 id="스펙">스펙</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ES6', '#sec-weakmap-objects', 'WeakMap')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-weakmap-objects', 'WeakMap')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>36</td> + <td>{{CompatGeckoDesktop("6.0")}}</td> + <td>11</td> + <td>{{ CompatOpera(23) }}</td> + <td>7.1</td> + </tr> + <tr> + <td><code>new WeakMap(iterable)</code></td> + <td>38</td> + <td>{{CompatGeckoDesktop("36")}}</td> + <td>{{CompatNo}}</td> + <td>{{ CompatOpera(25) }}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>clear()</code></td> + <td>36</td> + <td>{{CompatNo}} [1]</td> + <td>11</td> + <td>{{ CompatOpera(23) }}</td> + <td>7.1</td> + </tr> + <tr> + <td>Constructor argument: <code>new WeakMap(null)</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("37")}}</td> + <td>11</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Monkey-patched <code>set()</code> in constructor</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("37")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>WeakMap()</code> without <code>new</code> throws</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("42")}}</td> + <td>11</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>35</td> + <td>{{CompatGeckoMobile("6.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>8</td> + </tr> + <tr> + <td><code>new WeakMap(iterable)</code></td> + <td>38</td> + <td>{{CompatGeckoMobile("36")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>clear()</code></td> + <td>35</td> + <td>{{CompatNo}} [1]</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>8</td> + </tr> + <tr> + <td>Constructor argument: <code>new WeakMap(null)</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("37")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Monkey-patched <code>set()</code> in constructor</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("37")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>WeakMap()</code> without <code>new</code> throws</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("42")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] clear() 메서드는 버전 20부터 45(포함)까지 지원됐습니다.</p> + +<h2 id="참조">참조</h2> + +<ul> + <li><a class="link-https" href="https://bugzilla.mozilla.org/show_bug.cgi?id=547941">Mozilla에서 WeakMap 버그</a></li> + <li><a href="http://fitzgeraldnick.com/weblog/53/">ECMAScript 6 WeakMap으로 구현 정보 은닉</a></li> + <li>{{jsxref("Map")}}</li> + <li>{{jsxref("Set")}}</li> + <li>{{jsxref("WeakSet")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/weakmap/prototype/index.html b/files/ko/web/javascript/reference/global_objects/weakmap/prototype/index.html new file mode 100644 index 0000000000..48b4586b6e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/weakmap/prototype/index.html @@ -0,0 +1,142 @@ +--- +title: WeakMap.prototype +slug: Web/JavaScript/Reference/Global_Objects/WeakMap/prototype +tags: + - ECMAScript6 + - JavaScript + - Property + - WeakMap +translation_of: Web/JavaScript/Reference/Global_Objects/WeakMap +--- +<div>{{JSRef}}</div> + +<p><code><strong>WeakMap.prototype</strong></code> 속성(property)은 {{jsxref("WeakMap")}} 생성자에 대한 프로토타입을 나타냅니다.</p> + +<div>{{js_property_attributes(0,0,0)}}</div> + +<h2 id="설명">설명</h2> + +<p>{{jsxref("WeakMap")}} 인스턴스는 {{jsxref("WeakMap.prototype")}}에서 상속합니다. 모든 <code>WeakMap</code> 인스턴스에 속성 또는 메서드를 추가하기 위해 생성자의 프로토타입 객체를 사용할 수 있습니다.</p> + +<p><code>WeakMap.prototype</code>은 그 자체로 그냥 평범한 객체입니다:</p> + +<pre class="brush: js">Object.prototype.toString.call(WeakMap.prototype); // "[object Object]"</pre> + +<h2 id="속성">속성</h2> + +<dl> + <dt><code>WeakMap.prototype.constructor</code></dt> + <dd>인스턴스의 프로토타입을 생성한 함수를 반환합니다. 이는 기본으로 {{jsxref("WeakMap")}} 함수입니다.</dd> +</dl> + +<h2 id="메서드">메서드</h2> + +<dl> + <dt>{{jsxref("WeakMap.delete", "WeakMap.prototype.delete(key)")}}</dt> + <dd><code>key</code>와 관련된 모든 값을 제거합니다. <code>WeakMap.prototype.has(key)</code>는 그 뒤에 <code>false</code>를 반환합니다.</dd> + <dt>{{jsxref("WeakMap.get", "WeakMap.prototype.get(key)")}}</dt> + <dd><code>key</code>와 관련된 값 또는 관련 값이 없는 경우 <code>undefined</code>를 반환합니다.</dd> + <dt>{{jsxref("WeakMap.has", "WeakMap.prototype.has(key)")}}</dt> + <dd><code>WeakMap</code> 객체 내 <code>key</code>와 관련된 값이 있는지 여부를 주장하는(asserting, 나타내는) boolean을 반환합니다.</dd> + <dt>{{jsxref("WeakMap.set", "WeakMap.prototype.set(key, value)")}}</dt> + <dd><code>WeakMap</code> 객체 내 <code>key</code>에 대해 값을 설정합니다. <code>WeakMap</code> 객체를 반환합니다.</dd> + <dt><s class="obsoleteElement">{{jsxref("WeakMap.prototype.clear()")}} {{obsolete_inline}}</s></dt> + <dd><s class="obsoleteElement"><code>WeakMap</code> 객체에서 모든 키/값 쌍을 제거합니다. 메서드가 없는 <code>WeakMap</code> 객체를 캡슐화하여 <code>.clear()</code> 메서드가 있는 <code>WeakMap</code> 같은 객체 구현이 가능함을 주의하세요 ({{jsxref("WeakMap")}} 페이지 예 참조)</s></dd> +</dl> + +<h2 id="스펙">스펙</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-weakmap.prototype', 'WeakMap.prototype')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-weakmap.prototype', 'WeakMap.prototype')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>36</td> + <td>{{CompatGeckoDesktop("6.0")}}</td> + <td>11</td> + <td>23</td> + <td>7.1</td> + </tr> + <tr> + <td>Ordinary object</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("40")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile("6.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>8</td> + </tr> + <tr> + <td>Ordinary object</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("40")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("Map.prototype")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/weakset/index.html b/files/ko/web/javascript/reference/global_objects/weakset/index.html new file mode 100644 index 0000000000..17f818659d --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/weakset/index.html @@ -0,0 +1,108 @@ +--- +title: WeakSet +slug: Web/JavaScript/Reference/Global_Objects/WeakSet +tags: + - ECMAScript 2015 + - JavaScript + - Reference + - WeakSet +translation_of: Web/JavaScript/Reference/Global_Objects/WeakSet +--- +<div>{{JSRef}}</div> + +<p><strong><code>WeakSet</code></strong> 객체는 약하게 유지되는(held, 잡아두는) <em>객체</em>를 컬렉션에 저장할 수 있습니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">new WeakSet([iterable]);</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>iterable</code></dt> + <dd><a href="/ko/docs/Web/JavaScript/Reference/Statements/for...of">iterable 객체</a>가 전달된 경우, 모든 객체 요소는 새로운 <code>WeakSet</code>에 추가됩니다. null은 undefined로 취급됩니다.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p><code>WeakSet</code> 객체는 객체 컬렉션입니다. <code>WeakSet</code> 내 객체는 오직 한 번만 발생할 수 있습니다. 즉, <code>WeakSet</code> 컬렉션 내에서 유일합니다.</p> + +<p>{{jsxref("Set")}} 객체와 주된 차이는 다음과 같습니다:</p> + +<ul> + <li><code>Set</code>과 달리, <code>WeakSet</code>은 <strong>객체 만의 컬렉션</strong>이며 모든 유형의 임의 값(의 컬렉션)은 아닙니다.</li> + <li><code>WeakSet</code>은 약합니다(<em>weak</em>): 컬렉션 내 객체 참조는 약하게 유지됩니다. <code>WeakSet</code> 내 저장된 객체에 다른 참조가 없는 경우, 쓰레기 수집(garbage collection)될 수 있습니다. 이는 또한 컬렉션 내 현재 저장된 객체 목록이 없음을 뜻합니다. <code>WeakSets</code>은 열거불가입니다.</li> +</ul> + +<h2 id="속성">속성</h2> + +<dl> + <dt><code>WeakSet.length</code></dt> + <dd><code>length</code> 속성값은 0.</dd> + <dt>{{jsxref("WeakSet.prototype")}}</dt> + <dd><code>Set</code> 생성자에 대한 프로토타입을 나타냅니다. 모든 <code>WeakSet</code> 객체에 속성을 추가할 수 있습니다.</dd> +</dl> + +<h2 id="WeakSet_인스턴스"><code>WeakSet</code> 인스턴스</h2> + +<p>모든 <code>WeakSet</code> 인스턴스는 {{jsxref("WeakSet.prototype")}}에서 상속합니다.</p> + +<h3 id="속성_2">속성</h3> + +<p>{{page('ko/docs/Web/JavaScript/Reference/Global_Objects/WeakSet/prototype','속성')}}</p> + +<h3 id="메서드">메서드</h3> + +<p>{{page('ko/docs/Web/JavaScript/Reference/Global_Objects/WeakSet/prototype','메서드')}}</p> + +<h2 id="예제">예제</h2> + +<h3 id="WeakSet_객체_사용"><code>WeakSet</code> 객체 사용</h3> + +<pre class="brush: js">var ws = new WeakSet(); +var obj = {}; +var foo = {}; + +ws.add(window); +ws.add(obj); + +ws.has(window); // true +ws.has(foo); // false, foo가 집합에 추가되지 않았음 + +ws.delete(window); // 집합에서 window 제거함 +ws.has(window); // false, window가 제거되었음 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-weakset-objects', 'WeakSet')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-weakset-objects', 'WeakSet')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.WeakSet")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Map")}}</li> + <li>{{jsxref("Set")}}</li> + <li>{{jsxref("WeakMap")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/weakset/prototype/index.html b/files/ko/web/javascript/reference/global_objects/weakset/prototype/index.html new file mode 100644 index 0000000000..ee3f439ae9 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/weakset/prototype/index.html @@ -0,0 +1,141 @@ +--- +title: WeakSet.prototype +slug: Web/JavaScript/Reference/Global_Objects/WeakSet/prototype +tags: + - ECMAScript6 + - JavaScript + - Property + - WeakSet +translation_of: Web/JavaScript/Reference/Global_Objects/WeakSet +--- +<div>{{JSRef}}</div> + +<p><code><strong>WeakSet.prototype</strong></code> 속성(property)은 {{jsxref("WeakSet")}} 생성자에 대한 프로토타입을 나타냅니다.</p> + +<div>{{js_property_attributes(0,0,0)}}</div> + +<h2 id="설명">설명</h2> + +<p>{{jsxref("WeakSet")}} 인스턴스는 {{jsxref("WeakSet.prototype")}}에서 상속합니다. 모든 <code>WeakSet</code> 인스턴스에 속성 또는 메서드를 추가하기 위해 생성자의 프로토타입 객체를 사용할 수 있습니다.</p> + +<p><code>WeakSet.prototype</code>은 그 자체로 그냥 평범한 객체입니다:</p> + +<pre class="brush: js">Object.prototype.toString.call(WeakSet.prototype); // "[object Object]"</pre> + +<h2 id="속성">속성</h2> + +<dl> + <dt><code>WeakSet.prototype.constructor</code></dt> + <dd>인스턴스의 프로토타입을 생성한 함수를 반환합니다. 이는 기본으로 {{jsxref("WeakSet")}} 함수입니다.</dd> +</dl> + +<h2 id="메서드">메서드</h2> + +<dl> + <dt>{{jsxref("WeakSet.add", "WeakSet.prototype.add(value)")}}</dt> + <dd><code>WeakSet</code> 객체에 주어진 값을 갖는 새로운 객체를 추가합니다.</dd> + <dt>{{jsxref("WeakSet.delete", "WeakSet.prototype.delete(value)")}}</dt> + <dd><code>value</code>와 관련된 요소를 제거합니다. <code>WeakSet.prototype.has(value)</code>는 그 뒤에 <code>false</code>를 반환합니다.</dd> + <dt>{{jsxref("WeakSet.has", "WeakSet.prototype.has(value)")}}</dt> + <dd><code>WeakSet</code> 객체 내 주어진 값을 갖는 요소가 존재하는 지 여부를 주장하는(asserting, 나타내는) boolean을 반환합니다.</dd> + <dt><s class="obsoleteElement">{{jsxref("WeakSet.prototype.clear()")}} {{obsolete_inline}}</s></dt> + <dd><s class="obsoleteElement"><code>WeakSet</code> 객체에서 모든 요소를 제거합니다.</s></dd> +</dl> + +<h2 id="스펙">스펙</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-weakset.prototype', 'WeakSet.prototype')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-weakset.prototype', 'WeakSet.prototype')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>36</td> + <td>{{ CompatGeckoDesktop(34) }}</td> + <td>{{CompatNo}}</td> + <td>23</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Ordinary object</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("40")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome for Android</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{ CompatGeckoMobile(34) }}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Ordinary object</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("40")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("Set.prototype")}}</li> + <li>{{jsxref("WeakMap.prototype")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/webassembly/compile/index.html b/files/ko/web/javascript/reference/global_objects/webassembly/compile/index.html new file mode 100644 index 0000000000..eb7dd71f5f --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/webassembly/compile/index.html @@ -0,0 +1,83 @@ +--- +title: WebAssembly.compile() +slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/compile +translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/compile +--- +<div>{{JSRef}}</div> + +<p><strong><code>WebAssembly.compile()</code></strong>함수는 WebAssembly 바이너리 코드에서 {{jsxref ( "WebAssembly.Module")}}을 컴파일합니다. 이 함수는 모듈을 인스턴스화하기 전에 컴파일해야하는 경우에 유용합니다. 그렇지 않으면 {{jsxref ( "WebAssembly.instantiate ()")}} 함수를 사용해야합니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">Promise<WebAssembly.Module> WebAssembly.compile(bufferSource);</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><em>bufferSource</em></dt> + <dd>컴파일 할 .wasm 모듈의 이진 코드가 들어있는 <a href="/en-US/docs/Web/JavaScript/Typed_arrays">typed array</a> 또는 <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer">ArrayBuffer</a>입니다.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p><code>Promise</code>는 컴파일 된 모듈로 표현된 {{jsxref ( "WebAssembly.Module")}} 객체로 반환됩니다.</p> + +<h3 id="Exceptions">Exceptions</h3> + +<ul> + <li><code>bufferSource</code>가 <a href="/en-US/docs/Web/JavaScript/Typed_arrays">typed array</a>가 아니면 {{jsxref("TypeError")}}가 발생합니다.</li> + <li>컴파일에 실패하면 promise는 {{jsxref("WebAssembly.CompileError")}}와 함께 reject가 반환됩니다.</li> +</ul> + +<h2 id="Examples">Examples</h2> + +<p>다음은 <code>compile()</code> 함수를 사용하여 simple.wasm 바이트 코드를 컴파일 하고 <a href="/en-US/docs/Web/API/Worker/postMessage">postMessage()</a>를 사용하여 <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API">worker</a>에 보내는 예제입니다.</p> + +<pre class="brush: js">var worker = new Worker("wasm_worker.js"); + +fetch('simple.wasm').then(response => + response.arrayBuffer() +).then(bytes => + WebAssembly.compile(bytes) +).then(mod => + worker.postMessage(mod) +);</pre> + +<div class="note"> +<p><strong>Note</strong>: 대부분의 경우에 {{jsxref("WebAssembly.compileStreaming()")}}를 사용하는 것이 좋습니다. 이는 <code>compile()</code>보다 효율적이기 때문입니다.</p> +</div> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('WebAssembly JS', '#webassemblycompile', 'compile()')}}</td> + <td>{{Spec2('WebAssembly JS')}}</td> + <td>Initial draft definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.WebAssembly.compile")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/WebAssembly">WebAssembly</a> overview page</li> + <li><a href="/en-US/docs/WebAssembly/Concepts">WebAssembly concepts</a></li> + <li><a href="/en-US/docs/WebAssembly/Using_the_JavaScript_API">Using the WebAssembly JavaScript API</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/webassembly/compileerror/index.html b/files/ko/web/javascript/reference/global_objects/webassembly/compileerror/index.html new file mode 100644 index 0000000000..40ba328985 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/webassembly/compileerror/index.html @@ -0,0 +1,114 @@ +--- +title: WebAssembly.CompileError() +slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/CompileError +translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/CompileError +--- +<div>{{JSRef}}</div> + +<p><code><strong>WebAssembly.CompileError()</strong></code>생성자는 WebAssembly 디코딩 또는 유효성 검사 중에 발생한 오류를 나타내는 WebAssembly <code>CompileError</code> 객체를 새로 만듭니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code>new WebAssembly.CompileError(<var>message</var>, <var>fileName</var>, <var>lineNumber</var>)</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>message</code> {{optional_inline}}</dt> + <dd>사람이 읽을수 있는 형태의 에러에 대한 설명.</dd> + <dt><code>fileName</code> {{optional_inline}}{{non-standard_inline}}</dt> + <dd>예외의 원인이 된 코드가 들어있는 파일의 이름입니다.</dd> + <dt><code>lineNumber</code> {{optional_inline}}{{non-standard_inline}}</dt> + <dd>예외의 원인이 된 코드의 행 번호입니다.</dd> +</dl> + +<h2 id="Properties">Properties</h2> + +<p><em><code>CompileError</code> 생성자에는 고유 한 고유 속성이 없지만 프로토 타입 체인을 통해 일부 속성을 상속합니다.</em></p> + +<dl> + <dt><code>WebAssembly.CompileError.prototype.constructor</code></dt> + <dd>인스턴스의 프로토 타입을 작성한 함수를 지정합니다.</dd> + <dt>{{jsxref("Error.prototype.message", "WebAssembly.CompileError.prototype.message")}}</dt> + <dd>에러 메시지. ECMA-262는 {{jsxref ( "URIError")}}가 <a href="/en-US/docs/Mozilla/Projects/SpiderMonkey">SpiderMonkey</a>에서 자체 <code>message</code> 속성을 제공하도록 지정했지만 {{jsxref ( "Error.prototype.message")}}를 상속받습니다.</dd> + <dt>{{jsxref("Error.prototype.name", "WebAssembly.CompileError.prototype.name")}}</dt> + <dd>에러 명칭. {{jsxref("Error")}}에서 상속합니다.</dd> + <dt>{{jsxref("Error.prototype.fileName", "WebAssembly.CompileError.prototype.fileName")}}</dt> + <dd>에러가 발생한 파일의 경로. {{jsxref("Error")}}에서 상속합니다.</dd> + <dt>{{jsxref("Error.prototype.lineNumber", "WebAssembly.CompileError.prototype.lineNumber")}}</dt> + <dd>에러가 발생한 파일의 코드 줄번호. {{jsxref("Error")}}에서 상속합니다.</dd> + <dt>{{jsxref("Error.prototype.columnNumber", "WebAssembly.CompileError.prototype.columnNumber")}}</dt> + <dd>에러가 발생한 줄의 열 번호. {{jsxref("Error")}}에서 상속합니다.</dd> + <dt>{{jsxref("Error.prototype.stack", "WebAssembly.CompileError.prototype.stack")}}</dt> + <dd>스텍 추적. {{jsxref("Error")}}에서 상속합니다.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em><code>CompileError</code></em> 생성자에는 자체 메서드가 없지만 프로토 타입 체인을 통해 일부 메서드를 상속합니다.</p> + +<dl> + <dt>{{jsxref("Error.prototype.toSource", "WebAssembly.CompileError.prototype.toSource()")}}</dt> + <dd>동일한 오류로 판단할 수 있는 코드를 반환합니다. {{jsxref("Error")}}에서 상속합니다.</dd> + <dt>{{jsxref("Error.prototype.toString", "WebAssembly.CompileError.prototype.toString()")}}</dt> + <dd>지정된 Error 객체를 나타내는 문자열을 반환합니다. {{jsxref("Error")}}에서 상속합니다.</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<p>다음 스 니펫은 새 <code>CompileError</code> 인스턴스를 만들고 콘솔에 세부 정보를 기록합니다.</p> + +<pre class="brush: js">try { + throw new WebAssembly.CompileError('Hello', 'someFile', 10); +} catch (e) { + console.log(e instanceof CompileError); // true + console.log(e.message); // "Hello" + console.log(e.name); // "CompileError" + console.log(e.fileName); // "someFile" + console.log(e.lineNumber); // 10 + console.log(e.columnNumber); // 0 + console.log(e.stack); // returns the location where the code was run +}</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('WebAssembly JS', '#constructor-properties-of-the-webassembly-object', 'WebAssembly constructors')}}</td> + <td>{{Spec2('WebAssembly JS')}}</td> + <td>Initial WebAssembly draft definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-native-error-types-used-in-this-standard', 'NativeError')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Definition of standard NativeError types.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.WebAssembly.CompileError")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/WebAssembly">WebAssembly</a> overview page</li> + <li><a href="/en-US/docs/WebAssembly/Concepts">WebAssembly concepts</a></li> + <li><a href="/en-US/docs/WebAssembly/Using_the_JavaScript_API">Using the WebAssembly JavaScript API</a></li> +</ul> + +<dl> +</dl> diff --git a/files/ko/web/javascript/reference/global_objects/webassembly/compilestreaming/index.html b/files/ko/web/javascript/reference/global_objects/webassembly/compilestreaming/index.html new file mode 100644 index 0000000000..a713ca1c0d --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/webassembly/compilestreaming/index.html @@ -0,0 +1,79 @@ +--- +title: WebAssembly.compileStreaming() +slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/compileStreaming +translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/compileStreaming +--- +<div>{{JSRef}}</div> + +<p><strong><code>WebAssembly.compileStreaming()</code></strong>함수는 스트림 된 원본 소스에서 직접 {{jsxref ( "WebAssembly.Module")}}을 컴파일합니다. 이 함수는 모듈을 인스턴스화하기 전에 컴파일해야하는 경우 유용합니다 (그렇지 않으면 {{jsxref ( "WebAssembly.instantiateStreaming ()")}} 함수를 사용해야합니다).</p> + +<p> </p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">Promise<WebAssembly.Module> WebAssembly.compileStreaming(<em>source</em>);</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><em>source</em></dt> + <dd>스트리밍 및 컴파일하려는 .wasm 모듈의 기본 소스를 나타내는 {{domxref ( "Response")}} 객체 또는 약속을 수행합니다.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p><code>Promise</code>는 컴파일 된 모듈로 표현된 <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module" title="The documentation about this has not yet been written; please consider contributing!"><code>WebAssembly.Module</code></a> 객체로 반환됩니다.</p> + +<h3 id="Exceptions">Exceptions</h3> + +<ul> + <li><code>bufferSource</code>가 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays">typed array</a>가 아니면 <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/TypeError" title="TypeError 객체는 변수의 값이 원하는 타입이 아닐 때 발생하는 에러를 표현합니다."><code>TypeError</code></a>가 발생합니다.</li> + <li>컴파일에 실패하면 promise는 <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/CompileError" rel="nofollow" title="The documentation about this has not yet been written; please consider contributing!"><code>WebAssembly.CompileError</code></a>와 함께 reject가 반환됩니다.</li> +</ul> + +<h2 id="Examples">Examples</h2> + +<p>다음 예제 (GitHub의 <a href="https://github.com/mdn/webassembly-examples/blob/master/js-api-examples/compile-streaming.html">compile-streaming.html</a> 데모 및 <a href="https://mdn.github.io/webassembly-examples/js-api-examples/compile-streaming.html">라이브보기</a>)에서 기본 소스의 .wasm 모듈을 직접 스트리밍 한 다음 {{jsxref ( "WebAssembly.Module")}} 객체로 컴파일합니다. <code>compileStreaming()</code> 함수는 {{domxref ( "Response")}} 객체에 대한 promise를 받으므로 직접 {{domxref ( "WindowOrWorkerGlobalScope.fetch ()")}} 호출을 전달할 수 있습니다.</p> + +<pre class="brush: js">var importObject = { imports: { imported_func: arg => console.log(arg) } }; + +WebAssembly.compileStreaming(fetch('simple.wasm')) +.then(module => WebAssembly.instantiate(module, importObject)) +.then(instance => instance.exports.exported_func());</pre> + +<p>결과 모듈 인스턴스는 {{jsxref ( "WebAssembly.instantiate ()")}}를 사용하여 인스턴스화되고 내 보낸 함수가 호출됩니다.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('WebAssembly Embedding', '#webassemblycompilestreaming', 'compileStreaming()')}}</td> + <td>{{Spec2('WebAssembly Embedding')}}</td> + <td>Initial draft definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.WebAssembly.compileStreaming")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/WebAssembly">WebAssembly</a> overview page</li> + <li><a href="/en-US/docs/WebAssembly/Concepts">WebAssembly concepts</a></li> + <li><a href="/en-US/docs/WebAssembly/Using_the_JavaScript_API">Using the WebAssembly JavaScript API</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/webassembly/global/index.html b/files/ko/web/javascript/reference/global_objects/webassembly/global/index.html new file mode 100644 index 0000000000..c85d74b53c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/webassembly/global/index.html @@ -0,0 +1,116 @@ +--- +title: WebAssembly.Global +slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/Global +translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/Global +--- +<div>{{JSRef}}</div> + +<div> </div> + +<div><strong><code>WebAssembly.Global</code></strong> 객체는 전역 변수 인스턴스를 나타내며 JavaScript 및 하나 이상의 {{jsxref("WebAssembly.Module")}} 인스턴스에서 가져 오거나 내보낼 수 있습니다. 이렇게하면 여러 모듈을 동적으로 연결할 수 있습니다.</div> + +<h2 id="Constructor_Syntax">Constructor Syntax</h2> + +<pre class="syntaxbox">var myGlobal = new WebAssembly.Global(<em>descriptor</em>, <em>value</em>);</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><em>descriptor</em></dt> + <dd>A <code>GlobalDescriptor</code> dictionary object, 두 개의 속성이 포함되어 있습니다. + <ul> + <li><code>value</code>: {{domxref("USVString")}}는 전역의 데이터 유형을 나타냅니다. i32, i64, f32 및 f64 중 하나입니다.</li> + <li><code>mutable</code>: 전역 변수를 변경할 수 있는지 여부를 결정하는 부울 값입니다. 기본적으로 <code>false</code>입니다.</li> + </ul> + </dd> + <dt><em>value</em></dt> + <dd>변수에 포함 된 값입니다. 변수의 데이터 타입과 일치하는 한 모든 값을 사용할 수 있습니다.<br> + 변수에 포함 된 값입니다. 변수의 데이터 타입과 일치하는 모든 값을 사용할 수 있습니다. 값을 지정하지 않으면 <a href="https://webassembly.github.io/spec/js-api/#defaultvalue"><code>DefaultValue</code> 알고리즘</a>에 지정된대로 입력 된 0 값이 사용됩니다.</dd> +</dl> + +<h2 id="Function_properties_of_the_Module_constructor">Function properties of the <code>Module</code> constructor</h2> + +<p>None.</p> + +<h2 id="Global_instances">Global instances</h2> + +<p>모든 <code>Global</code> 인스턴스는 <code>Global()</code> 생성자의 <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Global/prototype">prototype object</a>에서 상속받습니다.이 인스턴스는 모든 <code>Global</code> 인스턴스에 영향을 미치도록 수정할 수 있습니다.</p> + +<h3 id="Instance_properties">Instance properties</h3> + +<p>{{page('/ko/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Global/prototype', 'Properties')}}</p> + +<h3 id="Instance_methods">Instance methods</h3> + +<p>{{page('/ko/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Global/prototype', 'Methods')}}</p> + +<h2 id="Examples">Examples</h2> + +<p>다음 예제에서는 <code>WebAssembly.Global()</code> 생성자를 사용하여 만드는 새 전역 인스턴스를 보여줍니다. 값이 0 인 변경 가능한 <code>i32</code> 유형으로 정의됩니다.</p> + +<p>The value of the global is then changed, first to <code>42</code> using the <code>Global.value</code> property, and then to 43 using the <code>incGlobal()</code> function exported out of the <code>global.wasm</code> module (this adds 1 to whatever value is given to it and then returns the new value). </p> + +<p>그런 다음 <code>global.value</code> 속성을 사용하여 <code>42</code>까지 전역 값을 변경 한 다음 <code>global.wasm</code> 모듈에서 내 보낸 <code>incGlobal()</code> 함수를 사용하여 43으로 변경합니다.(이것은 값이 주어진 값에 1을 더한 다음 새 값을 반환합니다.)</p> + +<pre class="brush: js">const output = document.getElementById('output'); + +function assertEq(msg, got, expected) { + output.innerHTML += `Testing ${msg}: `; + if (got !== expected) + output.innerHTML += `FAIL!<br>Got: ${got}<br>Expected: ${expected}<br>`; + else + output.innerHTML += `SUCCESS! Got: ${got}<br>`; +} + +assertEq("WebAssembly.Global exists", typeof WebAssembly.Global, "function"); + +const global = new WebAssembly.Global({value:'i32', mutable:true}, 0); + +WebAssembly.instantiateStreaming(fetch('global.wasm'), { js: { global } }) +.then(({instance}) => { + assertEq("getting initial value from wasm", instance.exports.getGlobal(), 0); + global.value = 42; + assertEq("getting JS-updated value from wasm", instance.exports.getGlobal(), 42); + instance.exports.incGlobal(); + assertEq("getting wasm-updated value from JS", global.value, 43); +});</pre> + +<div class="note"> +<p><strong>Note</strong>: GitHub에서 실행중인 예제(<a href="https://mdn.github.io/webassembly-examples/js-api-examples/global.html">running live on GitHub</a>)를 볼 수 있습니다. <a href="https://github.com/mdn/webassembly-examples/blob/master/js-api-examples/global.html">source code</a>도 참조하십시오.</p> +</div> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('WebAssembly JS', '#globals', 'WebAssembly.Global()')}}</td> + <td>{{Spec2('WebAssembly JS')}}</td> + <td>Initial draft definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.WebAssembly.Global")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/ko/docs/WebAssembly">WebAssembly</a> overview page</li> + <li><a href="/ko/docs/WebAssembly/Concepts">WebAssembly concepts</a></li> + <li><a href="/ko/docs/WebAssembly/Using_the_JavaScript_API">Using the WebAssembly JavaScript API</a></li> + <li><a href="https://github.com/WebAssembly/mutable-global/blob/master/proposals/mutable-global/Overview.md">Import/Export mutable globals proposal</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/webassembly/global/prototype/index.html b/files/ko/web/javascript/reference/global_objects/webassembly/global/prototype/index.html new file mode 100644 index 0000000000..3b7e8a9e2b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/webassembly/global/prototype/index.html @@ -0,0 +1,69 @@ +--- +title: WebAssembly.Global.prototype +slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/Global/prototype +translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/Global +--- +<div>{{JSRef}}</div> + +<p><code><strong>WebAssembly.Global</strong></code><strong><code>.prototype</code></strong> 속성은 {{jsxref("WebAssembly.Global()")}} 생성자의 프로토 타입을 나타냅니다.</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="Description">Description</h2> + +<p>모든 {{jsxref("WebAssembly.Global")}} 인스턴스는 <code>Global.prototype</code>에서 상속받습니다. {{jsxref("WebAssembly.Global()")}} 생성자의 프로토 타입 객체는 모든 {{jsxref( "WebAssembly.Global")}} 인스턴스에 영향을 미치도록 수정할 수 있습니다.</p> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt><code>Global.prototype.constructor</code></dt> + <dd>이 객체의 인스턴스를 생성 한 함수를 돌려줍니다. 기본적으로 이것은 {{jsxref("WebAssembly.Global()")}} 생성자입니다.</dd> + <dt><code>Global.prototype[@@toStringTag]</code></dt> + <dd><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag">@@toStringTag</a> 속성의 초기 값은 String 값인 "WebAssembly.Global"입니다.</dd> + <dt><code>Global.prototype.value</code></dt> + <dd>전역 변수에 포함 된 값 - 전역 값을 직접 설정하고 가져 오는 데 사용할 수 있습니다.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt><code>Global.prototype.valueOf()</code></dt> + <dd>전역 변수에 포함 된 값을 반환하는 Old-style 메서드입니다.</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('WebAssembly JS', '#globals', 'WebAssembly.Global()')}}</td> + <td>{{Spec2('WebAssembly JS')}}</td> + <td>Initial draft definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.WebAssembly.Global.prototype")}}</p> +</div> + +<div> + +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("WebAssembly.Global()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/webassembly/index.html b/files/ko/web/javascript/reference/global_objects/webassembly/index.html new file mode 100644 index 0000000000..8412c9f0e4 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/webassembly/index.html @@ -0,0 +1,100 @@ +--- +title: WebAssembly +slug: Web/JavaScript/Reference/Global_Objects/WebAssembly +translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly +--- +<div>{{JSRef}}</div> + +<p><strong><code>WebAssembly</code></strong> 자바스크립트 객체는 모든 <a href="/ko/docs/WebAssembly">WebAssembly</a>에 관계된 기능의 네임스페이스로서 역할합니다.</p> + +<p>대부분의 전역객체와 다르게, <code>WebAssembly</code>는 생성자가 아닙니다 (함수 객체가 아닙니다). 비슷한 예로 수학적인 상수나 함수들을 담고있는 {{jsxref("Math")}} 객체나, 국제화 관련 생성자나 언어에 민감한 다른 함수들을 담고있는 {{jsxref("Intl")}} 등이 있습니다.</p> + +<h2 id="설명">설명</h2> + +<p><code>WebAssembly</code> 객체의 기본적인 사용례는 다음과 같습니다:</p> + +<ul> + <li>{{jsxref("WebAssembly.instantiate()")}} 함수를 사용해서 웹어셈블리 코드 불러오기.</li> + <li>{{jsxref("WebAssembly.Memory()")}}/{{jsxref("WebAssembly.Table()")}} 생성자로 새 메모리와 테이블 인스턴스 생성하기.</li> + <li>{{jsxref("WebAssembly.CompileError()")}}/{{jsxref("WebAssembly.LinkError()")}}/{{jsxref("WebAssembly.RuntimeError()")}} 생성자로 웹어셈블리에서 발생하는 에러에 대한 처리장치 만들기.</li> +</ul> + +<h2 id="메서드">메서드</h2> + +<dl> + <dt>{{jsxref("WebAssembly.instantiate()")}}</dt> + <dd>WebAssembly 코드를 컴파일하고 인스턴스화하여 <code>Module</code>과 첫 번째 <code>Instance</code>를 반환하는 기본 API입니다.</dd> + <dt>{{jsxref("WebAssembly.instantiateStreaming()")}}</dt> + <dd>스트리밍 된 원본 소스에서 직접 WebAssembly 모듈을 컴파일하고 인스턴스화하여 <code>Module</code>과 첫 번째 <code>Instance</code>를 반환합니다.</dd> + <dt>{{jsxref("WebAssembly.compile()")}}</dt> + <dd>WebAssembly 바이너리 코드에서 {{jsxref("WebAssembly.Module")}}을 컴파일하여 인스턴스화를 별도의 단계로 남겨 둡니다.</dd> + <dt>{{jsxref("WebAssembly.compileStreaming()")}}</dt> + <dd>{{jsxref("WebAssembly.Module")}}을 스트림 된 원본 소스에서 직접 컴파일하여 인스턴스화를 별도의 단계로 남겨 둡니다.</dd> + <dt>{{jsxref("WebAssembly.validate()")}}</dt> + <dd>바이트가 유효한 WebAssembly 코드 (<code>true</code>)인지 아닌지 (<code>false</code>)를 반환하여 WebAssembly 바이너리 코드의 지정된 입력 된 배열을 확인합니다.</dd> +</dl> + +<h2 id="생성자">생성자</h2> + +<dl> + <dt>{{jsxref("WebAssembly.Global()")}}</dt> + <dd>Creates a new WebAssembly <code>Global</code> object.</dd> + <dt>{{jsxref("WebAssembly.Module()")}}</dt> + <dd>Creates a new WebAssembly <code>Module</code> object.</dd> + <dt>{{jsxref("WebAssembly.Instance()")}}</dt> + <dd>Creates a new WebAssembly <code>Instance</code> object.</dd> + <dt>{{jsxref("WebAssembly.Memory()")}}</dt> + <dd>Creates a new WebAssembly <code>Memory</code> object.</dd> + <dt>{{jsxref("WebAssembly.Table()")}}</dt> + <dd>Creates a new WebAssembly <code>Table</code> object.</dd> + <dt>{{jsxref("WebAssembly.CompileError()")}}</dt> + <dd>Creates a new WebAssembly <code>CompileError</code> object.</dd> + <dt>{{jsxref("WebAssembly.LinkError()")}}</dt> + <dd>Creates a new WebAssembly <code>LinkError</code> object.</dd> + <dt>{{jsxref("WebAssembly.RuntimeError()")}}</dt> + <dd>Creates a new WebAssembly <code>RuntimeError</code> object.</dd> +</dl> + +<h2 id="예제">예제</h2> + +<p>다음 예제 (GitHub의 <a href="https://github.com/mdn/webassembly-examples/blob/master/js-api-examples/instantiate-streaming.html">instantiate-streaming.html</a> 데모보기 및 <a href="https://mdn.github.io/webassembly-examples/js-api-examples/instantiate-streaming.html">라이브보기</a>)에서는 기본 소스에서 .wasm 모듈을 직접 스트리밍 한 다음 컴파일하고 인스턴스화합니다. 프로미스는 <code>ResultObject</code>로 충족됩니다. <code>instantiateStreaming()</code> 함수는 {{domxref ( "Response")}} 객체에 대한 promise를 받아들이므로 직접 {{domxref ( "WindowOrWorkerGlobalScope.fetch()")}} 호출에 전달할 수 있습니다.</p> + +<pre><code>var importObject = { imports: { imported_func: arg => console.log(arg) } }; + +WebAssembly.instantiateStreaming(fetch('simple.wasm'), importObject) +.then(obj => obj.instance.exports.exported_func());</code></pre> + +<p>그런 다음 ResultObject의 인스턴스 구성에 액세스하고 그 안에 있는 <code>exported_func</code>을 호출합니다.</p> + +<h2 id="스펙">스펙</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('WebAssembly JS', '#the-webassembly-object', 'WebAssembly')}}</td> + <td>{{Spec2('WebAssembly JS')}}</td> + <td>초안 정의</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.WebAssembly")}}</div> + + + +<h2 id="바깥_고리">바깥 고리</h2> + +<ul> + <li><a href="/ko/docs/WebAssembly">웹어셈블리</a> 개요 페이지</li> + <li><a href="/ko/docs/WebAssembly/Concepts">웹어셈블리의 컨셉</a></li> + <li><a href="/en-US/docs/WebAssembly/Using_the_JavaScript_API">Using the WebAssembly JavaScript API</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/webassembly/instance/index.html b/files/ko/web/javascript/reference/global_objects/webassembly/instance/index.html new file mode 100644 index 0000000000..3141c6809a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/webassembly/instance/index.html @@ -0,0 +1,74 @@ +--- +title: WebAssembly.Instance +slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance +translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance +--- +<div>{{JSRef}}</div> + +<p><strong><code>WebAssembly.Instance</code></strong> 개체는 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module">WebAssembly.Module</a>의 상태 저장되고 실행 가능한 인스턴스입니다. <code>Instance</code> 객체에는 JavaScript에서 WebAssembly 코드로 호출 할 수있는 모든 <a href="/ko/docs/WebAssembly/Exported_functions">Exported WebAssembly functions</a>가 포함되어 있습니다.</p> + +<p>주어진 {{jsxref ( "WebAssembly.Module")}} 객체를 동기적으로 인스턴스화하기 위해 <code>WebAssembly.Instance()</code> 생성자 함수를 호출 할 수 있습니다. 하지만 <code>Instance</code>를 가져 오는 주요 방법은 비동기 {{jsxref ( "WebAssembly.instantiateStreaming ()")}} 함수를 사용하는 것입니다.</p> + +<h2 id="생성자_구문">생성자 구문</h2> + +<div class="warning"> +<p><strong>중요</strong>: 대형 모듈의 인스턴스화는 비용이 많이들 수 있으므로 개발자는 동기 인스턴스 생성이 절대적으로 필요한 경우에만 Instance () 생성자를 사용해야합니다. 비동기 {{jsxref ( "WebAssembly.instantiateStreaming ()")}} 메서드를 사용하세요.</p> +</div> + +<pre class="syntaxbox">var myInstance = new WebAssembly.Instance(<em>module</em>, <em>importObject</em>);</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code><em>module</em></code></dt> + <dd>인스턴스화 할 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module" title="The Module() constructor of the WebAssembly global object creates a new Module object instance."><code>WebAssembly.Module</code></a> 객체입니다.</dd> + <dt><code><em>importObject</em></code> {{optional_inline}}</dt> + <dd>함수 또는 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory" title="The Memory() constructor of the WebAssembly global object creates a new Memory object instance, which represents a WebAssembly memory. These can be thought of as resizeable array buffers, wrappers around WebAssembly memories."><code>WebAssembly.Memory</code></a>객체와 같이 새로 생성 된 인스턴스로 가져올 값을 포함하는 객체입니다. 선언 된 각 <code>module</code> 가져오기에 대해 일치하는 속성이 하나 있어야합니다. 그렇지 않으면 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/LinkError">WebAssembly.LinkError</a>가 발생합니다.</dd> +</dl> + +<h2 id="Instance_인스턴스"><code>Instance</code> 인스턴스</h2> + +<p>모든 <code>Instance</code> 인스턴스는 <code>Instance()</code> 생성자의 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance/prototype">prototype object</a>에서 상속받습니다.이 인스턴스를 수정하면 모든 <code>Instance</code> 인스턴스에 영향을 줍니다.</p> + +<h3 id="인스턴스_속성">인스턴스 속성</h3> + +<p>{{page('/ko/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance/prototype', 'Properties')}}</p> + +<h3 id="인스턴스_메서드">인스턴스 메서드</h3> + +<p>{{page('/ko/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance/prototype', 'Methods')}}</p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('WebAssembly JS', '#webassemblyinstance-objects', 'Instance')}}</td> + <td>{{Spec2('WebAssembly JS')}}</td> + <td>Initial draft definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">브라우저 호환성</h2> + +<div> + + +<p>{{Compat("javascript.builtins.WebAssembly.Instance")}}</p> +</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/WebAssembly">WebAssembly</a> overview page</li> + <li><a href="/ko/docs/WebAssembly/Concepts">WebAssembly concepts</a></li> + <li><a href="/ko/docs/WebAssembly/Using_the_JavaScript_API">Using the WebAssembly JavaScript API</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/webassembly/instantiate/index.html b/files/ko/web/javascript/reference/global_objects/webassembly/instantiate/index.html new file mode 100644 index 0000000000..c7b250c090 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/webassembly/instantiate/index.html @@ -0,0 +1,168 @@ +--- +title: WebAssembly.instantiate() +slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate +translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate +--- +<div>{{JSRef}}</div> + +<p><strong><code>WebAssembly.instantiate()</code></strong> 함수를 사용하면 WebAssembly 코드를 컴파일하고 인스턴스화 할 수 있습니다. 이 함수에는 두개의 overloads가 있습니다.</p> + +<ul> + <li>기본 오버로드는 <a href="/en-US/docs/Web/JavaScript/Typed_arrays">typed array</a> 또는 {{jsxref ( "ArrayBuffer")}}의 형태로 WebAssembly 바이너리 코드를 취해 컴파일 및 인스턴스화를 한 번에 수행합니다. 반환 된 Promise는 컴파일 된 {{jsxref ( "WebAssembly.Module")}} 및 첫 번째 {{jsxref ( "WebAssembly.Instance")}}로 해석됩니다.</li> + <li>두번째 오버로드는 이미 컴파일 된 {{jsxref ( "WebAssembly.Module")}}을 취하여 해당 <code>Module</code>의 <code>Instance</code>로 해석되는 <code>Promise</code>을 반환합니다. 이 overload는 <code>Module</code>이 이미 컴파일된 경우 유용합니다.</li> +</ul> + +<div class="warning"> +<p><strong>중요 : </strong><strong>이 방법은 wasm 모듈을 가져와 인스턴스화하는 가장 효율적인 방법은 아닙니다. 가능하다면 원시 바이트 코드에서 모듈을 모두 한 단계로 가져오고, 컴파일하고 인스턴스화하는 대신 최신 {{jsxref ( "WebAssembly.instantiateStreaming ()")}} 메서드를 사용해야합니다. {{jsxref ( "ArrayBuffer")}} 로의 변환이 필요합니다.</strong></p> +</div> + +<h2 id="Syntax">Syntax</h2> + +<h3 id="Primary_overload_—_taking_wasm_binary_code">Primary overload — taking wasm binary code</h3> + +<pre class="syntaxbox">Promise<ResultObject> WebAssembly.instantiate(bufferSource, importObject); +</pre> + +<h4 id="Parameters">Parameters</h4> + +<dl> + <dt><em>bufferSource</em></dt> + <dd>컴파일 할 .wasm 모듈의 이진 코드가 들어있는 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays">typed array</a> 또는 {{jsxref("ArrayBuffer")}}입니다.</dd> + <dt><em>importObject</em> {{optional_inline}}</dt> + <dd>함수 또는 {{jsxref ( "WebAssembly.Memory")}} 객체와 같이 새로 생성 된 <code>인스턴스</code>로 가져올 값을 포함하는 객체입니다. 컴파일 된 모듈의 각 선언 된 가져 오기에 대해 하나의 일치하는 속성이 있어야합니다. 그렇지 않으면 {{jsxref("WebAssembly.LinkError")}}가 발생합니다.</dd> +</dl> + +<h4 id="Return_value">Return value</h4> + +<p>두개의 필드를 포함하는 <code>ResultObject</code>를 가진 <code>Promise</code>를 반환:</p> + +<ul> + <li><code>module</code>: 컴파일 된 WebAssembly 모듈을 나타내는 {{jsxref ( "WebAssembly.Module")}} 객체입니다. 이 <code>Module</code>은 {{domxref("Worker.postMessage", "postMessage()")}}를 통해 공유되거나 <a href="/en-US/docs/WebAssembly/Caching_modules">cached in IndexedDB</a>로 다시 인스턴스화 될 수 있습니다.</li> + <li><code>instance</code>: <a href="/en-US/docs/WebAssembly/Exported_functions">Exported WebAssembly functions</a>을 포함하는 {{jsxref ( "WebAssembly.Instance")}} 객체입니다.</li> +</ul> + +<h4 id="Exceptions">Exceptions</h4> + +<ul> + <li>매개 변수 중 하나가 올바른 유형 또는 구조가 아니면 {{jsxref ( "TypeError")}}가 발생합니다.</li> + <li>작업이 실패하면 promise는 실패 원인에 따라 {{jsxref ( "WebAssembly.CompileError")}}, {{jsxref ( "WebAssembly.LinkError")}} 또는 {{jsxref ( "WebAssembly.RuntimeError")}}로 reject됩니다.</li> +</ul> + +<h3 id="Secondary_overload_—_taking_a_module_object_instance">Secondary overload — taking a module object instance</h3> + +<pre class="syntaxbox">Promise<WebAssembly.Instance> WebAssembly.instantiate(module, importObject); +</pre> + +<h4 id="Parameters_2">Parameters</h4> + +<dl> + <dt><em>module</em></dt> + <dd>{{jsxref ( "WebAssembly.Module")}} 객체가 인스턴스화됩니다.</dd> + <dt><em>importObject</em> {{optional_inline}}</dt> + <dd>함수 또는 {{jsxref ( "WebAssembly.Memory")}} 객체와 같이 새로 생성 된 인스턴스로 가져올 값을 포함하는 객체입니다. 선언 된 각 <code>module</code> 가져 오기에 대해 일치하는 속성이 하나 있어야합니다. 그렇지 않으면 {{jsxref("WebAssembly.LinkError")}} 가 발생합니다.</dd> +</dl> + +<h4 id="Return_value_2">Return value</h4> + +<p>A <code>Promise</code> that resolves to an {{jsxref("WebAssembly.Instance")}} object.</p> + +<h4 id="Exceptions_2">Exceptions</h4> + +<ul> + <li>매개 변수 중 하나가 올바른 유형 또는 구조가 아니면 {{jsxref ( "TypeError")}}가 발생합니다.</li> + <li>If the operation fails, the promise rejects with a {{jsxref("WebAssembly.CompileError")}}, {{jsxref("WebAssembly.LinkError")}}, or {{jsxref("WebAssembly.RuntimeError")}}, depending on the cause of the failure. <br> + 작업이 실패하면 promise는 실패 원인에 따라 {{jsxref ( "WebAssembly.CompileError")}}, {{jsxref ( "WebAssembly.LinkError")}} 또는 {{jsxref ( "WebAssembly.RuntimeError")}}로 reject됩니다.</li> +</ul> + +<h2 id="Examples">Examples</h2> + +<p><strong>Note</strong>: 대부분의 경우 <code>instantiate()</code>보다 더 효율적이므로 {{jsxref ( "WebAssembly.instantiateStreaming ()")}}을 사용하는 것이 좋습니다.</p> + +<h3 id="First_overload_example">First overload example</h3> + +<p>fetch를 사용하여 일부 WebAssembly 바이트 코드를 가져온 후 우리는 {{jsxref ( "WebAssembly.instantiate ()")}} 함수를 사용하여 모듈을 컴파일하고 인스턴스화하여 해당 프로세스에서 JavaScript 함수를 WebAssembly 모듈로 가져옵니다. 그런 다음 <code>Instance</code>에서 <a href="/en-US/docs/WebAssembly/Exported_functions">Exported WebAssembly function</a>를 호출합니다.</p> + +<pre class="brush: js">var importObject = { + imports: { + imported_func: function(arg) { + console.log(arg); + } + } +}; + +fetch('simple.wasm').then(response => + response.arrayBuffer() +).then(bytes => + WebAssembly.instantiate(bytes, importObject) +).then(result => + result.instance.exports.exported_func() +);</pre> + +<div class="note"> +<p><strong>Note</strong>: 이 예제는 GitHub의 <a href="https://github.com/mdn/webassembly-examples/blob/master/js-api-examples/index.html">index.html</a>에서도 찾을 수 있습니다 (<a href="https://mdn.github.io/webassembly-examples/js-api-examples/">라이브보기도 있음</a>).</p> +</div> + +<h3 id="Second_overload_example">Second overload example</h3> + +<p>다음 예제는 (GitHub의 <a href="https://github.com/mdn/webassembly-examples/blob/master/js-api-examples/index-compile.html">index-compile.html</a> 데모 혹은 <a href="https://mdn.github.io/webassembly-examples/js-api-examples/index-compile.html">라이브로 보기</a>). {{jsxref ( "WebAssembly.compileStreaming ()")}} 메서드를 사용하여 로드된 simple.wasm 바이트 코드를 컴파일 한 다음 {{domxref("Worker.postMessage", "postMessage()")}}를 사용하여 <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API">worker</a>에게 전달합니다.</p> + +<pre class="brush: js">var worker = new Worker("wasm_worker.js"); + +WebAssembly.compileStreaming(fetch('simple.wasm')) +.then(mod => + worker.postMessage(mod) +);</pre> + +<p>작업자 (<code><a href="https://github.com/mdn/webassembly-examples/blob/master/js-api-examples/wasm_worker.js">wasm_worker.js</a></code> 참조)에서 모듈이 사용할 가져 오기 객체를 정의한 다음 주 스레드에서 모듈을 수신 할 이벤트 핸들러를 설정합니다. 모듈을 받으면 {{jsxref ( "WebAssembly.instantiate ()")}} 메소드를 사용하여 인스턴스를 만들고 내부에서 내 보낸 함수를 호출합니다.</p> + +<pre class="brush: js">var importObject = { + imports: { + imported_func: function(arg) { + console.log(arg); + } + } +}; + +onmessage = function(e) { + console.log('module received from main thread'); + var mod = e.data; + + WebAssembly.instantiate(mod, importObject).then(function(instance) { + instance.exports.exported_func(); + }); +};</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('WebAssembly JS', '#webassemblyinstantiate', 'instantiate()')}}</td> + <td>{{Spec2('WebAssembly JS')}}</td> + <td>Initial draft definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Browser compatibility</h2> + +<div> +<div class="hidden">The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</div> + +<p>{{Compat("javascript.builtins.WebAssembly.instantiate")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/WebAssembly">WebAssembly</a> overview page</li> + <li><a href="/en-US/docs/WebAssembly/Concepts">WebAssembly concepts</a></li> + <li><a href="/en-US/docs/WebAssembly/Using_the_JavaScript_API">Using the WebAssembly JavaScript API</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/webassembly/instantiatestreaming/index.html b/files/ko/web/javascript/reference/global_objects/webassembly/instantiatestreaming/index.html new file mode 100644 index 0000000000..e1b2fde3b7 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/webassembly/instantiatestreaming/index.html @@ -0,0 +1,83 @@ +--- +title: WebAssembly.instantiateStreaming() +slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiateStreaming +translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiateStreaming +--- +<div>{{JSRef}}</div> + +<p><strong><code>WebAssembly.instantiateStreaming()</code></strong> 함수는 스트림 된 원본 소스에서 직접 WebAssembly 모듈을 컴파일하고 인스턴스화합니다. Wasm 코드를로드하는 가장 효율적이고 최적화 된 방법입니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">Promise<ResultObject> WebAssembly.instantiateStreaming(<em>source</em>, <em>importObject</em>);</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><em>source</em></dt> + <dd>스트리밍, 컴파일 및 인스턴스화하려는 .wasm 모듈의 기본 소스를 나타내는 {{domxref ( "Response")}} 객체 또는 promise.</dd> + <dt><em>importObject</em> {{optional_inline}}</dt> + <dd>함수 또는 {{jsxref("WebAssembly.Memory")}} 객체와 같이 새로 생성 된 <code>Instance</code>로 가져올 값을 포함하는 객체입니다. 컴파일 된 모듈의 각 선언 된 가져 오기에 대해 하나의 일치하는 속성이 있어야합니다. 그렇지 않으면 <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/LinkError">WebAssembly.LinkError</a>가 발생합니다.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>두 개의 필드를 포함하는 <code>ResultObject</code>로 해석되는 <code>Promise</code> :</p> + +<ul> + <li><code>module</code>: 컴파일 된 WebAssembly 모듈을 나타내는 {{jsxref ( "WebAssembly.Module")}} 객체입니다. 이 <code>Module</code>은 다시 인스턴스화되거나 <a href="/en-US/docs/Web/API/Worker/postMessage">postMessage()</a>를 통해 공유 될 수 있습니다.</li> + <li><code>instance</code>: <a href="/en-US/docs/WebAssembly/Exported_functions">Exported WebAssembly functions</a>를 포함하는 {{jsxref ( "WebAssembly.Instance")}} 객체입니다.</li> +</ul> + +<h3 id="Exceptions">Exceptions</h3> + +<ul> + <li>매개 변수 중 하나가 올바른 유형 또는 구조가 아니면 {{jsxref ( "TypeError")}}가 발생합니다.</li> + <li>작업작업이 실패하면 promise는 실패 원인에 따라 {{jsxref ( "WebAssembly.CompileError")}}, {{jsxref ( "WebAssembly.LinkError")}} 또는 {{jsxref ( "WebAssembly.RuntimeError")}}로 거부됩니다.</li> +</ul> + +<h2 id="Examples">Examples</h2> + +<p>다음 예제 (GitHub의 <a href="https://github.com/mdn/webassembly-examples/blob/master/js-api-examples/instantiate-streaming.html">instantiate-streaming.html</a> 데모보기 및 <a href="https://mdn.github.io/webassembly-examples/js-api-examples/instantiate-streaming.html">view it live</a>)에서는 원본 소스에서 .wasm 모듈을 직접 스트리밍 한 다음 컴파일하고 인스턴스화합니다. 약속은 <code>ResultObject</code>로 충족됩니다.<code>instantiateStreaming()</code> 함수는 {{domxref("Response")}} 객체에 대한 promise를 받아들이므로 직접 {{domxref("WindowOrWorkerGlobalScope.fetch()")}} 호출을 전달할 수 있으며 응답을 수행하면 함수에 응답을 전달합니다.</p> + +<pre class="brush: js">var importObject = { imports: { imported_func: arg => console.log(arg) } }; + +WebAssembly.instantiateStreaming(fetch('simple.wasm'), importObject) +.then(obj => obj.instance.exports.exported_func());</pre> + +<p>그런 다음 <code>ResultObject</code>의 인스턴스 구성원에 액세스하고 포함 된 내 보낸 함수를 호출합니다.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('WebAssembly Embedding', '#webassemblyinstantiatestreaming', 'instantiateStreaming()')}}</td> + <td>{{Spec2('WebAssembly Embedding')}}</td> + <td>Initial draft definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.WebAssembly.instantiateStreaming")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/WebAssembly">WebAssembly</a> overview page</li> + <li><a href="/en-US/docs/WebAssembly/Concepts">WebAssembly concepts</a></li> + <li><a href="/en-US/docs/WebAssembly/Using_the_JavaScript_API">Using the WebAssembly JavaScript API</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/webassembly/linkerror/index.html b/files/ko/web/javascript/reference/global_objects/webassembly/linkerror/index.html new file mode 100644 index 0000000000..b9b5c3264c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/webassembly/linkerror/index.html @@ -0,0 +1,113 @@ +--- +title: WebAssembly.LinkError() +slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/LinkError +translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/LinkError +--- +<div>{{JSRef}}</div> + +<p>The <code><strong>WebAssembly.LinkError()</strong></code> constructor creates a new WebAssembly <code>LinkError</code> object, which indicates an error during module instantiation (besides <a href="http://webassembly.org/docs/semantics/#traps">traps</a> from the start function). </p> + +<p><code><strong>WebAssembly.LinkError()</strong></code> 생성자는 새 WebAssembly <code>LinkError</code> 객체를 만듭니다. 이 객체는 모듈 인스턴스화 중의 오류를 나타냅니다 (시작 함수의 <a href="http://webassembly.org/docs/semantics/#traps">traps</a>와 함께).</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">new WebAssembly.LinkError(<var>message</var>, <var>fileName</var>, <var>lineNumber</var>)</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>message</code> {{optional_inline}}</dt> + <dd>사람이 읽을 수 있는 오류 설명.</dd> + <dt><code>fileName</code> {{optional_inline}}{{non-standard_inline}}</dt> + <dd>예외의 원인이 된 코드가 들어있는 파일의 이름입니다.</dd> + <dt><code>lineNumber</code> {{optional_inline}}{{non-standard_inline}}</dt> + <dd>예외의 원인이 된 코드의 행 번호입니다.</dd> +</dl> + +<h2 id="Properties">Properties</h2> + +<p><em><code>LinkError</code></em> 생성자에는 고유 한 고유 속성이 없지만 프로토 타입 체인을 통해 일부 속성을 상속합니다.</p> + +<dl> + <dt><code>WebAssembly.LinkError.prototype.constructor</code></dt> + <dd>인스턴스의 프로토 타입을 작성한 함수를 지정합니다.</dd> + <dt>{{jsxref("Error.prototype.message", "WebAssembly.LinkError.prototype.message")}}</dt> + <dd>에러 메시지. ECMA-262는 {{jsxref ( "URIError")}}가 <a href="/en-US/docs/Mozilla/Projects/SpiderMonkey">SpiderMonkey</a>에서 자체 <code>message</code> 속성을 제공하도록 지정했지만 {{jsxref ( "Error.prototype.message")}}를 상속받습니다.</dd> + <dt>{{jsxref("Error.prototype.name", "WebAssembly.LinkError.prototype.name")}}</dt> + <dd>에러 이름. {{jsxref("Error")}}를 상속받습니다.</dd> + <dt>{{jsxref("Error.prototype.fileName", "WebAssembly.LinkError.prototype.fileName")}}</dt> + <dd>해당 에러가 발생한 파일의 경로. {{jsxref("Error")}}를 상속받습니다.</dd> + <dt>{{jsxref("Error.prototype.lineNumber", "WebAssembly.LinkError.prototype.lineNumber")}}</dt> + <dd>에러가 발생한 파일의 행 번호. {{jsxref("Error")}}를 상속받습니다.</dd> + <dt>{{jsxref("Error.prototype.columnNumber", "WebAssembly.LinkError.prototype.columnNumber")}}</dt> + <dd>이 오류가 발생한 행의 열 번호입니다.. {{jsxref("Error")}}를 상속받습니다.</dd> + <dt>{{jsxref("Error.prototype.stack", "WebAssembly.LinkError.prototype.stack")}}</dt> + <dd>스텍 추적. {{jsxref("Error")}}를 상속받습니다.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em><code>LinkError</code></em> 생성자에는 자체 메서드가 없지만 프로토 타입 체인을 통해 일부 메서드를 상속합니다.</p> + +<dl> + <dt>{{jsxref("Error.prototype.toSource", "WebAssembly.LinkError.prototype.toSource()")}}</dt> + <dd>동일한 오류로 평가 될 수있는 코드를 반환합니다. {{jsxref("Error")}}를 상속받습니다.</dd> + <dt>{{jsxref("Error.prototype.toString", "WebAssembly.LinkError.prototype.toString()")}}</dt> + <dd>지정된 Error 객체를 나타내는 문자열을 반환합니다. {{jsxref("Error")}}를 상속받습니다.</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<p>다음 snippet은 새 <code>LinkError</code> 인스턴스를 만들고 콘솔에 세부 정보를 기록합니다.</p> + +<pre class="brush: js">try { + throw new WebAssembly.LinkError('Hello', 'someFile', 10); +} catch (e) { + console.log(e instanceof LinkError); // true + console.log(e.message); // "Hello" + console.log(e.name); // "LinkError" + console.log(e.fileName); // "someFile" + console.log(e.lineNumber); // 10 + console.log(e.columnNumber); // 0 + console.log(e.stack); // returns the location where the code was run +}</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('WebAssembly JS', '#constructor-properties-of-the-webassembly-object', 'WebAssembly constructors')}}</td> + <td>{{Spec2('WebAssembly JS')}}</td> + <td>Initial WebAssembly draft definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-native-error-types-used-in-this-standard', 'NativeError')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Definition of standard NativeError types.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.WebAssembly.LinkError")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/WebAssembly">WebAssembly</a> overview page</li> + <li><a href="/en-US/docs/WebAssembly/Concepts">WebAssembly concepts</a></li> + <li><a href="/en-US/docs/WebAssembly/Using_the_JavaScript_API">Using the WebAssembly JavaScript API</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/webassembly/memory/index.html b/files/ko/web/javascript/reference/global_objects/webassembly/memory/index.html new file mode 100644 index 0000000000..96b1614fff --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/webassembly/memory/index.html @@ -0,0 +1,112 @@ +--- +title: WebAssembly.Memory() +slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory +translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory +--- +<div>{{JSRef}}</div> + +<p><code><strong>WebAssembly.Memory()</strong></code> 생성자는 WebAssembly <code>Instance</code>가 액세스하는 메모리의 원시 바이트를 가진 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer">ArrayBuffer</a>(크기조정이 가능)인 새 <code>Memory</code> 객체를 만듭니다.</p> + +<p>메모리는 자바스크립트 혹은 WebAssembly 코드 안에서 만들어지며 자바스크립트 그리고 WebAssembly에서 접근하거나 변경이 가능합니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">var myMemory = new WebAssembly.Memory(memoryDescriptor);</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><em>memoryDescriptor</em></dt> + <dd>다음의 멤버를 가질수 있는 객체입니다. + <dl> + <dt><em>initial</em></dt> + <dd>WebAssembly Page의 단위별 WebAssembly 메모리의 초기 크기입니다.</dd> + <dt><em>maximum {{optional_inline}}</em></dt> + <dd>WebAssembly 메모리의 최대 크기는 WebAssembly 페이지 단위로 증가 할 수 있습니다. 이 매개 변수가 있으면 <code>maximum</code> 매개 변수는 엔진에 대해 메모리를 전면에 예약하도록 합니다. 그러나 엔진은 이 예약 요청을 무시하거나 클램핑 할 수 있습니다. 일반적으로 대부분의 WebAssembly 모듈은 <code>maximum</code> 값을 설정할 필요가 없습니다.</dd> + </dl> + </dd> +</dl> + +<div class="note"> +<p><strong>Note</strong>: WebAssembly 페이지의 크기는 65,536 바이트로 64KiB로 고정되어 있습니다.</p> +</div> + +<h3 id="Exceptions">Exceptions</h3> + +<ul> + <li><code>memoryDescriptor</code>가 object 유형이 아닌 경우 {{jsxref ( "TypeError")}}가 발생합니다.</li> + <li><code>maximum</code>이 지정되고 <code>initial</code>보다 작은 경우 {{jsxref ( "RangeError")}}가 발생합니다.</li> +</ul> + +<h2 id="Memory_instances"><code>Memory</code> instances</h2> + +<p>모든 <code>Memory</code> 인스턴스는 <code>Memory()</code>생성자의 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory/prototype">prototype object</a>를 상속합니다.이 인스턴스는 모든 <code>Memory</code> 인스턴스에 적용되도록 수정할 수 있습니다.</p> + +<h3 id="Instance_properties">Instance properties</h3> + +<dl> + <dt><code>Memory.prototype.constructor</code></dt> + <dd>이 객체의 인스턴스를 생성 한 함수를 돌려줍니다. 기본적으로 이것은 {{jsxref("WebAssembly.Memory()")}} 생성자입니다.</dd> + <dt>{{jsxref("WebAssembly/Memory/buffer","Memory.prototype.buffer")}}</dt> + <dd>메모리에 포함 된 버퍼를 반환하는 접근 자 속성입니다.</dd> +</dl> + +<h3 id="Instance_methods">Instance methods</h3> + +<dl> + <dt>{{jsxref("WebAssembly/Memory/grow","Memory.prototype.grow()")}}</dt> + <dd>지정된 수의 WebAssembly 페이지 (각각 64KB 크기)만큼 메모리 인스턴스의 크기를 늘립니다.</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<p><code>WebAssembly.Memory</code> 객체를 가져 오는 두 가지 방법이 있습니다. 첫 번째 방법은 JavaScript에서 생성하는 것입니다. 다음 예제에서는 초기 크기가 10 페이지 (640KiB)이고 최대 크기가 100 페이지 (6.4MiB) 인 새 WebAssembly 메모리 인스턴스를 만듭니다.</p> + +<pre class="brush: js">var memory = new WebAssembly.Memory({initial:10, maximum:100});</pre> + +<p><code>WebAssembly.Memory</code> 객체를 가져 오는 두 번째 방법은 WebAssembly 모듈에서 내보냅니다. 다음 예제는 (GitHub의 <a href="https://github.com/mdn/webassembly-examples/blob/master/js-api-examples/memory.html">memory.html</a>을 보세요. <a href="https://mdn.github.io/webassembly-examples/js-api-examples/memory.html">라이브로 보기</a>) 생성된 메모리를 가져 오는 동안 {{jsxref("WebAssembly.instantiateStreaming()")}} 메소드를 사용하여로드 된 memory.wasm 바이트 코드를 가져 와서 인스턴스화합니다. 위의 줄에. 그런 다음 메모리에 일부 값을 저장 한 다음 함수를 내 보낸 다음 일부 값의 합계에 사용합니다.</p> + +<pre class="brush: js">WebAssembly.instantiateStreaming(fetch('memory.wasm'), { js: { mem: memory } }) +.then(obj => { + var i32 = new Uint32Array(memory.buffer); + for (var i = 0; i < 10; i++) { + i32[i] = i; + } + var sum = obj.instance.exports.accumulate(0, 10); + console.log(sum); +});</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('WebAssembly JS', '#webassemblymemory-objects', 'Memory')}}</td> + <td>{{Spec2('WebAssembly JS')}}</td> + <td>Initial draft definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.WebAssembly.Memory")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/WebAssembly">WebAssembly</a> overview page</li> + <li><a href="/en-US/docs/WebAssembly/Concepts">WebAssembly concepts</a></li> + <li><a href="/en-US/docs/WebAssembly/Using_the_JavaScript_API">Using the WebAssembly JavaScript API</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/webassembly/module/index.html b/files/ko/web/javascript/reference/global_objects/webassembly/module/index.html new file mode 100644 index 0000000000..814835fd00 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/webassembly/module/index.html @@ -0,0 +1,83 @@ +--- +title: WebAssembly.Module +slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/Module +translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/Module +--- +<div>{{JSRef}}</div> + +<p><strong><code>WebAssembly.Module</code></strong> 객체는 브라우저에서 이미 컴파일 된 stateless WebAssembly 코드를 포함하며 효율적으로 <a href="https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage">Workers와 공유</a>하고 여러 번 인스턴스화 할 수 있습니다. 모듈을 인스턴스화하려면 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate#Secondary_overload_%E2%80%94_taking_a_module_object_instance">WebAssembly.instantiate() 2차 오버로드를 호출</a>하세요.</p> + +<p><code>WebAssembly.Module()</code> 생성자 함수를 호출하여 지정된 WebAssembly 바이너리 코드를 동기식으로 컴파일 할 수 있습니다. 그러나 <code>Module</code>을 쓰는 주된 방법은 {{jsxref ( "WebAssembly.compile ()")}}과 같은 비동기 컴파일 함수를 사용하는 것입니다.</p> + +<h2 id="생성자_구문">생성자 구문</h2> + +<div class="warning"> +<p><strong>Important: </strong>대형 모듈의 컴파일은 비용이 많이들 수 있으므로 개발자는 동기 컴파일이 절대적으로 필요한 경우에만 Module () 생성자를 사용해야합니다. 비동기 {{jsxref ( "WebAssembly.compileStreaming ()")}} 메서드를 사용하세요.</p> +</div> + +<pre class="syntaxbox">var myModule = new WebAssembly.Module(bufferSource);</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code><em>bufferSource</em></code></dt> + <dd>컴파일 할 .wasm 모듈의 이진 코드가 들어있는 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays">typed array</a>또는 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer">ArrayBuffer</a>입니다.</dd> +</dl> + +<h2 id="Function_Properties_of_the_Module_Constructor">Function Properties of the <code>Module</code> Constructor</h2> + +<dl> + <dt>{{jsxref("Global_Objects/WebAssembly/Module/customSections", "WebAssembly.Module.customSections()")}}</dt> + <dd>모듈(<code>Module</code>)과 문자열이 주어지면 모듈의 모든 사용자 정의 섹션 내용의 사본을 주어진 문자열 이름으로 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/WebAssembly/Module/exports", "WebAssembly.Module.exports()")}}</dt> + <dd>모듈(<code>Module</code>)이 주어지면 선언 된 모든 내보내기에 대한 설명이 들어있는 배열을 반환합니다.</dd> + <dt>{{jsxref("Global_Objects/WebAssembly/Module/imports", "WebAssembly.Module.imports()")}}</dt> + <dd>모듈(<code>Module</code>)이 주어지면 선언 된 모든 가져오기에 대한 설명이 들어있는 배열을 반환합니다.</dd> +</dl> + +<h2 id="Module_instances"><code>Module</code> instances</h2> + +<p>모든 <code>Module</code> 인스턴스는 <code>Module()</code> 생성자의 <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module/prototype">prototype object</a>에서 상속받습니다.이 인스턴스는 모든 <code>Module</code> 인스턴스에 적용되도록 수정할 수 있습니다.</p> + +<h3 id="Instance_properties">Instance properties</h3> + +<p>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module/prototype', 'Properties')}}</p> + +<h3 id="Instance_methods">Instance methods</h3> + +<p>모듈 인스턴스에는 기본 메서드가 없습니다.</p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('WebAssembly JS', '#webassemblymodule-objects', 'WebAssembly.Module()')}}</td> + <td>{{Spec2('WebAssembly JS')}}</td> + <td>Initial draft definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">브라우저 호환성</h2> + +<div> + + +<p>{{Compat("javascript.builtins.WebAssembly.Module")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/WebAssembly">WebAssembly</a> overview page</li> + <li><a href="/en-US/docs/WebAssembly/Concepts">WebAssembly concepts</a></li> + <li><a href="/en-US/docs/WebAssembly/Using_the_JavaScript_API">Using the WebAssembly JavaScript API</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/webassembly/runtimeerror/index.html b/files/ko/web/javascript/reference/global_objects/webassembly/runtimeerror/index.html new file mode 100644 index 0000000000..ebd8da6f46 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/webassembly/runtimeerror/index.html @@ -0,0 +1,111 @@ +--- +title: WebAssembly.RuntimeError() +slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/RuntimeError +translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/RuntimeError +--- +<div>{{JSRef}}</div> + +<p><code><strong>WebAssembly.RuntimeError()</strong></code><strong> </strong>생성자는 WebAssembly에서 <a href="http://webassembly.org/docs/semantics/#traps">trap</a>을 지정할 때마다 throw되는 새 WebAssembly <code>RuntimeError</code> 객체를 만듭니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">new WebAssembly.RuntimeError(<var>message</var>, <var>fileName</var>, <var>lineNumber</var>)</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>message</code> {{optional_inline}}</dt> + <dd>인간이 읽을 수있는 오류 설명.</dd> + <dt><code>fileName</code> {{optional_inline}}{{non-standard_inline}}</dt> + <dd>예외의 원인이 된 코드가 들어있는 파일의 이름입니다.</dd> + <dt><code>lineNumber</code> {{optional_inline}}{{non-standard_inline}}</dt> + <dd>예외의 원인이 된 코드의 행 번호입니다.</dd> +</dl> + +<h2 id="Properties">Properties</h2> + +<p><em><code>RuntimeError</code> 생성자에는 고유 한 고유 속성이 없지만 프로토 타입 체인을 통해 일부 속성을 상속합니다.</em></p> + +<dl> + <dt><code>WebAssembly.RuntimeError.prototype.constructor</code></dt> + <dd>인스턴스의 프로토 타입을 작성한 함수를 지정합니다.</dd> + <dt>{{jsxref("Error.prototype.message", "WebAssembly.RuntimeError.prototype.message")}}</dt> + <dd>에러 메시지. ECMA-262는 {{jsxref ( "URIError")}}가 <a href="/en-US/docs/Mozilla/Projects/SpiderMonkey">SpiderMonkey</a>에서 자체 <code>message</code> 속성을 제공하도록 지정했지만 {{jsxref ( "Error.prototype.message")}}를 상속받습니다.</dd> + <dt>{{jsxref("Error.prototype.name", "WebAssembly.RuntimeError.prototype.name")}}</dt> + <dd>오류 이름. {{jsxref ( "Error")}}에서 상속됩니다.</dd> + <dt>{{jsxref("Error.prototype.fileName", "WebAssembly.RuntimeError.prototype.fileName")}}</dt> + <dd>이 오류를 발생시킨 파일의 경로입니다. {{jsxref ( "Error")}}에서 상속됩니다.</dd> + <dt>{{jsxref("Error.prototype.lineNumber", "WebAssembly.RuntimeError.prototype.lineNumber")}}</dt> + <dd>이 오류가 발생한 파일의 행 번호입니다. {{jsxref ( "Error")}}에서 상속됩니다.</dd> + <dt>{{jsxref("Error.prototype.columnNumber", "WebAssembly.RuntimeError.prototype.columnNumber")}}</dt> + <dd>이 오류가 발생한 행의 열 번호입니다. {{jsxref ( "Error")}}에서 상속됩니다.</dd> + <dt>{{jsxref("Error.prototype.stack", "WebAssembly.RuntimeError.prototype.stack")}}</dt> + <dd>스택 추적. {{jsxref ( "Error")}}에서 상속됩니다.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em><code>RuntimeError</code> 생성자에는 자체 메서드가 없지만 프로토 타입 체인을 통해 일부 메서드를 상속합니다.</em></p> + +<dl> + <dt>{{jsxref("Error.prototype.toSource", "WebAssembly.RuntimeError.prototype.toSource()")}}</dt> + <dd>동일한 오류로 평가 될 수있는 코드를 반환합니다. {{jsxref ( "Error")}}에서 상속됩니다.</dd> + <dt>{{jsxref("Error.prototype.toString", "WebAssembly.RuntimeError.prototype.toString()")}}</dt> + <dd>지정된 <code>Error</code> 객체를 나타내는 문자열을 반환합니다. {{jsxref ( "Error")}}에서 상속됩니다.</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<p>다음의 스니펫은, 새로운 RuntimeError 인스턴스를 작성해, 그 상세를 콘솔에 기록합니다.</p> + +<pre class="brush: js">try { + throw new WebAssembly.RuntimeError('Hello', 'someFile', 10); +} catch (e) { + console.log(e instanceof RuntimeError); // true + console.log(e.message); // "Hello" + console.log(e.name); // "RuntimeError" + console.log(e.fileName); // "someFile" + console.log(e.lineNumber); // 10 + console.log(e.columnNumber); // 0 + console.log(e.stack); // returns the location where the code was run +}</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('WebAssembly JS', '#constructor-properties-of-the-webassembly-object', 'WebAssembly constructors')}}</td> + <td>{{Spec2('WebAssembly JS')}}</td> + <td>Initial WebAssembly draft definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-native-error-types-used-in-this-standard', 'NativeError')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Definition of standard NativeError types.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.WebAssembly.RuntimeError")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/ko/docs/WebAssembly">WebAssembly</a> overview page</li> + <li><a href="/ko/docs/WebAssembly/Concepts">WebAssembly concepts</a></li> + <li><a href="/ko/docs/WebAssembly/Using_the_JavaScript_API">Using the WebAssembly JavaScript API</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/webassembly/table/index.html b/files/ko/web/javascript/reference/global_objects/webassembly/table/index.html new file mode 100644 index 0000000000..9d86fe40c7 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/webassembly/table/index.html @@ -0,0 +1,130 @@ +--- +title: WebAssembly.Table() +slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/Table +translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/Table +--- +<div>{{JSRef}}</div> + +<p><code><strong>WebAssembly.Table()</strong></code> 생성자는 지정된 크기 및 요소 유형의 새 <code>Table</code> 객체를 만듭니다.</p> + +<p>이것은 자바 스크립트 래퍼 객체로, 함수 참조를 저장하는 WebAssembly 테이블을 나타내는 배열과 같은 구조입니다. JavaScript 또는 WebAssembly 코드로 작성된 테이블은 JavaScript 및 WebAssembly에서 액세스 및 변경할 수 있습니다.</p> + +<div class="note"> +<p><strong>Note</strong>: 테이블은 현재 function references만 저장할 수 있지만 나중에 확장 될 수 있습니다.</p> +</div> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">var myTable = new WebAssembly.Table(tableDescriptor);</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><em>tableDescriptor</em></dt> + <dd>다음 멤버를 포함 할 수있는 객체입니다: + <dl> + <dt><em>element</em></dt> + <dd>테이블에 저장 될 값 유형을 나타내는 문자열. 현재로서는 <code>"anyfunc"</code>(함수) 값만있을 수 있습니다.</dd> + <dt><em>initial</em></dt> + <dd>WebAssembly 테이블의 초기 요소 수입니다.</dd> + <dt><em>maximum {{optional_inline}}</em></dt> + <dd>WebAssembly 테이블의 최대 증가 요소 수입니다.</dd> + </dl> + </dd> +</dl> + +<h3 id="Exceptions">Exceptions</h3> + +<ul> + <li><code>tableDescriptor</code>가 object 유형이 아닌 경우 {{jsxref ( "TypeError")}}가 발생합니다.</li> + <li><code>maximum</code>이 지정되고 initial보다 작은 경우 {{jsxref ( "RangeError")}}가 발생합니다.</li> +</ul> + +<h2 id="Table_instances"><code>Table</code> instances</h2> + +<p>모든 <code>Table</code> 인스턴스는 <code>Table()</code>생성자의 <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Table/prototype">prototype object</a>에서 상속받습니다.이 인스턴스는 모든 <code>Table</code> 인스턴스에 적용되도록 수정할 수 있습니다.</p> + +<h3 id="Instance_properties">Instance properties</h3> + +<dl> + <dt><code>Table.prototype.constructor</code></dt> + <dd>이 객체의 인스턴스를 생성 한 함수를 돌려줍니다. 기본적으로 이것은 {{jsxref("WebAssembly.Table()")}} 생성자입니다.</dd> + <dt>{{jsxref("WebAssembly/Table/length","Table.prototype.length")}}</dt> + <dd>테이블의 길이, 즉 요소의 수를 돌려줍니다.</dd> +</dl> + +<h3 id="Instance_methods">Instance methods</h3> + +<dl> + <dt>{{jsxref("WebAssembly/Table/get","Table.prototype.get()")}}</dt> + <dd>접근 자 함수 - 주어진 색인에 저장된 요소를 가져옵니다.</dd> + <dt>{{jsxref("WebAssembly/Table/grow","Table.prototype.grow()")}}</dt> + <dd>지정된 요소 수만큼 Table 인스턴스의 크기를 늘립니다.</dd> + <dt>{{jsxref("WebAssembly/Table/set","Table.prototype.set()")}}</dt> + <dd>지정된 인덱스에 격납되어있는 요소를, 지정된 값으로 설정합니다.</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<p>다음 예제 (table2.html <a href="https://github.com/mdn/webassembly-examples/blob/master/js-api-examples/table2.html">source code</a> 및 <a href="https://mdn.github.io/webassembly-examples/js-api-examples/table2.html">live version</a> 참조)는 초기 크기가 2인 새 WebAssembly Table 인스턴스를 만듭니다. 그런 다음 두 개의 인덱스 (표 {{jsxref ( "WebAssembly / Table / get", "Table.prototype.get ()")}}를 통해 검색하여 테이블의 길이와 내용을 인쇄합니다. 길이가 2이고 {{jsxref ( "null")}}이 두개라고 출력됩니다.</p> + +<pre class="brush: js">var tbl = new WebAssembly.Table({initial:2, element:"anyfunc"}); +console.log(tbl.length); // "2" +console.log(tbl.get(0)); // "null" +console.log(tbl.get(1)); // "null"</pre> + +<p>그런 다음 테이블을 포함한 <code>importObj</code>를 만듭니다.</p> + +<pre class="brush: js">var importObj = { + js: { + tbl:tbl + } +};</pre> + +<p>마지막으로 {{jsxref ( "WebAssembly.instantiateStreaming ()")}} 메소드를 사용하여 wasm 모듈 (table2.wasm)을 로드하고 인스턴스화합니다. table2.wasm 모듈에는 두 개의 함수 (하나는 42를 반환하고 다른 하나는 83을 반환하는 함수)가 들어 있고 가져온 테이블의 요소 0과 1에 둘 다 저장합니다 (<a href="https://github.com/mdn/webassembly-examples/blob/master/js-api-examples/table2.wat">text representation</a> 참조). 인스턴스화 후에도 테이블의 길이는 여전히 2이지만 JS에 호출 할 수있는 호출 가능한 <a href="/en-US/docs/WebAssembly/Exported_functions">Exported WebAssembly Functions</a>가 요소에 포함됩니다.</p> + +<pre class="brush: js">WebAssembly.instantiateStreaming(fetch('table2.wasm'), importObject) +.then(function(obj) { + console.log(tbl.length); + console.log(tbl.get(0)()); + console.log(tbl.get(1)()); +});</pre> + +<p>액세서의 끝 부분에 두 번째 함수 호출 연산자를 포함시켜 실제로 참조 된 함수를 호출하고 그 안에 저장된 값을 기록해야합니다 (예 : <code>get(0)</code> 대신 <code>get(0)()</code>).</p> + +<p>이 예제는 자바 스크립트에서 테이블을 만들고 액세스하고 있지만 wasm 인스턴스 내부에서도 같은 테이블을 볼 수 있고 호출 할 수 있음을 보여줍니다.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('WebAssembly JS', '#webassemblytable-objects', 'Table')}}</td> + <td>{{Spec2('WebAssembly JS')}}</td> + <td>Initial draft definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.WebAssembly.Table")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/WebAssembly">WebAssembly</a> overview page</li> + <li><a href="/en-US/docs/WebAssembly/Concepts">WebAssembly concepts</a></li> + <li><a href="/en-US/docs/WebAssembly/Using_the_JavaScript_API">Using the WebAssembly JavaScript API</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/webassembly/validate/index.html b/files/ko/web/javascript/reference/global_objects/webassembly/validate/index.html new file mode 100644 index 0000000000..a5ea4850e5 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/webassembly/validate/index.html @@ -0,0 +1,75 @@ +--- +title: WebAssembly.validate() +slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/validate +translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/validate +--- +<div>{{JSRef}}</div> + +<p><strong><code>WebAssembly.validate()</code> </strong>함수는 바이트가 유효한 wasm 모듈을 형성하는지 (<code>true</code>) 또는 생성하지 않는지 (<code>false</code>)를 반환하여 WebAssembly 바이너리 코드의 지정된 <a href="/ko/docs/Web/JavaScript/Typed_arrays">typed array</a>의 유효성을 검사합니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntax">WebAssembly.validate(bufferSource);</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code><em>bufferSource</em></code></dt> + <dd>유효성을 검사 할 WebAssembly 바이너리 코드가 들어있는 <a href="/ko/docs/Web/JavaScript/Typed_arrays">typed array</a> 또는 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer">ArrayBuffer</a>입니다.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p><code>bufferSource</code>가 유효한 wasm 코드 (<code>true</code>)인지 아닌지 (<code>false</code>)를 지정하는 부울입니다.</p> + +<h3 id="Exceptions">Exceptions</h3> + +<p><code>bufferSource</code>가 <a href="/ko/docs/Web/JavaScript/Typed_arrays">typed array</a>이나 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer">ArrayBuffer</a>가 아닌 경우 {{jsxref ( "TypeError")}}가 발생합니다.</p> + +<h2 id="Examples">Examples</h2> + +<p>다음 예제 (validate.html <a href="https://github.com/mdn/webassembly-examples/blob/master/js-api-examples/validate.html">source code</a> 참조 및 <a href="https://mdn.github.io/webassembly-examples/js-api-examples/validate.html">see it live</a>)는 .wasm 모듈을 가져 와서 형식화 된 배열로 변환합니다. 그런 다음 <code>validate()</code> 메서드를 사용하여 모듈이 유효한지 확인합니다.</p> + +<pre class="brush: js">fetch('simple.wasm').then(response => + response.arrayBuffer() +).then(function(bytes) { + var valid = WebAssembly.validate(bytes); + console.log("The given bytes are " + + (valid ? "" : "not ") + "a valid wasm module"); +}); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('WebAssembly JS', '#webassemblyvalidate', 'validate()')}}</td> + <td>{{Spec2('WebAssembly JS')}}</td> + <td>Initial draft definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.WebAssembly.validate")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/ko/docs/WebAssembly">WebAssembly</a> overview page</li> + <li><a href="/ko/docs/WebAssembly/Concepts">WebAssembly concepts</a></li> + <li><a href="/ko/docs/WebAssembly/Using_the_JavaScript_API">Using the WebAssembly JavaScript API</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/index.html b/files/ko/web/javascript/reference/index.html new file mode 100644 index 0000000000..c7d883f2b1 --- /dev/null +++ b/files/ko/web/javascript/reference/index.html @@ -0,0 +1,48 @@ +--- +title: JavaScript 참고자료 +slug: Web/JavaScript/Reference +tags: + - JavaScript +translation_of: Web/JavaScript/Reference +--- +<div>{{JsSidebar}}</div> + +<p>MDN 내 JavaScript 절의 이 부분은 JavaScript 언어에 관한 정보 저장소(facts repository)로 쓸 수 있습니다. <a href="/ko/docs/Web/JavaScript/Reference/About">이 참고서에 관하여</a>를 더 읽어보세요.</p> + +<h2 id="전역_객체들">전역 객체들</h2> + +<p>이 장은 모든 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects">JavaScript 표준 내장 객체</a>를, 메서드 및 속성(property)을 위주로 문서화합니다.</p> + +<div>{{page('/ko/docs/Web/JavaScript/Reference/Global_Objects', '항목별_표준_객체')}}</div> + +<h2 id="문">문</h2> + +<p>이 장은 모든 <a href="/ko/docs/Web/JavaScript/Reference/Statements" title="JavaScript statements and declarations">JavaScript 문 및 선언</a>을 문서화합니다.</p> + +<div>{{page('/ko/docs/Web/JavaScript/Reference/Statements', '항목별_문_및_선언')}}</div> + +<h2 id="표현식_및_연산자">표현식 및 연산자</h2> + +<p>이 장은 모든 <a href="/ko/docs/Web/JavaScript/Reference/Operators" title="JavaScript expressions and operators">JavaScript 표현식 및 연산자</a>를 문서화합니다.</p> + +<div>{{page('/ko/docs/Web/JavaScript/Reference/Operators', '항목별_식_및_연산자')}}</div> + +<h2 id="함수">함수</h2> + +<p>이 장은 응용 프로그램을 개발하기 위해 <a href="/ko/docs/Web/JavaScript/Reference/Functions">JavaScript 함수</a>로 작업하는 법을 문서화합니다.</p> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Reference/Functions/arguments"><code>arguments</code></a></li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Functions/애로우_펑션" title="Arrow functions">화살표 함수</a></li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Functions/Default_parameters" title="Default parameters">기본 매개변수</a></li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Functions/rest_parameters" title="Rest parameters">나머지 매개변수</a></li> +</ul> + +<h2 id="추가_참고_페이지">추가 참고 페이지</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Reference/Lexical_grammar" title="Lexical grammar">어휘 문법</a></li> + <li><a href="/ko/docs/Web/JavaScript/Data_structures" title="Data types and data structures">데이터 형 및 데이터 구조</a></li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Strict_mode" title="Strict mode">엄격 모드</a></li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features" title="Deprecated features">사라진 기능</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/iteration_protocols/index.html b/files/ko/web/javascript/reference/iteration_protocols/index.html new file mode 100644 index 0000000000..bddc56a50f --- /dev/null +++ b/files/ko/web/javascript/reference/iteration_protocols/index.html @@ -0,0 +1,394 @@ +--- +title: Iteration protocols +slug: Web/JavaScript/Reference/Iteration_protocols +translation_of: Web/JavaScript/Reference/Iteration_protocols +--- +<div>{{jsSidebar("More")}}</div> + +<p>ECMAScript 2015 (ES6)에는 새로운 문법이나 built-in 뿐만이 아니라, protocols(표현법들)도 추가되었습니다. 이 protocol 은 일정 규칙만 충족한다면 어떠한 객체에 의해서도 구현될 수 있습니다.</p> + +<p>2개의 protocol이 있습니다 : <a href="#iterable">iterable protocol</a> 과 <a href="#iterator">iterator protocol</a>.</p> + +<h2 id="iterable" name="iterable">The iterable protocol</h2> + +<p><strong>iterable</strong> protocol 은 JavaScript 객체들이, 예를 들어 {{jsxref("Statements/for...of", "for..of")}} 구조에서 어떠한 value 들이 loop 되는 것과 같은 iteration 동작을 정의하거나 사용자 정의하는 것을 허용합니다. 다른 type 들({{jsxref("Object")}} 와 같은)이 그렇지 않은 반면에, 어떤 built-in type 들은 {{jsxref("Array")}} 또는 {{jsxref("Map")}} 과 같은 default iteration 동작으로 <a href="#Builtin_iterables">built-in iterables</a> 입니다.</p> + +<p><strong>iterable </strong>하기 위해서 object는 <strong>@@iterator</strong> 메소드를 구현해야 합니다. 이것은 object (또는 <a href="/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain">prototype chain</a> 의 오브젝트 중 하나) 가 <code>{{jsxref("Symbol.iterator")}} </code>key 의 속성을 가져야 한다는 것을 의미합니다 :</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Property</th> + <th scope="col">Value</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>[Symbol.iterator]</code></td> + <td>object를 반환하는, arguments 없는 function. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterator">iterator protocol</a> 을 따른다.</td> + </tr> + </tbody> +</table> + +<p>어떠한 객체가 반복(Iterate)되어야 한다면 이 객체의 <code>@@iterator</code> 메소드가 인수없이 호출되고, 반환된 <strong>iterator</strong>는 반복을 통해서 획득할 값들을 얻을 때 사용됩니다.</p> + +<h2 id="iterator" name="iterator">The iterator protocol</h2> + +<p><strong>iterator </strong>protocol 은 value( finite 또는 infinite) 들의 sequence 를 만드는 표준 방법을 정의합니다. </p> + +<p>객체가 <code><strong>next()</strong></code> 메소드를 가지고 있고, 아래의 규칙에 따라 구현되었다면 그 객체는 iterator이다:</p> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Property</th> + <th scope="col">Value</th> + </tr> + <tr> + <td><code>next</code></td> + <td> + <p>아래 2개의 속성들을 가진 object 를 반환하는 arguments 없는 함수 :</p> + + <ul> + <li><code>done</code> (boolean) + + <ul> + <li>Iterator(반복자)가 마지막 반복 작업을 마쳤을 경우 <code>true</code>. 만약 iterator(반복자)에 <em>return 값</em>이 있다면 <code>value</code>의 값으로 지정된다. 반환 값에 대한 설명은 <a href="http://www.2ality.com/2013/06/iterators-generators.html#generators-as-threads">여기</a>.</li> + <li>Iterator(반복자)의 작업이 남아있을 경우 <code>false</code>. Iterator(반복자)에 <code>done</code> 프로퍼티 자체를 특정짓지 않은 것과 동일하다.</li> + </ul> + </li> + <li><code>value</code> - Iterator(반복자)으로부터 반환되는 모든 자바스크립트 값이며 <code>done</code>이 <code>true</code>일 경우 생략될 수 있다.</li> + </ul> + </td> + </tr> + </tbody> +</table> + +<p>몇몇 iterator들은 iterable(반복 가능)이다:</p> + +<pre class="brush: js">var someArray = [1, 5, 7]; +var someArrayEntries = someArray.entries(); + +someArrayEntries.toString(); // "[object Array Iterator]" +someArrayEntries === someArrayEntries[Symbol.iterator](); // true +</pre> + +<h2 id="Iteration_protocols_사용_예시"> Iteration protocols 사용 예시</h2> + +<p>{{jsxref("String")}} 은 built-in iterable 객체의 한 예시입니다.</p> + +<pre class="brush: js">var someString = "hi"; +typeof someString[Symbol.iterator]; // "function" +</pre> + +<p><code>String</code> 의 기본 iterator 는 string 의 문자를 하나씩 반환합니다.</p> + +<pre class="brush: js">var iterator = someString[Symbol.iterator](); +iterator + ""; // "[object String Iterator]" + +iterator.next(); // { value: "h", done: false } +iterator.next(); // { value: "i", done: false } +iterator.next(); // { value: undefined, done: true }</pre> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator">spread operator</a>와 같은 특정 내장 구조(built-in constructs)들은 실제로는 동일한 iteration protocol을 사용한다:</p> + +<pre class="brush: js">[...someString] // ["h", "i"]</pre> + +<p>사용자만의 <code>@@iterator</code>를 특정함으로써 원하는 반복 행위(iteration behavior)를 설정할 수 있다:</p> + +<pre class="brush: js">var someString = new String("hi"); // need to construct a String object explicitly to avoid auto-boxing + +someString[Symbol.iterator] = function() { + return { // this is the iterator object, returning a single element, the string "bye" + next: function() { + if (this._first) { + this._first = false; + return { value: "bye", done: false }; + } else { + return { done: true }; + } + }, + _first: true + }; +}; +</pre> + +<p>재설정된 <code>@@iterator</code>가 어떻게 내장 구조(built-in constructs)의 반복 행위에 영향을 주는지 참고:</p> + +<pre class="brush: js">[...someString]; // ["bye"] +someString + ""; // "hi" +</pre> + +<h2 id="Iterable_예시">Iterable 예시</h2> + +<h3 id="내장_iterables">내장 iterables</h3> + +<p>{{jsxref("String")}}, {{jsxref("Array")}}, {{jsxref("TypedArray")}}, {{jsxref("Map")}} and {{jsxref("Set")}} 는 모두 내장 iterable이다. 이 객체들의 프로토타입 객체들은 모두 <code>@@</code><code>iterator</code> 메소드를 가지고 있기 때문이다.</p> + +<h3 id="사용자_정의된_iterables">사용자 정의된 iterables</h3> + +<p>이렇게 고유한 iterables 를 만들 수 있다.</p> + +<pre class="brush: js">var myIterable = {}; +myIterable[Symbol.iterator] = function* () { + yield 1; + yield 2; + yield 3; +}; +[...myIterable]; // [1, 2, 3] +</pre> + +<h3 id="Iterable을_허용하는_내장_API들">Iterable을 허용하는 내장 API들</h3> + +<p>Iterable을 허용하는 많은 내장 API들이 있다. 예를 들어: {{jsxref("Map", "Map([iterable])")}}, {{jsxref("WeakMap", "WeakMap([iterable])")}}, {{jsxref("Set", "Set([iterable])")}} and {{jsxref("WeakSet", "WeakSet([iterable])")}}이 그것이다:</p> + +<pre class="brush: js">var myObj = {}; +new Map([[1,"a"],[2,"b"],[3,"c"]]).get(2); // "b" +new WeakMap([[{},"a"],[myObj,"b"],[{},"c"]]).get(myObj); // "b" +new Set([1, 2, 3]).has(3); // true +new Set("123").has("2"); // true +new WeakSet(function*() { + yield {}; + yield myObj; + yield {}; +}()).has(myObj); // true +</pre> + +<p>뿐만 아니라 {{jsxref("Promise.all", "Promise.all(iterable)")}}, {{jsxref("Promise.race", "Promise.race(iterable)")}}와 {{jsxref("Array.from", "Array.from()")}} 또한 해당된다.</p> + +<h3 id="Iterable과_함께_사용되는_문법">Iterable과 함께 사용되는 문법</h3> + +<p><code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for-of</a></code> loops, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator">spread operator</a>, <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/yield*">yield*</a>와</code> <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">destructuring assignment</a>는 iterable과 함께 사용되는 구문(statements)과 표현(expressions)이다.</p> + +<pre class="brush: js">for(let value of ["a", "b", "c"]){ + console.log(value); +} +// "a" +// "b" +// "c" + +[..."abc"]; // ["a", "b", "c"] + +function* gen(){ + yield* ["a", "b", "c"]; +} + +gen().next(); // { value:"a", done:false } + +[a, b, c] = new Set(["a", "b", "c"]); +a // "a" + +</pre> + +<h3 id="잘_정의되지_못한_iterables">잘 정의되지 못한 iterables</h3> + +<p>만약 Iterable의 <code>@@iterator</code> 메소드가 iterator 객체를 반환하지 않는다면 그것은 잘 정의되지 못한 iterable이라고 할 수 있다. 이러한 iterable을 사용하는 것은 런타임 예외나 예상치 못한 결과를 불러올 수 있다:</p> + +<pre class="brush: js">var nonWellFormedIterable = {} +nonWellFormedIterable[Symbol.iterator] = () => 1 +[...nonWellFormedIterable] // TypeError: [] is not a function +</pre> + +<h2 id="Iterator_예시">Iterator 예시</h2> + +<h3 id="간단한_iterator">간단한 iterator</h3> + +<pre class="brush: js">function makeIterator(array){ + var nextIndex = 0; + + return { + next: function(){ + return nextIndex < array.length ? + {value: array[nextIndex++], done: false} : + {done: true}; + } + }; +} + +var it = makeIterator(['yo', 'ya']); + +console.log(it.next().value); // 'yo' +console.log(it.next().value); // 'ya' +console.log(it.next().done); // true +</pre> + +<h3 id="무한_iterator">무한 iterator</h3> + +<pre class="brush: js">function idMaker(){ + var index = 0; + + return { + next: function(){ + return {value: index++, done: false}; + } + }; +} + +var it = idMaker(); + +console.log(it.next().value); // '0' +console.log(it.next().value); // '1' +console.log(it.next().value); // '2' +// ... +</pre> + +<h3 id="Generator와_함께_사용된_iterator">Generator와 함께 사용된 iterator</h3> + +<pre class="brush: js">function* makeSimpleGenerator(array){ + var nextIndex = 0; + + while(nextIndex < array.length){ + yield array[nextIndex++]; + } +} + +var gen = makeSimpleGenerator(['yo', 'ya']); + +console.log(gen.next().value); // 'yo' +console.log(gen.next().value); // 'ya' +console.log(gen.next().done); // true + + + +function* idMaker(){ + var index = 0; + while(true) + yield index++; +} + +var gen = idMaker(); + +console.log(gen.next().value); // '0' +console.log(gen.next().value); // '1' +console.log(gen.next().value); // '2' +// ... +</pre> + +<h2 id="generator_object_는_iterator_또는_iterable_인가">generator object 는 iterator 또는 iterable 인가?</h2> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator">generator object</a> 는 iterator 이면서 iterable 입니다.</p> + +<pre class="brush: js">var aGeneratorObject = function*(){ + yield 1; + yield 2; + yield 3; +}(); +typeof aGeneratorObject.next; +// "function", 이것은 next 메서드를 가지고 있기 때문에 iterator입니다. +typeof aGeneratorObject[Symbol.iterator]; +// "function", 이것은 @@iterator 메서드를 가지고 있기 때문에 iterable입니다. +aGeneratorObject[Symbol.iterator]() === aGeneratorObject; +// true, 이 Object의 @@iterator 메서드는 자기자신(iterator)을 리턴하는 것으로 보아 잘 정의된 iterable이라고 할 수 있습니다. +[...aGeneratorObject]; +// [1, 2, 3] +</pre> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(39.0)}}</td> + <td>{{CompatGeckoDesktop("27.0")}}</td> + <td>{{CompatNo}}</td> + <td>26</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>IteratorResult</code> object instead of throwing</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("29.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("27.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(39.0)}}</td> + </tr> + <tr> + <td><code>IteratorResult</code> object instead of throwing</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("29.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Firefox-specific_notes">Firefox-specific notes</h2> + +<h3 id="IteratorResult_object_returned_instead_of_throwing"><code>IteratorResult</code> object returned instead of throwing</h3> + +<p>Starting with Gecko 29 {{geckoRelease(29)}}, the completed generator function no longer throws a {{jsxref("TypeError")}} "generator has already finished". Instead, it returns an <code>IteratorResult</code> object like <code>{ value: undefined, done: true }</code> ({{bug(958951)}}).</p> + +<h3 id="Iterator_property_and_iterator_symbol"><code>Iterator</code> property and <code>@@iterator</code> symbol</h3> + +<p>From Gecko 17 (Firefox 17 / Thunderbird 17 / SeaMonkey 2.14) to Gecko 26 (Firefox 26 / Thunderbird 26 / SeaMonkey 2.23 / Firefox OS 1.2) the <code>iterator</code> property was used (<a href="https://bugzilla.mozilla.org/show_bug.cgi?id=907077">bug 907077</a>), and from Gecko 27 to Gecko 35 the <code>"@@iterator"</code> placeholder was used. In Gecko 36 (Firefox 36 / Thunderbird 36 / SeaMonkey 2.33), the <code>@@iterator</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol">symbol</a> got implemented (<a href="https://bugzilla.mozilla.org/show_bug.cgi?id=918828">bug 918828</a>).</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-iteration', 'Iteration')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-iteration', 'Iteration')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="See_also">See also</h2> + +<ul> + <li>ES6 제너레이터에 대한 더 상세한 정보는 <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function*">the function*() documentation</a> 를 참조하시기 바랍니다.</li> +</ul> diff --git a/files/ko/web/javascript/reference/lexical_grammar/index.html b/files/ko/web/javascript/reference/lexical_grammar/index.html new file mode 100644 index 0000000000..74e4e63788 --- /dev/null +++ b/files/ko/web/javascript/reference/lexical_grammar/index.html @@ -0,0 +1,657 @@ +--- +title: 어휘 문법 +slug: Web/JavaScript/Reference/Lexical_grammar +tags: + - JavaScript + - Keyword + - Lexical Grammar + - 문법 +translation_of: Web/JavaScript/Reference/Lexical_grammar +--- +<div>{{JsSidebar("More")}}</div> + +<p>이 페이지는 JavaScript의 어휘 문법(lexical grammar)을 설명합니다. ECMAScript 소스 본문은 왼쪽에서 오른쪽 방향으로 분석되고 토큰, 제어문자, 줄바꿈, 주석, 또는 공백으로 구성되는 입력 요소 시퀀스로 바뀝니다. 또한 ECMAScript는 특별한 키워드와 리터럴을 정의하고 있으며 명령문 끝에 자동으로 세미콜론을 추가하는 규칙이 있습니다.</p> + +<h2 id="제어_문자">제어 문자</h2> + +<p>제어 문자는 눈에 보이지 않지만 스크립트 소스 본문 해석을 제어하는 데 사용됩니다.</p> + +<table class="standard-table"> + <caption>유니코드 형식 제어 문자</caption> + <tbody> + <tr> + <th>코드 포인트</th> + <th>이름</th> + <th>축약형</th> + <th>설명</th> + </tr> + <tr> + <td><code>U+200C</code></td> + <td>Zero width non-joiner</td> + <td><ZWNJ></td> + <td> + <p>특정 언어에서 문자들이 연결선으로 묶이지 않게 하기 위해 문자 사이에 위치한다(<a href="http://en.wikipedia.org/wiki/Zero-width_non-joiner">Wikipedia</a>).</p> + </td> + </tr> + <tr> + <td><code>U+200D</code></td> + <td>Zero width joiner</td> + <td><ZWJ></td> + <td> + <p>특정 언어에서, 보통은 연결되지 않는 문자이나 해당 문자를 연결된 형태로 그리기 위해서(to be rendered) 사용하며 문자 사이에 위치한다(<a href="http://en.wikipedia.org/wiki/Zero-width_joiner">Wikipedia</a>).</p> + </td> + </tr> + <tr> + <td><code>U+FEFF</code></td> + <td>Byte order mark</td> + <td><BOM></td> + <td> + <p>스크립트 맨 앞에 두어 스크립트 본문의 byte order와 유니코드를 표시하는 데에 사용한다.(<a href="http://en.wikipedia.org/wiki/Byte_order_mark">Wikipedia</a>).</p> + </td> + </tr> + </tbody> +</table> + +<h2 id="공백">공백</h2> + +<p>공백 문자는 소스 본문을 읽기 좋게 만들고 토큰을 구분합니다. 이 공백 문자들은 보통 코드의 기능에 필요한 것은 아닙니다. 최소화 도구(<a href="http://en.wikipedia.org/wiki/Minification_%28programming%29">Minification tools</a>)는 종종 전송해야하는 데이터 크기를 줄이기 위해서 공백을 제거합니다.</p> + +<table class="standard-table"> + <caption>공백 문자</caption> + <tbody> + <tr> + <th>코드 포인트</th> + <th>이름</th> + <th>축약형</th> + <th>설명</th> + <th>이스케이프 시퀀스</th> + </tr> + <tr> + <td>U+0009</td> + <td>Character tabulation</td> + <td><HT></td> + <td>Horizontal tabulation</td> + <td>\t</td> + </tr> + <tr> + <td>U+000B</td> + <td>Line tabulation</td> + <td><VT></td> + <td>Vertical tabulation</td> + <td>\v</td> + </tr> + <tr> + <td>U+000C</td> + <td>Form feed</td> + <td><FF></td> + <td>Page breaking control character (<a href="http://en.wikipedia.org/wiki/Page_break#Form_feed">Wikipedia</a>).</td> + <td>\f</td> + </tr> + <tr> + <td>U+0020</td> + <td>Space</td> + <td><SP></td> + <td>Normal space</td> + <td></td> + </tr> + <tr> + <td>U+00A0</td> + <td>No-break space</td> + <td><NBSP></td> + <td>Normal space, but no point at which a line may break</td> + <td></td> + </tr> + <tr> + <td>Others</td> + <td>Other Unicode space characters</td> + <td><USP></td> + <td><a href="http://en.wikipedia.org/wiki/Space_%28punctuation%29#Spaces_in_Unicode">Spaces in Unicode on Wikipedia</a></td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="개행_문자">개행 문자</h2> + +<p>공백문자와 더불어, 개행 문자는 소스 본문의 가독성을 향상시킵니다. 하지만, 몇몇 상황에서 개행 문자는 코드 내부에 숨겨지기 때문에 자바스크립트 코드 실행에 영향을 미칩니다. 개행 문자는 자동 새미콜론 삽입(<a href="#Automatic_semicolon_insertion">automatic semicolon insertion</a>) 규칙에도 영향을 줍니다. 개행 문자는 표준 표현방식(<a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions">regular expressions</a>)의 클래스인 \s로 매치됩니다.</p> + +<p>아래의 유니코드 문자만이 ECMAScript에서 라인 종결자로 다뤄지며, 라인을 바꾸는 다른 문자들은 공백으로 생각하시면 됩니다(예를 들어, Next Line, NEL, U+0085는 공백으로 간주).</p> + +<table class="standard-table"> + <caption>개행 문자</caption> + <tbody> + <tr> + <th>코드 포인트</th> + <th>이름</th> + <th>축약형</th> + <th>설명</th> + <th>이스케이프 시퀀스</th> + </tr> + <tr> + <td>U+000A</td> + <td>Line Feed</td> + <td><LF></td> + <td>New line character in UNIX systems.</td> + <td>\n</td> + </tr> + <tr> + <td>U+000D</td> + <td>Carriage Return</td> + <td><CR></td> + <td>New line character in Commodore and early Mac systems.</td> + <td>\r</td> + </tr> + <tr> + <td>U+2028</td> + <td>Line Separator</td> + <td><LS></td> + <td><a href="http://en.wikipedia.org/wiki/Newline">Wikipedia</a></td> + <td></td> + </tr> + <tr> + <td>U+2029</td> + <td>Paragraph Separator</td> + <td><PS></td> + <td><a href="http://en.wikipedia.org/wiki/Newline">Wikipedia</a></td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="주석">주석</h2> + +<p>주석은 힌트, 필기, 제안이나 주의할 점들을 자바스크립트 코드에 넣을 때 사용합니다. 이는 더 쉽게 읽고 이해할 수 있게 도와줍니다. 또한 특정 코드가 실행되지 않도록 막아주기도 합니다. 따라서 주석은 유용한 디버깅 도구라고도 할 수 있습니다.</p> + +<p>자바스크립트에는 코드 속에 주석을 쓰는 두 가지 방식이 있습니다.</p> + +<p>첫 번째, '//'로 첨언하기입니다. 이는 아래의 예시처럼 같은 줄에 있는 모든 코드를 주석으로 바꿉니다.</p> + +<pre class="brush: js notranslate">function comment() { + // 자바스크립트의 각주 한 줄입니다. + console.log("Hello world!"); +} +comment(); +</pre> + +<p>두 번째, 좀 더 유연하게 쓸 수 있는 '/* */'로 첨언하기입니다.</p> + +<p>예를 들면, 한 줄에 첨언할 때는 이렇게 쓸 수 있습니다 :</p> + +<pre class="brush: js notranslate">function comment() { + /* 자바스크립트 각주 한 줄입니다. */ + console.log("Hello world!"); +} +comment();</pre> + +<p>여러 줄로 첨언할 때는, 이렇게 씁니다 :</p> + +<pre class="brush: js notranslate">function comment() { + /* This comment spans multiple lines. Notice + that we don't need to end the comment until we're done. */ + console.log("Hello world!"); +} +comment();</pre> + +<p>원한다면, 라인 중간에도 사용할 수 있습니다. 물론 코드의 가독성이 떨어지게 됩니다. 그러니 주의를 기울여 사용해야 합니다:</p> + +<p>function comment(x) {</p> + +<pre class="brush: js notranslate"> console.log("Hello " + x /* insert the value of x */ + " !"); +} +comment("world");</pre> + +<p>게다가, 코드 실행을 막기 위해 코드를 무용화 시키는데도 사용할 수 있습니다. 아래처럼 코드를 코멘트로 감싸는 거죠:</p> + +<pre class="brush: js notranslate">function comment() { + /* console.log("Hello world!"); */ +} +comment();</pre> + +<p>In this case, the <code>console.log()</code> call is never issued, since it's inside a comment. Any number of lines of code can be disabled this way.</p> + +<h2 id="해시뱅_주석">해시뱅 주석</h2> + +<p>A specialized third comment syntax, the <strong>hashbang comment</strong>, is in the process of being standardized in ECMAScript (see the <a href="https://github.com/tc39/proposal-hashbang">Hashbang Grammar proposal</a>).</p> + +<p>A hashbang comment behaves exactly like a single line-only (<code>//</code>) comment, but it instead begins with <code>#!</code> and<strong> is only valid at the absolute start of a script or module</strong>. Note also that no whitespace of any kind is permitted before the <code>#!</code>. The comment consists of all the characters after <code>#!</code> up to the end of the first line; only one such comment is permitted.</p> + +<p>The hashbang comment specifies the path to a specific JavaScript interpreter<br> + that you want to use to execute the script. An example is as follows:</p> + +<pre class="brush: js notranslate">#!/usr/bin/env node + +console.log("Hello world"); +</pre> + +<div class="blockIndicator note"> +<p><strong>Note</strong>: Hashbang comments in JavaScript mimic <a href="https://en.wikipedia.org/wiki/Shebang_(Unix)">shebangs in Unix</a> used to run files with proper interpreter.</p> +</div> + +<div class="blockIndicator warning"> +<p>Although <a href="https://en.wikipedia.org/wiki/Byte_order_mark">BOM</a> before hashbang comment will work in a browser it is not advised to use BOM in a script with hasbang. BOM will not work when you try to run the script in Unix/Linux. So use UTF-8 without BOM if you want to run scripts directly from shell.</p> +</div> + +<p>You must only use the <code>#!</code> comment style to specify a JavaScript interpreter. In all other cases just use a <code>//</code> comment (or mulitiline comment).</p> + +<h2 id="키워드">키워드</h2> + +<h3 id="ECMAScript_2015_기준_예약_키워드">ECMAScript 2015 기준 예약 키워드</h3> + +<ul class="threecolumns"> + <li>{{jsxref("Statements/break", "break")}}</li> + <li>{{jsxref("Statements/switch", "case")}}</li> + <li>{{jsxref("Statements/try...catch", "catch")}}</li> + <li>{{jsxref("Statements/class", "class")}}</li> + <li>{{jsxref("Statements/const", "const")}}</li> + <li>{{jsxref("Statements/continue", "continue")}}</li> + <li>{{jsxref("Statements/debugger", "debugger")}}</li> + <li>{{jsxref("Statements/default", "default")}}</li> + <li>{{jsxref("Operators/delete", "delete")}}</li> + <li>{{jsxref("Statements/do...while", "do")}}</li> + <li>{{jsxref("Statements/if...else", "else")}}</li> + <li>{{jsxref("Statements/export", "export")}}</li> + <li>{{jsxref("Statements/class", "extends")}}</li> + <li>{{jsxref("Statements/try...catch", "finally")}}</li> + <li>{{jsxref("Statements/for", "for")}}</li> + <li>{{jsxref("Statements/function", "function")}}</li> + <li>{{jsxref("Statements/if...else", "if")}}</li> + <li>{{jsxref("Statements/import", "import")}}</li> + <li>{{jsxref("Operators/in", "in")}}</li> + <li>{{jsxref("Operators/instanceof", "instanceof")}}</li> + <li>{{jsxref("Operators/new", "new")}}</li> + <li>{{jsxref("Statements/return", "return")}}</li> + <li>{{jsxref("Operators/super", "super")}}</li> + <li>{{jsxref("Statements/switch", "switch")}}</li> + <li>{{jsxref("Operators/this", "this")}}</li> + <li>{{jsxref("Statements/throw", "throw")}}</li> + <li>{{jsxref("Statements/try...catch", "try")}}</li> + <li>{{jsxref("Operators/typeof", "typeof")}}</li> + <li>{{jsxref("Statements/var", "var")}}</li> + <li>{{jsxref("Operators/void", "void")}}</li> + <li>{{jsxref("Statements/while", "while")}}</li> + <li>{{jsxref("Statements/with", "with")}}</li> + <li>{{jsxref("Operators/yield", "yield")}}</li> +</ul> + +<h3 id="확장_예약_키워드">확장 예약 키워드</h3> + +<p>The following are reserved as future keywords by the ECMAScript specification. They have no special functionality at present, but they might at some future time, so they cannot be used as identifiers.</p> + +<p>These are always reserved:</p> + +<ul> + <li><code>enum</code></li> +</ul> + +<p>The following are only reserved when they are found in strict mode code:</p> + +<ul class="threecolumns"> + <li><code>implements</code></li> + <li><code>interface</code></li> + <li>{{jsxref("Statements/let", "let")}}</li> + <li><code>package</code></li> + <li><code>private</code></li> + <li><code>protected</code></li> + <li><code>public</code></li> + <li><code>static</code></li> +</ul> + +<p>The following are only reserved when they are found in module code:</p> + +<ul> + <li><code>await</code></li> +</ul> + +<h4 id="구형_표준의_확장_예약_키워드">구형 표준의 확장 예약 키워드</h4> + +<p>The following are reserved as future keywords by older ECMAScript specifications (ECMAScript 1 till 3).</p> + +<ul class="threecolumns"> + <li><code>abstract</code></li> + <li><code>boolean</code></li> + <li><code>byte</code></li> + <li><code>char</code></li> + <li><code>double</code></li> + <li><code>final</code></li> + <li><code>float</code></li> + <li><code>goto</code></li> + <li><code>int</code></li> + <li><code>long</code></li> + <li><code>native</code></li> + <li><code>short</code></li> + <li><code>synchronized</code></li> + <li><code>throws</code></li> + <li><code>transient</code></li> + <li><code>volatile</code></li> +</ul> + +<p>Additionally, the literals <code>null</code>, <code>true</code>, and <code>false</code> cannot be used as identifiers in ECMAScript.</p> + +<h3 id="예약어_사용법">예약어 사용법</h3> + +<p>Reserved words actually only apply to Identifiers (vs. <code>IdentifierNames</code>) . As described in <a href="http://es5.github.com/#A.1">es5.github.com/#A.1</a>, these are all <code>IdentifierNames</code> which do not exclude <code>ReservedWords</code>.</p> + +<pre class="brush: js notranslate">a.import +a['import'] +a = { import: 'test' }. +</pre> + +<p>On the other hand the following is illegal because it's an <code>Identifier</code>, which is an <code>IdentifierName</code> without the reserved words. Identifiers are used for <code>FunctionDeclaration, FunctionExpression, VariableDeclaration</code> and so on. <code>IdentifierNames </code>are used for<code> MemberExpression, CallExpression</code> and so on.</p> + +<pre class="brush: js notranslate">function import() {} // Illegal.</pre> + +<h2 id="리터럴">리터럴</h2> + +<h3 id="Null_리터럴">Null 리터럴</h3> + +<p>See also <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/null"><code>null</code></a> for more information.</p> + +<pre class="brush: js notranslate">null</pre> + +<h3 id="불리언_리터럴">불리언 리터럴</h3> + +<p>See also <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean"><code>Boolean</code></a> for more information.</p> + +<pre class="brush: js notranslate">true +false</pre> + +<h3 id="숫자_리터럴">숫자 리터럴</h3> + +<h4 id="10진법">10진법</h4> + +<pre class="brush: js notranslate">1234567890 +42 + +// Caution when using with a leading zero: +0888 // 888 parsed as decimal +0777 // parsed as octal, 511 in decimal +</pre> + +<p>Note that decimal literals can start with a zero (<code>0</code>) followed by another decimal digit, but If all digits after the leading <code>0</code> are smaller than 8, the number is interpreted as an octal number. This won't throw in JavaScript, see {{bug(957513)}}. See also the page about <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#Octal_interpretations_with_no_radix"><code>parseInt()</code></a>.</p> + +<h5 id="Exponential">Exponential</h5> + +<p>The decimal exponential literal is specified by the following format: <code>beN</code>; where <code>b</code> is a base number (integer or floating), followed by <code>e</code> char (which serves as separator or <em>exponent indicator</em>) and<em> </em><code>N</code>, which is <em>exponent</em> or <em>power</em> number – a signed integer (as per 2019 ECMA-262 specs): </p> + +<pre class="notranslate">0e-5 // => 0 +0e+5 // => 0 +5e1 // => 50 +175e-2 // => 1.75 +1e3 // => 1000 +1e-3 // => 0.001</pre> + +<h4 id="2진법">2진법</h4> + +<p>Binary number syntax uses a leading zero followed by a lowercase or uppercase Latin letter "B" (<code>0b</code> or <code>0B</code>). Because this syntax is new in ECMAScript 2015, see the browser compatibility table, below. If the digits after the <code>0b</code> are not 0 or 1, the following <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError">SyntaxError</a></code> is thrown: "Missing binary digits after 0b".</p> + +<pre class="brush: js notranslate">var FLT_SIGNBIT = 0b10000000000000000000000000000000; // 2147483648 +var FLT_EXPONENT = 0b01111111100000000000000000000000; // 2139095040 +var FLT_MANTISSA = 0B00000000011111111111111111111111; // 8388607</pre> + +<h4 id="8진법">8진법</h4> + +<p>Octal number syntax uses a leading zero followed by a lowercase or uppercase Latin letter "O" (<code>0o</code> or <code>0O)</code>. Because this syntax is new in ECMAScript 2015, see the browser compatibility table, below. If the digits after the <code>0o</code> are outside the range (01234567), the following <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError">SyntaxError</a></code> is thrown: "Missing octal digits after 0o".</p> + +<pre class="brush: js notranslate">var n = 0O755; // 493 +var m = 0o644; // 420 + +// Also possible with just a leading zero (see note about decimals above) +0755 +0644 +</pre> + +<h4 id="16진법">16진법</h4> + +<p>Hexadecimal number syntax uses a leading zero followed by a lowercase or uppercase Latin letter "X" (<code>0x</code> or <code>0X)</code>. If the digits after 0x are outside the range (0123456789ABCDEF), the following <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError">SyntaxError</a></code> is thrown: "Identifier starts immediately after numeric literal".</p> + +<pre class="brush: js notranslate">0xFFFFFFFFFFFFFFFFF // 295147905179352830000 +0x123456789ABCDEF // 81985529216486900 +0XA // 10 +</pre> + +<h4 id="BigInt_literal">BigInt literal</h4> + +<p>The {{jsxref("BigInt")}} type is a numeric primitive in JavaScript that can represent integers with arbitrary precision. BigInt literals are created by appending <code>n</code> to the end of an integer.</p> + +<pre class="notranslate">123456789123456789n // 123456789123456789 +0o777777777777n // 68719476735 +0x123456789ABCDEFn // 81985529216486895 +0b11101001010101010101n // 955733 +</pre> + +<p>Note that legacy octal numbers with just a leading zero won't work for <code>BigInt</code>:</p> + +<pre class="example-bad notranslate">// 0755n +// SyntaxError: invalid BigInt syntax</pre> + +<p>For octal <code>BigInt</code> numbers, always use zero followed by the letter "o" (uppercase or lowercase):</p> + +<pre class="example-good notranslate">0o755n</pre> + +<p>For more information about <code>BigInt</code>, see also <a href="https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#BigInt_type">JavaScript data structures</a>.</p> + +<h4 id="Numeric_separators">Numeric separators</h4> + +<p>To improve readability for numeric literals, underscores (<code>_</code>, <code>U+005F</code>) can be used as separators:</p> + +<pre class="notranslate">// separators in decimal numbers +1_000_000_000_000 +1_050.95 + +// separators in binary numbers +0b1010_0001_1000_0101 + +// separators in octal numbers +0o2_2_5_6 + +// separators in hex numbers +0xA0_B0_C0 + +// separators in BigInts +1_000_000_000_000_000_000_000n +</pre> + +<p>Note these limitations:</p> + +<pre class="example-bad notranslate">// More than one underscore in a row is not allowed +100__000; // SyntaxError + +// Not allowed at the end of numeric literals +100_; // SyntaxError + +// Can not be used after leading 0 +0_1; // SyntaxError +</pre> + +<h3 id="객체_리터럴">객체 리터럴</h3> + +<p>See also {{jsxref("Object")}} and <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer">Object initializer</a> for more information.</p> + +<pre class="brush: js notranslate">var o = { a: 'foo', b: 'bar', c: 42 }; + +// shorthand notation. New in ES2015 +var a = 'foo', b = 'bar', c = 42; +var o = {a, b, c}; + +// instead of +var o = { a: a, b: b, c: c }; +</pre> + +<h3 id="배열_리터럴">배열 리터럴</h3> + +<p>See also {{jsxref("Array")}} for more information.</p> + +<pre class="brush: js notranslate">[1954, 1974, 1990, 2014]</pre> + +<h3 id="문자열_리터럴">문자열 리터럴</h3> + +<p>A string literal is zero or more Unicode code points enclosed in single or double quotes. Unicode code points may also be represented by an escape sequence. All code points may appear literally in a string literal except for these closing quote code points:</p> + +<ul> + <li>U+005C (backslash),</li> + <li>U+000D <CR>,</li> + <li>and U+000A <LF>.</li> +</ul> + +<p>Prior to the <a href="https://github.com/tc39/proposal-json-superset">proposal to make all JSON text valid ECMA-262</a>, U+2028 <LS> and U+2029 <PS>, were also disallowed from appearing unescaped in string literals.</p> + +<p>Any code points may appear in the form of an escape sequence. String literals evaluate to ECMAScript String values. When generating these String values Unicode code points are UTF-16 encoded.</p> + +<pre class="brush: js notranslate">'foo' +"bar"</pre> + +<h4 id="16진수_이스케이프_시퀀스">16진수 이스케이프 시퀀스</h4> + +<p>Hexadecimal escape sequences consist of <code>\x</code> followed by exactly two hexadecimal digits representing a code unit or code point in the range 0x0000 to 0x00FF.</p> + +<pre class="brush: js notranslate">'\xA9' // "©" +</pre> + +<h4 id="유니코드_이스케이프_시퀀스">유니코드 이스케이프 시퀀스</h4> + +<p>A Unicode escape sequence consists of exactly four hexadecimal digits following <code>\u</code>. It represents a code unit in the UTF-16 encoding. For code points U+0000 to U+FFFF, the code unit is equal to the code point. Code points U+10000 to U+10FFFF require two escape sequences representing the two code units (a surrogate pair) used to encode the character; the surrogate pair is distinct from the code point.</p> + +<p>See also {{jsxref("String.fromCharCode()")}} and {{jsxref("String.prototype.charCodeAt()")}}.</p> + +<pre class="brush: js notranslate">'\u00A9' // "©" (U+A9)</pre> + +<h4 id="유니코드_코드_포인트_시퀀스">유니코드 코드 포인트 시퀀스</h4> + +<p>A Unicode code point escape consists of <code>\u{</code>, followed by a code point in hexadecimal base, followed by <code>}</code>. The value of the hexadecimal digits must be in the range 0 and 0x10FFFF inclusive. Code points in the range U+10000 to U+10FFFF do not need to be represented as a surrogate pair. Code point escapes were added to JavaScript in ECMAScript 2015 (ES6).</p> + +<p>See also {{jsxref("String.fromCodePoint()")}} and {{jsxref("String.prototype.codePointAt()")}}.</p> + +<pre class="brush: js notranslate">'\u{2F804}' // CJK COMPATIBILITY IDEOGRAPH-2F804 (U+2F804) + +// the same character represented as a surrogate pair +'\uD87E\uDC04'</pre> + +<h3 id="정규_표현식_리터럴">정규 표현식 리터럴</h3> + +<p>See also <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp"><code>RegExp</code></a> for more information.</p> + +<pre class="brush: js notranslate">/ab+c/g + +// An "empty" regular expression literal +// The empty non-capturing group is necessary +// to avoid ambiguity with single-line comments. +/(?:)/</pre> + +<h3 id="템플릿_리터럴">템플릿 리터럴</h3> + +<p>See also <a href="/en-US/docs/Web/JavaScript/Reference/template_strings">template strings</a> for more information.</p> + +<pre class="brush: js notranslate">`string text` + +`string text line 1 + string text line 2` + +`string text ${expression} string text` + +tag `string text ${expression} string text`</pre> + +<h2 id="자동_세미콜론_삽입">자동 세미콜론 삽입</h2> + +<p>Some <a href="/en-US/docs/Web/JavaScript/Reference/Statements">JavaScript statements</a> must be terminated with semicolons and are therefore affected by automatic semicolon insertion (ASI):</p> + +<ul> + <li>Empty statement</li> + <li><code>let</code>, <code>const</code>, variable statement</li> + <li><code>import</code>, <code>export</code>, module declaration</li> + <li>Expression statement</li> + <li><code>debugger</code></li> + <li><code>continue</code>, <code>break</code>, <code>throw</code></li> + <li><code>return</code></li> +</ul> + +<p>The ECMAScript specification mentions<a href="https://tc39.github.io/ecma262/#sec-rules-of-automatic-semicolon-insertion"> three rules of semicolon insertion</a>.</p> + +<p>1. A semicolon is inserted before, when a <a href="#Line_terminators">Line terminator</a> or "}" is encountered that is not allowed by the grammar.</p> + +<pre class="brush: js notranslate">{ 1 2 } 3 + +// is transformed by ASI into + +{ 1 2 ;} 3;</pre> + +<p>2. A semicolon is inserted at the end, when the end of the input stream of tokens is detected and the parser is unable to parse the single input stream as a complete program.</p> + +<p>Here <code>++</code> is not treated as a <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment">postfix operator</a> applying to variable <code>b</code>, because a line terminator occurs between <code>b</code> and <code>++</code>.</p> + +<pre class="brush: js notranslate">a = b +++c + +// is transformend by ASI into + +a = b; +++c; +</pre> + +<p>3. A semicolon is inserted at the end, when a statement with restricted productions in the grammar is followed by a line terminator. These statements with "no LineTerminator here" rules are:</p> + +<ul> + <li>PostfixExpressions (<code>++</code> and <code>--</code>)</li> + <li><code>continue</code></li> + <li><code>break</code></li> + <li><code>return</code></li> + <li><code>yield</code>, <code>yield*</code></li> + <li><code>module</code></li> +</ul> + +<pre class="brush: js notranslate">return +a + b + +// is transformed by ASI into + +return; +a + b; +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2("ES1")}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-7', 'Lexical Conventions')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-ecmascript-language-lexical-grammar', 'Lexical Grammar')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Added: Binary and Octal Numeric literals, Unicode code point escapes, Templates</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-ecmascript-language-lexical-grammar', 'Lexical Grammar')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.grammar")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Boolean")}}</li> + <li>{{jsxref("Number")}}</li> + <li>{{jsxref("RegExp")}}</li> + <li>{{jsxref("String")}}</li> + <li><a href="http://whereswalden.com/2013/08/12/micro-feature-from-es6-now-in-firefox-aurora-and-nightly-binary-and-octal-numbers/">Jeff Walden: Binary and octal numbers</a></li> + <li><a href="http://mathiasbynens.be/notes/javascript-escapes">Mathias Bynens: JavaScript character escape sequences</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/liveconnect/index.html b/files/ko/web/javascript/reference/liveconnect/index.html new file mode 100644 index 0000000000..dfa43d52d0 --- /dev/null +++ b/files/ko/web/javascript/reference/liveconnect/index.html @@ -0,0 +1,17 @@ +--- +title: LiveConnect +slug: Web/JavaScript/Reference/LiveConnect +translation_of: Archive/Web/LiveConnect +--- +<p>이 절(section)은 생성자, 메소드와 함께 LiveConnect에 쓰이는 Java 클래스를 상세히 기록합니다. 이 클래스들은 Java 객체가 JavaScript 코드에 접근할 수 있게 합니다.</p> +<p><a href="ko/Core_JavaScript_1.5_Reference/LiveConnect/JSException">JSException</a></p> +<dl> + <dd> + public 클래스 <code>JSException</code>은 <code>RuntimeException</code>를 상속하고, JavaScript가 에러를 반환하면 발생됩니다.</dd> +</dl> +<p><a href="ko/Core_JavaScript_1.5_Reference/LiveConnect/JSObject">JSObject</a></p> +<dl> + <dd> + public 클래스 <code>JSObject</code>는 <code>Object</code>를 상속합니다. JavaScript 개체는 클래스 <code>JSObject</code>의 인스턴스(instance)로 싸여 Java가 JavaScript 개체를 다루게 하도록 Java에 건네집니다.</dd> +</dl> +<p>{{ languages( { "en": "en/Core_JavaScript_1.5_Reference/LiveConnect", "pl": "pl/Dokumentacja_j\u0119zyka_JavaScript_1.5/LiveConnect" } ) }}</p> diff --git a/files/ko/web/javascript/reference/operators/addition/index.html b/files/ko/web/javascript/reference/operators/addition/index.html new file mode 100644 index 0000000000..0a624fdd16 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/addition/index.html @@ -0,0 +1,77 @@ +--- +title: Addition (+) +slug: Web/JavaScript/Reference/Operators/Addition +translation_of: Web/JavaScript/Reference/Operators/Addition +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>증가 연산자<sup>addition operator</sup> (<code>+</code>)는 숫자 또는 여러 문자열의 더합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-addition.html")}}</div> + +<div></div> + + + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox notranslate"><strong>Operator:</strong> <var>x</var> + <var>y</var> +</pre> + +<h2 id="Examples">Examples</h2> + +<h3 id="Numeric_addition">Numeric addition</h3> + +<pre class="brush: js notranslate">// Number + Number -> addition +1 + 2 // 3 + +// Boolean + Number -> addition +true + 1 // 2 + +// Boolean + Boolean -> addition +false + false // 0 +</pre> + +<h3 id="String_concatenation">String concatenation</h3> + +<pre class="brush: js notranslate">// String + String -> concatenation +'foo' + 'bar' // "foobar" + +// Number + String -> concatenation +5 + 'foo' // "5foo" + +// String + Boolean -> concatenation +'foo' + false // "foofalse"</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-addition-operator-plus', 'Addition operator')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.operators.addition")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Subtraction">Subtraction operator</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Division">Division operator</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Multiplication">Multiplication operator</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder">Remainder operator</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation">Exponentiation operator</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment">Increment operator</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Decrement">Decrement operator</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_negation">Unary negation operator</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus">Unary plus operator</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/arithmetic_operators/index.html b/files/ko/web/javascript/reference/operators/arithmetic_operators/index.html new file mode 100644 index 0000000000..8b2b274aa6 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/arithmetic_operators/index.html @@ -0,0 +1,290 @@ +--- +title: 산술 연산자 +slug: Web/JavaScript/Reference/Operators/Arithmetic_Operators +tags: + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><span class="seoSummary"><strong>산술 연산자는</strong> 숫자 값(리터럴 또는 변수)을 피연산자로 받아 하나의 숫자 값을 반환합니다.</span> 표준 산술 연산자는 덧셈(+), 뺄셈(-), 곱셈(*), 나눗셈(/)입니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-arithmetic.html")}}</div> + + + +<h2 id="덧셈"><a id="Addition" name="Addition">덧셈 (+)</a></h2> + +<p>덧셈 연산자는 숫자 피연산자를 더한 값, 또는 문자열을 연결한 값을 생성합니다.</p> + +<h3 id="구문">구문</h3> + +<pre class="syntaxbox"><strong>연산자:</strong> x + y +</pre> + +<h3 id="예제">예제</h3> + +<pre class="brush: js">// Number + Number -> 합 +1 + 2 // 3 + +// Boolean + Number -> 합 +true + 1 // 2 + +// Boolean + Boolean -> 합 +false + false // 0 + +// Number + String -> 연결 +5 + "foo" // "5foo" + +// String + Boolean -> 연결 +"foo" + false // "foofalse" + +// String + String -> 연결 +"foo" + "bar" // "foobar" +</pre> + +<h2 id="뺄셈_-"><a id="Subtraction" name="Subtraction">뺄셈 (-)</a></h2> + +<p>뺄셈 연산자는 두 개의 피연산자를 뺀 값을 생성합니다.</p> + +<h3 id="구문_2">구문</h3> + +<pre class="syntaxbox"><strong>연산자:</strong> x - y +</pre> + +<h3 id="예제_2">예제</h3> + +<pre class="brush: js">5 - 3 // 2 +3 - 5 // -2 +"foo" - 3 // NaN</pre> + +<h2 id="나눗셈"><a id="Division" name="Division">나눗셈 (/)</a></h2> + +<p>나눗셈 연산자는 왼쪽 피연산자를 피제수로, 오른쪽 피연산자를 제수로 한 몫을 생성합니다.</p> + +<h3 id="구문_3">구문</h3> + +<pre class="syntaxbox"><strong>연산자:</strong> x / y +</pre> + +<h3 id="예제_3">예제</h3> + +<pre class="brush: js">1 / 2 // JavaScript에선 0.5 +1 / 2 // Java에선 0 +// (양쪽 피연산자 모두 명시적인 부동소수점 숫자가 아님) + +1.0 / 2.0 // JavaScript와 Java 둘 다 0.5 + +2.0 / 0 // JavaScript에서 Infinity +2.0 / 0.0 // 동일하게 Infinity +2.0 / -0.0 // JavaScript에서 -Infinity</pre> + +<h2 id="곱셈_*"><a id="Multiplication" name="Multiplication">곱셈 (*)</a></h2> + +<p>곱셈 연산자는 두 연산자의 곱을 생성합니다.</p> + +<h3 id="구문_4">구문</h3> + +<pre class="syntaxbox"><strong>연산자:</strong> x * y +</pre> + +<h3 id="예제_4">예제</h3> + +<pre class="brush: js">2 * 2 // 4 +-2 * 2 // -4 +Infinity * 0 // NaN +Infinity * Infinity // Infinity +"foo" * 2 // NaN +</pre> + +<h2 id="나머지"><a id="Remainder" name="Remainder">나머지 (%)</a></h2> + +<p>나머지 연산자는 왼쪽 피연산자를 오른쪽 피연산자로 나눴을 때의 나머지를 반환합니다. 결과는 항상 피제수의 부호를 따라갑니다.</p> + +<h3 id="구문_5">구문</h3> + +<pre class="syntaxbox"><strong>연산자:</strong> var1 % var2 +</pre> + +<h3 id="예제_5">예제</h3> + +<pre class="brush: js">12 % 5 // 2 +-1 % 2 // -1 +NaN % 2 // NaN +1 % 2 // 1 +2 % 3 // 2 +-4 % 2 // -0 +5.5 % 2 // 1.5 +</pre> + +<h2 id="거듭제곱_**"><a name="Exponentiation">거듭제곱 (**)</a></h2> + +<p>거듭제곱 연산자는 첫 번째 피연산자를 밑으로, 두 번째 피연산자를 지수로 한 값을 생성합니다. 즉, <code>var1</code>과 <code>var2</code>가 변수일 때, <code>var1<sup>var2</sup></code>의 값을 생성합니다. 거듭제곱 연산자는 우결합성을 가집니다. 따라서 <code>a ** b ** c</code>는 <code>a ** (b ** c)</code>와 같습니다.</p> + +<h3 id="구문_6">구문</h3> + +<pre class="syntaxbox"><strong>연산자:</strong> var1 ** var2 +</pre> + +<h3 id="참고">참고</h3> + +<p>PHP와 Python 등 거듭제곱 연산자를 가진 대부분의 언어는 거듭제곱 연산자의 우선순위가 +와 - 등 단항 연산자보다 높습니다. 그러나 Bash는 단항 연산자가 거듭제곱 연산자보다 우선순위가 높은 등 일부 예외도 있습니다. JavaScript는 단항 연산자(<code>+/-/~/!/delete/void/typeof</code>)를 왼쪽 피연산자 앞에 배치할 수 없으므로, 모호한 표현도 작성할 수 없습니다.</p> + +<pre class="brush: js">-2 ** 2; +// Bash에서 4, 다른 언어에서는 -4. +// 모호한 표현이므로 JavaScript에서는 유효하지 않음 + + +-(2 ** 2); +// JavaScript에서 -4, 작성자의 의도가 명확함 +</pre> + +<h3 id="예제_6">예제</h3> + +<pre class="brush: js">2 ** 3 // 8 +3 ** 2 // 9 +3 ** 2.5 // 15.588457268119896 +10 ** -1 // 0.1 +NaN ** 2 // NaN + +2 ** 3 ** 2 // 512 +2 ** (3 ** 2) // 512 +(2 ** 3) ** 2 // 64 +</pre> + +<p>결과의 부호를 뒤집으려면 다음과 같이 작성합니다.</p> + +<pre class="brush: js">-(2 ** 2) // -4 +</pre> + +<p>거듭제곱의 밑을 음수로 강제하려면 다음과 같이 작성합니다.</p> + +<pre class="brush: js">(-2) ** 2 // 4 +</pre> + +<div class="note"> +<p><strong>참고:</strong> JavaScript는 <a href="/ko/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_XOR">비트 연산자 ^ (논리 XOR)</a>도 가지고 있습니다. <code>**</code>와 <code>^</code>는 다릅니다. (예 : <code>2 ** 3 === 8</code>이지만 <code>2 ^ 3 === 1</code>)</p> +</div> + +<h2 id="증가"><a id="Increment" name="Increment">증가 (++)</a></h2> + +<p>증가 연산자는 피연산자를 증가(1을 덧셈)시키고, 그 값을 반환합니다.</p> + +<ul> + <li>피연산자 뒤에 붙여(예: <code>x++</code>) 접미사로 사용한 경우 증가하기 전의 값을 반환합니다.</li> + <li>피연산자 앞에 붙여(예: <code>++x</code>) 접두사로 사용한 경우 증가한 후의 값을 반환합니다.</li> +</ul> + +<h3 id="구문_7">구문</h3> + +<pre class="syntaxbox"><strong>연산자:</strong> x++ or ++x +</pre> + +<h3 id="예제_7">예제</h3> + +<pre class="brush: js">// 접미사 +var x = 3; +y = x++; // y = 3, x = 4 + +// 접두사 +var a = 2; +b = ++a; // a = 3, b = 3 +</pre> + +<h2 id="감소_--"><a id="Decrement" name="Decrement">감소 (--)</a></h2> + +<p>감소 연산자는 피연산자를 감소(1을 뺄셈)시키고, 그 값을 반환합니다.</p> + +<ul> + <li>피연산자 뒤에 붙여(예: <code>x--</code>) 접미사로 사용한 경우 감소하기 전의 값을 반환합니다.</li> + <li>피연산자 앞에 붙여(예: <code>--x</code>) 접두사로 사용한 경우 감소한 후의 값을 반환합니다.</li> +</ul> + +<h3 id="구문_8">구문</h3> + +<pre class="syntaxbox"><strong>연산자:</strong> x-- or --x +</pre> + +<h3 id="예제_8">예제</h3> + +<pre class="brush: js">// 접미사 +var x = 3; +y = x--; // y = 3, x = 2 + +// 접두사 +var a = 2; +b = --a; // a = 1, b = 1 +</pre> + +<h2 id="단항_부정_-"><a name="Unary_negation">단항 부정 (-)</a></h2> + +<p>단항 부정 연산자는 피연산자의 앞에 위치하며 부호를 뒤집습니다.</p> + +<h3 id="구문_9">구문</h3> + +<pre class="syntaxbox"><strong>연산자:</strong> -x +</pre> + +<h3 id="예제_9">예제</h3> + +<pre class="brush: js">var x = 3; +y = -x; // y = -3, x = 3 + +// 단항 부정 연산자는 숫자가 아닌 값을 숫자로 변환함 +var x = "4"; +y = -x; // y = -4</pre> + +<h2 id="단항_양부호"><a name="Unary_plus">단항 양부호 (+)</a></h2> + +<p>단항 양부호 연산자는 피연산자의 앞에 위치하며 피연산자의 값 그대로 평가되지만, 값이 숫자가 아닐 경우 숫자로 변환을 시도합니다. 단항 부정(-) 연산자도 숫자가 아닌 값을 변환할 수 있지만, 단항 양부호가 속도도 제일 빠르고 다른 연산도 수행하지 않으므로 선호해야 할 방법입니다. 문자열로 표현한 정수 및 부동소수점 실수, 문자열이 아닌 <code>true</code>, <code>false</code>, <code>null</code>도 변환할 수 있습니다. 10진수와 (앞에 "0x"가 붙은) 16진수 정수 모두 지원합니다. 음수도 지원하지만 16진수 음수에는 사용할 수 없습니다. 어떤 값을 분석할 수 없으면 {{jsxref("NaN")}}으로 평가됩니다.</p> + +<h3 id="구문_10">구문</h3> + +<pre class="syntaxbox"><strong>연산자:</strong> +x +</pre> + +<h3 id="예제_10">예제</h3> + +<pre class="brush: js">+3 // 3 ++"3" // 3 ++true // 1 ++false // 0 ++null // 0 ++function(val) { return val } // NaN +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-additive-operators', 'Additive operators')}}</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-postfix-expressions', 'Postfix expressions')}}</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-11.5', 'Multiplicative operators')}}</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-11.4', 'Unary operator')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.operators.arithmetic")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Reference/Operators/Assignment_Operators">할당 연산자</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/assignment_operators/index.html b/files/ko/web/javascript/reference/operators/assignment_operators/index.html new file mode 100644 index 0000000000..d7f195c803 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/assignment_operators/index.html @@ -0,0 +1,394 @@ +--- +title: 할당 연산자 +slug: Web/JavaScript/Reference/Operators/Assignment_Operators +tags: + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators#Assignment_operators +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>할당 연산자</strong>는 오른쪽 피연산자의 값을 왼쪽 피연산자에 할당합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-assignment.html")}}</div> + + + +<h2 id="개요">개요</h2> + +<p>기본 할당연산자는 등호(<code>=</code>)로, 오른쪽 피연산자의 값을 왼쪽 피연산자에 할당합니다. 즉, <code>x = y</code>는 <code>y</code>의 값을 <code>x</code>에 할당힙니다. 다른 할당 연산자는 보통 표준 연산의 축약형으로, 다음 표에서 종류와 예시를 확인할 수 있습니다.</p> + +<table class="standard-table"> + <tbody> + <tr> + <th>이름</th> + <th>단축 연산자</th> + <th>의미</th> + </tr> + <tr> + <td><a href="#Assignment">할당</a></td> + <td><code>x = y</code></td> + <td><code>x = y</code></td> + </tr> + <tr> + <td><a href="#Addition_assignment">덧셈 할당</a></td> + <td><code>x += y</code></td> + <td><code>x = x + y</code></td> + </tr> + <tr> + <td><a href="#Subtraction_assignment">뺄셈 할당</a></td> + <td><code>x -= y</code></td> + <td><code>x = x - y</code></td> + </tr> + <tr> + <td><a href="#Multiplication_assignment">곱셈 할당</a></td> + <td><code>x *= y</code></td> + <td><code>x = x * y</code></td> + </tr> + <tr> + <td><a href="#Division_assignment">나눗셈 할당</a></td> + <td><code>x /= y</code></td> + <td><code>x = x / y</code></td> + </tr> + <tr> + <td><a href="#Remainder_assignment">나머지 연산 할당</a></td> + <td><code>x %= y</code></td> + <td><code>x = x % y</code></td> + </tr> + <tr> + <td><a href="#Exponentiation_assignment">지수 연산 할당</a></td> + <td><code>x **= y</code></td> + <td><code>x = x ** y</code></td> + </tr> + <tr> + <td><a href="#Left_shift_assignment">왼쪽 시프트 할당</a></td> + <td><code>x <<= y</code></td> + <td><code>x = x << y</code></td> + </tr> + <tr> + <td><a href="#Right_shift_assignment">오른쪽 시프트 할당</a></td> + <td><code>x >>= y</code></td> + <td><code>x = x >> y</code></td> + </tr> + <tr> + <td><a href="#Unsigned_right_shift_assignment">부호없는 오른쪽 시프트 할당</a></td> + <td><code>x >>>= y</code></td> + <td><code>x = x >>> y</code></td> + </tr> + <tr> + <td><a href="#Bitwise_AND_assignment">비트 AND 할당</a></td> + <td><code>x &= y</code></td> + <td><code>x = x & y</code></td> + </tr> + <tr> + <td><a href="#Bitwise_XOR_assignment">비트 XOR 할당</a></td> + <td><code>x ^= y</code></td> + <td><code>x = x ^ y</code></td> + </tr> + <tr> + <td><a href="#Bitwise_OR_assignment">비트 OR 할당</a></td> + <td><code>x |= y</code></td> + <td><code>x = x | y</code></td> + </tr> + </tbody> +</table> + +<h2 id="할당"><a name="Assignment">할당</a></h2> + +<p>단순 할당 연산자는 값을 변수에 할당합니다. 할당 연산자는 할당의 결과값으로 평가됩니다. 할당 연산자를 연속해서 사용해, 다수의 변수에 하나의 값을 한꺼번에 할당할 수 있습니다. 예제를 참고하세요.</p> + +<h4 id="구문">구문</h4> + +<pre class="syntaxbox"><strong>연산자:</strong> x = y +</pre> + +<h4 id="예제">예제</h4> + +<pre class="brush: js">// 다음과 같은 변수를 가정 +// x = 5 +// y = 10 +// z = 25 + +x = y // x는 10 +x = y = z // x, y, z 모두 25 +</pre> + +<h3 id="덧셈_할당"><a name="Addition_assignment">덧셈 할당</a></h3> + +<p>덧셈 할당 연산자는 변수에 오른쪽 피연산자의 값을 더하고, 그 결과를 변수에 할당합니다. 두 피연산자의 자료형이 덧셈 할당 연산자의 행동을 결정합니다. 덧셈 연산자처럼 합 또는 연결이 가능합니다. 자세한 내용은 {{jsxref("Operators/Arithmetic_Operators", "덧셈 연산자", "#Addition", 1)}}를 참고하세요.</p> + +<h4 id="구문_2">구문</h4> + +<pre class="syntaxbox"><strong>연산자:</strong> x += y +<strong>의미:</strong> x = x + y +</pre> + +<h4 id="예제_2">예제</h4> + +<pre class="brush: js">// 다음과 같은 변수를 가정 +// foo = "foo" +// bar = 5 +// baz = true + + +// Number + Number -> 합 +bar += 2 // 7 + +// Boolean + Number -> 합 +baz += 1 // 2 + +// Boolean + Boolean -> 합 +baz += false // 1 + +// Number + String -> 연결 +bar += 'foo' // "5foo" + +// String + Boolean -> 연결 +foo += false // "foofalse" + +// String + String -> 연결 +foo += 'bar' // "foobar" +</pre> + +<h3 id="뺄셈_할당"><a name="Subtraction_assignment">뺄셈 할당</a></h3> + +<p>뺄셈 할당 연산자는 변수에서 오른쪽 피연산자의 값을 빼고, 그 결과를 변수에 할당합니다. 더 자세한 내용은 {{jsxref("Operators/Arithmetic_Operators", "뺄셈 연산자", "#Subtraction", 1)}}를 참고하세요.</p> + +<h4 id="구문_3">구문</h4> + +<pre class="syntaxbox"><strong>연산자:</strong> x -= y +<strong>의미:</strong> x = x - y +</pre> + +<h4 id="예제_3">예제</h4> + +<pre class="brush: js">// 다음과 같은 변수를 가정 +// bar = 5 + +bar -= 2 // 3 +bar -= "foo" // NaN +</pre> + +<h3 id="곱셈_할당"><a name="Multiplication_assignment">곱셈 할당</a></h3> + +<p>곱셈 할당 연산자는 변수에 오른쪽 피연산자의 값을 곱하고, 그 결과를 변수에 할당합니다. 더 자세한 내용은 {{jsxref("Operators/Arithmetic_Operators", "곱셈 연산자", "#Multiplication", 1)}}를 참고하세요.</p> + +<h4 id="구문_4">구문</h4> + +<pre class="syntaxbox"><strong>연산자:</strong> x *= y +<strong>의미:</strong> x = x * y +</pre> + +<h4 id="예제_4">예제</h4> + +<pre class="brush: js">// 다음과 같은 변수를 가정 +// bar = 5 + +bar *= 2 // 10 +bar *= "foo" // NaN +</pre> + +<h3 id="나눗셈_할당"><a name="Division_assignment">나눗셈 할당</a></h3> + +<p>나눗셈 할당 연산자는 변수를 오른쪽 피연산자로 나누고, 그 결과를 변수에 할당합니다. 더 자세한 내용은 {{jsxref("Operators/Arithmetic_Operators", "나눗셈 연산자", "#Division", 1)}}를 참고하세요.</p> + +<h4 id="구문_5">구문</h4> + +<pre class="syntaxbox"><strong>연산자:</strong> x /= y +<strong>의미:</strong> x = x / y +</pre> + +<h4 id="예제_5">예제</h4> + +<pre class="brush: js">// 다음과 같은 변수를 가정 +// bar = 5 + +bar /= 2 // 2.5 +bar /= "foo" // NaN +bar /= 0 // Infinity +</pre> + +<h3 id="나머지_연산_할당"><a name="Remainder_assignment">나머지 연산 할당</a></h3> + +<p>나머지 연산 할당은 변수를 오른쪽 피연산자로 나눈 나머지를 변수에 할당합니다. 더 자세한 내용은 {{jsxref("Operators/Arithmetic_Operators", "나머지 연산자", "#Remainder", 1)}}를 참고하세요.</p> + +<h4 id="구문_6">구문</h4> + +<pre class="syntaxbox"><strong>연산자:</strong> x %= y +<strong>의미:</strong> x = x % y +</pre> + +<h4 id="예제_6">예제</h4> + +<pre class="brush: js">// 다음과 같은 변수를 가정 +// bar = 5 + +bar %= 2 // 1 +bar %= "foo" // NaN +bar %= 0 // NaN +</pre> + +<h3 id="거듭제곱_할당"><a id="Exponentiation_assignment" name="Exponentiation_assignment">거듭제곱 할당</a></h3> + +<p>거듭제곱 할당 연산자는 변수를 오른쪽 피연산자만큼 거듭제곱한 결과를 변수에 할당합니다. 자세한 내용은 {{jsxref("Operators/Arithmetic_Operators", "거듭제곱 연산자", "#Exponentiation", 1)}}를 참고하세요.</p> + +<h4 id="구문_7">구문</h4> + +<pre class="syntaxbox"><strong>연산자:</strong> x **= y +<strong>의미:</strong> x = x ** y +</pre> + +<h4 id="예제_7">예제</h4> + +<pre class="brush: js">// 다음과 같은 변수를 가정 +// bar = 5 + +bar **= 2 // 25 +bar **= "foo" // NaN</pre> + +<h3 id="왼쪽_시프트_할당"><a name="Left_shift_assignment">왼쪽 시프트 할당</a></h3> + +<p>왼쪽 시프트 할당 연산자는 변수의 비트를 오른쪽 피연산자의 값만큼 왼쪽으로 이동하고, 그 결과를 변수에 할당합니다. 더 자세한 내용은 {{jsxref("Operators/Bitwise_Operators", "left shift operator", "#Left_shift", 1)}}를 참고하세요.</p> + +<h4 id="구문_8">구문</h4> + +<pre class="syntaxbox"><strong>연산자:</strong> x <<= y +<strong>의미:</strong> x = x << y +</pre> + +<h4 id="예제_8">예제</h4> + +<pre class="brush: js">var bar = 5; // (00000000000000000000000000000101) +bar <<= 2; // 20 (00000000000000000000000000010100) +</pre> + +<h3 id="오른쪽_시프트_할당"><a name="Right_shift_assignment">오른쪽 시프트 할당</a></h3> + +<p>오른쪽 시프트 할당 연산자는 변수의 비트를 오른쪽 피연산자의 값만큼 우측으로 이동하고, 그 결과를 변수에 할당합니다. 자세한 내용은 {{jsxref("Operators/Bitwise_Operators", "right shift operator", "#Right_shift", 1)}}를 참고하세요.</p> + +<h4 id="구문_9">구문</h4> + +<pre class="syntaxbox"><strong>연산자:</strong> x >>= y +<strong>의미:</strong> x = x >> y +</pre> + +<h4 id="예제_9">예제</h4> + +<pre class="brush: js">var bar = 5; // (00000000000000000000000000000101) +bar >>= 2; // 1 (00000000000000000000000000000001) + +var bar -5; // (-00000000000000000000000000000101) +bar >>= 2; // -2 (-00000000000000000000000000000010) +</pre> + +<h3 id="부호_없는_오른쪽_시프트_할당"><a name="Unsigned_right_shift_assignment">부호 없는 오른쪽 시프트 할당</a></h3> + +<p>부호 없는 오른쪽 시프트 할당 연산자는 변수의 비트를 오른쪽 피연산자의 값만큼 우측으로 이동하고, 그 결과를 변수에 할당합니다. 자세한 내용은 {{jsxref("Operators/Bitwise_Operators", " unsigned right shift operator", "#Unsigned_right_shift", 1)}}을 참고하세요.</p> + +<h4 id="구문_10">구문</h4> + +<pre class="syntaxbox"><strong>연산자:</strong> x >>>= y +<strong>의미:</strong> x = x >>> y +</pre> + +<h4 id="예제_10">예제</h4> + +<pre class="brush: js">var bar = 5; // (00000000000000000000000000000101) +bar >>>= 2; // 1 (00000000000000000000000000000001) + +var bar = -5; // (-00000000000000000000000000000101) +bar >>>= 2; // 1073741822 (00111111111111111111111111111110)</pre> + +<h3 id="비트_AND_할당"><a name="Bitwise_AND_assignment">비트 AND 할당</a></h3> + +<p>비트 AND 할당 연산자는 양쪽 피연산자의 이진 표현을 AND 연산한 후, 그 결과를 변수에 할당합니다. 자세한 내용은{{jsxref("Operators/Bitwise_Operators", "bitwise AND operator", "#Bitwise_AND", 1)}}을 참고하세요.</p> + +<h4 id="구문_11">구문</h4> + +<pre class="syntaxbox"><strong>연산자:</strong> x &= y +<strong>의미:</strong> x = x & y +</pre> + +<h4 id="예제_11">예제</h4> + +<pre class="brush: js">var bar = 5; +// 5: 00000000000000000000000000000101 +// 2: 00000000000000000000000000000010 +bar &= 2; // 0 +</pre> + +<h3 id="비트_XOR_할당"><a name="Bitwise_XOR_assignment">비트 XOR 할당</a></h3> + +<p>비트 XOR 할당 연산자는 양쪽 피연산자의 이진 표현을 XOR 연산한 후, 그 결과를 변수에 할당합니다. 자세한 내용은 {{jsxref("Operators/Bitwise_Operators", "bitwise XOR operator", "#Bitwise_XOR", 1)}}를 참고하세요.</p> + +<h4 id="구문_12">구문</h4> + +<pre class="syntaxbox"><strong>연산자:</strong> x ^= y +<strong>의미:</strong> x = x ^ y +</pre> + +<h4 id="예제_12">예제</h4> + +<pre class="brush: js">var bar = 5; +bar ^= 2; // 7 +// 5: 00000000000000000000000000000101 +// 2: 00000000000000000000000000000010 +// ----------------------------------- +// 7: 00000000000000000000000000000111 +</pre> + +<h3 id="비트_OR_할당"><a name="Bitwise_OR_assignment">비트 OR 할당</a></h3> + +<p>비트 OR 할당 연산자는 양쪽 피연산자의 이진 표현을 OR 연산한 후, 그 결과를 변수에 할당합니다. 자세한 내용은 {{jsxref("Operators/Bitwise_Operators", "bitwise OR operator", "#Bitwise_OR", 1)}}를 참고하세요.</p> + +<h4 id="문법">문법</h4> + +<pre class="syntaxbox"><strong>연산자:</strong> x |= y +<strong>의미:</strong> x = x | y +</pre> + +<h4 id="예제_13">예제</h4> + +<pre class="brush: js">var bar = 5; +bar |= 2; // 7 +// 5: 00000000000000000000000000000101 +// 2: 00000000000000000000000000000010 +// ----------------------------------- +// 7: 00000000000000000000000000000111 +</pre> + +<h2 id="예제_14">예제</h2> + +<h3 id="다른_할당_연산자를_갖는_왼쪽_피연산자">다른 할당 연산자를 갖는 왼쪽 피연산자</h3> + +<p>드물게, 할당 연산자(예: <code>x += y</code>)와 그 의미를 나타낸 표현(<code>x = x + y</code>)이 동일하지 않은 경우가 있습니다. 할당 연산자의 왼쪽 피연산자가 다른 할당 연산자를 포함할 때, 왼쪽 피연산자는 한 번만 평가됩니다. 예를 들면 다음과 같습니다.</p> + +<pre class="brush: js">a[i++] += 5 // i는 한 번만 평가됨 +a[i++] = a[i++] + 5 // i는 두 번 평가됨 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-assignment-operators', 'Assignment operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.operators.assignment")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators">산술 연산자</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/async_function/index.html b/files/ko/web/javascript/reference/operators/async_function/index.html new file mode 100644 index 0000000000..d1ec146ca4 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/async_function/index.html @@ -0,0 +1,96 @@ +--- +title: async function 표현식 +slug: Web/JavaScript/Reference/Operators/async_function +translation_of: Web/JavaScript/Reference/Operators/async_function +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong><code>async function</code></strong> 키워드는 표현식 내에서 <code>async</code> 함수를 정의하기 위해 사용됩니다.</p> + +<p>또한 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function" title="The async function keyword can be used to define async functions inside expressions.">async function statement</a>을 사용하여 async 함수를 정의할 수 있습니다.</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox">async function [<em>name</em>]([<em>param1</em>[, <em>param2[</em>, ..., <em>paramN</em>]]]) { <em>statements </em>}</pre> + +<p>ES2015에서와 같이 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow functions</a>를 사용해도 됩니다.</p> + +<h3 id="인수">인수</h3> + +<dl> + <dt><code><var>name</var></code></dt> + <dd>함수 이름. 생략가능하며 이경우함수는 <em>anonymous</em> 형식임 이름은 함수 몸체에 대해 지역적으로 사용.</dd> + <dt><code><var>paramN</var></code></dt> + <dd>함수에 전달될 인수의 이름.</dd> + <dt><code><var>statements</var></code></dt> + <dd>함수 몸체를 구성하는 명령문들.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p><code>async function</code> 표현식은 {{jsxref('Statements/async_function', '<code>async function</code> 선언')}} 문법과 유사하며, 거의 동일합니다. <code>async function</code> 표현식과 <code>async function</code> 선언문의 주요 차이점은 익명함수로써의 사용 여부로, <code>async function</code> 표현식은 함수 이름을 생략하면 익명함수를 만듭니다. <code>async function</code> 표현식은 {{Glossary("IIFE")}}(즉시실행함수)로 사용할 수 있습니다. <code><a href="/en-US/docs/Web/JavaScript/Reference/Functions">functions</a></code>문서를 참고하세요.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Simple_example">Simple example</h3> + +<pre><code>function resolveAfter2Seconds(x) { + return new Promise(resolve => { + setTimeout(() => { + resolve(x); + }, 2000); + }); +}; + + +var add = async function(x) { // async function 표현식을 변수에 할당 + var a = await resolveAfter2Seconds(20); + var b = await resolveAfter2Seconds(30); + return x + a + b; +}; + +add(10).then(v => { + console.log(v); // 4초 뒤에 60 출력 +}); + + +(async function(x) { // async function 표현식을 IIFE로 사용 + var p_a = resolveAfter2Seconds(20); + var p_b = resolveAfter2Seconds(30); + return x + await p_a + await p_b; +})(10).then(v => { + console.log(v); // 2초 뒤에 60 출력 +});</code></pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-async-function-definitions', 'async function')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Initial definition in ES2017.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{Compat("javascript.operators.async_function_expression")}} </div> + +<div id="compat-mobile"></div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Statements/async_function", "async function")}}</li> + <li>{{jsxref("AsyncFunction")}} object</li> + <li>{{jsxref("Operators/await", "await")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/await/index.html b/files/ko/web/javascript/reference/operators/await/index.html new file mode 100644 index 0000000000..00b5fd3eff --- /dev/null +++ b/files/ko/web/javascript/reference/operators/await/index.html @@ -0,0 +1,137 @@ +--- +title: await +slug: Web/JavaScript/Reference/Operators/await +translation_of: Web/JavaScript/Reference/Operators/await +--- +<div>{{jsSidebar("Operators")}}</div> + +<div><code>await</code>연산자는 {{jsxref("Promise")}}를 기다리기 위해 사용됩니다. 연산자는 {{jsxref("Statements/async_function", "async function")}} 내부에서만 사용할 수 있습니다.</div> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox notranslate">[<em>rv</em>] = await <em>expression</em>;</pre> + +<dl> + <dt><code>expression</code></dt> + <dd>{{jsxref("Promise")}} 혹은 기다릴 어떤 값입니다.</dd> + <dt><code>rv</code></dt> + <dd> + <p>{{jsxref("Promise")}}에 의해 만족되는 값이 반환됩니다. {{jsxref("Promise")}}가 아닌 경우에는 그 값 자체가 반환됩니다.</p> + </dd> +</dl> + +<h2 id="설명">설명</h2> + +<p><code>await</code> 문은 <code>Promise</code>가 fulfill되거나 <code>reject</code> 될 때까지 <code>async</code> 함수의 실행을 일시 정지하고, <code>Promise</code>가 fulfill되면 <code>async</code> 함수를 일시 정지한 부분부터 실행합니다. 이때 <code>await</code> 문의 반환값은 <code>Promise</code> 에서 fulfill된 값이 됩니다.</p> + +<p>만약 <code>Promise</code>가 <code>reject</code>되면, <code>await</code> 문은 <code>reject</code>된 값을 <code>throw</code>합니다.</p> + +<p><code>await</code> 연산자 다음에 나오는 문의 값이 <code>Promise</code>가 아니면 해당 값을 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve">resolved Promise</a>로 변환시킵니다.</p> + +<p>An <code>await</code> can split execution flow, allowing the caller of the <code>await</code>'s function to resume execution before the deferred continuation of the <code>await</code>'s function. After the <code>await</code> defers the continuation of its function, if this is the first <code>await</code> executed by the function, immediate execution also continues by returning to the function's caller a pending <code>Promise</code> for the completion of the <code>await</code>'s function and resuming execution of that caller.</p> + +<h2 id="예제">예제</h2> + +<p>만약 <code>Promise</code>가 <code>await</code>에 넘겨지면, <code>await</code>은 <code>Promise</code>가 fulfill되기를 기다렸다가, 해당 값을 리턴합니다.</p> + +<pre class="brush: js notranslate">function resolveAfter2Seconds(x) { + return new Promise(resolve => { + setTimeout(() => { + resolve(x); + }, 2000); + }); +} + +async function f1() { + var x = await resolveAfter2Seconds(10); + console.log(x); // 10 +} + +f1(); +</pre> + +<p>{{jsxref("Global_Objects/Promise/then", "Thenable objects")}} will be fulfilled just the same.</p> + +<pre class="notranslate"><code>async function f2() { + const thenable = { + then: function(resolve, _reject) { + resolve('resolved!') + } + }; + console.log(await thenable); // resolved! +} + +f2();</code></pre> + +<p>만약 값이 <code>Promise</code>가 아니라면, 해당 값은 <code>resolve</code>된 <code>Promise</code>로 변환되며 이를 기다립니다.</p> + +<pre class="brush: js notranslate">async function f2() { + var y = await 20; + console.log(y); // 20 +} +f2(); +</pre> + +<p>만약 <code>Promise</code>가 <code>reject</code>되면, <code>reject</code>된 값이 <code>throw</code>됩니다.</p> + +<pre class="brush: js notranslate">async function f3() { + try { + var z = await Promise.reject(30); + } catch(e) { + console.log(e); // 30 + } +} +f3(); +</pre> + +<p>try블럭 없이 rejected <code>Promise</code>다루기</p> + +<pre class="notranslate"><code>var response = await promisedFunction().catch((err) => { console.error(err); }); +// response will be undefined if the promise is rejected</code></pre> + +<h2 id="Specifications">Specifications</h2> + +<table> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("ESDraft", "#sec-async-function-definitions", "async functions")}}</td> + <td>{{Spec2("ESDraft")}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName("ES2018", "#sec-async-function-definitions", "async functions")}}</td> + <td>{{Spec2("ES2018")}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName("ES2017", "#sec-async-function-definitions", "async functions")}}</td> + <td>{{Spec2("ES2017")}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> +<div> + + +<p>{{Compat("javascript.operators.await")}}</p> +</div> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Statements/async_function", "async function")}}</li> + <li>{{jsxref("Operators/async_function", "async function expression")}}</li> + <li>{{jsxref("AsyncFunction")}} object</li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/bitwise_operators/index.html b/files/ko/web/javascript/reference/operators/bitwise_operators/index.html new file mode 100644 index 0000000000..e94e176e08 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/bitwise_operators/index.html @@ -0,0 +1,540 @@ +--- +title: 비트 연산자 +slug: Web/JavaScript/Reference/Operators/Bitwise_Operators +tags: + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>비트 연산자</strong>는 피연산자를 10진수, 16진수, 8진수가 아니라, 32개의 비트(0과 1) 집합으로 취급합니다. 예를 들어, 10진수 9의 2진수 표기법은 1001입니다. 이렇게, 비트 연산자는 값의 2진수 표현을 사용해 연산하지만, 결과는 표준 JavaScript 숫자 값으로 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-bitwiseoperators.html")}}</div> + + + +<p>다음은 JavaScript의 비트 연산자를 요약한 표입니다.</p> + +<table class="standard-table"> + <tbody> + <tr> + <th>연산자</th> + <th>사용방법</th> + <th>설명</th> + </tr> + <tr> + <td><a href="#Bitwise_AND">비트 AND</a></td> + <td><code>a & b</code></td> + <td>피연산자를 비트로 바꿨을 때 각각 대응하는 비트가 모두 1이면 그 비트값에 1을 반환.</td> + </tr> + <tr> + <td><a href="#Bitwise_OR">비트 OR</a></td> + <td><code>a | b</code></td> + <td>피연산자를 비트로 바꿨을 때 각각 대응하는 비트가 모두 1이거나 한 쪽이 1이면 1을 반환.</td> + </tr> + <tr> + <td><a href="#Bitwise_XOR">비트 XOR</a></td> + <td><code>a ^ b</code></td> + <td>피연산자를 비트로 바꿨을 때 대응하는 비트가 서로 다르면 1을 반환.</td> + </tr> + <tr> + <td><a href="#Bitwise_NOT">비트 NOT</a></td> + <td><code>~ a</code></td> + <td>피연산자의 반전된 값을 반환.</td> + </tr> + <tr> + <td><a href="#Left_shift">왼쪽 시프트</a></td> + <td><code>a << b</code></td> + <td>Shifts <code>a</code> in binary representation <code>b</code> (< 32) bits to the left, shifting in zeros from the right.</td> + </tr> + <tr> + <td><a href="#Right_shift">부호 유지 오른쪽 시프트</a></td> + <td><code>a >> b</code></td> + <td>Shifts <code>a</code> in binary representation <code>b</code> (< 32) bits to the right, discarding bits shifted off.</td> + </tr> + <tr> + <td><a href="#Unsigned_right_shift">부호 버림 오른쪽 시프트</a></td> + <td><code>a >>> b</code></td> + <td>Shifts <code>a</code> in binary representation <code>b</code> (< 32) bits to the right, discarding bits shifted off, and shifting in zeros from the left.</td> + </tr> + </tbody> +</table> + +<h2 id="부호_있는_32비트_정수">부호 있는 32비트 정수</h2> + +<p>The operands of all bitwise operators are converted to signed 32-bit integers in two's <a href="https://en.wikipedia.org/wiki/Method_of_complements">complement format</a>, except for zero-fill right shift which results in an unsigned 32-bit integer.</p> + +<p><em>Two's complement format</em> means that a number's negative counterpart (e.g. <code>5</code> vs. <code>-5</code>) is all the number's bits inverted (bitwise NOT of the number, or <em>ones' complement</em> of the number) plus one.</p> + +<p>For example, the following encodes the integer <code>314</code>:</p> + +<pre>00000000000000000000000100111010 +</pre> + +<p>The following encodes <code>~314</code>, i.e. the one's complement of <code>314</code>:</p> + +<pre>11111111111111111111111011000101 +</pre> + +<p>Finally, the following encodes <code>-314,</code> i.e. the two's complement of <code>314</code>:</p> + +<pre>11111111111111111111111011000110 +</pre> + +<p>The two's complement guarantees that the left-most bit is 0 when the number is positive and 1 when the number is negative. Thus, it is called the <em>sign bit</em>.</p> + +<p>The number <code>0</code> is the integer that is composed completely of 0 bits.</p> + +<pre>0 (base 10) = 00000000000000000000000000000000 (base 2) +</pre> + +<p>The number <code>-1</code> is the integer that is composed completely of 1 bits.</p> + +<pre>-1 (base 10) = 11111111111111111111111111111111 (base 2) +</pre> + +<p>The number <code>-2147483648</code> (hexadecimal representation: <code>-0x80000000</code>) is the integer that is composed completely of 0 bits except the first (left-most) one.</p> + +<pre>-2147483648 (base 10) = 10000000000000000000000000000000 (base 2) +</pre> + +<p>The number <code>2147483647</code> (hexadecimal representation: <code>0x7fffffff</code>) is the integer that is composed completely of 1 bits except the first (left-most) one.</p> + +<pre>2147483647 (base 10) = 01111111111111111111111111111111 (base 2) +</pre> + +<p>The numbers <code>-2147483648</code> and <code>2147483647</code> are the minimum and the maximum integers representable throught a 32bit signed number.</p> + +<h2 id="비트_논리_연산자">비트 논리 연산자</h2> + +<p>비트 논리 연산자는 다음과 같이 사용됩니다.</p> + +<ul> + <li>피연산자는 32비트 정수로 변환되고, 이진법으로 표현됩니다 (0과 1).</li> + <li>이진법으로 표현된 첫 번째 피연산자는 두 번째 피연산자와 쌍을 이룹니다: 첫 번째는 첫 번째 비트끼리, 두 번째는 두 번째 비트끼리...</li> + <li>연산자는 각각의 비트쌍에 적용되고, 결과 또한 이진법으로 구성됩니다.</li> +</ul> + +<h3 id="비트_AND"><a id="Bitwise_AND" name="Bitwise_AND">& (비트 AND)</a></h3> + +<p>비트 연산자 AND를 비트 쌍으로 실행합니다.</p> + +<p>Performs the AND operation on each pair of bits. <code>a</code> AND <code>b</code> yields 1 only if both <code>a</code> and <code>b</code> are 1. The truth table for the AND operation is:</p> + +<table class="standard-table"> + <tbody> + <tr> + <td class="header">a</td> + <td class="header">b</td> + <td class="header">a AND b</td> + </tr> + <tr> + <td>0</td> + <td>0</td> + <td>0</td> + </tr> + <tr> + <td>0</td> + <td>1</td> + <td>0</td> + </tr> + <tr> + <td>1</td> + <td>0</td> + <td>0</td> + </tr> + <tr> + <td>1</td> + <td>1</td> + <td>1</td> + </tr> + </tbody> +</table> + +<pre> 9 (base 10) = 00000000000000000000000000001001 (base 2) + 14 (base 10) = 00000000000000000000000000001110 (base 2) + -------------------------------- +14 & 9 (base 10) = 00000000000000000000000000001000 (base 2) = 8 (base 10) +</pre> + +<p>Bitwise ANDing any number <code>x</code> with <code>0</code> yields <code>0</code>. <span style="letter-spacing: -0.00278rem;">Bitwise ANDing any number <code>x</code> with <code>-1</code> yields <code>x</code>.</span></p> + +<h3 id="비트_OR"><a id="Bitwise_OR" name="Bitwise_OR">| (비트 OR)</a></h3> + +<p>Performs the OR operation on each pair of bits. <code>a</code> OR <code>b</code> yields 1 if either <code>a</code> or <code>b</code> is 1. The truth table for the OR operation is:</p> + +<table class="standard-table"> + <tbody> + <tr> + <td class="header">a</td> + <td class="header">b</td> + <td class="header">a OR b</td> + </tr> + <tr> + <td>0</td> + <td>0</td> + <td>0</td> + </tr> + <tr> + <td>0</td> + <td>1</td> + <td>1</td> + </tr> + <tr> + <td>1</td> + <td>0</td> + <td>1</td> + </tr> + <tr> + <td>1</td> + <td>1</td> + <td>1</td> + </tr> + </tbody> +</table> + +<pre> 9 (base 10) = 00000000000000000000000000001001 (base 2) + 14 (base 10) = 00000000000000000000000000001110 (base 2) + -------------------------------- +14 | 9 (base 10) = 00000000000000000000000000001111 (base 2) = 15 (base 10) +</pre> + +<p>Bitwise ORing any number x with 0 yields x.</p> + +<p>Bitwise ORing any number x with -1 yields -1.</p> + +<h3 id="비트_XOR"><a id="Bitwise_XOR" name="Bitwise_XOR">^ (비트 XOR)</a></h3> + +<p>Performs the XOR operation on each pair of bits. <code>a</code> XOR <code>b</code> yields 1 if <code>a</code> and <code>b</code> are different. The truth table for the XOR operation is:</p> + +<table class="standard-table"> + <tbody> + <tr> + <td class="header">a</td> + <td class="header">b</td> + <td class="header">a XOR b</td> + </tr> + <tr> + <td>0</td> + <td>0</td> + <td>0</td> + </tr> + <tr> + <td>0</td> + <td>1</td> + <td>1</td> + </tr> + <tr> + <td>1</td> + <td>0</td> + <td>1</td> + </tr> + <tr> + <td>1</td> + <td>1</td> + <td>0</td> + </tr> + </tbody> +</table> + +<pre> 9 (base 10) = 00000000000000000000000000001001 (base 2) + 14 (base 10) = 00000000000000000000000000001110 (base 2) + -------------------------------- +14 ^ 9 (base 10) = 00000000000000000000000000000111 (base 2) = 7 (base 10) +</pre> + +<p>Bitwise XORing any number x with 0 yields x.</p> + +<p>Bitwise XORing any number x with -1 yields ~x.</p> + +<h3 id="비트_NOT"><a id="Bitwise_NOT" name="Bitwise_NOT">~ (비트 NOT)</a></h3> + +<p>Performs the NOT operator on each bit. NOT <code>a</code> yields the inverted value (a.k.a. one's complement) of <code>a</code>. The truth table for the NOT operation is:</p> + +<table class="standard-table"> + <tbody> + <tr> + <td class="header">a</td> + <td class="header">NOT a</td> + </tr> + <tr> + <td>0</td> + <td>1</td> + </tr> + <tr> + <td>1</td> + <td>0</td> + </tr> + </tbody> +</table> + +<pre> 9 (base 10) = 00000000000000000000000000001001 (base 2) + -------------------------------- +~9 (base 10) = 11111111111111111111111111110110 (base 2) = -10 (base 10) +</pre> + +<p>Bitwise NOTing any number x yields -(x + 1). For example, ~5 yields -6.</p> + +<h2 id="비트_시프트_연산자">비트 시프트 연산자</h2> + +<p>The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be shifted. The direction of the shift operation is controlled by the operator used.</p> + +<p>Shift operators convert their operands to 32-bit integers in big-endian order and return a result of the same type as the left operand. The right operand should be less than 32, but if not only the low five bits will be used.</p> + +<h3 id="<<_Left_shift"><a id="Left_shift" name="Left_shift"><< (Left shift)</a></h3> + +<p>This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right.</p> + +<p>For example, <code>9 << 2</code> yields 36:</p> + +<pre> 9 (base 10): 00000000000000000000000000001001 (base 2) + -------------------------------- +9 << 2 (base 10): 00000000000000000000000000100100 (base 2) = 36 (base 10) +</pre> + +<p>Bitwise shifting any number <strong>x</strong> to the left by <strong>y</strong> bits yields <strong>x * 2^y</strong>.</p> + +<h3 id=">>_Sign-propagating_right_shift"><a id="Right_shift" name="Right_shift">>> (Sign-propagating right shift)</a></h3> + +<p>This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left. Since the new leftmost bit has the same value as the previous leftmost bit, the sign bit (the leftmost bit) does not change. Hence the name "sign-propagating".</p> + +<p>For example, <code>9 >> 2</code> yields 2:</p> + +<pre> 9 (base 10): 00000000000000000000000000001001 (base 2) + -------------------------------- +9 >> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10) +</pre> + +<p>Likewise, <code>-9 >> 2</code> yields -3, because the sign is preserved:</p> + +<pre> -9 (base 10): 11111111111111111111111111110111 (base 2) + -------------------------------- +-9 >> 2 (base 10): 11111111111111111111111111111101 (base 2) = -3 (base 10) +</pre> + +<h3 id=">>>_Zero-fill_right_shift"><a id="Unsigned_right_shift" name="Unsigned_right_shift">>>> (Zero-fill right shift)</a></h3> + +<p>This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left. The sign bit becomes 0, so the result is always non-negative.</p> + +<p>For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result. For example, <code>9 >>> 2</code> yields 2, the same as <code>9 >> 2</code>:</p> + +<pre> 9 (base 10): 00000000000000000000000000001001 (base 2) + -------------------------------- +9 >>> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10) +</pre> + +<p>However, this is not the case for negative numbers. For example, <code>-9 >>> 2</code> yields 1073741821, which is different than <code>-9 >> 2</code> (which yields -3):</p> + +<pre> -9 (base 10): 11111111111111111111111111110111 (base 2) + -------------------------------- +-9 >>> 2 (base 10): 00111111111111111111111111111101 (base 2) = 1073741821 (base 10) +</pre> + +<h2 id="예제">예제</h2> + +<h3 id="Flags_and_bitmasks">Flags and bitmasks</h3> + +<p>The bitwise logical operators are often used to create, manipulate, and read sequences of <em>flags</em>, which are like binary variables. Variables could be used instead of these sequences, but binary flags take much less memory (by a factor of 32).</p> + +<p>Suppose there are 4 flags:</p> + +<ul> + <li>flag A: we have an ant problem</li> + <li>flag B: we own a bat</li> + <li>flag C: we own a cat</li> + <li>flag D: we own a duck</li> +</ul> + +<p>These flags are represented by a sequence of bits: DCBA. When a flag is <em>set</em>, it has a value of 1. When a flag is <em>cleared</em>, it has a value of 0. Suppose a variable <code>flags</code> has the binary value 0101:</p> + +<pre class="brush: js">var flags = 5; // binary 0101 +</pre> + +<p>This value indicates:</p> + +<ul> + <li>flag A is true (we have an ant problem);</li> + <li>flag B is false (we don't own a bat);</li> + <li>flag C is true (we own a cat);</li> + <li>flag D is false (we don't own a duck);</li> +</ul> + +<p>Since bitwise operators are 32-bit, 0101 is actually 00000000000000000000000000000101, but the preceding zeroes can be neglected since they contain no meaningful information.</p> + +<p>A <em>bitmask</em> is a sequence of bits that can manipulate and/or read flags. Typically, a "primitive" bitmask for each flag is defined:</p> + +<pre class="brush: js">var FLAG_A = 1; // 0001 +var FLAG_B = 2; // 0010 +var FLAG_C = 4; // 0100 +var FLAG_D = 8; // 1000 +</pre> + +<p>New bitmasks can be created by using the bitwise logical operators on these primitive bitmasks. For example, the bitmask 1011 can be created by ORing FLAG_A, FLAG_B, and FLAG_D:</p> + +<pre class="brush: js">var mask = FLAG_A | FLAG_B | FLAG_D; // 0001 | 0010 | 1000 => 1011 +</pre> + +<p>Individual flag values can be extracted by ANDing them with a bitmask, where each bit with the value of one will "extract" the corresponding flag. The bitmask <em>masks</em> out the non-relevant flags by ANDing with zeros (hence the term "bitmask"). For example, the bitmask 0100 can be used to see if flag C is set:</p> + +<pre class="brush: js">// if we own a cat +if (flags & FLAG_C) { // 0101 & 0100 => 0100 => true + // do stuff +} +</pre> + +<p>A bitmask with multiple set flags acts like an "either/or". For example, the following two are equivalent:</p> + +<pre class="brush: js">// if we own a bat or we own a cat +if ((flags & FLAG_B) || (flags & FLAG_C)) { // (0101 & 0010) || (0101 & 0100) => 0000 || 0100 => true + // do stuff +} +</pre> + +<pre class="brush: js">// if we own a bat or cat +var mask = FLAG_B | FLAG_C; // 0010 | 0100 => 0110 +if (flags & mask) { // 0101 & 0110 => 0100 => true + // do stuff +} +</pre> + +<p>Flags can be set by ORing them with a bitmask, where each bit with the value one will set the corresponding flag, if that flag isn't already set. For example, the bitmask 1100 can be used to set flags C and D:</p> + +<pre class="brush: js">// yes, we own a cat and a duck +var mask = FLAG_C | FLAG_D; // 0100 | 1000 => 1100 +flags |= mask; // 0101 | 1100 => 1101 +</pre> + +<p>Flags can be cleared by ANDing them with a bitmask, where each bit with the value zero will clear the corresponding flag, if it isn't already cleared. This bitmask can be created by NOTing primitive bitmasks. For example, the bitmask 1010 can be used to clear flags A and C:</p> + +<pre class="brush: js">// no, we don't have an ant problem or own a cat +var mask = ~(FLAG_A | FLAG_C); // ~0101 => 1010 +flags &= mask; // 1101 & 1010 => 1000 +</pre> + +<p>The mask could also have been created with <code>~FLAG_A & ~FLAG_C</code> (De Morgan's law):</p> + +<pre class="brush: js">// no, we don't have an ant problem, and we don't own a cat +var mask = ~FLAG_A & ~FLAG_C; +flags &= mask; // 1101 & 1010 => 1000 +</pre> + +<p>Flags can be toggled by XORing them with a bitmask, where each bit with the value one will toggle the corresponding flag. For example, the bitmask 0110 can be used to toggle flags B and C:</p> + +<pre class="brush: js">// if we didn't have a bat, we have one now, and if we did have one, bye-bye bat +// same thing for cats +var mask = FLAG_B | FLAG_C; +flags = flags ^ mask; // 1100 ^ 0110 => 1010 +</pre> + +<p>Finally, the flags can all be flipped with the NOT operator:</p> + +<pre class="brush: js">// entering parallel universe... +flags = ~flags; // ~1010 => 0101 +</pre> + +<h3 id="Conversion_snippets">Conversion snippets</h3> + +<p>Convert a binary <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String" title="/en-US/docs/JavaScript/Reference/Global_Objects/String">string</a></code> to a decimal <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Number" title="/en-US/docs/JavaScript/Reference/Global_Objects/Number">number</a></code>:</p> + +<pre class="brush: js">var sBinString = "1011"; +var nMyNumber = parseInt(sBinString, 2); +alert(nMyNumber); // prints 11, i.e. 1011 +</pre> + +<p>Convert a decimal <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Number" title="/en-US/docs/JavaScript/Reference/Global_Objects/Number">number</a></code> to a binary <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String" title="/en-US/docs/JavaScript/Reference/Global_Objects/String">string</a></code>:</p> + +<pre class="brush: js">var nMyNumber = 11; +var sBinString = nMyNumber.toString(2); +alert(sBinString); // prints 1011, i.e. 11 +</pre> + +<h3 id="Automate_Mask_Creation">Automate Mask Creation</h3> + +<p>If you have to create many masks from some <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Boolean" title="/en-US/docs/JavaScript/Reference/Global_Objects/Boolean">boolean</a></code> values, you can automatize the process:</p> + +<pre class="brush: js">function createMask () { + var nMask = 0, nFlag = 0, nLen = arguments.length > 32 ? 32 : arguments.length; + for (nFlag; nFlag < nLen; nMask |= arguments[nFlag] << nFlag++); + return nMask; +} +var mask1 = createMask(true, true, false, true); // 11, i.e.: 1011 +var mask2 = createMask(false, false, true); // 4, i.e.: 0100 +var mask3 = createMask(true); // 1, i.e.: 0001 +// etc. + +alert(mask1); // prints 11, i.e.: 1011 +</pre> + +<h3 id="Reverse_algorithm_an_array_of_booleans_from_a_mask">Reverse algorithm: an array of booleans from a mask</h3> + +<p>If you want to create an <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array" title="/en-US/docs/JavaScript/Reference/Global_Objects/Array">array</a></code> of <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Boolean" title="/en-US/docs/JavaScript/Reference/Global_Objects/Boolean">booleans</a></code> from a mask you can use this code:</p> + +<pre class="brush: js">function arrayFromMask (nMask) { + // nMask must be between -2147483648 and 2147483647 + if (nMask > 0x7fffffff || nMask < -0x80000000) { throw new TypeError("arrayFromMask - out of range"); } + for (var nShifted = nMask, aFromMask = []; nShifted; aFromMask.push(Boolean(nShifted & 1)), nShifted >>>= 1); + return aFromMask; +} + +var array1 = arrayFromMask(11); +var array2 = arrayFromMask(4); +var array3 = arrayFromMask(1); + +alert("[" + array1.join(", ") + "]"); +// prints "[true, true, false, true]", i.e.: 11, i.e.: 1011 +</pre> + +<p>You can test both algorithms at the same time…</p> + +<pre class="brush: js">var nTest = 19; // our custom mask +var nResult = createMask.apply(this, arrayFromMask(nTest)); + +alert(nResult); // 19 +</pre> + +<p>For didactic purpose only (since there is the <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Number/toString" title="/en-US/docs/JavaScript/Reference/Global_Objects/Number/toString">Number.toString(2)</a></code> method), we show how it is possible to modify the <code>arrayFromMask</code> algorithm in order to create a <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String" title="/en-US/docs/JavaScript/Reference/Global_Objects/String">string</a></code> containing the binary representation of a <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Number" title="/en-US/docs/JavaScript/Reference/Global_Objects/Number">number</a></code>, rather than an <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array" title="/en-US/docs/JavaScript/Reference/Global_Objects/Array">array</a></code> of <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Boolean" title="/en-US/docs/JavaScript/Reference/Global_Objects/Boolean">booleans</a></code>:</p> + +<pre class="brush: js">function createBinaryString (nMask) { + // nMask must be between -2147483648 and 2147483647 + for (var nFlag = 0, nShifted = nMask, sMask = ""; nFlag < 32; nFlag++, sMask += String(nShifted >>> 31), nShifted <<= 1); + return sMask; +} + +var string1 = createBinaryString(11); +var string2 = createBinaryString(4); +var string3 = createBinaryString(1); + +alert(string1); +// prints 00000000000000000000000000001011, i.e. 11 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-bitwise-not-operator', 'Bitwise NOT Operator')}}</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-binary-bitwise-operators', 'Binary Bitwise Operators')}}</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-bitwise-shift-operators', 'Bitwise Shift Operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.operators.bitwise")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Reference/Operators/%EB%85%BC%EB%A6%AC_%EC%97%B0%EC%82%B0%EC%9E%90(Logical_Operators)">논리 연산자</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/class/index.html b/files/ko/web/javascript/reference/operators/class/index.html new file mode 100644 index 0000000000..d15b532fbc --- /dev/null +++ b/files/ko/web/javascript/reference/operators/class/index.html @@ -0,0 +1,100 @@ +--- +title: class 식 +slug: Web/JavaScript/Reference/Operators/class +tags: + - ECMAScript 2015 + - Expression + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/class +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>class 표현식</strong>은 ECMAScript 2015 (ES6)에서 클래스를 정의하는 한 방법입니다. <a href="/ko/docs/Web/JavaScript/Reference/Operators/function">function 식</a>과 비슷하게, class 식은 기명(named) 또는 익명(unnamed)일 수 있습니다. 기명인 경우, 클래스명은 클래스 본체(body)에서만 지역(local)입니다. JavaScript 클래스는 프로토타입(원형) 기반 상속을 사용합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-classexpression.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox notranslate">var MyClass = class <em>[className]</em> [extends] { + // class body +};</pre> + +<h2 id="설명">설명</h2> + +<p>class 식은 <a href="/ko/docs/Web/JavaScript/Reference/Statements/class">class 문</a>과 구문이 비슷합니다. 그러나, class 식의 경우 클래스명("binding identifier")을 생략할 수 있는데 class 문으로는 할 수 없습니다.</p> + +<p>class 문과 같이, class 식의 본체는 <a href="/ko/docs/Web/JavaScript/Reference/Strict_mode" title="strict mode">엄격 모드</a>에서 실행됩니다.</p> + + + +<h2 id="예제">예제</h2> + +<h3 id="간단한_class_식">간단한 class 식</h3> + +<p>이게 바로 변수 "Foo"를 사용하여 참조할 수 있는 간단한 익명 class 식입니다.</p> + +<pre class="brush: js notranslate">var Foo = class { + constructor() {} + bar() { + return "Hello World!"; + } +}; + +var instance = new Foo(); +instance.bar(); // "Hello World!" +Foo.name; // "" +</pre> + +<h3 id="Named_class_식">Named class 식</h3> + +<p>당신이 클래스 몸통 내에서 현재 클래스를 참조하고 싶다면, 유명 class 식을 만들 수 있습니다. 이 이름은 오직 class 식 자체 범위에서만 볼 수 있습니다.</p> + +<pre class="brush: js notranslate">var Foo = class NamedFoo { + constructor() {} + whoIsThere() { + return NamedFoo.name; + } +} +var bar = new Foo(); +bar.whoIsThere(); // "NamedFoo" +NamedFoo.name; // ReferenceError: NamedFoo가 정의되지 않음 +Foo.name; // "NamedFoo" +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.operators.class")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Reference/Operators/function"><code>function</code> 식</a></li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Statements/class"><code>class</code> 문</a></li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Classes">Classes</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/comma_operator/index.html b/files/ko/web/javascript/reference/operators/comma_operator/index.html new file mode 100644 index 0000000000..d2c4caae0e --- /dev/null +++ b/files/ko/web/javascript/reference/operators/comma_operator/index.html @@ -0,0 +1,91 @@ +--- +title: 쉼표 연산자 +slug: Web/JavaScript/Reference/Operators/Comma_Operator +tags: + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Comma_Operator +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>쉼표 연산자</strong>는 각각의 피연산자를 왼쪽에서 오른쪽 순서로 평가하고, 마지막 연산자의 값을 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-commaoperators.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><em>expr1</em>, <em>expr2, expr3...</em></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>expr1</code>, <code>expr2, expr3...</code></dt> + <dd>아무 표현식.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p>단일 표현식을 요구하는 곳에 복수의 표현식을 사용하고 싶을 때 쉼표 연산자를 사용할 수 있습니다. 가장 흔히 사용되는 곳은 <code>for</code> 반복문에 다수의 매개변수를 제공할 때입니다.</p> + +<p>쉼표 연산자는 배열, 객체, 함수의 매개변수와 호출 인수에서 사용하는 쉼표와는 전혀 다릅니다.</p> + +<h2 id="예제">예제</h2> + +<p><code>a</code>를 한 행에 10개의 요소를 가진 2차원 배열이라고 가정할 때, 아래 예제는 쉼표 연산자를 사용해 한 번에 <code>i</code>는 증가시키고 <code>j</code>는 감소시킵니다.</p> + +<p>다음 코드는 2차원 배열의 대각선에 위치하는 요소의 값을 출력합니다.</p> + +<pre class="brush:js;highlight:[1]">for (var i = 0, j = 9; i <= 9; i++, j--) + console.log("a[" + i + "][" + j + "] = " + a[i][j]); +</pre> + +<p>쉼표 연산자를 할당에 사용하면, 할당 연산이 표현식에 포함되지 않아 예상한 결과와는 다소 다를 수 있습니다. 다음 예제에서, <code>a</code>는 <code>b = 3</code>의 값(3)을 할당받지만, <code>c = 4</code> 표현식 역시 평가되어 콘솔에 기록됩니다. <a href="/ko/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">연산자 우선순위와 결합성</a> 때문입니다.</p> + +<pre class="brush: js">var a, b, c; + +a = b = 3, c = 4; // 콘솔에는 4를 반환 +console.log(a); // 3 (제일 왼쪽) + +var x, y, z; + +x = (y = 5, z = 6); // 콘솔에는 6을 반환 +console.log(x); // 6 (제일 오른쪽) +</pre> + +<h3 id="연산_후_반환">연산 후 반환</h3> + +<p>쉼표 연산자를 사용하는 다른 방법은 값을 반환하기 전에 연산을 수행하는 것입니다. 쉼표 연산자는 마지막 표현식의 평가 결과만 반환하지만, 이전 피연산자에 대해서도 평가는 수행하므로 다음과 같은 코드를 작성할 수 있습니다.</p> + +<pre class="brush: js">function myFunc () { + var x = 0; + + return (x += 1, x); // ++x 와 같은 효과 +}</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-comma-operator', 'Comma operator')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.operators.comma")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Reference/Statements/for"><code>for</code> 반복문</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/comparison_operators/index.html b/files/ko/web/javascript/reference/operators/comparison_operators/index.html new file mode 100644 index 0000000000..ecfd46d6e5 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/comparison_operators/index.html @@ -0,0 +1,215 @@ +--- +title: 비교 연산자 +slug: Web/JavaScript/Reference/Operators/Comparison_Operators +tags: + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>JavaScript는 엄격한 비교와 형변환 비교 두 가지의 비교 방법을 모두 가지고 있습니다. 엄격(일치) 비교(<code>===</code>)는 두 피연산자가 같은 자료형에, 그 내용도 일치해야만 참입니다. 추상(동등) 비교(<code>==</code>)는 비교 전에 두 피연산자를 동일한 자료형으로 변환합니다. 관계 추상 비교(<code><=</code>)의 경우 {{glossary("primitive", "원시값")}}으로 바꾸고, 같은 자료형으로 다시 바꾼후 비교를 수행합니다.</p> + +<p>문자열의 경우 {{glossary("unicode", "유니코드")}} 값을 사용한 사전순으로 비교합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-comparisonoperators.html")}}</div> + + + +<p>비교 연산의 특징은 다음과 같습니다.</p> + +<ul> + <li>두 문자열이 같은 문자 시퀀스로 구성되고, 같은 길이를 가지며, 같은 위치에 같은 문자가 존재하면 일치합니다.</li> + <li>두 숫자는 숫자로서 같은 값(같은 숫자 값)이면 일치합니다. {{jsxref("NaN")}}은 자기 자신을 포함한 그 무엇과도 동등하지 않습니다. <code>+0</code>과 <code>-0</code>은 서로 일치합니다.</li> + <li>두 불리언은 둘 다 <code>true</code>거나 <code>false</code>이면 일치합니다.</li> + <li>서로 다른 두 객체는 절대 일치하지도, 동등하지도 않습니다.</li> + <li>객체를 비교하는 표현식은 두 피연산자가 동일한 객체를 참조하는 경우에만 참입니다.</li> + <li>{{jsxref("null")}}과 {{jsxref("undefined")}}는 자기 자신과 일치하며, 서로 동등합니다.</li> +</ul> + +<h2 id="동치_연산자">동치 연산자</h2> + +<h3 id="동등_연산자"><a name="Equality">동등 연산자 (==)</a></h3> + +<p>동등 연산자는 두 피연산자의 자료형이 같지 않은 경우 같아지도록 변환한 후, 엄격 비교를 수행합니다. 피연산자가 모두 객체라면, JavaScript는 내부 참조를 보고, 둘 다 메모리의 같은 객체를 바라보고 있는지 판별합니다.</p> + +<h4 id="구문">구문</h4> + +<pre class="syntaxbox">x == y +</pre> + +<h4 id="예제">예제</h4> + +<pre class="brush: js"> 1 == 1 // true + "1" == 1 // true + 1 == '1' // true + 0 == false // true + 0 == null // false + + 0 == undefined // false +null == undefined // true +</pre> + +<h3 id="부등_연산자_!"><a name="Inequality">부등 연산자 (!=)</a></h3> + +<p>부등 연산자는 두 피연산자가 같지 않은 경우 참을 반환합니다. 피연산자의 자료형이 일치하지 않는 경우 적절한 자료형으로의 변환을 시도합니다. 피연산자가 모두 객체라면, JavaScript는 내부 참조를 보고, 서로 메모리의 다른 객체를 바라보고 있는지 판별합니다.</p> + +<h4 id="구문_2">구문</h4> + +<pre class="syntaxbox">x != y</pre> + +<h4 id="예제_2">예제</h4> + +<pre class="brush: js">1 != 2 // true +1 != "1" // false +1 != '1' // false +1 != true // false +0 != false // false +</pre> + +<h3 id="일치_연산자"><a name="Identity">일치 연산자 (===)</a></h3> + +<p>일치 연산자는 자료형 변환 없이 두 연산자가 엄격히 같은지 판별합니다.</p> + +<h4 id="구문_3">구문</h4> + +<pre class="syntaxbox">x === y</pre> + +<h4 id="예제_3">예제</h4> + +<pre class="brush: js ">3 === 3 // true +3 === '3' // false</pre> + +<h3 id="불일치_연산자_!"><a name="Nonidentity">불일치 연산자 (!==)</a></h3> + +<p>일치 연산자는 두 연산자가 같지 않거나, 같은 자료형이 아닐 때 참을 반환합니다.</p> + +<h4 id="구문_4">구문</h4> + +<pre class="syntaxbox">x !== y</pre> + +<h4 id="예제_4">예제</h4> + +<pre class="brush: js">3 !== '3' // true +4 !== 3 // true +</pre> + +<h2 id="관계_연산자">관계 연산자</h2> + +<p>이 항목의 모든 연산자는 비교 전에 피연산자를 {{glossary("primitive", "원시값")}}으로 <a href="/ko/docs/Glossary/Type_coercion">변환</a>합니다. 둘 다 문자열이 되는 경우 사전순으로 비교하고, 그렇지 않으면 숫자로 변환합니다. {{jsxref("NaN")}}과의 비교는 항상 <code>false</code>를 반환합니다.</p> + +<h3 id="초과_연산자_>"><a name="Greater_than_operator">초과 연산자 (>)</a></h3> + +<p>초과 연산자는 왼쪽 피연산자가 오른쪽 피연산자보다 큰 경우 참을 반환합니다.</p> + +<h4 id="구문_5">구문</h4> + +<pre class="syntaxbox">x > y</pre> + +<h4 id="예제_5">예제</h4> + +<pre class="brush: js">4 > 3 // true +</pre> + +<h3 id="이상_연산자_>"><a name="Greater_than_or_equal_operator">이상 연산자 (>=)</a></h3> + +<p>이상 연산자는 왼쪽 피연산자가 오른쪽 피연산자보다 크거나 같으면 참을 반환합니다.</p> + +<h4 id="구문_6">구문</h4> + +<pre class="syntaxbox"> x >= y</pre> + +<h4 id="예제_6">예제</h4> + +<pre class="brush: js">4 >= 3 // true +3 >= 3 // true +</pre> + +<h3 id="미만_연산자_<"><a name="Less_than_operator">미만 연산자 (<)</a></h3> + +<p>미만 연산자는 왼쪽 피연산자가 오른쪽 피연산자보다 작은 경우 참을 반환합니다.</p> + +<h4 id="구문_7">구문</h4> + +<pre class="syntaxbox">x < y</pre> + +<h4 id="예제_7">예제</h4> + +<pre class="brush: js">3 < 4 // true</pre> + +<h3 id="이하_연산자_<"><a id="Less_than_or_equal_operator" name="Less_than_or_equal_operator">이하 연산자 (<=)</a></h3> + +<p>이하 연산자는 왼쪽 피연산자가 오른쪽 피연산자보다 작거나 같으면 참을 반환합니다.</p> + +<h4 id="구문_8">구문</h4> + +<pre class="syntaxbox"> x <= y</pre> + +<h4 id="예제_8">예제</h4> + +<pre class="brush: js">3 <= 4 // true +</pre> + +<h2 id="동치_연산자_사용하기">동치 연산자 사용하기</h2> + +<p>표준 동치, 동등 연산자(<code>==</code>, <code>!=</code>)는 두 피연산자를 비교하기 위해 <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3">추상 동치 비교 알고리즘</a>(Abstract Equlity Comparison Algorithm)을 사용합니다. 피연산자 간 자료형이 일치하지 않으면 우선 변환을 시도합니다. 예를 들어 표현식 <code>5 == '5'</code>에서는 비교 전 오른쪽 문자열을 {{jsxref("Number")}}로 변환합니다.</p> + +<p>엄격 동치, 일치 연산자(<code>===</code>, <code>!==</code>)는 <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.6">엄격 동치 비교 알고리즘</a>(Strict Equality Comparison Algorithm)을 사용하며, 같은 자료형을 가진 피연산자를 비교하기 위해 사용합니다. 피연산자 간 자료형이 일치하지 않으면 항상 <code>false</code>이므로, <code>5 !== '5'</code>입니다.</p> + +<p>피연산자의 값은 물론 특정 자료형이어야 하는 경우 일치 연산자를 사용하세요. 그렇지 않은 경우 형변환을 자동으로 해주는 동등 연산자를 사용할 수도 있습니다.</p> + +<p>비교 과정에 자료형 변환이 필요한 경우 JavaScript는 {{jsxref("String")}}, {{jsxref("Number")}}, {{jsxref("Boolean")}}, {{jsxref("Object")}} 자료형을 다음과 같이 변환합니다.</p> + +<ul> + <li>숫자와 문자열을 비교할 땐 문자열을 숫자로 변환합니다. 우선, 문자열에서 수학적 값을 도출합니다. 그 후 가장 가까운 <code>Number</code> 자료형 값으로 반올림합니다.</li> + <li>하나의 연산자가 <code>Boolean</code>인 경우, <code>true</code>는 <code>1</code>, <code>false</code>는 <code>0</code>으로 변환합니다.</li> + <li>객체를 문자열이나 숫자와 비교하는 경우, JavaScript는 객체의 기본값을 사용합니다. 연산자는 우선 객체의 <code>valueOf()</code> 또는 <code>toString()</code> 메서드를 사용해 문자열 혹은 숫자 값을 받으려 시도합니다. 실패할 경우 런타임 오류가 발생합니다.</li> + <li>객체를 원시값과 비교하는 경우에만 객체의 변환이 발생합니다. 두 연산자가 모두 객체인 경우 변환하지 않으며, 둘 다 같은 객체를 참조하는 경우 참을 반환합니다.</li> +</ul> + +<div class="note"><strong>참고:</strong> <code>String</code> 객체는 자료형 객체지, 문자열이 아닙니다! <code>String</code> 객체는 거의 쓰이지 않으며, 이런 성질로 인해 아래의 결과는 예상치 못한 값일 수 있습니다.</div> + +<pre class="brush:js">// true as both operands are type String (i.e. string primitives): +'foo' === 'foo' + +var a = new String('foo'); +var b = new String('foo'); + +// false as a and b are type Object and reference different objects +a == b + +// false as a and b are type Object and reference different objects +a === b + +// true as a and 'foo' are of different type and, the Object (a) +// is converted to String 'foo' before comparison +a == 'foo'</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Status</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-equality-operators', 'Equality Operators')}}</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-relational-operators', 'Relational Operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.operators.comparison")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Object.is()")}}</li> + <li>{{jsxref("Math.sign()")}}</li> + <li><a href="/ko/docs/Web/JavaScript/Equality_comparisons_and_sameness">동치 비교와 동일성</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/conditional_operator/index.html b/files/ko/web/javascript/reference/operators/conditional_operator/index.html new file mode 100644 index 0000000000..90f59ea4cd --- /dev/null +++ b/files/ko/web/javascript/reference/operators/conditional_operator/index.html @@ -0,0 +1,193 @@ +--- +title: 삼항 조건 연산자 +slug: Web/JavaScript/Reference/Operators/Conditional_Operator +tags: + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Conditional_Operator +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>조건부 삼항 연산자</strong>는 JavaScript에서 세 개의 피연산자를 취할 수 있는 유일한 연산자입니다. 보통 <a href="/ko/docs/Web/JavaScript/Reference/Statements/if...else"><code>if</code></a> 명령문의 단축 형태로 쓰입니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-conditionaloperators.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox notranslate"><em>condition</em> ? <em>exprIfTrue</em> : <em>exprIfFalse</em> </pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>condition</code></dt> + <dd>An expression whose value is used as a condition.</dd> + <dt><code>exprIfTrue</code></dt> + <dd>An expression which is evaluated if the <code>condition</code> evaluates to a {{Glossary("truthy")}} value (one which equals or can be converted to <code>true</code>).</dd> + <dt><code>exprIfFalse</code></dt> + <dd>An expression which is executed if the <code>condition</code> is {{Glossary("falsy")}} (that is, has a value which can be converted to <code>false</code>).</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p><font face="Open Sans, Arial, sans-serif"><code>condition</code>이 </font><code>true</code>이면, 연산자는 <code>expr1</code>의 값을 반환하며, 반대의 경우 <code>expr2</code>를 반환한다.</p> + +<h2 id="예제">예제</h2> + +<p>여러분이 술을 마실수 있는지 확인할 수 있는 간단한 예제가 여기 있습니다.</p> + +<pre class="notranslate"><code>var age = 29; +var canDrinkAlcohol = (age > 19) ? "True, over 19" : "False, under 19"; +console.log(canDrinkAlcohol); // "True, over 19"</code> +</pre> + +<p>isMember 변수의 값을 기준으로 다른 메시지를 보여주고자 한다면, 다음과 같이 표현할 수 있다.</p> + +<pre class="brush: js notranslate">"The fee is " + (isMember ? "$2.00" : "$10.00") +</pre> + +<p>또한 다음과 같이 삼항(ternary)의 결과에 따라 변수를 할당할 수도 있다.</p> + +<pre class="brush: js notranslate">var elvisLives = Math.PI > 4 ? "Yep" : "Nope";</pre> + +<p>다음의 예제처럼, 다중 삼항(ternary) 평가도 가능하다(주의: 조건 연산은 우측부터 그룹핑 됩니다.)</p> + +<pre class="brush: js notranslate">var firstCheck = false, + secondCheck = false, + access = firstCheck ? "Access denied" : secondCheck ? "Access denied" : "Access granted"; + +console.log( access ); // logs "Access granted"</pre> + +<p>또한 다중 조건 IF 문과 같은 방식으로 여러개의 조건을 사용할 수도 있습니다.</p> + +<pre class="notranslate"><code>var condition1 = true, + condition2 = false, + access = condition1 ? (condition2 ? "true true": "true false") : (condition2 ? "false true" : "false false"); + +console.log(access); // logs "true false"</code></pre> + +<p>참고 : 괄호는 필수는 아니며 기능에 영향을주지 않습니다. 결과가 어떻게 처리되는지 시각화하는 데 도움이됩니다.</p> + +<p>삼항(ternary) 평가는 다른 연산을 하기 위해 쓸 수도 있습니다.</p> + +<pre class="brush: js notranslate">var stop = false, age = 16; + +age > 18 ? location.assign("continue.html") : stop = true; +</pre> + +<p>하나의 케이스 당 둘 이상의 단일 작업을 수행하려면 쉼표로 구분하고 괄호로 묶으세요.</p> + +<pre class="brush: js notranslate">var stop = false, age = 23; + +age > 18 ? ( + alert("OK, you can go."), + location.assign("continue.html") +) : ( + stop = true, + alert("Sorry, you are much too young!") +); +</pre> + +<p>또한, 값을 할당하는 동안 하나 이상의 연산도 가능합니다. 이 경우에, 괄호 안의 값중 마지막 쉼표 (,) 다음의 값이 최종 할당 값이 됩니다.</p> + +<pre class="brush: js notranslate">var age = 16; + +var url = age > 18 ? ( + alert("OK, you can go."), + // alert returns "undefined", but it will be ignored because + // isn't the last comma-separated value of the parenthesis + "continue.html" // the value to be assigned if age > 18 +) : ( + alert("You are much too young!"), + alert("Sorry :-("), + // etc. etc. + "stop.html" // the value to be assigned if !(age > 18) +); + +location.assign(url); // "stop.html"</pre> + + + +<h3 id="삼항_연산자로_반환하기">삼항 연산자로 반환하기</h3> + +<p>삼항 연산자는 <code>if / else</code> 문을 사용하는 함수를 반환하는 데 적합합니다.</p> + +<pre class="notranslate"><code>var func1 = function( .. ) { + if (condition1) { return value1 } + else { return value2 } +} + +var func2 = function( .. ) { + return condition1 ? value1 : value2 +}</code></pre> + +<p>다음과 같이 법적으로 술을 마실수 있는지 여부를 반환하는 함수를 만들수 있습니다.</p> + +<pre class="notranslate"><code>function canDrinkAlcohol(age) { + return (age > 21) ? "True, over 21" : "False, under 21"; +} +var output = canDrinkAlcohol(26); +console.log(output); // "True, over 21"</code></pre> + +<p><code>if / else</code> 문을 대체하는 삼항연산자가 <code>return</code>을 여러 번 사용하고 if 블록 내부에서 한줄만 나올때 <code>return</code>을 대체 할 수 있는 좋은 방법이됩니다.</p> + +<p>삼항연산자를 여러 행으로 나누고 그 앞에 공백을 사용하면 긴 <code>if / else</code> 문을 매우 깔끔하게 만들 수 있습니다. 이것은 동일한 로직을 표현하지만 코드를 읽기 쉽게 만들어 줍니다.</p> + +<pre class="notranslate"><code>var func1 = function( .. ) { + if (condition1) { return value1 } + else if (condition2) { return value2 } + else if (condition3) { return value3 } + else { return value4 } +} + +var func2 = function( .. ) { + return condition1 ? value1 + : condition2 ? value2 + : condition3 ? value3 + : value4 +}</code> +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-conditional-operator', 'Conditional Operator')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-conditional-operator', 'Conditional Operator')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11.12', 'The conditional operator')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-11.12', 'The conditional operator')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.operators.conditional")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Reference/Statements/if...else">if statement</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/delete/index.html b/files/ko/web/javascript/reference/operators/delete/index.html new file mode 100644 index 0000000000..037c3bcd98 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/delete/index.html @@ -0,0 +1,282 @@ +--- +title: delete 연산자 +slug: Web/JavaScript/Reference/Operators/delete +tags: + - JavaScript + - Operator + - Property + - Reference +translation_of: Web/JavaScript/Reference/Operators/delete +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong><code>delete</code></strong> <strong>연산자</strong>는 객체의 속성을 제거합니다. 제거한 객체의 참조를 어디에서도 사용하지 않는다면 나중에 자원을 회수합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-deleteoperator.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">delete <em>expression</em> </pre> + +<p><code>expression</code>은 속성 참조여야 합니다. 예컨대,</p> + +<pre class="syntaxbox">delete <em>object.property</em> +delete <em>object</em>['<em>property</em>'] +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>object</code></dt> + <dd>객체의 이름, 또는 평가했을 때 객체를 반환하는 표현식.</dd> + <dt><code>property</code></dt> + <dd>제거하려는 속성.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p><code>true</code>. 단, 비엄격 모드에서 속성이 {{jsxref("Object.prototype.hasOwnProperty", "자신의 속성", "", 0)}}이며 <a href="/ko/docs/Web/JavaScript/Reference/Errors/Cant_delete">설정 불가능</a>한 경우 <code>false</code>.</p> + +<h3 id="예외">예외</h3> + +<p>엄격 모드에서, 속성이 자신의 속성이며 설정 불가능한 경우 {{jsxref("TypeError")}}.</p> + +<h2 id="설명">설명</h2> + +<p>일반적으로 생각하고 있는것과는 다르게 <code>delete</code> 는 메모리 해제에 관하여 직접적으로 어떠한 작업도 하지 않습니다. 메모리 관리는 breaking references를 통하여 간접적으로 일어납니다. 자세한 걸 알고 싶다면 <a href="/en-US/docs/Web/JavaScript/Memory_Management">memory management</a> 를 보세요.</p> + +<p><code><strong>delete</strong></code>연산자는 오브젝트로 부터 해당 프로퍼티를 삭제합니다. 삭제를 하면 true를 반환, 아니면 false를 반환합니다. 그렇지만 아래 경우를 고려해야만 합니다. </p> + +<ul> + <li>만약 존재하지 않는 속성을 삭제하려고 하면 delete는 어떠한 작업도 없이 true를 반환합니다.</li> + <li>오브젝트의 프로토타입 체인에 같은 이름의 속성이 있다면, 삭제 후에, 오브젝트의 프로토타입체인을 통해 프로퍼티를 사용 할 수 있습니다. (즉, <code>delete</code>는 오직 자신의 프로퍼티만 삭제 합니다.</li> + <li>{{jsxref("Statements/var","var")}}로 선언된 어떠한 프로퍼티라도 글로벌 스코프나 펑션 스코프로부터 삭제될 수 없습니다. + <ul> + <li>결국, <code>delete</code>는 글로벌 스코프의 어떤 함수도 삭제 할 수 없습니다. (함수 정의식이건 함수 표현식이건 삭제 불가)</li> + <li>오브젝트의 속성으로 있는 함수인 경우(글로벌 스코프를 제외하고)는 <code>delete</code>로 삭제할 수 있습니다.</li> + </ul> + </li> + <li>{{jsxref("Statements/let","let")}}과 {{jsxref("Statements/const","const")}}로 선언한 속성은 어느 스코프에 정의되어 있건 삭제 할 수 없습니다.</li> + <li>Non-configurable 속성은 삭제 할 수 없습니다. 이것은 {{jsxref("Math")}}, {{jsxref("Array")}}, {{jsxref("Object")}}와 같은 built-in objects의 속성들이나 {{jsxref("Object.defineProperty()")}} 같은 메소드로 만든 non-configurable속성들을 포함합니다.</li> +</ul> + +<p>간단한 예제입니다.</p> + +<pre class="brush: js">var Employee = { + age: 28, + name: 'abc', + designation: 'developer' +} + +console.log(delete Employee.name); // returns true +console.log(delete Employee.age); // returns true + +// 존재하지 않는 속성을 삭제하려하면 +// true를 리턴합니다. +console.log(delete Employee.salary); // returns true +</pre> + +<h3 id="설정_불가능한_속성">설정 불가능한 속성</h3> + +<p>non-configurable 속성은 <code>delete</code>로 삭제할 수 없으며, <code>false</code>를 반환할 것입니다(*strict mode에서는 <code>SyntaxError</code>를 발생시킴).</p> + +<pre class="brush: js">var Employee = {}; +Object.defineProperty(Employee, 'name', {configurable: false}); + +console.log(delete Employee.name); // returns false +</pre> + +<p>{{jsxref("Statements/var","var")}}, {{jsxref("Statements/let","let")}}, {{jsxref("Statements/const","const")}}로 선언된 변수는 non-configurable 속성으로 구분되며, <code>delete</code>로 삭제될 수 없습니다.</p> + +<pre class="brush: js">var nameOther = 'XYZ'; + +// 우리는 이를 사용해 글로벌 속성에 접근 할 수 있습니다: +Object.getOwnPropertyDescriptor(window, 'nameOther'); + +// output: Object { value: "XYZ", +// writable: true, +// enumerable: true, +// <strong>configurable: false </strong>} + +// "nameOther"은 var로 선언되었기 때문에 +// 이는 "non-configurable" 속성으로 구분됩니다. + +delete nameOther; // return false</pre> + +<p>strict mode, this would have raised an exception.</p> + +<h3 id="엄격_vs._비엄격_모드">엄격 vs. 비엄격 모드</h3> + +<p>엄격 모드에서 <code>delete</code>로 변수나 함수를 삭제하려고 하면 {{jsxref("SyntaxError")}}가 발생합니다. </p> + +<p><code>var</code>로 정의된 변수는 non-configurable로 구분됩니다. 다음 예제에서, <code>salary</code>는 non-configurable이며 삭제될 수 없습니다. non-strict mode에서 non-configurable에 <code>delete</code>를 쓰면 <code>false</code>를 반환합니다.</p> + +<pre class="brush: js">function Employee() { + delete salary; + var salary; +} + +Employee(); +</pre> + +<p>그러나 strict mode에서는 <code>false</code>를 반환하는 대신, <code>SyntaxError</code>를 발생시킵니다.</p> + +<pre class="brush: js">"use strict"; + +function Employee() { + delete salary; // SyntaxError + var salary; +} + +// 이와 마찬가지로, delete로 함수를 삭제하는 것도 +// SyntaxError를 발생시킵니다. + +function DemoFunction() { + //some code +} + +delete DemoFunction; // SyntaxError +</pre> + +<h2 id="예제">예제</h2> + +<pre class="brush: js">// 전역스코프에 adminName라는 프로퍼티를 만듭니다. +adminName = 'xyz'; + +// 전역스코프에 empCount라는 프로퍼티를 만듭니다. +// var를 사용해서 선언했으므로, 이는 non-configurable로 구분됩니다. +// let 이나 const를 사용하더라도 마찬가지로 non-configurable 입니다. +var empCount = 43; + +EmployeeDetails = { + name: 'xyz', + age: 5, + designation: 'Developer' +}; + +// adminName은 전역변수입니다. +// 이는 var를 사용하여 선언되지 않았기에 configurable하며 delete로 삭제될 수 있습니다. +delete adminName; // returns true + +// 이와 반대로, empCount는 var를 사용하였기에 non-configurable이며 +// 그러므로 delete로 삭제할 수 없습니다. +delete empCount; // returns false + +// delete는 객체의 프로퍼티를 지울 때 사용됩니다. +delete EmployeeDetails.name; // returns true + +// 해당 프로퍼티가 존재하지 않는 상황에서도 "true"를 리턴합니다. +delete EmployeeDetails.salary; // returns true + +// 내장되어있는 정적 프로퍼티에는 delete가 영향을 미치지 않습니다. +delete Math.PI; // returns false + +// EmployeeDetails 은 전역스코프의 프로퍼티 입니다. +// "var"를 사용하지 않고 선언되었기 때문에 이는 configurable입니다. +delete EmployeeDetails; // returns true + +function f() { + var z = 44; + + // 지역변수에는 delete가 영향을 미치지 않습니다. + delete z; // returns false +}</pre> + +<h3 id="delete와_프로토타입_체인"><code>delete</code>와 프로토타입 체인</h3> + +<p>In the following example, we delete an own property of an object while a property with the same name is available on the prototype chain:</p> + +<pre class="brush: js">function Foo() { + this.bar = 10; +} + +Foo.prototype.bar = 42; + +var foo = new Foo(); + +// Returns true, since the own property +// has been deleted on the foo object +delete foo.bar; + +// foo.bar is still available, since it +// is available in the prototype chain. +console.log(foo.bar); + +// We delete the property on the prototype +delete Foo.prototype.bar; + +// logs "undefined" since the property +// is no longer inherited +console.log(foo.bar); </pre> + +<h3 id="객체_요소_제거하기">객체 요소 제거하기</h3> + +<p>When you delete an array element, the array length is not affected. This holds even if you delete the last element of the array.</p> + +<p>When the <code>delete</code> operator removes an array element, that element is no longer in the array. In the following example, <code>trees[3]</code> is removed with <code>delete</code>.</p> + +<pre class="brush: js">var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; +delete trees[3]; +if (3 in trees) { + // this does not get executed +}</pre> + +<p>If you want an array element to exist but have an undefined value, use the <code>undefined</code> value instead of the <code>delete</code> operator. In the following example, <code>trees[3]</code> is assigned the value undefined, but the array element still exists:</p> + +<pre class="brush: js">var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; +trees[3] = undefined; +if (3 in trees) { + // this gets executed +}</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-delete-operator', 'The delete Operator')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-delete-operator', 'The delete Operator')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11.4.1', 'The delete Operator')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-11.4.1', 'The delete Operator')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div id="compat-mobile">{{Compat("javascript.operators.delete")}}</div> + +<h2 id="크로스_브라우저_참고사항">크로스 브라우저 참고사항</h2> + +<p>Although ECMAScript makes iteration order of objects implementation-dependent, it may appear that all major browsers support an iteration order based on the earliest added property coming first (at least for properties not on the prototype). However, in the case of Internet Explorer, when one uses <code>delete</code> on a property, some confusing behavior results, preventing other browsers from using simple objects like object literals as ordered associative arrays. In Explorer, while the property <em>value</em> is indeed set to undefined, if one later adds back a property with the same name, the property will be iterated in its <em>old</em> position--not at the end of the iteration sequence as one might expect after having deleted the property and then added it back.</p> + +<p>If you want to use an ordered associative array in a cross-browser environment, use a {{jsxref("Map")}} object if available, or simulate this structure with two separate arrays (one for the keys and the other for the values), or build an array of single-property objects, etc.</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="http://perfectionkills.com/understanding-delete/">In depth analysis on delete</a></li> + <li>{{jsxref("Reflect.deleteProperty()")}}</li> + <li>{{jsxref("Map.prototype.delete()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/destructuring_assignment/index.html b/files/ko/web/javascript/reference/operators/destructuring_assignment/index.html new file mode 100644 index 0000000000..d078e94c38 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/destructuring_assignment/index.html @@ -0,0 +1,409 @@ +--- +title: 구조 분해 할당 +slug: Web/JavaScript/Reference/Operators/Destructuring_assignment +tags: + - Destructuring + - ECMAScript 2015 + - JavaScript + - Operator + - Reference + - 구조 분해 +translation_of: Web/JavaScript/Reference/Operators/Destructuring_assignment +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>구조 분해 할당</strong> 구문은 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 JavaScript 표현식입니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-destructuringassignment.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="brush: js">var a, b, rest; +[a, b] = [10, 20]; +console.log(a); // 10 +console.log(b); // 20 + +[a, b, ...rest] = [10, 20, 30, 40, 50]; +console.log(a); // 10 +console.log(b); // 20 +console.log(rest); // [30, 40, 50] + +({ a, b } = { a: 10, b: 20 }); +console.log(a); // 10 +console.log(b); // 20 + + +// Stage 4(finished) proposal +({a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}); +console.log(a); // 10 +console.log(b); // 20 +console.log(rest); // {c: 30, d: 40} +</pre> + +<h2 id="설명">설명</h2> + +<p>객체 및 배열 리터럴 표현식을 사용하면 즉석에서 쉽게 데이터 뭉치를 만들 수 있습니다.</p> + +<pre class="brush: js">var x = [1, 2, 3, 4, 5];</pre> + +<p>구조 분해 할당의 구문은 위와 비슷하지만, 대신 할당문의 좌변에서 사용하여, 원래 변수에서 어떤 값을 분해해 할당할지 정의합니다.</p> + +<pre class="brush: js">var x = [1, 2, 3, 4, 5]; +var [y, z] = x; +console.log(y); // 1 +console.log(z); // 2 +</pre> + +<p>구조 분해 할당은 Perl이나 Python 등 다른 언어가 가지고 있는 기능입니다.</p> + +<h2 id="배열_구조_분해">배열 구조 분해</h2> + +<h3 id="기본_변수_할당">기본 변수 할당</h3> + +<pre class="brush: js">var foo = ["one", "two", "three"]; + +var [one, two, three] = foo; +console.log(one); // "one" +console.log(two); // "two" +console.log(three); // "three" +</pre> + +<h3 id="선언에서_분리한_할당">선언에서 분리한 할당</h3> + +<p>변수의 선언이 분리되어도 구조 분해를 통해 값을 할당할 수 있습니다.</p> + +<pre class="brush:js">var a, b; + +[a, b] = [1, 2]; +console.log(a); // 1 +console.log(b); // 2 +</pre> + +<h3 id="기본값">기본값</h3> + +<p>변수에 기본값을 할당하면, 분해한 값이 {{jsxref("undefined")}}일 때 그 값을 대신 사용합니다.</p> + +<pre class="brush: js">var a, b; + +[a=5, b=7] = [1]; +console.log(a); // 1 +console.log(b); // 7 +</pre> + +<h3 id="변수_값_교환하기">변수 값 교환하기</h3> + +<p>하나의 구조 분해 표현식만으로 두 변수의 값을 교환할 수 있습니다.</p> + +<p>구조 분해 할당 없이 두 값을 교환하려면 임시 변수가 필요합니다. (일부 로우 레벨 언어에서는 <a class="external" href="http://en.wikipedia.org/wiki/XOR_swap">XOR 교체 트릭</a>을 사용할 수 있습니다)</p> + +<pre class="brush:js">var a = 1; +var b = 3; + +[a, b] = [b, a]; +console.log(a); // 3 +console.log(b); // 1 +</pre> + +<h3 id="함수가_반환한_배열_분석">함수가 반환한 배열 분석</h3> + +<p>함수는 이전부터 배열을 반환할 수 있었습니다. 구조 분해를 사용하면 반환된 배열에 대한 작업을 더 간결하게 수행할 수 있습니다.</p> + +<p>아래 예제에서 <code>f()</code>는 출력으로 배열 <code>[1, 2]</code>을 반환하는데, 하나의 구조 분해만으로 값을 분석할 수 있습니다.</p> + +<pre class="brush:js">function f() { + return [1, 2]; +} + +var a, b; +[a, b] = f(); +console.log(a); // 1 +console.log(b); // 2 +</pre> + +<h3 id="일부_반환_값_무시하기">일부 반환 값 무시하기</h3> + +<p>다음과 같이 필요하지 않은 반환 값을 무시할 수 있습니다.</p> + +<pre class="brush:js">function f() { + return [1, 2, 3]; +} + +var [a, , b] = f(); +console.log(a); // 1 +console.log(b); // 3 +</pre> + +<p>반환 값을 모두 무시할 수도 있습니다.</p> + +<pre class="brush:js">[,,] = f(); +</pre> + +<h3 id="변수에_배열의_나머지를_할당하기">변수에 배열의 나머지를 할당하기</h3> + +<p>배열을 구조 분해할 경우, 나머지 구문을 이용해 분해하고 남은 부분을 하나의 변수에 할당할 수 있습니다.</p> + +<pre class="brush: js">var [a, ...b] = [1, 2, 3]; +console.log(a); // 1 +console.log(b); // [2, 3] +</pre> + +<p>나머지 요소의 오른쪽 뒤에 쉼표가 있으면 {{jsxref("SyntaxError")}}가 발생합니다.</p> + +<pre class="brush: js example-bad">var [a, ...b,] = [1, 2, 3]; +// SyntaxError: rest element may not have a trailing comma +</pre> + +<h3 id="정규_표현식과_일치하는_값_해체하기">정규 표현식과 일치하는 값 해체하기</h3> + +<p>정규 표현식의 <code><a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec"> exec()</a></code> 메서드는 일치하는 부분를 찾으면 그 문자열에서 정규식과 일치하는 부분 전체를 배열의 맨 앞에, 그리고 그 뒤에 정규식에서 괄호로 묶인 각 그룹과 일치하는 부분을 포함하는 배열을 반환합니다. 구조 분해 할당은 필요하지 않은 경우 일치하는 전체 부분은 무시하고 필요한 부분만 쉽게 빼올 수 있습니다.</p> + +<pre class="brush: js">function parseProtocol(url) { + var parsedURL = /^(\w+)\:\/\/([^\/]+)\/(.*)$/.exec(url); + if (!parsedURL) { + return false; + } + console.log(parsedURL); // ["https://developer.mozilla.org/en-US/Web/JavaScript", "https", "developer.mozilla.org", "en-US/Web/JavaScript"] + + var [, protocol, fullhost, fullpath] = parsedURL; + return protocol; +} + +console.log(parseProtocol('https://developer.mozilla.org/en-US/Web/JavaScript')); // "https"</pre> + +<h2 id="객체_구조_분해">객체 구조 분해</h2> + +<h3 id="기본_할당">기본 할당</h3> + +<pre class="brush: js">var o = {p: 42, q: true}; +var {p, q} = o; + +console.log(p); // 42 +console.log(q); // true +</pre> + +<h3 id="선언_없는_할당">선언 없는 할당</h3> + +<p>구조 분해를 통해 변수의 선언과 분리하여 변수에 값을 할당할 수 있습니다.</p> + +<pre class="brush:js">var a, b; + +({a, b} = {a: 1, b: 2});</pre> + +<div class="note"> +<p><strong>참고</strong>: 할당 문을 둘러싼 <code>( .. )</code>는 선언 없이 객체 리터럴(object literal) 비구조화 할당을 사용할 때 필요한 구문입니다.</p> + +<p><code>{a, b} = {a:1, b:2}</code>는 유효한 독립 구문이 아닙니다. 좌변의 <code>{a, b}</code>이 객체 리터럴이 아닌 블록으로 간주되기 때문입니다.</p> + +<p>하지만, <code>({a, b} = {a:1, b:2})</code>는 유효한데, <code>var {a, b} = {a:1, b:2}</code>와 같습니다.</p> + +<p><code>( .. )</code> 표현식 앞에는 세미콜론이 있어야 합니다. 그렇지 않을 경우 이전 줄과 연결되어 함수를 실행하는데 이용될 수 있습니다.</p> +</div> + +<h3 id="새로운_변수_이름으로_할당하기">새로운 변수 이름으로 할당하기</h3> + +<p>객체로부터 속성을 해체하여 객체의 원래 속성명과는 다른 이름의 변수에 할당할 수 있습니다.</p> + +<pre class="brush: js">var o = {p: 42, q: true}; +var {p: foo, q: bar} = o; + +console.log(foo); // 42 +console.log(bar); // true</pre> + +<h3 id="기본값_2">기본값</h3> + +<p>객체로부터 해체된 값이 <code>undefined</code>인 경우, 변수에 기본값을 할당할 수 있습니다.</p> + +<pre class="brush: js">var {a = 10, b = 5} = {a: 3}; + +console.log(a); // 3 +console.log(b); // 5</pre> + +<h3 id="기본값_갖는_새로운_이름의_변수에_할당하기">기본값 갖는 새로운 이름의 변수에 할당하기</h3> + +<p>새로운 변수명 할당과 기본값 할당을 한번에 할 수 있습니다.</p> + +<pre class="brush: js">var {a: aa = 10, b: bb = 5} = {a: 3}; + +console.log(aa); // 3 +console.log(bb); // 5 +</pre> + +<h3 id="함수_매개변수의_기본값_설정하기">함수 매개변수의 기본값 설정하기</h3> + +<h4 id="ES5_버전">ES5 버전</h4> + +<pre class="brush: js">function drawES5Chart(options) { + options = options === undefined ? {} : options; + var size = options.size === undefined ? 'big' : options.size; + var cords = options.cords === undefined ? { x: 0, y: 0 } : options.cords; + var radius = options.radius === undefined ? 25 : options.radius; + console.log(size, cords, radius); + // 이제 드디어 차트 그리기 수행 +} + +drawES5Chart({ + cords: { x: 18, y: 30 }, + radius: 30 +});</pre> + +<h4 id="ES2015_버전">ES2015 버전</h4> + +<pre class="brush: js">function drawES2015Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25} = {}) { + console.log(size, cords, radius); + // 차트 그리기 수행 +} + +drawES2015Chart({ + cords: { x: 18, y: 30 }, + radius: 30 +});</pre> + +<div class="note"> +<p>위의 <strong><code>drawES2015Chart</code></strong> 함수의 원형에서 구조 분해된 좌변에 빈 오브젝트 리터럴을 할당하는 것을 볼 수 있습니다 <code>{size = 'big', cords = {x: 0, y: 0}, radius = 25} = {}</code>. 빈 오브젝트를 우변에 할당하지 않고도 함수를 작성할 수 있습니다. 하지만, 지금의 형태에서는 단순히 <code><strong>drawES2015Chart()</strong></code>와 같이 어떤 매개변수 없이도 호출할 수 있지만, 우변의 빈 오브젝트 할당을 없앤다면 함수 호출시 적어도 하나의 인자가 제공되어야만 합니다. 이 함수가 어떠한 매개변수 없이도 호출할 수 있길 원한다면 지금 형태가 유용하고, 무조건 객체를 넘기길 원하는 경우에는 빈 객체 할당을 하지 않는 것이 유용할 수 있습니다.</p> +</div> + +<h3 id="중첩된_객체_및_배열의_구조_분해">중첩된 객체 및 배열의 구조 분해</h3> + +<pre class="brush:js">var metadata = { + title: "Scratchpad", + translations: [ + { + locale: "de", + localization_tags: [ ], + last_edit: "2014-04-14T08:43:37", + url: "/de/docs/Tools/Scratchpad", + title: "JavaScript-Umgebung" + } + ], + url: "/en-US/docs/Tools/Scratchpad" +}; + +var { title: englishTitle, translations: [{ title: localeTitle }] } = metadata; + +console.log(englishTitle); // "Scratchpad" +console.log(localeTitle); // "JavaScript-Umgebung"</pre> + +<h3 id="for_of_반복문과_구조_분해">for of 반복문과 구조 분해</h3> + +<pre class="brush: js">var people = [ + { + name: "Mike Smith", + family: { + mother: "Jane Smith", + father: "Harry Smith", + sister: "Samantha Smith" + }, + age: 35 + }, + { + name: "Tom Jones", + family: { + mother: "Norah Jones", + father: "Richard Jones", + brother: "Howard Jones" + }, + age: 25 + } +]; + +for (var {name: n, family: { father: f } } of people) { + console.log("Name: " + n + ", Father: " + f); +} + +// "Name: Mike Smith, Father: Harry Smith" +// "Name: Tom Jones, Father: Richard Jones"</pre> + +<h3 id="함수_매개변수로_전달된_객체에서_필드_해체하기">함수 매개변수로 전달된 객체에서 필드 해체하기</h3> + +<pre class="brush:js">function userId({id}) { + return id; +} + +function whois({displayName: displayName, fullName: {firstName: name}}){ + console.log(displayName + " is " + name); +} + +var user = { + id: 42, + displayName: "jdoe", + fullName: { + firstName: "John", + lastName: "Doe" + } +}; + +console.log("userId: " + userId(user)); // "userId: 42" +whois(user); // "jdoe is John"</pre> + +<p>이 예제는 user 객체로부터 <code>id</code>, <code>displayName</code> 및 <code>firstName</code> 을 해체해 출력합니다.</p> + +<h3 id="계산된_속성_이름과_구조_분해">계산된 속성 이름과 구조 분해</h3> + +<p>계산된 속성 이름(computed property name)은, <a href="/ko/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names" title="object literals">객체 리터럴</a>과 비슷하게 구조 분해에도 사용될 수 있습니다.</p> + +<pre class="brush: js">let key = "z"; +let { [key]: foo } = { z: "bar" }; + +console.log(foo); // "bar" +</pre> + +<h3 id="객체_구조_분해에서_Rest">객체 구조 분해에서 Rest</h3> + +<p><a class="external external-icon" href="https://github.com/tc39/proposal-object-rest-spread">Rest/Spread Properties for ECMAScript</a> 제안(stage 3)에서는 구조 분해에 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest</a> 구문을 추가하고 있습니다. rest 속성은 구조 분해 패턴으로 걸러지지 않은 열거형 속성의 키를 가진 나머지 항목들을 모읍니다.</p> + +<pre class="brush: js">let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40} +a; // 10 +b; // 20 +rest; // { c: 30, d: 40 } +</pre> + +<h3 id="속성_이름이_유효한_JavaScript_식별자명이_아닌_경우">속성 이름이 유효한 JavaScript 식별자명이 아닌 경우</h3> + +<p>구조 분해는 JavaScript {{glossary("Identifier", "식별자")}} 이름으로 적합하지 않은 속성명이 제공된 경우에도 이용할 수 있습니다. 이 때는 대체할 유효한 식별자명을 제공해야 합니다.</p> + +<pre class="brush: js">const foo = { 'fizz-buzz': true }; +const { 'fizz-buzz': fizzBuzz } = foo; + +console.log(fizzBuzz); // "true" +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-destructuring-assignment', 'Destructuring assignment')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-destructuring-assignment', 'Destructuring assignment')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div> +<div> + + +<p>{{Compat("javascript.operators.destructuring")}}</p> +</div> +</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Reference/Operators/Assignment_Operators" title="Assignment operators">할당 연산자</a></li> + <li><a href="https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/">"ES6 in Depth: Destructuring" on hacks.mozilla.org</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/equality/index.html b/files/ko/web/javascript/reference/operators/equality/index.html new file mode 100644 index 0000000000..5ebe238590 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/equality/index.html @@ -0,0 +1,123 @@ +--- +title: 동등 연산자(==) +slug: Web/JavaScript/Reference/Operators/Equality +translation_of: Web/JavaScript/Reference/Operators/Equality +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>동등 연산자(==)는 두 개의 피연산자가 동일한지 확인하며, Boolean값을 반환합니다. <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality">일치 연산자</a>(===)와는 다르게 다른 타입의 피연산자들끼리의 비교를 시도합니다. </p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-equality.html")}}</div> + +<div class="hidden">The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</div> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox notranslate">x == y +</pre> + +<h2 id="상세_설명">상세 설명</h2> + +<p>동등 연산자 (<code>==</code> 와 <code>!=</code>)는 두 피연산자를 비교하기 위해 <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3">Abstract Equality Comparison Algorithm</a>를 사용합니다. 다음과 같이 간략히 설명할 수 있습니다:</p> + +<ul> + <li>두 피연산자가 모두 객체일때, 두 피연산자가 동일한 객체를 참조할때에만 true를 반환합니다.</li> + <li>하나의 피연산자가 <code>null</code>이고 다른 하나가 <code>undefined</code>일때, <code>true</code>를 반환합니다.</li> + <li>두 피연산자의 타입이 다를 경우, 비교하기 전에 동일한 타입으로 변환하도록 합니다: + <ul> + <li>숫자와 문자열을 비교할 경우, 문자열을 숫자로 변환하도록 합니다.</li> + <li>하나의 피연산자가 <code>Boolean</code>일 경우, Boolean 피연산자가 true일 경우 1로 변환하고, false일 경우, +0으로 변환합니다.</li> + <li>하나의 피연산자가 객체이고 다른하나가 숫자나 문자열이면, 객체를 <code>valueOf()</code>나<code>toString()</code>를 사용해 기본 데이터 타입으로 변환하도록 합니다.</li> + </ul> + </li> + <li>두개의 피연산자가 동일한 타입일 경우, 다음과 같이 비교됩니다: + <ul> + <li><code>String</code>: 두 피연산자가 동일한 문자순서가 동일한 문자열일 경우, <code>true</code>를 반환합니다.</li> + <li><code>Number</code>: 두 피연산자가 동일한 값을 가질 경우, <code>true</code>을 반환합니다. +0 과 -0 은 동일한 값으로 취급합니다. 어느 한쪽이 <code>NaN</code>일 경우, <code>false</code>를 반환합니다.</li> + <li><code>Boolean</code>: 두 피연산자가 모두 <code>true</code>이거나, 모두 <code>false</code>일 경우, <code>true</code>를 반환합니다. </li> + </ul> + </li> +</ul> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality">일치연산자</a> (<code>===</code>)와의 가장 두드러지는 차이점은 일치 연산자는 타입변환을 시도하지 않는다는 것입니다. 일치 연산자는 다른 타입을 가진 피연산자는 다르다고 판단합니다.</p> + +<h2 id="예시">예시</h2> + +<h3 id="타입변환_없이_비교">타입변환 없이 비교</h3> + +<pre class="brush: js notranslate">1 == 1; // true +"hello" == "hello"; // true</pre> + +<h3 id="타입변환을_이용한_비교">타입변환을 이용한 비교</h3> + +<pre class="brush: js notranslate">"1" == 1; // true +1 == "1"; // true +0 == false; // true +0 == null; // false +0 == undefined; // false +0 == !!null; // true, look at Logical NOT operator +0 == !!undefined; // true, look at Logical NOT operator +null == undefined; // true + +const number1 = new Number(3); +const number2 = new Number(3); +number1 == 3; // true +number1 == number2; // false</pre> + +<h3 id="객체들_간의_비교">객체들 간의 비교</h3> + +<pre class="brush: js notranslate">const object1 = {"key": "value"} +const object2 = {"key": "value"}; + +object1 == object2 // false +object2 == object2 // true</pre> + +<h3 id="String과_String_objects의_비교">String과 String objects의 비교</h3> + +<p><code>new String()</code> 을 통해 생성된 문자열들은 객체입니다. 이 객체중 하나를 문자열과 비교한다면, <code>String</code> 객체가 문자열로 변환된 후 비교될 것입니다. 그러나 두개의 피연산자 모두 <code>String</code> 객체라면, 객체로써 비교가 이루어지기 때문에 같은 값으로 취급될려면 같은 객체를 참조하고 있어야 합니다:</p> + +<pre class="brush: js notranslate">const string1 = "hello"; +const string2 = String("hello"); +const string3 = new String("hello"); +const string4 = new String("hello"); + +console.log(string1 == string2); // true +console.log(string1 == string3); // true +console.log(string2 == string3); // true +console.log(string3 == string4); // false +console.log(string4 == string4); // true</pre> + +<h3 id="Comparing_Dates_and_strings">Comparing Dates and strings</h3> + +<pre class="brush: js notranslate">const d = new Date('December 17, 1995 03:24:00'); +const s = d.toString(); // for example: "Sun Dec 17 1995 03:24:00 GMT-0800 (Pacific Standard Time)" +console.log(d == s); //true</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-equality-operators', 'Equality operators')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.operators.equality")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Inequality">Inequality operator</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality">Strict equality operator</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Strict_inequality">Strict inequality operator</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/expression_closures/index.html b/files/ko/web/javascript/reference/operators/expression_closures/index.html new file mode 100644 index 0000000000..bf44be6cd7 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/expression_closures/index.html @@ -0,0 +1,79 @@ +--- +title: 표현식 클로저 +slug: Web/JavaScript/Reference/Operators/Expression_closures +tags: + - Function + - JavaScript + - Non-standard + - Obsolete + - Operator + - Reference +translation_of: Archive/Web/JavaScript/Expression_closures +--- +<div>{{JSSidebar("Operators")}}{{Non-standard_Header}}{{Obsolete_Header("gecko60")}} +<div class="warning"><strong>Non-standard. Do not use!</strong><br> +The expression closure syntax is a deprecated Firefox-specific feature and has been removed starting with Firefox 60. For future-facing usages, consider using <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow functions</a>.</div> +</div> + +<p>클로져는 간단한 함수를 작성하기 위한 짧은 함수구문 입니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">function [<em>name</em>]([<em>param1</em>[, <em>param2[</em>, ..., <em>paramN</em>]]]) + <em>expression</em> +</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>name</code></dt> + <dd>함수의 이름입니다. 익명함수의 경우에는 생략할 수 있습니다. 이름은 함수본문에만 국한됩니다.</dd> + <dt><code>paramN</code></dt> + <dd>함수에 전달할 인수의 이름입니다. 함수는 최대 255개의 인수를 가질 수 있습니다.</dd> + <dt><code>expression</code></dt> + <dd>함수의 본문을 구성하는 표현식입니다.</dd> +</dl> + +<h2 id="Description">Description</h2> + +<p>이 추가적인 기능은 <a class="external" href="http://en.wikipedia.org/wiki/Lambda_calculus#Lambda_calculus_and_programming_languages">람다 표기법</a>과 비슷한 언어를 제공하기위해 간단한 기능을 작성하는데 필요한 단축형일 뿐입니다.</p> + +<p>JavaScript 1.7 and older:</p> + +<pre class="brush: js">function(x) { return x * x; }</pre> + +<p>JavaScript 1.8:</p> + +<pre class="brush: js">function(x) x * x</pre> + +<p>이 구문을 사용하면 중괄호나 'return'문을 생략하여 암시적으로 만들 수 있습니다. 코드를 더 짧게 만들 수 있는 것 이외의 이방법으로 얻을 수 있는 추가 이점은 없습니다.</p> + +<h2 id="Examples">Examples</h2> + +<p>바인딩 이벤트 리스너의 간단한 예제:</p> + +<pre class="brush: js"> document.addEventListener('click', function() false, true); +</pre> + +<p>JavaScript 1.6의 일부 배열 함수에 이 표기법을 사용합니다:</p> + +<pre class="brush: js">elems.some(function(elem) elem.type == 'text'); +</pre> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.operators.expression_closures")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Functions_and_function_scope", "Functions and function scope")}}</li> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("Statements/function", "function statement")}}</li> + <li>{{jsxref("Operators/function", "function expression")}}</li> + <li>{{jsxref("Statements/function*", "function* statement")}}</li> + <li>{{jsxref("Operators/function*", "function* expression")}}</li> + <li>{{jsxref("GeneratorFunction")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/function/index.html b/files/ko/web/javascript/reference/operators/function/index.html new file mode 100644 index 0000000000..5f4977bfc7 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/function/index.html @@ -0,0 +1,154 @@ +--- +title: 함수 표현식 +slug: Web/JavaScript/Reference/Operators/function +tags: + - Function + - JavaScript + - Operator + - Primary Expressions +translation_of: Web/JavaScript/Reference/Operators/function +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong><code>function</code></strong> 키워드는 어떤 표현식(expression) 내에서 함수를 정의하는 데 사용될 수 있습니다.</p> + +<p>또한 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Function">Function</a> 생성자와 <a href="/ko/docs/Web/JavaScript/Reference/Statements/function">함수 선언(function declaration)</a>을 이용해 함수를 정의할 수도 있습니다. </p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-functionexpression.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">var myFunction = function [<em>name</em>]([<em>param1</em>[, <em>param2[</em>, ..., <em>paramN</em>]]]) { <em>statements </em>};</pre> + +<p><a href="/ko/docs/">ES2015</a>에서 <a href="/ko/docs/Web/JavaScript/Reference/Functions/%EC%95%A0%EB%A1%9C%EC%9A%B0_%ED%8E%91%EC%85%98">화살표 함수(arrow functions)</a>를 사용할 수도 있습니다.</p> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>name</code></dt> + <dd>함수 이름. 함수가 이름 없는(anonymous) 함수인 경우, 생략될 수 있음. 이 함수 이름은 함수의 몸통 내에서만 사용할 수 있습니다.</dd> + <dt><code>paramN</code></dt> + <dd>함수로 전달되는 인수(argument) 의 이름.</dd> + <dt><code>statements</code></dt> + <dd>함수 몸통을 구성하는 문(statement).</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p>함수 표현식(function expression)은 function 문과 매우 비슷하고 구문(syntax)이 거의 같습니다 (자세한 사항은 <a href="/ko/docs/Web/JavaScript/Reference/Statements/function" title="function statement">function 문</a> 참조). 함수 표현식과 function 문 사이의 주요 차이점은 함수 이름으로, 함수 표현식으로 <em>익명</em> 함수를 만들 경우 이 이름을 생략할 수 있습니다. 함수 표현식은 정의하자마자 실행되는 <a href="https://developer.mozilla.org/en-US/docs/Glossary/IIFE">IIFE (즉시 호출되는 함수 표현식)</a>로 사용될 수 있습니다. 더 자세한 정보는 <a href="/ko/docs/Web/JavaScript/Reference/Functions" title="functions">함수</a> 장 참조.</p> + +<h3 id="Function_expression_끌어올리기">Function expression 끌어올리기</h3> + +<p>자바스크립트에서 함수 표현식은 {{jsxref("Statements/function", "함수 선언", "#Function_declaration_hoisting")}}과는 달리 끌어올려지지 않습니다. 함수 표현식을 정의하기 전에는 사용할 수 없습니다.</p> + +<pre><code>console.log(notHoisted) // undefined +//even the variable name is hoisted, the definition wasn't. so it's undefined. +notHoisted(); // TypeError: notHoisted is not a function + +var notHoisted = function() { + console.log('bar'); +};</code></pre> + +<h3 id="유명(named)_함수_표현식">유명(named) 함수 표현식</h3> + +<p>함수 몸통 안 쪽에서 현재 함수를 참고하고 싶다면, 유명 함수를 생성해야 합니다. <u><strong>이 함수 이름은 함수의 몸통(범위) 안에서만 사용할 수 있습니다</strong></u>. 이로써 비표준 <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee">arguments.callee</a></code> 속성을 사용하는 것을 피할 수도 있습니다.</p> + +<pre><code>var math = { + 'factit': function factorial(n) { + console.log(n) + if (n <= 1) + return 1; + return n * factorial(n - 1); + } +}; + +math.factit(3) //3;2;1;</code> +</pre> + +<p>함수가 할당된 변수는 <code>name</code> 속성을 가지게됩니다. 다른 변수에 할당되더라도 그 name 속성의 값은 변하지 않습니다. 함수의 이름이 생략되었다면, name 속성의 값은 그 변수의 이름(암묵적 이름)이 될 것입니다. 함수의 이름이 있다면 name 속성의 값은 그 함수의 이름(명시적 이름)이 될 것입니다. 이는 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">화살표 함수(arrow functions)</a>에도 적용됩니다 (화살표 함수는 이름을 가지지 않으므로 해당 변수에 암묵적인 이름만 줄 수 있습니다).</p> + +<pre><code>var foo = function() {} +foo.name // "foo" + +var foo2 = foo +foo2.name // "foo" + +var bar = function baz() {} +bar.name // "baz" + +console.log(foo === foo2); // true +console.log(typeof baz); // undefined +console.log(bar === baz); // false (errors because baz == undefined)</code> +</pre> + +<p> </p> + +<h2 id="Examples">Examples</h2> + +<p>다음 예제는 이름 없는 함수를 정의하고 그 함수를 <code>x</code>에 할당합니다. 함수는 인수의 제곱을 반환합니다:</p> + +<pre><code>var x = function(y) { + return y * y; +};</code></pre> + +<p><a href="https://developer.mozilla.org/ko/docs/Glossary/Callback_function">callback</a>으로 더 자주 사용됩니다:</p> + +<pre><code>button.addEventListener('click', function(event) { + console.log('button is clicked!') +})</code></pre> + +<p> </p> + +<p> </p> + +<h2 id="스펙">스펙</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-13', 'Function definition')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES3', '#sec-13', 'Function definition')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>초기 정의. JavaScript 1.5에서 구현됨.</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.operators.function")}}</p> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("Arrow_functions", "Arrow functions")}}</li> + <li>{{jsxref("Functions_and_function_scope", "Functions and function scope")}}</li> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("Statements/function", "function statement")}}</li> + <li>{{jsxref("Statements/function*", "function* statement")}}</li> + <li>{{jsxref("Operators/function*", "function* expression")}}</li> + <li>{{jsxref("GeneratorFunction")}}</li> + <li>{{jsxref("Statements/async_function", "async function")}}</li> + <li>{{jsxref("Operators/async_function", "async function expression")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/function_star_/index.html b/files/ko/web/javascript/reference/operators/function_star_/index.html new file mode 100644 index 0000000000..7187f985bc --- /dev/null +++ b/files/ko/web/javascript/reference/operators/function_star_/index.html @@ -0,0 +1,85 @@ +--- +title: function* expression +slug: Web/JavaScript/Reference/Operators/function* +tags: + - ECMAScript6 + - Function + - Generator + - JavaScript +translation_of: Web/JavaScript/Reference/Operators/function* +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong><code>function*</code></strong> keyword 는 표현식 내에서 generator function 을 정의합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-functionasteriskexpression.html")}}</div> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">function* [<em>name</em>]([<em>param1</em>[, <em>param2[</em>, ..., <em>paramN</em>]]]) { + <em>statements</em> +}</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>name</code></dt> + <dd>함수명. 생략하면, 익명 함수가 됩니다. 함수명은 함수내에만 한정됩니다.</dd> + <dt><code>paramN</code></dt> + <dd>함수에 전달되는 인수의 이름. 함수는 최대 255 개의 인수를 가질 수 있습니다.</dd> + <dt><code>statements</code></dt> + <dd>함수의 본체를 구성하는 구문들.</dd> +</dl> + +<h2 id="Description">Description</h2> + +<p><code>function*</code> expression 은 {{jsxref('Statements/function*', 'function* statement')}} 과 매우 유사하고 형식도 같습니다. <code>function*</code> expression 과 <code>function*</code> statement 의 주요한 차이점은 함수명으로,<em> </em><code>function*</code> expressions 에서는 익명 함수로 만들기 위해 함수명이 생략될 수 있습니다.보다 자세한 내용은 <a href="/ko/docs/Web/JavaScript/Reference/Functions">functions</a> 을 참조하십시오.</p> + +<h2 id="Examples">Examples</h2> + +<p>아래의 예제는 이름이 없는 generator function 을 정의하고 이를 x 에 할당합니다. function 은 인자로 들어온 값의 제곱을 생산(yield)합니다.</p> + +<pre class="brush: js">var x = function*(y) { + yield y * y; +}; +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#', 'function*')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#', 'function*')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{Compat("javascript.operators.function_star")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Statements/function*", "function* statement")}}</li> + <li>{{jsxref("GeneratorFunction")}} object</li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/The_Iterator_protocol">The Iterator protocol</a></li> + <li>{{jsxref("Operators/yield", "yield")}}</li> + <li>{{jsxref("Operators/yield*", "yield*")}}</li> + <li>{{jsxref("Function")}} object</li> + <li>{{jsxref("Statements/function", "function statement")}}</li> + <li>{{jsxref("Operators/function", "function expression")}}</li> + <li>{{jsxref("Functions_and_function_scope", "Functions and function scope")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/generator_comprehensions/index.html b/files/ko/web/javascript/reference/operators/generator_comprehensions/index.html new file mode 100644 index 0000000000..927b613dc6 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/generator_comprehensions/index.html @@ -0,0 +1,174 @@ +--- +title: 생성기 내포 +slug: Web/JavaScript/Reference/Operators/Generator_comprehensions +tags: + - JavaScript + - Non-standard + - Obsolete + - Reference +translation_of: Archive/Web/JavaScript/Generator_comprehensions +--- +<div>{{JSSidebar("Operators")}}{{Non-standard_Header}}{{Obsolete_Header("gecko58")}} +<div class="blockIndicator warning"> +<p><strong>Non-standard. Do not use!</strong><br> + The generator comprehensions syntax is non-standard and removed starting with Firefox 58. For future-facing usages, consider using {{JSxRef("Statements/function*", "generator", "", 1)}}.</p> +</div> +</div> + +<p>The <strong>generator comprehension</strong> syntax was a JavaScript expression which allowed you to quickly assemble a new generator function based on an existing iterable object. However, it has been removed from the standard and the Firefox implementation. Do not use it!</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">(for (x of iterable) x) +(for (x of iterable) if (condition) x) +(for (x of iterable) for (y of iterable) x + y) +</pre> + +<h2 id="Description">Description</h2> + +<p>Inside generator comprehensions, these two kinds of components are allowed:</p> + +<ul> + <li>{{JSxRef("Statements/for...of", "for...of")}} and</li> + <li>{{JSxRef("Statements/if...else", "if")}}</li> +</ul> + +<p>The <code>for-of</code> iteration is always the first component. Multiple <code>for-of</code> iterations or if statements are allowed.</p> + +<p>A significant drawback of {{JSxRef("Operators/Array_comprehensions","array comprehensions","","true")}} is that they cause an entire new array to be constructed in memory. When the input to the comprehension is itself a small array the overhead involved is insignificant — but when the input is a large array or an expensive (or indeed infinite) generator the creation of a new array can be problematic.</p> + +<p>Generators enable lazy computation of sequences, with items calculated on-demand as they are needed. Generator comprehensions are syntactically almost identical to array comprehensions — they use parentheses instead of braces— but instead of building an array they create a generator that can execute lazily. You can think of them as short hand syntax for creating generators.</p> + +<p>Suppose we have an iterator <code>it</code> which iterates over a large sequence of integers. We want to create a new iterator that will iterate over their doubles. An array comprehension would create a full array in memory containing the doubled values:</p> + +<pre class="brush: js">var doubles = [for (i in it) i * 2]; +</pre> + +<p>A generator comprehension on the other hand would create a new iterator which would create doubled values on demand as they were needed:</p> + +<pre class="brush: js">var it2 = (for (i in it) i * 2); +console.log(it2.next()); // The first value from it, doubled +console.log(it2.next()); // The second value from it, doubled +</pre> + +<p>When a generator comprehension is used as the argument to a function, the parentheses used for the function call means that the outer parentheses can be omitted:</p> + +<pre class="brush: js">var result = doSomething(for (i in it) i * 2); +</pre> + +<p>The significant difference between the two examples being that by using the generator comprehension, you would only have to loop over the 'obj' structure once, total, as opposed to once when comprehending the array, and again when iterating through it.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Simple_generator_comprehensions">Simple generator comprehensions</h3> + +<pre class="brush:js">(for (i of [1, 2, 3]) i * i ); +// generator function which yields 1, 4, and 9 + +[...(for (i of [1, 2, 3]) i * i )]; +// [1, 4, 9] + +var abc = ['A', 'B', 'C']; +(for (letters of abc) letters.toLowerCase()); +// generator function which yields "a", "b", and "c" +</pre> + +<h3 id="Generator_comprehensions_with_if_statement">Generator comprehensions with if statement</h3> + +<pre class="brush: js">var years = [1954, 1974, 1990, 2006, 2010, 2014]; + +(for (year of years) if (year > 2000) year); +// generator function which yields 2006, 2010, and 2014 + +(for (year of years) if (year > 2000) if (year < 2010) year); +// generator function which yields 2006, the same as below: + +(for (year of years) if (year > 2000 && year < 2010) year); +// generator function which yields 2006 +</pre> + +<h3 id="Generator_comprehensions_compared_to_generator_function">Generator comprehensions compared to generator function</h3> + +<p>An easy way to understand generator comprehension syntax, is to compare it with the generator function.</p> + +<p>Example 1: Simple generator.</p> + +<pre class="brush: js">var numbers = [1, 2, 3]; + +// Generator function +(function*() { + for (let i of numbers) { + yield i * i; + } +})(); + +// Generator comprehension +(for (i of numbers) i * i ); + +// Result: both return a generator which yields [1, 4, 9] +</pre> + +<p>Example 2: Using <code>if</code> in generator.</p> + +<pre class="brush: js">var numbers = [1, 2, 3]; + +// Generator function +(function*() { + for (let i of numbers) { + if (i < 3) { + yield i * 1; + } + } +})(); + +// Generator comprehension +(for (i of numbers) if (i < 3) i); + +// Result: both return a generator which yields [1, 2]</pre> + +<h2 id="Specifications">Specifications</h2> + +<p>Generator comprehensions were initially in the ECMAScript 2015 draft, but got removed in revision 27 (August 2014). Please see older revisions of ES2015 for specification semantics.</p> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.operators.generator_comprehensions")}}</p> + +<h2 id="Differences_to_the_older_JS1.7JS1.8_comprehensions">Differences to the older JS1.7/JS1.8 comprehensions</h2> + +<div class="blockIndicator warning">JS1.7/JS1.8 comprehensions are removed from Gecko 46 ({{bug(1220564)}}).</div> + +<p><strong>Old comprehensions syntax (do not use anymore!):</strong></p> + +<pre class="brush: js example-bad">(X for (Y in Z)) +(X for each (Y in Z)) +(X for (Y of Z)) +</pre> + +<p>Differences:</p> + +<ul> + <li>ES7 comprehensions create one scope per "for" node instead of the comprehension as a whole. + <ul> + <li>Old: <code>[...(()=>x for (x of [0, 1, 2]))][1]() // 2</code></li> + <li>New: <code>[...(for (x of [0, 1, 2]) ()=>x)][1]() // 1, each iteration creates a fresh binding for x. </code></li> + </ul> + </li> + <li>ES7 comprehensions start with "for" instead of the assignment expression. + <ul> + <li>Old: <code>(i * 2 for (i of numbers))</code></li> + <li>New: <code>(for (i of numbers) i * 2)</code></li> + </ul> + </li> + <li>ES7 comprehensions can have multiple <code>if</code> and <code>for</code> components.</li> + <li>ES7 comprehensions only work with <code>{{JSxRef("Statements/for...of", "for...of")}}</code> and not with <code>{{JSxRef("Statements/for...in", "for...in")}}</code> iterations.</li> +</ul> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{JSxRef("Statements/for...of", "for...of")}}</li> + <li>{{JSxRef("Operators/Array_comprehensions", "Array comprehensions")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/grouping/index.html b/files/ko/web/javascript/reference/operators/grouping/index.html new file mode 100644 index 0000000000..a8823ff961 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/grouping/index.html @@ -0,0 +1,92 @@ +--- +title: 그룹 연산자 +slug: Web/JavaScript/Reference/Operators/Grouping +tags: + - JavaScript + - Operator + - Primary Expressions + - Reference +translation_of: Web/JavaScript/Reference/Operators/Grouping +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>그룹 연산자 <code>()</code></strong>는 표현식 내에서 평가의 우선순위를 제어합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-groupingoperator.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"> ( )</pre> + +<h2 id="설명">설명</h2> + +<p>그룹 연산자는 표현식이나 중첩 표현식 주위를 감싸는 한 쌍의 괄호로 이루어진 연산자로, 감싸인 식이 더 높은 우선순위를 갖도록 일반적인 <a href="/ko/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">연산자 우선순위</a>를 재정의합니다. 이름 그대로, 그룹 연산자는 괄호 안의 내용을 묶습니다.</p> + +<h2 id="예제">예제</h2> + +<p>다음 예제에서는 곱셈과 나눗셈 이후 덧셈과 뺄셈을 사용하는 일반적인 연산 순서를 그룹 연산자를 사용해 바꿉니다.</p> + +<pre class="brush:js">var a = 1; +var b = 2; +var c = 3; + +// 기본 우선순위 +a + b * c // 7 +// 이것과 같음 +a + (b * c) // 7 + +// 더하기를 곱하기보다 먼저 하도록 +// 우선순위 변경 +(a + b) * c // 9 + +// 이것과 같음 +a * c + b * c // 9 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-grouping-operator', 'The Grouping Operator')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-grouping-operator', 'The Grouping Operator')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11.1.6', 'The Grouping Operator')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-11.1.4', 'The Grouping Operator')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.operators.grouping")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">연산자 우선순위</a></li> + <li>{{jsxref("Operators/delete", "delete")}}</li> + <li>{{jsxref("Operators/typeof", "typeof")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/in/index.html b/files/ko/web/javascript/reference/operators/in/index.html new file mode 100644 index 0000000000..dea26b496d --- /dev/null +++ b/files/ko/web/javascript/reference/operators/in/index.html @@ -0,0 +1,188 @@ +--- +title: in 연산자 +slug: Web/JavaScript/Reference/Operators/in +tags: + - JavaScript + - Operator + - Relational Operators + - 관계형 연산자 + - 연산자 + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Operators/in +--- +<div>{{jsSidebar("Operators")}}</div> + +<p> <strong><code>in</code> 연산자</strong>는 명시된 속성이 명시된 객체에 존재하면 <code>true</code>를 반환합니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><em>속성</em> in <em>객체명</em></pre> + +<h3 id="인자">인자</h3> + +<dl> + <dt><code>속성</code></dt> + <dd>속성의 이름이나 배열의 인덱스를 뜻하는 문자열 또는 수 값입니다.</dd> +</dl> + +<dl> + <dt><code>객체명</code></dt> + <dd>객체의 이름입니다.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p> 다음 예제들은 <code>in</code> 연산자의 용도를 보여 줍니다.</p> + +<pre class="brush:js">// 배열 +var trees = new Array("redwood", "bay", "cedar", "oak", "maple"); +0 in trees // true를 반환합니다. +3 in trees // true를 반환합니다. +(1 + 2) in trees // true를 반환합니다. 연산자 우선 순위에 의하여 이 구문의 괄호는 없어도 됩니다. +6 in trees // false를 반환합니다. +"bay" in trees // false를 반환합니다. 당신은 배열의 내용이 아닌, 인덱스 값을 명시하여야 합니다. +"length" in trees // true를 반환합니다. length는 Array(배열) 객체의 속성입니다. + +// 미리 정의된 객체 +"PI" in Math // true를 반환합니다. +"P" + "I" in Math // true를 반환합니다. + +// 사용자가 정의한 객체 +var myCar = {company: "Lamborghini", model: "Lamborghini Veneno Roadster", year: 2014}; +"company" in myCar // true를 반환합니다. +"model" in myCar // true를 반환합니다. +</pre> + +<p> 당신은 반드시 <code>in</code> 연산자의 오른쪽에 객체를 명시하여야 합니다. 예컨대 당신은 <code>String</code> 생성자로 만들어진 문자열을 명시할 수 있지만 문자열 리터럴은 명시할 수 없습니다.</p> + +<pre class="brush:js">var color1 = new String("green"); +"length" in color1 // true를 반환합니다. + +var color2 = "coral"; +"length" in color2 // color2는 String 객체가 아니기에 오류를 냅니다. +</pre> + +<h3 id="제거되었거나_정의되지_않은_속성에_대하여_in_연산자_사용하기">제거되었거나 정의되지 않은 속성에 대하여 <code>in</code> 연산자 사용하기</h3> + +<p> <code>in</code> 연산자는 <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete" title="en-US/docs/JavaScript/Reference/Operators/Special/delete">delete</a></code> 연산자로 제거된 속성에 대하여 <code>false</code>를 반환합니다.</p> + +<pre class="brush:js">var myCar = {company: "Lamborghini", model: "Lamborghini Veneno Roadster", year: 2014}; +delete myCar.company; +"company" in myCar; // false를 반환합니다. + +var trees = new Array("redwood", "bay", "cedar", "oak", "maple"); +delete trees[3]; +3 in trees; // false를 반환합니다. +</pre> + +<p> 만약 당신이 속성을 {{jsxref("Global_Objects/undefined", "undefined")}}로 설정하였는데 그것을 제거하지 않으면, <code>in</code> 연산자는 그 속성에 대하여 <code>true</code>를 반환합니다.</p> + +<pre class="brush:js">var myCar = {company: "Lamborghini", model: "Lamborghini Veneno Roadster", year: 2014}; +myCar.company = undefined; +"company" in myCar; // true를 반환합니다. +</pre> + +<pre class="brush:js">var trees = new Array("redwood", "bay", "cedar", "oak", "maple"); +trees[3] = undefined; +3 in trees; // true를 반환합니다. +</pre> + +<h3 id="상속된_속성">상속된 속성</h3> + +<p> <code>in</code> 연산자는 프로토타입 체인에 의하여 접근할 수 있는 속성에 대하여 <code>true</code>를 반환합니다.</p> + +<pre class="brush:js">"toString" in {}; // true를 반환합니다. +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-relational-operators', 'Relational Operators')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-relational-operators', 'Relational Operators')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11.8.7', 'The in Operator')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES3', '#sec-11.8.7', 'The in Operator')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>초기의 정의가 담겨 있습니다. JavaScript 1.4에 추가되었습니다.</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>기능</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>지원</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>기능</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>지원</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="관련_문서">관련 문서</h2> + +<ul> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete" title="en-US/docs/JavaScript/Reference/Operators/Special/delete">delete</a></code></li> + <li>{{jsxref("Object.prototype.hasOwnProperty()")}}</li> + <li>{{jsxref("Reflect.has()")}}</li> + <li><a href="/en-US/docs/Enumerability_and_ownership_of_properties" title="/en-US/docs/Enumerability_and_ownership_of_properties">속성의, 소유와 셀 수 있는 성질</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/index.html b/files/ko/web/javascript/reference/operators/index.html new file mode 100644 index 0000000000..9605b84278 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/index.html @@ -0,0 +1,304 @@ +--- +title: 식 및 연산자 +slug: Web/JavaScript/Reference/Operators +tags: + - JavaScript + - Operators + - Overview + - Reference +translation_of: Web/JavaScript/Reference/Operators +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>이 장은 JavaScript의 모든 연산자<sup>operator</sup>, 식<sup>expression</sup> 및 키워드를 나열합니다.</p> + +<h2 id="항목별_식_및_연산자">항목별 식 및 연산자</h2> + +<p>알파벳순 목록은 왼쪽 사이드바를 보세요.</p> + +<h3 id="기본_식">기본 식</h3> + +<p>기본 키워드 및 JavaScript의 일반 식.</p> + +<dl> + <dt>{{JSxRef("Operators/this", "this")}}</dt> + <dd><code>this</code> 키워드는 실행 문맥의 특별한 속성을 가리킵니다.</dd> + <dt>{{JSxRef("Operators/function", "function")}}</dt> + <dd><code>function</code> 키워드는 함수를 정의합니다.</dd> + <dt>{{JSxRef("Operators/class", "class")}}</dt> + <dd><code>class</code> 키워드는 클래스를 정의합니다.</dd> + <dt>{{JSxRef("Operators/function*", "function*")}}</dt> + <dd><code>function*</code> 키워드는 생성기<sup>generator</sup> 함수 식을 정의합니다.</dd> + <dt>{{JSxRef("Operators/yield", "yield")}}</dt> + <dd>생성기 함수를 일시정지 및 재개합니다.</dd> + <dt>{{JSxRef("Operators/yield*", "yield*")}}</dt> + <dd>다른 생성기 함수 또는 순회가능 객체로 위임합니다.</dd> + <dt>{{JSxRef("Operators/async_function", "async function")}}</dt> + <dd><code>async function</code>은 비동기 함수 표현식을 정의합니다.</dd> +</dl> + +<dl> + <dt>{{JSxRef("Operators/await", "await")}}</dt> + <dd>비동기 함수를 일시 중지했다가 다시 시작하고 promise의 resolution/rejection을 기다립니다.</dd> +</dl> + +<dl> + <dt>{{JSxRef("Global_Objects/Array", "[]")}}</dt> + <dd>배열 초기자 및 리터럴 구문.</dd> + <dt>{{JSxRef("Operators/Object_initializer", "{}")}}</dt> + <dd>객체 초기자 및 리터럴 구문.</dd> + <dt>{{JSxRef("Global_Objects/RegExp", "/ab+c/i")}}</dt> + <dd>정규식 리터럴 구문.</dd> + <dt>{{JSxRef("Operators/Grouping", "( )")}}</dt> + <dd>그룹 연산자.</dd> +</dl> + +<h3 id="좌변_식">좌변 식</h3> + +<p>좌변값은 할당 대상입니다.</p> + +<dl> + <dt>{{JSxRef("Operators/Property_accessors", "Property accessors", "", 1)}}</dt> + <dd>속성 접근자는 객체의 속성 또는 메서드에 대한 접근 방법을 제공합니다.<br> + (<code>object.property</code>, <code>object["property"]</code>)</dd> + <dt>{{JSxRef("Operators/new", "new")}}</dt> + <dd><code>new</code> 연산자는 생성자의 인스턴스를 만듭니다.</dd> + <dt>{{JSxRef("Operators/new%2Etarget", "new.target")}}</dt> + <dd>생성자 문맥에서, <code>new.target</code>은 {{jsxref("Operators/new", "new")}}에 의해 호출된 생성자를 말합니다.</dd> + <dt>{{JSxRef("Operators/super", "super")}}</dt> + <dd><code>super</code> 키워드는 부모 생성자를 호출합니다.</dd> + <dt>{{JSxRef("Operators/Spread_syntax", "...obj")}}</dt> + <dd>전개 연산자는 (함수 호출 시) 매개변수 여럿이나, (배열 리터럴에서) 다수의 요소를 필요로 하는 곳에서 표현식을 확장합니다.</dd> +</dl> + +<h3 id="증가_및_감소">증가 및 감소</h3> + +<p>접두/접미 증감 연산자입니다.</p> + +<dl> + <dt>{{JSxRef("Operators/Increment", "A++")}}</dt> + <dd>접미 증가 연산자.</dd> + <dt>{{JSxRef("Operators/Decrement", "A--")}}</dt> + <dd>접미 감소 연산자.</dd> + <dt>{{JSxRef("Operators/Increment", "++A")}}</dt> + <dd>접두 증가 연산자.</dd> + <dt>{{JSxRef("Operators/Decrement", "--A")}}</dt> + <dd>접두 감소 연산자.</dd> +</dl> + +<h3 id="단항_연산자">단항 연산자</h3> + +<p>단항 연산은 피연산자가 하나뿐인 연산입니다.</p> + +<dl> + <dt>{{JSxRef("Operators/delete", "delete")}}</dt> + <dd><code>delete</code> 연산자는 객체에서 속성을 지웁니다.</dd> + <dt>{{JSxRef("Operators/void", "void")}}</dt> + <dd><code>void</code> 연산자는 식의 반환값을 버립니다.</dd> + <dt>{{JSxRef("Operators/typeof", "typeof")}}</dt> + <dd><code>typeof</code> 연산자는 주어진 객체의 형을 판별합니다.</dd> + <dt>{{JSxRef("Operators/Unary_plus", "+")}}</dt> + <dd>단항 더하기 연산자는 피연산자를 숫자로 변환합니다.</dd> + <dt>{{JSxRef("Operators/Unary_negation", "-")}}</dt> + <dd>단항 부정 연산자는 피연산자를 숫자로 변환한 뒤 부호를 바꿉니다.</dd> + <dt>{{JSxRef("Operators/Bitwise_NOT", "~")}}</dt> + <dd>비트 NOT 연산자.</dd> + <dt>{{JSxRef("Operators/Logical_NOT", "!")}}</dt> + <dd>논리 NOT 연산자.</dd> +</dl> + +<h3 id="산술_연산자">산술 연산자</h3> + +<p>산술 연산자는 피연산자로 숫자 값(리터럴이나 변수)을 취하고 숫자 값 하나를 반환합니다.</p> + +<dl> + <dt>{{JSxRef("Operators/Addition", "+")}}</dt> + <dd>덧셈 연산자.</dd> + <dt>{{JSxRef("Operators/Subtraction", "-")}}</dt> + <dd>뺄셈 연산자.</dd> + <dt>{{JSxRef("Operators/Division", "/")}}</dt> + <dd>나눗셈 연산자.</dd> + <dt>{{JSxRef("Operators/Multiplication", "*")}}</dt> + <dd>곱셈 연산자.</dd> + <dt>{{JSxRef("Operators/Remainder", "%")}}</dt> + <dd>나머지 연산자.</dd> +</dl> + +<dl> + <dt>{{JSxRef("Operators/Exponentiation", "**")}}</dt> + <dd>지수 연산자.</dd> +</dl> + +<h3 id="관계_연산자">관계 연산자</h3> + +<p>비교 연산자는 피연산자를 비교하고, 비교가 참인지 여부를 나타내는 {{jsxref("Boolean")}} 값을 반환합니다.</p> + +<dl> + <dt>{{JSxRef("Operators/in", "in")}}</dt> + <dd><code>in</code> 연산자는 객체에 주어진 속성이 있는지를 결정합니다.</dd> + <dt>{{JSxRef("Operators/instanceof", "instanceof")}}</dt> + <dd><code>instanceof</code> 연산자는 객체가 다른 객체의 인스턴스인지 판별합니다.</dd> + <dt>{{JSxRef("Operators/Less_than", "<")}}</dt> + <dd>작음 연산자.</dd> + <dt>{{JSxRef("Operators/Greater_than", ">")}}</dt> + <dd>큼 연산자.</dd> + <dt>{{JSxRef("Operators/Less_than_or_equal", "<=")}}</dt> + <dd>작거나 같음 연산자.</dd> + <dt>{{JSxRef("Operators/Greater_than_or_equal", ">=")}}</dt> + <dd>크거나 같음 연산자.</dd> +</dl> + +<div class="note"> +<p><strong>참고: =></strong> 는 연산자가 아니고, <a href="/ko/docs/Web/JavaScript/Reference/Functions/Arrow_functions">화살표 함수</a>의 표기법입니다.</p> +</div> + +<h3 id="같음_연산자">같음 연산자</h3> + +<p>같음 연산자의 평가 결과는 항상 {{jsxref("Boolean")}} 형으로 비교가 참인지 나타냅니다.</p> + +<dl> + <dt>{{JSxRef("Operators/Equality", "==")}}</dt> + <dd>동등 연산자.</dd> + <dt>{{JSxRef("Operators/Inequality", "!=")}}</dt> + <dd>부등 연산자.</dd> + <dt>{{JSxRef("Operators/Strict_equality", "===")}}</dt> + <dd>일치<sup>identity</sup> 연산자.</dd> + <dt>{{JSxRef("Operators/Strict_inequality", "!==")}}</dt> + <dd>불일치 연산자.</dd> +</dl> + +<h3 id="비트_시프트_연산자">비트 시프트 연산자</h3> + +<p>피연산자의 모든 비트를 이동<sup>shift</sup>하는 연산.</p> + +<dl> + <dt>{{JSxRef("Operators/Left_shift", "<<")}}</dt> + <dd>비트 좌로 시프트 연산자.</dd> + <dt>{{JSxRef("Operators/Right_shift", ">>")}}</dt> + <dd>비트 우로 시프트 연산자.</dd> + <dt>{{JSxRef("Operators/Unsigned_right_shift", ">>>")}}</dt> + <dd>비트 부호 없는 우로 시프트 연산자.</dd> +</dl> + +<h3 id="이진_비트_연산자">이진 비트 연산자</h3> + +<p>비트 연산자는 피연산자를 32비트 집합(0과 1)으로 다루고 표준 JavaScript 숫자 값을 반환합니다.</p> + +<dl> + <dt>{{JSxRef("Operators/Bitwise_AND", "&")}}</dt> + <dd>비트 AND.</dd> + <dt>{{JSxRef("Operators/Bitwise_OR", "|")}}</dt> + <dd>비트 OR.</dd> + <dt>{{JSxRef("Operators/Bitwise_XOR", "^")}}</dt> + <dd>비트 XOR.</dd> +</dl> + +<h3 id="이진_논리_연산자">이진 논리 연산자</h3> + +<p>논리 연산자는 보통 사용될 때 불리언(논리) 값으로 사용되고, 불리언 값을 반환합니다.</p> + +<dl> + <dt>{{JSxRef("Operators/Logical_AND", "&&")}}</dt> + <dd>논리 AND.</dd> + <dt>{{JSxRef("Operators/Logical_OR", "||")}}</dt> + <dd>논리 OR.</dd> + <dt>{{JSxRef("Operators/Nullish_coalescing_operator", "??")}}</dt> + <dd>Nullish 통합 연산자.</dd> +</dl> + +<h3 id="조건부삼항_연산자">조건부(삼항) 연산자</h3> + +<dl> + <dt>{{JSxRef("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}</dt> +</dl> + +<p>조건부 연산자는 조건의 논리값에 따라 두 값 중 하나를 반환합니다.</p> + +<h3 id="선택적_연결_연산자">선택적 연결 연산자</h3> + +<dl> + <dt>{{JSxRef("Operators/Optional_chaining", "?.")}}</dt> + <dd> + <p>선택적 연결 연산자는 참조가 <a href="https://developer.mozilla.org/en-US/docs/Glossary/nullish">nullish</a> (<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null"><code>null</code></a> 또는 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined"><code>undefined</code></a>) 인 경우 오류를 발생시키는 대신 <code>undefined</code>를 반환합니다.</p> + </dd> +</dl> + +<h3 id="할당_연산자">할당 연산자</h3> + +<p>할당 연산자는 값을 그 우변 피연산자의 값에 따라 좌변 피연산자에 할당합니다.</p> + +<dl> + <dt>{{JSxRef("Operators/Assignment", "=")}}</dt> + <dd>할당 연산자.</dd> + <dt>{{JSxRef("Operators/Multiplication_assignment", "*=")}}</dt> + <dd>곱셈 할당.</dd> + <dt>{{JSxRef("Operators/Exponentiation_assignment", "**=")}}</dt> + <dd>Exponentiation assignment.</dd> + <dt>{{JSxRef("Operators/Division_assignment", "/=")}}</dt> + <dd>나눗셈 할당.</dd> + <dt>{{JSxRef("Operators/Remainder_assignment", "%=")}}</dt> + <dd>나머지 할당.</dd> + <dt>{{JSxRef("Operators/Addition_assignment", "+=")}}</dt> + <dd>덧셈 할당.</dd> + <dt>{{JSxRef("Operators/Subtraction_assignment", "-=")}}</dt> + <dd>뺄셈 할당</dd> + <dt>{{JSxRef("Operators/Left_shift_assignment", "<<=")}}</dt> + <dd>좌로 이동 할당.</dd> + <dt>{{JSxRef("Operators/Right_shift_assignment", ">>=")}}</dt> + <dd>우로 이동 할당.</dd> + <dt>{{JSxRef("Operators/Unsigned_right_shift_assignment", ">>>=")}}</dt> + <dd>부호 없는 우로 이동 할당.</dd> + <dt>{{JSxRef("Operators/Bitwise_AND_assignment", "&=")}}</dt> + <dd>비트 AND 할당.</dd> + <dt>{{JSxRef("Operators/Bitwise_XOR_assignment", "^=")}}</dt> + <dd>비트 XOR 할당.</dd> + <dt>{{JSxRef("Operators/Bitwise_OR_assignment", "|=")}}</dt> + <dd>비트 OR 할당.</dd> +</dl> + +<dl> + <dt>{{JSxRef("Operators/Logical_AND_assignment", "&&=")}}</dt> + <dd>논리적 AND 할당.</dd> + <dt>{{JSxRef("Operators/Logical_OR_assignment", "||=")}}</dt> + <dd>논리적 OR 할당.</dd> + <dt>{{JSxRef("Operators/Logical_nullish_assignment", "??=")}}</dt> + <dd>논리적 nullish 할당.</dd> +</dl> + +<dl> + <dt>{{JSxRef("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}<br> + {{JSxRef("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}</dt> + <dd> + <p>구조 분해 할당은 배열 또는 객체의 속성을 배열 또는 객체 리터럴과 비슷해 보이는 구문을 사용하여 변수에 할당할 수 있게 합니다.</p> + </dd> +</dl> + +<h3 id="쉼표_연산자">쉼표 연산자</h3> + +<dl> + <dt>{{jsxref("Operators/Comma_Operator", ",")}}</dt> + <dd>쉼표 연산자는 여러 식을 단문으로 평가되게 하고 마지막 식의 결과를 반환합니다.</dd> +</dl> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.operators")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Reference/Operators/연산자_우선순위">연산자 우선순위</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/instanceof/index.html b/files/ko/web/javascript/reference/operators/instanceof/index.html new file mode 100644 index 0000000000..0ac15b7ffe --- /dev/null +++ b/files/ko/web/javascript/reference/operators/instanceof/index.html @@ -0,0 +1,161 @@ +--- +title: instanceof +slug: Web/JavaScript/Reference/Operators/instanceof +tags: + - JavaScript + - Operator + - Reference + - Relational Operators +translation_of: Web/JavaScript/Reference/Operators/instanceof +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong><code>instanceof</code> 연산자</strong>는 생성자의 <code>prototype</code> 속성이 객체의 프로토타입 체인 어딘가 존재하는지 판별합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-instanceof.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><em>object</em> instanceof <em>constructor</em></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>object</code></dt> + <dd>판별할 객체.</dd> + <dt><code>constructor</code></dt> + <dd>판별 목표 함수.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p><code>instanceof</code> 연산자는 <code>object</code>의 프로토타입 체인에 <code>constructor.prototype</code>이 존재하는지 판별합니다.</p> + +<pre class="brush: js">// 생성자 정의 +function C(){} +function D(){} + +var o = new C(); + +// true, 왜냐하면 Object.getPrototypeOf(o) === C.prototype +o instanceof C; + +// false, 왜냐하면 D.prototype이 o 객체의 프로토타입 체인에 없음 +o instanceof D; + +o instanceof Object; // true, 왜냐하면 +C.prototype instanceof Object // true + +C.prototype = {}; +var o2 = new C(); + +o2 instanceof C; // true + +// false, 왜냐하면 C.prototype이 +// 더 이상 o의 프로토타입 체인에 없음 +o instanceof C; + +D.prototype = new C(); // C를 D의 [[Prototype]] 링크로 추가 +var o3 = new D(); +o3 instanceof D; // true +o3 instanceof C; // true, 왜냐하면 이제 C.prototype이 o3의 프로토타입 체인에 존재 +</pre> + +<p><code>instanceof</code> 의 값은 생성자 <code>prototype</code> 프로퍼티의 변화에 따라 바뀔수 있으며, <code>Object.setPrototypeOf</code>의 사용함에 따라서도 바뀔 수 있음에 주의하세요. 또한 non-standard의 <code>__proto__ </code>슈도-프로퍼티도 사용할 수 있도록 만들어 줍니다.</p> + +<h3 id="instanceof_와_multiple_context_(예._프레임_또는_창)"><code>instanceof</code> 와 multiple context (예. 프레임 또는 창)</h3> + +<p>다른 스코프는 다른 실행 환경을 가집니다. 이것은 다른 스코프는 다른 고정된 요소들(다른 전역 오브젝트, 다른 생성자들 등)을 가지고 있음을 의미합니다. 이 사실은 예상치 못한 결과를 가져올 수도 있습니다. 예를 들면, [] <code>instanceof window.frames[0].Array</code>는 <code>false</code>를 리턴할 것입니다. 왜냐하면, <code>Array.prototype !== </code><code>window.frames[0].Array</code> 이며, arrays 는 상위로부터 상속받기 때문입니다. 이것은 처음에는 말이 되지 않을 수도 있습니다. 하지만, 스크립트에서 여러 프레임이나 창을 다루며, 객체를 함수를 통하여 하나의 컨텍스트에서 다른 컨텍스트로 오브젝트를 넘기게 된다면, 이건 충분히 일어날 수 있는 일이며, 아주 큰 이슈가 될 것입니다. 예를 들어, 주어진 오브젝트가 실제로 <code>Array.isArray(myObj)</code>를 사용한 Array인지 안전하게 확인 할 수 있습니다. </p> + +<div class="note"><strong>Mozilla 개발자들을 위한 메모:</strong><br> +XPCOM <code>instanceof</code> 을 사용하는 코드에서는 특별한 효과를 가집니다. : <code>obj instanceof </code><em><code>xpcomInterface </code></em>(예. <code>Components.interfaces.nsIFile</code>)가 <code>obj.QueryInterface(<em>xpcomInterface</em>)</code>를<code> </code>호출하고, 만약 QueryInterface 가 성공하면 <code>true</code> 를 리턴합니다. 이 호출의 부가 효과로는 <code>obj</code> 에서 성공적인 <code>instanceof</code> 테스트 후에 <em><code>xpcomInterface</code></em>'s의 프로퍼티를 사용할 수 있습니다. 스탠다드 JavaScript 전역속성들과는 달리, 테스트 <code>obj instanceof xpcomInterface</code>는 <code>obj</code>가 다른 스코프에 있더라도 작동합니다.</div> + +<h2 id="예제">예제</h2> + +<h3 id="String과_Date는_타입_Object이며_예외적인_경우임을_입증하기"><code>String</code>과 <code>Date</code>는 타입 <code>Object</code>이며, 예외적인 경우임을 입증하기</h3> + +<p>아래의 코드는 <code>instanceof</code> 를 <code>String</code> 과 <code>Date</code> 오브젝트도 타입 <code>Object</code>임을 확인하기 위해 사용합니다.(이 오브젝트들은 <code>Object </code>로부터 파생되었습니다.)</p> + +<p>그러나, 여기서 오브젝트 리터럴 노테이션으로 생성된 오브젝트는 예외적입니다. : 비록 프로토 타입이 정의되지 않았지만, <code>instanceof Object</code>는<code> true</code>를 리턴합니다.</p> + +<pre class="brush: js">var simpleStr = "This is a simple string"; +var myString = new String(); +var newStr = new String("String created with constructor"); +var myDate = new Date(); +var myObj = {}; + +simpleStr instanceof String; // returns false, prototype chain을 확인하고, undefined를 찾는다. +myString instanceof String; // returns true +newStr instanceof String; // returns true +myString instanceof Object; // returns true + +myObj instanceof Object; // returns true, undefined prototype 임에도 불구하고 true. +({}) instanceof Object; // returns true, 위의 경우와 동일. + +myString instanceof Date; // returns false + +myDate instanceof Date; // returns true +myDate instanceof Object; // returns true +myDate instanceof String; // returns false +</pre> + +<h3 id="mycar는_타입_Car와_타입_Object임을_입증하기"><code>mycar</code>는 타입 <code>Car</code>와 타입 <code>Object</code>임을 입증하기</h3> + +<p>다음의 코드는 <code>Car</code> 오브젝트 타입과 그 오브젝트 타입의 인스턴스 <code>mycar</code>를 생성합니다. <code>instanceof</code> 연산자는 <code>mycar</code> 오브젝트는 타입 <code>Car</code> 와 타입 <code>Object </code>라는 것은 보여줍니다.</p> + +<pre class="brush: js">function Car(make, model, year) { + this.make = make; + this.model = model; + this.year = year; +} +var mycar = new Car("Honda", "Accord", 1998); +var a = mycar instanceof Car; // returns true +var b = mycar instanceof Object; // returns true +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-relational-operators', 'Relational Operators')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-relational-operators', 'Relational Operators')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11.8.6', 'The instanceof operator')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES3', '#sec-11.8.6', 'The instanceof operator')}}</td> + <td>{{Spec2('ES3')}}</td> + <td> + <p>초기 정의. JavaScript 1.4에서 구현됨.</p> + </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.operators.instanceof")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Operators/typeof", "typeof")}}</li> + <li>{{jsxref("Symbol.hasInstance")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/new.target/index.html b/files/ko/web/javascript/reference/operators/new.target/index.html new file mode 100644 index 0000000000..9c480c1513 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/new.target/index.html @@ -0,0 +1,93 @@ +--- +title: new.target +slug: Web/JavaScript/Reference/Operators/new.target +tags: + - Classes + - ECMAScript 2015 + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Operators/new.target +--- +<div>{{JSSidebar("Operators")}}</div> + +<p><strong><code>new.target</code></strong> 속성(property)은 함수 또는 생성자가 <a href="/ko/docs/Web/JavaScript/Reference/Operators/new">new</a> 연산자를 사용하여 호출됐는지를 감지할 수 있습니다. <a href="/ko/docs/Web/JavaScript/Reference/Operators/new">new</a> 연산자로 인스턴스화된 생성자 및 함수에서, <code>new.target</code>은 생성자 또는 함수 참조를 반환합니다. 일반 함수 호출에서는, <code>new.target</code>은 {{jsxref("undefined")}}입니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-newtarget.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">new.target</pre> + +<h2 id="설명">설명</h2> + +<p><code>new.target</code> 구문은 키워드 "<code>new</code>", 점 및 속성명 "<code>target</code>"으로 구성됩니다. 보통 "<code>new.</code>"은 속성 접근을 위한 문맥(context)으로 제공하지만 여기서 "<code>new.</code>"은 정말 객체가 아닙니다. 그러나, 생성자 호출에서 <code>new.target</code>은 <code>new</code>에 의해 호출된 생성자를 가리키고 그래서 "<code>new.</code>"은 가상 문맥이 됩니다.</p> + +<p><code>new.target</code> 속성은 모든 함수가 이용할 수 있는 메타 속성입니다. <a href="/ko/docs/Web/JavaScript/Reference/Functions/애로우_펑션">화살표 함수</a>에서, <code>new.target</code>은 둘러싸는 함수의 <code>new.target</code>을 말합니다.</p> + +<h2 id="예">예</h2> + +<h3 id="함수_호출에서_new.target">함수 호출에서 new.target</h3> + +<p>일반 함수 호출(생성자 함수 호출과는 반대로)에서, <code>new.target</code>은 {{jsxref("undefined")}}입니다. 이는 함수가 생성자로서 <a href="/ko/docs/Web/JavaScript/Reference/Operators/new">new</a>로 호출된 경우를 감지할 수 있습니다.</p> + +<pre class="brush: js">function Foo() { + if (!new.target) throw "Foo() must be called with new"; + console.log("Foo instantiated with new"); +} + +Foo(); // throws "Foo() must be called with new" +new Foo(); // logs "Foo instantiated with new" +</pre> + +<h3 id="생성자에서_new.target">생성자에서 new.target</h3> + +<p>클래스 생성자에서, <code>new.target</code>은 <code>new</code>에 의해 직접 호출된 생성자를 가리킵니다. 이는 그 생성자가 부모 클래스에 있고 자식 생성자로부터 위임받은 경우도 그 경우입니다.</p> + +<pre class="brush: js">class A { + constructor() { + console.log(new.target.name); + } +} + +class B extends A { constructor() { super(); } } + +var a = new A(); // logs "A" +var b = new B(); // logs "B" +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-built-in-function-objects', 'Built-in Function Objects')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-built-in-function-objects', 'Built-in Function Objects')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.operators.new_target")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Reference/Functions">함수</a></li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Classes">클래스</a></li> + <li><code><a href="/ko/docs/Web/JavaScript/Reference/Operators/new">new</a></code></li> + <li><code><a href="/ko/docs/Web/JavaScript/Reference/Operators/this">this</a></code></li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/new/index.html b/files/ko/web/javascript/reference/operators/new/index.html new file mode 100644 index 0000000000..a28d21de18 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/new/index.html @@ -0,0 +1,187 @@ +--- +title: new operator +slug: Web/JavaScript/Reference/Operators/new +tags: + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/new +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong><code>new</code> 연산자</strong>는 사용자 정의 객체 타입 또는 내장 객체 타입의 인스턴스를 생성한다.</p> + +<p>{{EmbedInteractiveExample("pages/js/expressions-newoperator.html")}}</p> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">new <em>constructor</em>[([<em>arguments</em>])]</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>constructor</code></dt> + <dd>객체 인스턴스의 타입을 기술(명세)하는 함수</dd> +</dl> + +<dl> + <dt><code>arguments</code></dt> + <dd><code>constructor</code>와 함께 호출될 값 목록</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p>사용자 정의 객체를 생성에는 두 단계가 필요하다:</p> + +<ol> + <li>함수를 작성하여 객체 타입을 정의한다.</li> + <li><code>new</code> 연산자로 객체의 인스턴스를 생성한다.</li> +</ol> + +<p>객체의 타입을 정의하기 위해, 객체의 이름과 속성을 명세하는 함수를 만든다. 객체는 그 자체가 또 다른 객체인 속성을 가질 수 있다. 아래의 예를 본다.</p> + +<p>코드 <code>new Foo(...)</code>가 실행될 때 다음과 같은 일이 발생한다:</p> + +<ol> + <li><code>Foo.prototype</code>을 상속하는 새로운 객체가 하나 생성된다.</li> + <li>명시된 인자 그리고 새롭게 생성된 객체에 바인드된 this와 함께 생성자 함수 <code>Foo</code>가 호출된다.<code>new Foo</code>는 <code>new Foo()</code>와 동일하다. 즉 인자가 명시되지 않은 경우, 인자 없이 <code>Foo</code>가 호출된다.</li> + <li>생성자 함수에 의해 리턴된 객체는 전체 <code>new</code> 호출 결과가 된다. 만약 생성자 함수가 명시적으로 객체를 리턴하지 않는 경우, 첫 번째 단계에서 생성된 객체가 대신 사용된다.(일반적으로 생성자는 값을 리턴하지 않는다. 그러나 일반적인 객체 생성을 재정의(override)하기 원한다면 그렇게 하도록 선택할 수 있다.)</li> +</ol> + +<p>언제든 이전에 정의된 객체에 속성을 추가할 수 있다. 예를 들면, <code>car1.color = "black"</code> 구문은 <code>color</code> 속성을 <code>car1</code>에 추가하고 해당 속성에 "<code>black</code>"이란 값을 할당한다. 그러나, 이것이 다른 객체들에게는 영향을 주지 않는다. 동일한 타입의 모든 객체들에게 새로운 속성을 추가하려면, <code>Car</code> 객체 타입의 정의에 이 속성을 추가해야한다.</p> + +<p><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype">Function.prototype</a></code> 속성을 사용하여 이전에 정의된 객체 타입에 공유 속성을 추가할 수 있다. 이것은 객체 타입의 인스턴스 하나에만 적용되는 것이 아니라 이 함수로 생성하는 모든 객체와 공유하는 속성을 정의한다.</p> + +<p>다음의 코드는 <code>car</code> 타입의 모든 객체에 "<code>original color</code>" 값을 갖는 color 속성을 추가한다. 그리고 <code>car1</code> 객체 인스턴스에서만 이 값을 문자열 "<code>black</code>"으로 덮어쓴다. 더 많은 정보는 <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype">prototype</a>을 참조한다.</p> + +<pre class="brush: js">function Car() {} +car1 = new Car(); +car2 = new Car(); + +console.log(car1.color); // undefined + +Car.prototype.color = "original color"; +console.log(car1.color); // original color + +car1.color = 'black'; +console.log(car1.color); // black + +console.log(car1.__proto__.color) //original color +console.log(car2.__proto__.color) //original color +console.log(car1.color) // black +console.log(car2.color) // original color +</pre> + +<h2 id="예제">예제</h2> + +<h3 id="객체_타입과_객체_인스턴스">객체 타입과 객체 인스턴스</h3> + +<p>cars를 위한 객체 타입을 생성하기 원한다고 가정해 보자. 이 객체 타입이 <code>car</code>로 불리기 원하고, make, model, 그리고 year 속성을 갖게 하고 싶다. 이렇게 하기 위해서 다음과 같은 함수를 작성할 것이다:</p> + +<pre class="brush: js">function Car(make, model, year) { + this.make = make; + this.model = model; + this.year = year; +} +</pre> + +<p>이제 다음과 같이, <code>mycar</code>로 불리는 객체를 생성할 수 있다:</p> + +<pre class="brush: js">var mycar = new Car("Eagle", "Talon TSi", 1993); +</pre> + +<p>이 구문은 <code>mycar</code> 를 생성하고 명시한 값을 속성값으로 설정한다. 그래서 <code>mycar.make</code>의 값은 문자열 "Eagle"이고, <code>mycar.year</code>는 정수 1993이며 나머지도 마찬가지이다.</p> + +<p><code>new</code>를 호출해서 얼마든지 <code>car</code> 객체를 생성할 수 있다. 예를 들면:</p> + +<pre class="brush: js">var kenscar = new Car("Nissan", "300ZX", 1992); +</pre> + +<h3 id="속성_그_자신이_다른_객체인_객체의_속성">속성 그 자신이 다른 객체인 객체의 속성</h3> + +<p><code>person</code>이라고 불리는 객체를 다음과 같이 정의한다고 가정해보자:</p> + +<pre class="brush: js">function Person(name, age, sex) { + this.name = name; + this.age = age; + this.sex = sex; +} +</pre> + +<p>그리고 다음과 같이 두 개의 <code>person</code> 객체 인스턴스를 새롭게 생성한다:</p> + +<pre class="brush: js">var rand = new Person("Rand McNally", 33, "M"); +var ken = new Person("Ken Jones", 39, "M"); +</pre> + +<p>그런 다음 <code>owner</code> 속성을 포함하는 <code>car</code>의 정의를 다시 쓸 수 있다. 이 owner 속성은 다음과 같은 person 객체를 취한다:</p> + +<pre class="brush: js">function Car(make, model, year, owner) { + this.make = make; + this.model = model; + this.year = year; + this.owner = owner; +} +</pre> + +<p>새로운 객체의 인스턴스를 생성하기 위해 다음과 같이 사용한다:</p> + +<pre class="brush: js">var car1 = new Car("Eagle", "Talon TSi", 1993, rand); +var car2 = new Car("Nissan", "300ZX", 1992, ken); +</pre> + +<p>새로운 객체를 생성할 때 문자열이나 숫자 값을 넘겨주는 대신에, 위의 구문은 owner를 위한 매개변수로 <code>rand</code>와 <code>ken</code> 객체를 넘겨준다. <code>car2</code>의 owner name을 확인해보기 위해서, 다음의 속성에 접근할 수 있다:</p> + +<pre class="brush: js">car2.owner.name +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-new-operator', 'The new Operator')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-new-operator', 'The new Operator')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11.2.2', 'The new Operator')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES3', '#sec-11.2.2', 'The new Operator')}}</td> + <td>{{Spec2('ES3')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-11.2.2', 'The new Operator')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.operators.new")}}</p> + +<h2 id="관련_문서">관련 문서</h2> + +<ul> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("Reflect.construct()")}}</li> + <li>{{jsxref("Object.prototype")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/nullish_coalescing_operator/index.html b/files/ko/web/javascript/reference/operators/nullish_coalescing_operator/index.html new file mode 100644 index 0000000000..cae74ea29d --- /dev/null +++ b/files/ko/web/javascript/reference/operators/nullish_coalescing_operator/index.html @@ -0,0 +1,161 @@ +--- +title: Nullish coalescing operator +slug: Web/JavaScript/Reference/Operators/Nullish_coalescing_operator +translation_of: Web/JavaScript/Reference/Operators/Nullish_coalescing_operator +--- +<p>{{JSSidebar("Operators")}}</p> + +<p><strong>널 병합 연산자 (<code>??</code>)</strong> 는 왼쪽 피연산자가 {{jsxref("null")}} 또는 {{jsxref("undefined")}}일 때 오른쪽 피연산자를 반환하고, 그렇지 않으면 왼쪽 피연산자를 반환하는 논리 연산자이다.</p> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_OR_2">논리 연산자 OR (<code>||</code>)</a>와 달리, 왼쪽 피연산자가 <code>null</code> 또는 <code>undefined</code>가 아닌 <em><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Description">falsy</a> </em>값이면 반환된다. 즉, 만약 다른 변수 foo에게 기본 값을 제공하기 위해 <code>||</code>을 사용 경우, <em><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Description">falsy</a> </em>값( <code>''</code> 또는 <code>0</code>)을 사용하는 것을 고려했다면 예기치 않는 동작이 발생할 수 있다. 더 많은 예제는 아래를 보자.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-nullishcoalescingoperator.html")}}</div> + +<p class="hidden">The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.<br> + 이 예제의 추가는 <a href="https://github.com/mdn/interactive-examples/pull/1482#issuecomment-553841750">PR #1482</a>를 참조해라.</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox notranslate"><var>leftExpr</var> ?? <var>rightExpr</var> +</pre> + +<h2 id="설명">설명</h2> + +<p>널 병합 연산자는 만약 왼쪽 표현식이 {{jsxref("null")}} 또는 {{jsxref("undefined")}}인 경우, 오른쪽 표현식의 결과를 반환한다.</p> + +<h3 id="변수에_기본값_할당">변수에 기본값 할당</h3> + +<p>이전에는 변수에 기본값을 할당하고 싶을 때, 논리 연산자 OR (<code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_OR_2">||</a></code>)을 사용하는 것이 일반적인 패턴이다:</p> + +<pre class="brush: js notranslate">let foo; +... +// foo is never assigned any value so it is still undefined +let someDummyText = foo || 'Hello!';</pre> + +<p>그러나 <code>||</code> boolean 논리 연산자 때문에, 왼쪽 피연산자는 boolean으로 강제로 변환되었고 <em>falsy</em> 한 값(<code>0</code>, <code>''</code>, <code>NaN</code>, <code>null</code>, <code>undefined</code>)은 반환되지 않았다. 이 동작은 만약 <code>0</code>, <code>''</code> or <code>NaN</code>을 유효한 값으로 생각한 경우 예기치 않는 결과를 초래할 수 있다.</p> + +<pre class="brush: js notranslate">let count; +let text; +... +count = 0; +text = ""; +... +let qty = count || 42; +let message = text || "hi!"; +console.log(qty); // 42 and not 0 +console.log(message); // "hi!" and not "" +</pre> + +<p>널 병합 연산자는 첫 번째 연산자가 <code>null</code> 또는 <code>undefined</code>로 평가될 때만, 두 번째 피연산자를 반환함으로써 이러한 위험을 피한다:</p> + +<pre class="brush: js notranslate">let myText = ''; // An empty string (which is also a falsy value) + +let notFalsyText = myText || 'Hello world'; +console.log(notFalsyText); // Hello world + +let preservingFalsy = myText ?? 'Hi neighborhood'; +console.log(preservingFalsy); // '' (as myText is neither undefined nor null) +</pre> + +<h3 id="단락">단락</h3> + +<p>OR과 AND 같은 논리 연산자들과 마찬가지로, 만약 왼쪽이 <code>null</code> 또는 <code>undefined</code>가 아님이 판명되면 오른쪽 표현식은 평가되지 않는다.</p> + +<pre class="brush: js notranslate">function A() { console.log('A was called'); return undefined;} +function B() { console.log('B was called'); return false;} +function C() { console.log('C was called'); return "foo";} + +console.log( A() ?? C() ); +// logs "A was called" then "C was called" and then "foo" +// as A() returned undefined so both expressions are evaluated + +console.log( B() ?? C() ); +// logs "B was called" then "false" +// as B() returned false (and not null or undefined), the right +// hand side expression was not evaluated +</pre> + +<h3 id="No_chaining_with_AND_or_OR_operators">No chaining with AND or OR operators</h3> + +<p>AND (<code>&&</code>) 와 OR 연산자 (<code>||</code>)를 <code>??</code>와 직접적으로 결합하여 사용하는 것은 불가능하다. 이 경우 <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError">SyntaxError</a></code>가 발생된다.</p> + +<pre class="brush: js notranslate">null || undefined ?? "foo"; // raises a SyntaxError +true || undefined ?? "foo"; // raises a SyntaxError</pre> + +<p>그러나 우선 순위를 명시적으로 나타내기 위해 괄호를 사용하면 가능하다:</p> + +<pre class="brush: js notranslate">(null || undefined ) ?? "foo"; // returns "foo" +</pre> + +<h3 id="Optional_chaining_연산자.와의_관계">Optional chaining 연산자(<code>?.</code>)와의 관계</h3> + +<p>널 병합 연산자는 명확한 값으로 <code>undefined</code>과 <code>null</code>을 처리하고, <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining">optional chaining 연산자 (<code>?.</code>)</a>는 <code>null</code> or <code>undefined</code>일 수 있는 객체의 속성에 접근할 때 유용하다.</p> + +<pre class="brush: js notranslate">let foo = { someFooProp: "hi" }; + +console.log(foo.someFooProp?.toUpperCase()); // "HI" +console.log(foo.someBarProp?.toUpperCase()); // undefined +</pre> + +<h2 id="예제">예제</h2> + +<p>이 예제는 기본 값을 제공하지만 <code>null</code> or <code>undefined</code> 이외의 값을 를 유지한다. </p> + +<pre class="brush: js notranslate">function getMiscObj(){ + return { + aNullProperty: null, + emptyText: "", // this is not falsy + someNumber: 42 + }; +}; + +const miscObj = getMiscObj(); + +const newObj = {}; +newObj.propA = miscObj.aNullProperty ?? "default for A"; +newObj.propB = miscObj.emptyText ?? "default for B"; +newObj.propC = miscObj.someNumber ?? 0; + +console.log(newObj.propA); // "default for A" +console.log(newObj.propB); // "" (as the empty string is not null or undefined) +console.log(newObj.propC); // 42 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td><a href="https://tc39.es/proposal-nullish-coalescing/#top">Proposal for the "nullish coalescing" operator</a></td> + <td>Stage 3</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.operators.nullish_coalescing")}}</p> + +<h3 id="구현_진행">구현 진행</h3> + +<p>The following table provides a daily implementation status for this feature, because this feature has not yet reached cross-browser stability. The data is generated by running the relevant feature tests in <a href="https://github.com/tc39/test262">Test262</a>, the standard test suite of JavaScript, in the nightly build, or latest release of each browser's JavaScript engine.</p> + +<div>{{EmbedTest262ReportResultsTable("coalesce-expression")}}</div> + +<h2 id="참고">참고</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining">The optional chaining operator</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_OR_2">The logical OR (<code>||</code>) operator</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters">Default paramaters in functions</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/object_initializer/index.html b/files/ko/web/javascript/reference/operators/object_initializer/index.html new file mode 100644 index 0000000000..825c854848 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/object_initializer/index.html @@ -0,0 +1,302 @@ +--- +title: 객체 초기자 +slug: Web/JavaScript/Reference/Operators/Object_initializer +tags: + - ECMAScript 2015 + - ECMAScript6 + - JSON + - JavaScript + - Literal + - Methods + - Object + - Primary Expression + - computed + - mutation + - properties +translation_of: Web/JavaScript/Reference/Operators/Object_initializer +--- +<div>{{JsSidebar("Operators")}}</div> + +<p>객체는 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Object"><code>new Object()</code></a>, <code><a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Object/create">Object.create()</a></code> 또는 <em>리터럴</em> 표기법 (<em>initializer</em> 표기법)을 사용하여 초기화될 수 있습니다. 객체 초기자(object initializer)는 0개 이상인 객체 속성명 및 관련값 쌍 목록이 콤마로 분리되어 중괄호(<code>{}</code>)로 묶인 형태입니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/expressions-objectinitializer.html", "taller")}}</p> + +<div class="hidden"> +<p>The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p> +</div> + +<h2 id="구문">구문</h2> + +<pre class="brush: js notranslate">var o = {}; +var o = { a: "foo", b: 42, c: {} }; + +var a = "foo", b = 42, c = {}; +var o = { a: a, b: b, c: c }; + +var o = { + <var>property: function </var>([<var>parameters</var>]) {}, + get <var>property</var>() {}, + set <var>property</var>(<var>value</var>) {}, +}; +</pre> + +<h3 id="ECMAScript_2015의_새로운_표기법">ECMAScript 2015의 새로운 표기법</h3> + +<p>이 표기법에 대한 지원은 호환성 표를 참조해 주세요. 비지원 환경에서, 이 표기법은 구문 오류로 이어집니다.</p> + +<pre class="brush: js notranslate">// 단축 속성명 (ES2015) +let a = "foo", b = 42, c = {} +let o = { a, b, c } + +// 단축 메서드명 (ES2015) +var o = { + <var>property</var>([<var>parameters</var>]) {} +} + +// 계산된 속성명 (ES2015) +var prop = 'foo' +var o = { + [prop]: 'hey', + ['b' + 'ar']: 'there' +}</pre> + +<h2 id="설명">설명</h2> + +<p>객체 초기자는 {{jsxref("Object")}}의 초기화를 기술하는 표현식(expression)입니다. 객체는 객체를 설명하는 데 사용되는<em>속성</em>으로 구성됩니다. 객체의 속성값은 {{Glossary("primitive")}} 데이터 형 또는 다른 객체를 포함할 수 있습니다.</p> + +<h3 id="객체_리터럴_표기법_vs_JSON">객체 리터럴 표기법 vs JSON</h3> + +<p>객체 리터럴 표기법은 <strong>J</strong>ava<strong>S</strong>cript <strong>O</strong>bject <strong>N</strong>otation (<a href="/ko/docs/Glossary/JSON">JSON</a>)과 같지 않습니다. 비슷해 보이지만, 차이가 있습니다:</p> + +<ul> + <li>JSON은 <code>"property": value</code> 구문을 사용한 속성 정의<em>만</em> 허용합니다. 속성명은 큰 따옴표로 묶여야 하고, 정의는 단축(명)일 수 없습니다.</li> + <li>JSON에서 값은 오직 문자열, 숫자, 배열, <code>true</code>, <code>false</code>, <code>null</code> 또는 다른 (JSON) 객체만 될 수 있습니다.</li> + <li>함수 값(아래 "메서드" 참조)은 JSON에서 값에 할당될 수 없습니다.</li> + <li>{{jsxref("Date")}} 같은 객체는 {{jsxref("JSON.parse()")}} 후에 문자열이 됩니다.</li> + <li>{{jsxref("JSON.parse()")}}는 계산된 속성명을 거부하고 오류를 발생합니다.</li> +</ul> + +<h2 id="예제">예제</h2> + +<h3 id="객체_생성">객체 생성</h3> + +<p>속성이 없는 빈 객체는 다음과 같이 만들 수 있습니다:</p> + +<pre class="brush: js notranslate">var object = {};</pre> + +<p>그러나, 리터럴(<em>literal</em>) 또는 초기자(<em>initializer</em>) 표기법의 이점은, 빠르게 중괄호 내 속성이 있는 객체를 만들 수 있다는 것입니다. 당신은 그저 쉼표로 구분된 <strong><code>키: 값</code></strong> 쌍 목록을 표기합니다.</p> + +<p>다음 코드는 키가 <code>"foo"</code>, <code>"age"</code> 및 <code>"baz"</code>인 세 속성이 있는 객체를 만듭니다. 이들 키값은 문자열 <code>"bar"</code>, 숫자 <code>42</code> 그리고 세 번째 속성은 그 값으로 다른 객체를 갖습니다.</p> + +<pre class="brush: js notranslate">var object = { + foo: "bar", + age: 42, + baz: { myProp: 12 }, +}</pre> + +<h3 id="속성_접근">속성 접근</h3> + +<p>일단 객체를 생성하면, 읽거나 바꿀 수 있습니다. 객체 속성은 점 표기법 또는 각괄호 표기법을 사용하여 액세스될 수 있습니다. (자세한 사항은 <a href="/ko/docs/Web/JavaScript/Reference/Operators/Property_Accessors" title="property accessors">속성 접근자</a> 참조.)</p> + +<pre class="brush: js notranslate">object.foo; // "bar" +object["age"]; // 42 + +object.foo = "baz"; +</pre> + +<h3 id="속성_정의">속성 정의</h3> + +<p>우리는 이미 초기자 구문을 사용한 속성 표기법을 배웠습니다. 가끔, 객체 안에 두고 싶은 코드 속 변수가 있습니다. 다음과 같은 코드가 보입니다:</p> + +<pre class="brush: js notranslate">var a = "foo", + b = 42, + c = {}; + +var o = { + a: a, + b: b, + c: c +};</pre> + +<p>ECMAScript 2015의 경우, 똑같은 일을 할 수 있는 더 짧은 표기법이 있습니다:</p> + +<pre class="brush: js notranslate">var a = "foo", + b = 42, + c = {}; + +// 단축 속성명 (ES6) +var o = { a, b, c } + +// 다시 말해서, +console.log((o.a === {a}.a)) // true +</pre> + +<h4 id="중복된_속성명">중복된 속성명</h4> + +<p>속성이 같은 이름을 쓰는 경우, 두 번째 속성은 첫 번째를 겹쳐씁니다.</p> + +<pre class="brush: js notranslate">var a = {x: 1, x: 2}; +console.log(a); // {x: 2} +</pre> + +<p>ECMAScript 5 엄격 모드 코드에서, 중복된 속성명은 {{jsxref("SyntaxError")}}로 간주됐습니다. 런타임에 중복을 가능케 하는 속성 계산명 도입으로, ECMAScript 2015는 이 제한을 제거했습니다.</p> + +<pre class="brush: js notranslate">function haveES6DuplicatePropertySemantics(){ + "use strict"; + try { + ({ prop: 1, prop: 2 }); + + // 오류 미 발생, 중복 속성명은 엄격 모드에서 허용됨 + return true; + } catch (e) { + // 오류 발생, 중복은 엄격 모드에서 금지됨 + return false; + } +}</pre> + +<h3 id="메서드_정의">메서드 정의</h3> + +<p>객체의 속성은 <a href="/ko/docs/Web/JavaScript/Reference/Functions">함수</a>나 <a href="/ko/docs/Web/JavaScript/Reference/Functions/get">getter</a> 또는 <a href="/ko/docs/Web/JavaScript/Reference/Functions/set">setter</a> 메서드를 참조할 수도 있습니다.</p> + +<pre class="brush: js notranslate">var o = { + <var>property: function </var>([<var>parameters</var>]) {}, + get <var>property</var>() {}, + set <var>property</var>(<var>value</var>) {}, +};</pre> + +<p>ECMAScript 2015에서는, 단축 표기법을 이용할 수 있습니다, 그래서 키워드 "<code>function</code>"은 더 이상 필요치 않습니다.</p> + +<pre class="brush: js notranslate">// 단축 메서드 명 (ES6) +var o = { + <var>property</var>([<var>parameters</var>]) {}, +}</pre> + +<p>ECMAScript 2015에는 값이 생성기 함수인 속성을 간결하게 정의하는 법도 있습니다:</p> + +<pre class="brush: js notranslate">var o = { + *<var>generator</var>() { + ........... + } +};</pre> + +<p>ECMAScript 5에서는 다음과 같이 작성할 수 있습니다 (하지만 ES5는 생성기가 없음을 주의하세요):</p> + +<pre class="brush: js notranslate">var o = { + generator<var>Method: function* </var>() { + ........... + } +};</pre> + +<p>메서드에 관한 자세한 사항 및 예는, <a href="/ko/docs/Web/JavaScript/Reference/Functions/Method_definitions">메서드 정의</a> 참조.</p> + +<h3 id="계산된_속성명">계산된 속성명</h3> + +<p>ECMAScript 2015를 시작으로, 객체 초기화 구문은 계산된 속성명(computed property name)도 지원합니다. 각괄호 <code>[]</code> 안에 식을 넣을 수 있고, 식이 계산되고 그 결과가 속성명으로 사용됩니다. 이는 이미 속성을 읽고 설정하는 데 사용했을 수 있는 <a href="/ko/docs/Web/JavaScript/Reference/Operators/Property_Accessors" title="property accessor">속성 접근자</a> 구문의 각괄호 표기법을 연상시킵니다. </p> + +<p>이제 당신은 객체 리터럴에서도 같은 구문을 쓸 수 있습니다:</p> + +<pre class="brush: js notranslate">// 계산된 속성명 (ES6) +var i = 0; +var a = { + ["foo" + ++i]: i, + ["foo" + ++i]: i, + ["foo" + ++i]: i +}; + +console.log(a.foo1); // 1 +console.log(a.foo2); // 2 +console.log(a.foo3); // 3 + +var param = 'size'; +var config = { + [param]: 12, + ["mobile" + param.charAt(0).toUpperCase() + param.slice(1)]: 4 +}; + +console.log(config); // { size: 12, mobileSize: 4 }</pre> + +<h3 id="전개_속성">전개 속성</h3> + +<p><a href="https://github.com/tc39/proposal-object-rest-spread">ECMASCript의 나머지/전개 속성</a> 제안 (stage 4) 으로 <a href="https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator">전개(spread)</a> 속성이 객체 리터럴에 추가됩니다. 이 속성은 제공된 객체의 열거 가능한(enumerable) 속성을 새 객체로 복사합니다.</p> + +<p>(<code>prototype</code>을 제외하는) 얕은 복제(Shallow-cloning) 나 객체 합침(merging objects)이 이제{{jsxref("Object.assign()")}} 보다 짧은 문법으로 가능해집니다.</p> + +<pre class="notranslate">let obj1 = { foo: 'bar', x: 42 } +let obj2 = { foo: 'baz', y: 13 } + +let clonedObj = { ...obj1 } +// Object { foo: "bar", x: 42 } + +let mergedObj = { ...obj1, ...obj2 } +// Object { foo: "baz", x: 42, y: 13 }</pre> + +<div class="blockIndicator warning"> +<p>{{jsxref("Object.assign()")}}는 <a href="https://wiki.developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/set">setters</a>를 작동시키지만, 전개 연산자(spread operator)는 아니라는 걸 주목하세요!</p> +</div> + +<h3 id="프로토타입_변이">프로토타입 변이</h3> + +<p><code>__proto__: value</code> 또는 <code>"__proto__": value</code> 형태의 속성 정의는 이름이 <code>__proto__</code>인 속성을 만들지 않습니다. 대신, 제공된 값이 객체 또는 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/null"><code>null</code></a>이면, 생성된 객체의 <code>[[Prototype]]</code>을 그 값으로 바꿉니다. (값이 객체나 null이 아니면, 객체는 바뀌지 않습니다.)</p> + +<pre class="brush: js notranslate">var obj1 = {}; +assert(Object.getPrototypeOf(obj1) === Object.prototype); + +var obj2 = { __proto__: null }; +assert(Object.getPrototypeOf(obj2) === null); + +var protoObj = {}; +var obj3 = { "__proto__": protoObj }; +assert(Object.getPrototypeOf(obj3) === protoObj); + +var obj4 = { __proto__: "not an object or null" }; +assert(Object.getPrototypeOf(obj4) === Object.prototype); +assert(!obj4.hasOwnProperty("__proto__")); +</pre> + +<p>단일 프로토타입 변이(mutation)만 객체 리터럴에 허용됩니다: 다중 프로토타입 변이는 구문 오류입니다.</p> + +<p>"colon" 표기법을 쓰지 않는 속성 정의는 프로토타입 변이가 아닙니다: 그들은 다른 이름을 사용하는 비슷한 정의와 동일하게 동작하는 속성 정의입니다.</p> + +<pre class="brush: js notranslate">var __proto__ = "variable"; + +var obj1 = { __proto__ }; +assert(Object.getPrototypeOf(obj1) === Object.prototype); +assert(obj1.hasOwnProperty("__proto__")); +assert(obj1.__proto__ === "variable"); + +var obj2 = { __proto__() { return "hello"; } }; +assert(obj2.__proto__() === "hello"); + +var obj3 = { ["__prot" + "o__"]: 17 }; +assert(obj3.__proto__ === 17); +</pre> + +<h2 id="스펙">스펙</h2> + +<table> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object-initializer', 'Object Initializer')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div class="hidden"> +<p>The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> +</div> + +<p>{{Compat("javascript.operators.object_initializer")}}</p> + +<h2 id="참조">참조</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Reference/Operators/Property_Accessors">속성 접근자</a></li> + <li><code><a href="/ko/docs/Web/JavaScript/Reference/Functions/get">get</a></code> / <code><a href="/ko/docs/Web/JavaScript/Reference/Functions/set">set</a></code></li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Functions/Method_definitions">메서드 정의</a></li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Lexical_grammar" title="Lexical grammar">어휘 문법</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/optional_chaining/index.html b/files/ko/web/javascript/reference/operators/optional_chaining/index.html new file mode 100644 index 0000000000..cdf88c138b --- /dev/null +++ b/files/ko/web/javascript/reference/operators/optional_chaining/index.html @@ -0,0 +1,187 @@ +--- +title: Optional chaining +slug: Web/JavaScript/Reference/Operators/Optional_chaining +translation_of: Web/JavaScript/Reference/Operators/Optional_chaining +--- +<div>{{JSSidebar("Operators")}}</div> + +<p>{{SeeCompatTable}}</p> + +<p><strong>optional chaining</strong> 연산자 <strong><code>?.</code></strong> 는 체인의 각 참조가 유효한지 명시적으로 검증하지 않고, 연결된 객체 체인 내에 깊숙이 위치한 속성 값을 읽을 수 있다. <span class="seoSummary"><code>?.</code> 연산자는 <code>.</code> 체이닝 연산자와 유사하게 작동하지만, 만약 참조가 {{glossary("nullish")}} ({{JSxRef("null")}} 또는 {{JSxRef("undefined")}})이라면, 에러가 발생하는 것 대신에 표현식의 리턴 값은 <code>undefined</code>로 단락된다.</span> 함수 호출에서 사용될 때, 만약 주어진 함수가 존재하지 않는다면, <code>undefined</code>를 리턴한다.</p> + +<p>이것은 참조가 누락될 가능성이 있는 경우 연결된 속성으로 접근할 때 더 짧고 간단한 표현식이 생성된다. 어떤 속성이 필요한지에 대한 보증이 확실하지 않는 경우 객체의 내용을 탐색하는 동안 도움이 될 수 있다.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-optionalchainingoperator.html")}}</div> + +<div></div> + +<p class="hidden">이 대화식 예제의 소스는 GitHub repository에 저장된다. 만약 너가 대화식 예제 프로젝트에 기여하려면, <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a>를 복제(clone)하고 풀 리퀘스트를 보내라.</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox"><var>obj</var>?.<var>prop</var> +<var>obj</var>?.[<var>expr</var>] +<em>arr</em>?.[<var>index</var>] +<var>func</var>?.(<var>args</var>) +</pre> + +<h2 id="설명">설명</h2> + +<p>optional chaining 연산자는 참조나 기능이 <code>undefined</code> 또는 <code>null</code>일 수 있을 때 연결된 객체의 값에 접근하는 단순화할 수 있는 방법을 제공한다.</p> + +<p>예를 들어, 중첩된 구조를 가진 객체에서 <code>obj</code>가 있다. optional chaining이 없이 깊이 중첩된 하위 속성을 찾으려면, 다음과 같이 참조를 확인해야 한다:</p> + +<pre class="brush: js">let nestedProp = obj.first && obj.first.second;</pre> + +<p><code>obj.first</code>의 값은 <code>obj.first.second</code>의 값에 접근하기 전에 <code>null</code> (그리고 <code>undefined</code>)가 아니라는 점을 검증한다. 이는 만약에 <code>obj.first</code>를 테스트 없이 <code>obj.first.second</code> 에 직접 접근할 때 일어날 수 있는 에러를 방지한다. </p> + +<p>그러나 optional chaining 연산자(<code>?.</code>)를 사용하여, <code>obj.first.second</code> 에 접근하기 전에 <code>obj.first</code>의 상태에 따라 명시적으로 테스트하거나 단락시키지 않아도 된다:</p> + +<pre class="brush: js">let nestedProp = obj.first?.second;</pre> + +<p><code>.</code> 대신에 <code>?.</code> 연산자를 사용함으로써, 자바스크립트는 <code>obj.first.second</code>에 접근하기 전에 <code>obj.first</code>가 <code>null</code> 또는 <code>undefined</code>가 아니라는 것을 암묵적으로 확인하는 것을 알고 있다. 만약 <code>obj.first</code>가 <code>null</code> 또는 <code>undefined</code>이라면, 그 표현식은 자동으로 단락되어 <code>undefined</code>가 반환된다.</p> + +<p>이는 다음과 같다:</p> + +<pre class="brush: js">let nestedProp = ((obj.first === null || obj.first === undefined) ? undefined : obj.first.second);</pre> + +<h3 id="함수의_호출과_Optional_chaining">함수의 호출과 Optional chaining</h3> + +<p>존재하지 않을 수 있는 매서드를 호출할 때, optional chaining을 사용할 수 있다. 예를 들어, 구현 기간이나 사용자 장치에서 사용할 수 없는 기능 때문에 메서드를 사용할 수 없는 API를 사용할 경우, 유용할 수 있다.</p> + +<p>함수 호출과 optional chaining을 사용함으로써 메서드를 찾을 수 없는 경우에 예외를 발생시키는 것 대신에 그 표현식은 자동으로 <code>undefined</code>를 반환한다:</p> + +<pre class="brush: js">let result = someInterface.customMethod?.();</pre> + +<div class="blockIndicator note"> +<p><strong>메모:</strong> 만약 속성에 해당 이름이 있지만 함수가 아니라면, <code>?.</code>의 사용은 여전히 예외를 발생시킨다. {{JSxRef("TypeError")}} exception (<code>x.y</code><code> is not a function</code>).</p> +</div> + +<h4 id="optional_callbacks과_event_handlers_다루기">optional callbacks과 event handlers 다루기</h4> + +<p>만약 객체에서 <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring">destructuring assignment</a>로 callbacks 또는 fetch 메서드를 사용한다면, 그 존재 여부를 테스트하지 않으면 함수로 호출할 수 없는 존재 하지 않는 값을 가질 수 있다. <code>?.</code>을 사용하면, 다음 추가 테스트를 피할 수 있다:</p> + +<pre class="brush: js">// Written as of ES2019 +function doSomething(onContent, onError) { + try { + // ... do something with the data + } + catch (err) { + if (onError) { // Testing if onError really exists + onError(err.message); + } + } +} +</pre> + +<pre class="brush: js">// Using optional chaining with function calls +function doSomething(onContent, onError) { + try { + // ... do something with the data + } + catch (err) { + onError?.(err.message); // no exception if onError is undefined + } +} +</pre> + +<h3 id="표현식에서_Optional_chaining">표현식에서 Optional chaining</h3> + +<p>optional chaining 연산자를 속성에 표현식으로 접근할 때 대괄호 표기법(<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#Bracket_notation">the bracket notation of the property accessor</a>)을 사용할 수 있다:</p> + +<pre class="brush: js">let nestedProp = obj?.['prop' + 'Name']; +</pre> + +<h3 id="Optional_chaining으로_배열_항목에_접근하기">Optional chaining으로 배열 항목에 접근하기</h3> + +<pre class="brush: js">let arrayItem = arr?.[42];</pre> + +<h2 id="예제">예제</h2> + +<h3 id="기본_예제">기본 예제</h3> + +<p>이 예제는 해당 멤버가 없을 때, map에서 멤버 bar의 <code>name</code>의 속성 값을 찾는다. 그러므로 결과는 <code>undefined</code>이다.</p> + +<pre class="brush: js">let myMap = new Map(); +myMap.set("foo", {name: "baz", desc: "inga"}); + +let nameBar = myMap.get("bar")?.name;</pre> + +<h3 id="단락_평가">단락 평가</h3> + +<p>표현식에서 optional chaining을 사용할 때, 만약 왼쪽에 있는 피연산자가 <code>null</code> or <code>undefined</code>인 경우, 그 표현식은 평가되지 않는다. 예들 들어:</p> + +<pre class="brush: js">let potentiallyNullObj = null; +let x = 0; +let prop = potentiallyNullObj?.[x++]; + +console.log(x); // 0 x는 증가하지 않음 +</pre> + +<h3 id="optional_chaining_연산자_쌓기">optional chaining 연산자 쌓기</h3> + +<p>중첩된 구조에서는 optional chaining을 여러 번 사용할 수 있다:</p> + +<pre class="brush: js">let customer = { + name: "Carl", + details: { + age: 82, + location: "Paradise Falls" // detailed address is unknown + } +}; +let customerCity = customer.details?.address?.city; + +// … this also works with optional chaining function call +let duration = vacations.trip?.getTime?.(); +</pre> + +<h3 id="널_병합_연산자와_같이_사용하기">널 병합 연산자와 같이 사용하기</h3> + +<p>널 병합 연산자는 optional chaining를 사용한 후에 아무 값도 찾을 수 없을 때 기본 값을 주기 위해 사용될 수 있다:</p> + +<pre class="brush: js">let customer = { + name: "Carl", + details: { age: 82 } +}; +const customerCity = customer?.city ?? "Unknown city"; +console.log(customerCity); // Unknown city</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td><a href="https://tc39.es/proposal-optional-chaining/#top">Proposal for the "optional chaining" operator</a></td> + <td>Stage 4</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div> + + +<p>{{Compat("javascript.operators.optional_chaining")}}</p> +</div> + +<h3 id="구현_진행">구현 진행</h3> + +<p>The following table provides a daily implementation status for this feature, because this feature has not yet reached cross-browser stability. The data is generated by running the relevant feature tests in <a href="https://github.com/tc39/test262">Test262</a>, the standard test suite of JavaScript, in the nightly build, or latest release of each browser's JavaScript engine.</p> + +<div>{{EmbedTest262ReportResultsTable("optional-chaining")}}</div> + +<h2 id="참고">참고</h2> + +<ul> + <li>The {{JSxRef("Operators/Nullish_Coalescing_Operator", "Nullish Coalescing Operator", '', 1)}}</li> + <li><a href="https://github.com/tc39/proposals">TC39 proposals</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/pipeline_operator/index.html b/files/ko/web/javascript/reference/operators/pipeline_operator/index.html new file mode 100644 index 0000000000..42eb62e545 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/pipeline_operator/index.html @@ -0,0 +1,76 @@ +--- +title: 파이프 연산자 +slug: Web/JavaScript/Reference/Operators/Pipeline_operator +tags: + - Experimental + - JavaScript + - Operator +translation_of: Web/JavaScript/Reference/Operators/Pipeline_operator +--- +<div>{{jsSidebar("Operators")}} {{SeeCompatTable}}</div> + +<p><span class="seoSummary"><strong>파이프 연산자</strong>(<code>|></code>)는 실험적 기능(stage 1)으로, 표현식의 값을 함수에 전달합니다. 파이프 연산자를 활용하면 중첩 함수 호출을 좀 더 읽기 좋은 형식으로 작성할 수 있습니다.</span> 결과물은 문법적 설탕<sup>syntactic sugar</sup>으로, 하나의 인수를 제공하는 함수 호출은 다음 코드처럼 쓸 수 있습니다.</p> + +<pre class="brush: js">let url = "%21" |> decodeURI;</pre> + +<p>전통적인 구문에서는 아래처럼 호출합니다.</p> + +<pre class="brush: js">let url = decodeURI("%21"); +</pre> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><em>expression</em> |> <em>function</em> +</pre> + +<p>지정한 <code>expression</code>의 값이 <code>function</code>의 유일한 매개변수로 전달됩니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="함수_체이닝">함수 체이닝</h3> + +<p>파이프 연산자를 사용해, 여러 번 중첩된 함수 호출을 읽기 편한 형태로 바꿀 수 있습니다.</p> + +<pre class="brush: js">const double = (n) => n * 2; +const increment = (n) => n + 1; + +// 파이프 연산자 없이 +double(increment(double(double(5)))); // 42 + +// 파이프 연산자 사용 +5 |> double |> double |> increment |> double; // 42 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td><a href="https://tc39.github.io/proposal-pipeline-operator/#sec-intro">Pipeline operator draft</a></td> + <td>Stage 1</td> + <td>Not part of the ECMAScript specification yet.</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div> + + +<p>{{Compat("javascript.operators.pipeline")}}</p> +</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="https://github.com/tc39/proposal-pipeline-operator">Github - Proposal-pipeline-operator</a></li> + <li><a href="https://github.com/tc39/proposals">TC39 제안서</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/property_accessors/index.html b/files/ko/web/javascript/reference/operators/property_accessors/index.html new file mode 100644 index 0000000000..83ae2e0b80 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/property_accessors/index.html @@ -0,0 +1,153 @@ +--- +title: 속성 접근자 +slug: Web/JavaScript/Reference/Operators/Property_Accessors +tags: + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Property_Accessors +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>속성 접근자</strong>는 점 또는 괄호 표기법으로 객체의 속성에 접근할 수 있도록 해줍니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-propertyaccessors.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">object.property +object['property'] +</pre> + +<h2 id="설명">설명</h2> + +<p>객체는 속성의 이름을 키로 사용하는 연관 배열(다른 이름으로는 맵, 딕셔너리, 해시, 룩업 테이블)로 생각할 수 있습니다. 보통 객체의 속성을 메서드와 구별해서 말하곤 하지만, 서로의 차이는 관례에 불과합니다. 메서드는 호출할 수 있는 속성일 뿐으로, 속성의 값이 {{jsxref("Function")}}을 가리키는 참조라면 그 속성을 메서드라고 합니다.</p> + +<p>속성에 접근하는 법은 점 표기법과 괄호 표기법 두 가지가 있습니다.</p> + +<h3 id="점_표기법">점 표기법</h3> + +<pre class="brush: js">get = object.property; +object.property = set; +</pre> + +<p>이 코드에서, <code>property</code>는 유효한 JavaScript {{glossary("identifier", "식별자")}}여야합니다. 따라서 <code>object.$1</code>은 유효하지만 <code>object.1</code>은 아닙니다.</p> + +<pre class="brush: js">document.createElement('pre'); +</pre> + +<p>여기서는 "createElement"라는 이름을 가진 메서드를 <code>document</code>에서 찾아 호출하고 있습니다.</p> + +<p>소숫점 없는 숫자 리터럴의 메서드를 호출하고 싶으면, 메서드의 접근자 앞에 공백을 한 칸 추가해 점이 소숫점으로 인식되지 않도록 해야 합니다.</p> + +<pre><code>77 .toExponential(); +// or +77 +.toExponential(); +// or +(77).toExponential(); +// or +77..toExponential(); +// or +77.0.toExponential(); +// because 77. === 77.0, no ambiguity</code> +</pre> + +<h3 id="괄호_표기법">괄호 표기법</h3> + +<pre class="brush: js">get = object[property_name]; +object[property_name] = set; +</pre> + +<p>괄호 표기법에서는 <code>property_name</code>으로 문자열이나 {{jsxref("Symbol")}}을 사용할 수 있습니다. 문자열은 유효한 식별자가 아니어도 괜찮습니다. "<code>1foo</code>", "<code>!bar!</code>", 심지어 "<code> </code>"(공백)도 가능합니다.</p> + +<pre class="brush: js">document['createElement']('pre'); +</pre> + +<p>이 코드는 점 표기법의 예시와 동일합니다.</p> + +<p>괄호 앞에 공백이 올 수도 있습니다.</p> + +<pre><code>document ['createElement']('pre');</code> +</pre> + +<h3 id="속성_이름">속성 이름</h3> + +<p>속성의 이름은 문자열이나 {{jsxref("Symbol")}}입니다. 숫자 등의 다른 자료형은 문자열로 변환됩니다.</p> + +<pre class="brush: js">var object = {}; +object['1'] = 'value'; +console.log(object[1]); +</pre> + +<p>위 코드의 <code>1</code>은 <code>'1'</code>로 변환되므로, 출력 결과는 "value"입니다.</p> + +<pre class="brush: js">var foo = {unique_prop: 1}, bar = {unique_prop: 2}, object = {}; +object[foo] = 'value'; +console.log(object[bar]); +</pre> + +<p>위의 코드 역시 <code>foo</code>와 <code>bar</code>가 같은 문자열(<a href="/ko/docs/SpiderMonkey">SpiderMonkey</a> JavaScript 엔진에서는 문자열 "<code>['object Object']</code>")로 변환되므로, 출력 결과는 동일하게 "value"입니다.</p> + +<h3 id="메서드_바인딩">메서드 바인딩</h3> + +<p>메서드는 해당 메서드의 객체에 바인딩되지 않습니다. 특히 <code>this</code>는 메서드 내에 고정되지 않으므로 <code>this</code>가 항상 현재 메서드를 포함하는 객체를 참조하는건 아닙니다. 대신, <code>this</code>는 함수 호출 방식에 따라 "전달"됩니다. <a href="/ko/docs/Web/JavaScript/Reference/Operators/this#bind_메서드" title="method binding">메서드 바인딩</a>을 참고하세요.</p> + +<h3 id="eval()_주의사항"><code>eval()</code> 주의사항</h3> + +<p>JavaScript 초심자로써는 괄호 표기법을 사용할 수 있는 장소에 {{jsxref("eval", "eval()")}}을 남용하기 쉽습니다. 간혹 스크립트에서 다음과 같은 구문을 찾아볼 수 있습니다.</p> + +<pre class="brush: js">x = eval('document.forms.form_name.elements.' + strFormControl + '.value'); +</pre> + +<p><code>eval()</code>은 느리고, 가능하다면 최대한 피해야 합니다. 또한, <code>strFormControl</code>은 유효한 식별자여야 하지만, 폼 컨트롤의 ID나 이름은 식별자가 아닐 수도 있습니다. 따라서 괄호 표기법을 대신 사용하는 것이 좋습니다.</p> + +<pre class="brush: js">x = document.forms["form_name"].elements[strFormControl].value; +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-property-accessors', 'Property Accessors')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-property-accessors', 'Property Accessors')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11.2.1', 'Property Accessors')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-11.2.1', 'Property Accessors')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>초기 정의. JavaScript 1.0에서 구현됨.</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.operators.property_accessors")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Object")}}</li> + <li>{{jsxref("Object.defineProperty()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/remainder/index.html b/files/ko/web/javascript/reference/operators/remainder/index.html new file mode 100644 index 0000000000..beeb0033a3 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/remainder/index.html @@ -0,0 +1,73 @@ +--- +title: 나머지 연산자 (%) +slug: Web/JavaScript/Reference/Operators/Remainder +translation_of: Web/JavaScript/Reference/Operators/Remainder +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>나머지 연산자(<code>%</code>)는 피제수가 제수에 의해 나누어진 후, 그 나머지를 반환합니다. 항상 피제수의 부호를 따릅니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-remainder.html")}}</div> + +<div></div> + + + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox notranslate"><strong>Operator:</strong> <var>var1</var> % <var>var2</var> +</pre> + +<h2 id="예시">예시</h2> + +<h3 id="피제수의_나머지">(+)피제수의 나머지</h3> + +<pre class="brush: js notranslate"> 12 % 5 // 2 + 1 % -2 // 1 + 1 % 2 // 1 + 2 % 3 // 2 +5.5 % 2 // 1.5 +</pre> + +<h3 id="-피제수의_나머지">(-)피제수의 나머지</h3> + +<pre class="brush: js notranslate">-12 % 5 // -2 +-1 % 2 // -1 +-4 % 2 // -0</pre> + +<h3 id="NaN의_나머지">NaN의 나머지</h3> + +<pre class="brush: js notranslate">NaN % 2 // NaN</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-multiplicative-operators', 'Remainder operator')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.operators.remainder")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Addition">Addition operator</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Subtraction">Subtraction operator</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Division">Division operator</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Multiplication">Multiplication operator</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation">Exponentiation operator</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment">Increment operator</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Decrement">Decrement operator</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_negation">Unary negation operator</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus">Unary plus operator</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/spread_syntax/index.html b/files/ko/web/javascript/reference/operators/spread_syntax/index.html new file mode 100644 index 0000000000..d2174a53bb --- /dev/null +++ b/files/ko/web/javascript/reference/operators/spread_syntax/index.html @@ -0,0 +1,255 @@ +--- +title: 전개 구문 +slug: Web/JavaScript/Reference/Operators/Spread_syntax +tags: + - ECMAScript 2015 + - Iterator + - JavaScript + - Reference + - Spread + - 전개 연산자 +translation_of: Web/JavaScript/Reference/Operators/Spread_syntax +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>전개 구문</strong>을 사용하면 배열이나 문자열과 같이 반복 가능한 문자를 0개 이상의 인수 (함수로 호출할 경우) 또는 요소 (배열 리터럴의 경우)로 확장하여, 0개 이상의 키-값의 쌍으로 객체로 확장시킬 수 있습니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-spreadsyntax.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<p>함수 호출:</p> + +<pre class="syntaxbox">myFunction(...iterableObj); +</pre> + +<p>배열 리터럴과 문자열:</p> + +<pre class="syntaxbox">[...iterableObj, '4', 'five', 6];</pre> + +<p>객체 리터럴(ECMAScript 2018에서 추가):</p> + +<pre class="syntaxbox">let objClone = { ...obj };</pre> + +<h2 id="예제">예제</h2> + +<h3 id="함수_호출에서의_전개">함수 호출에서의 전개</h3> + +<h4 id="apply()_대체"><code>apply()</code> 대체</h4> + +<p>일반적으로 배열의 엘리먼트를 함수의 인수로 사용하고자 할 때 {{jsxref( "Function.prototype.apply()")}} 를 사용하였습니다.</p> + +<pre class="brush: js">function myFunction(x, y, z) { } +var args = [0, 1, 2]; +myFunction.apply(null, args);</pre> + +<p>전개 구문을 사용해 위 코드는 다음과 같이 작성될 수 있습니다.</p> + +<pre class="brush: js">function myFunction(x, y, z) { } +var args = [0, 1, 2]; +myFunction(...args);</pre> + +<p>인수 목록의 모든 인수는 전개 구문을 사용할 수 있으며, 여러번 사용될 수도 있습니다.</p> + +<pre class="brush: js">function myFunction(v, w, x, y, z) { } +var args = [0, 1]; +myFunction(-1, ...args, 2, ...[3]);</pre> + +<h4 id="new에_적용"><code>new</code>에 적용</h4> + +<p>{{jsxref("Operators/new", "new")}}를 사용해 생성자를 호출 할 때, 배열과 <code>apply</code> (<code>apply</code> 는 <code>[[Call]]</code> 을 하지만 <code>[[Construct]]</code> 는 그렇지 않음) 를 <strong>직접</strong> 사용하는 것은 불가했습니다. 하지만, 전개 구문 덕분에 배열을 <code>new</code> 와 함께 쉽게 사용될 수 있습니다.</p> + +<pre class="brush: js">var dateFields = [1970, 0, 1]; // 1 Jan 1970 +var d = new Date(...dateFields); +</pre> + +<p>전개 구문 없이 파라미터의 배열과 함께 <code>new</code>를 사용하려면, 부분적인 어플리케이션을 통해 <strong>간접적</strong>으로 해야 합니다.</p> + +<pre class="brush: js">function applyAndNew(constructor, args) { + function partial () { + return constructor.apply(this, args); + }; + if (typeof constructor.prototype === "object") { + partial.prototype = Object.create(constructor.prototype); + } + return partial; +} + + +function myConstructor () { + console.log("arguments.length: " + arguments.length); + console.log(arguments); + this.prop1="val1"; + this.prop2="val2"; +}; + +var myArguments = ["hi", "how", "are", "you", "mr", null]; +var myConstructorWithArguments = applyAndNew(myConstructor, myArguments); + +console.log(new myConstructorWithArguments); +// (internal log of myConstructor): arguments.length: 6 +// (internal log of myConstructor): ["hi", "how", "are", "you", "mr", null] +// (log of "new myConstructorWithArguments"): {prop1: "val1", prop2: "val2"}</pre> + +<h3 id="배열_리터럴에서의_전개">배열 리터럴에서의 전개</h3> + +<h4 id="더_강력한_배열_리터럴">더 강력한 배열 리터럴</h4> + +<p>전개 구문 없이, 이미 존재하는 배열을 일부로 하는 새로운 배열을 생성하기에, 배열 리터럴 문법은 더 이상 충분하지 않으며 {{jsxref("Array.prototype.push", "push()")}}, {{jsxref("Array.prototype.splice", "splice()")}}, {{jsxref("Array.prototype.concat", "concat()")}} 등의 조합을 사용하는 대신 명령형 코드를 사용해야 했습니다. 전개 구문으로 이는 훨씬 더 간결해졌습니다.</p> + +<pre class="brush: js">var parts = ['shoulders', 'knees']; +var lyrics = ['head', ...parts, 'and', 'toes']; +// ["head", "shoulders", "knees", "and", "toes"] +</pre> + +<p>인수 목록을 위한 spread 처럼, <code>...</code> 은 배열 리터럴의 어디에서든 사용될 수 있으며 여러번 사용될 수도 있습니다.</p> + +<h4 id="배열_복사">배열 복사</h4> + +<pre class="brush: js">var arr = [1, 2, 3]; +var arr2 = [...arr]; // arr.slice() 와 유사 +arr2.push(4); + +// arr2 은 [1, 2, 3, 4] 이 됨 +// arr 은 영향을 받지 않고 남아 있음 +</pre> + +<div class="blockIndicator note"> +<p><strong>참고:</strong> Spread 문법은 배열을 복사할 때 1 레벨 깊이에서 효과적으로 동작합니다. 그러므로, 다음 예제와 같이 다차원 배열을 복사하는것에는 적합하지 않을 수 있습니다. ({{jsxref("Object.assign()")}} 과 전개 구문이 동일합니다)</p> +</div> + +<pre class="brush: js">var a = [[1], [2], [3]]; +var b = [...a]; +b.shift().shift(); // 1 +// 이제 배열 a 도 영향을 받음: [[], [2], [3]] +</pre> + +<h4 id="배열을_연결하는_더_나은_방법">배열을 연결하는 더 나은 방법</h4> + +<p>{{jsxref("Array.prototype.concat()")}} 은 배열을 존재하는 배열의 끝에 이어붙이는데 종종 사용됩니다. 전개 구문 없이, 이는 다음과 같이 작성됩니다.</p> + +<pre class="brush: js">var arr1 = [0, 1, 2]; +var arr2 = [3, 4, 5]; +// arr2 의 모든 항목을 arr1 에 붙임 +arr1 = arr1.concat(arr2);</pre> + +<p>전개 구문을 사용해 이는 다음과 같아집니다.</p> + +<pre class="brush: js">var arr1 = [0, 1, 2]; +var arr2 = [3, 4, 5]; +arr1 = [...arr1, ...arr2]; // arr1 은 이제 [0, 1, 2, 3, 4, 5] +</pre> + +<p>{{jsxref("Array.prototype.unshift()")}}는 존재하는 배열의 시작 지점에 배열의 값들을 삽입하는데 종종 사용됩니다. 전개 구문 없이, 이는 다음과 같이 작성됩니다.</p> + +<pre class="brush: js">var arr1 = [0, 1, 2]; +var arr2 = [3, 4, 5]; +// arr2 의 모든 항목을 arr1 의 앞에 붙임 +Array.prototype.unshift.apply(arr1, arr2) // arr1 은 이제 [3, 4, 5, 0, 1, 2] 가 됨</pre> + +<p>전개 구문으로, 이는 다음과 같아집니다.</p> + +<pre class="brush: js">var arr1 = [0, 1, 2]; +var arr2 = [3, 4, 5]; +arr1 = [...arr2, ...arr1]; // arr1 은 이제 [3, 4, 5, 0, 1, 2] 가 됨 +</pre> + +<div class="blockIndicator note"> +<p><strong>참고</strong>: <code>unshift()</code>와 달리, 위 예제는 새로운 <code>arr1</code>을 만들며 기존 배열을 변형하지 않습니다.</p> +</div> + +<h3 id="객체_리터럴에서의_전개">객체 리터럴에서의 전개</h3> + +<p><a href="https://github.com/tc39/proposal-object-rest-spread">ECMAScript의 Rest/Spread 프로퍼티</a> 제안 (stage 4) 은 <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Object_initializer">객체 리터럴</a>에 속성 전개를 추가합니다. 이는 제공된 객체가 소유한 열거형 프로퍼티를 새로운 객체로 복사합니다.</p> + +<p>얕은 복제(prototype 제외) 또는 객체의 병합은 이제 {{jsxref("Object.assign()")}} 보다 더 짧은 문법을 사용해 가능합니다.</p> + +<pre class="brush: js">var obj1 = { foo: 'bar', x: 42 }; +var obj2 = { foo: 'baz', y: 13 }; + +var clonedObj = { ...obj1 }; +// Object { foo: "bar", x: 42 } + +var mergedObj = { ...obj1, ...obj2 }; +// Object { foo: "baz", x: 42, y: 13 }</pre> + +<p>{{jsxref("Object.assign()")}} 은 <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/set">setters</a> 를 트리거하지만 전개 구문은 그렇지 않음을 유의합니다.</p> + +<p>{{jsxref("Object.assign()")}} 함수를 대체하거나 흉내낼 수 없음을 유의합니다.</p> + +<pre><code>var obj1 = { foo: 'bar', x: 42 }; +var obj2 = { foo: 'baz', y: 13 }; +const merge = ( ...objects ) => ( { ...objects } ); + +var mergedObj = merge ( obj1, obj2); +// Object { 0: { foo: 'bar', x: 42 }, 1: { foo: 'baz', y: 13 } } + +var mergedObj = merge ( {}, obj1, obj2); +// Object { 0: {}, 1: { foo: 'bar', x: 42 }, 2: { foo: 'baz', y: 13 } }</code></pre> + +<p>위 예제에서, 전개 구문은 예상대로 동작하지 않습니다. 나머지 매개변수로 인해, 인수 배열을 객체 리터럴로 전개합니다.</p> + +<h3 id="이터러블_전용">이터러블 전용</h3> + +<p>전개 구문 (spread 프로퍼티인 경우 제외) 은 <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator">iterable</a> 객체에만 적용됩니다.</p> + +<pre class="brush: js">var obj = {'key1': 'value1'}; +var array = [...obj]; // TypeError: obj is not iterable +</pre> + +<h3 id="많은_값과_Spread">많은 값과 Spread</h3> + +<p>함수 호출에서 spread 문법을 사용할 때, 자바스크립트 엔진의 인수 길이 제한을 초과하지 않도록 주의합니다. 자세한 내용은 <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Function/apply" title="The apply() method calls a function with a given this value, and arguments provided as an array (or an array-like object)."><code>apply()</code></a> 를 보세요.</p> + +<h2 id="나머지_구문_(매개변수)">나머지 구문 (매개변수)</h2> + +<p>나머지 구문은 전개 구문과 정확히 같아보이지만, 대신 배열이나 객체를 분해할 때 사용됩니다. 어떤 면에서, 나머지 구문은 전개 구문과 반대입니다. 전개는 배열을 그 엘리먼트로 '확장' 하는 반면, 나머지는 여러 엘리먼트를 수집하며 이를 하나의 엘리먼트로 '압축' 합니다. <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/rest_parameters">나머지 매개변수</a> 문서를 보세요.</p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">코멘트</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ES2015', '#sec-array-initializer')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>명세의 여러 섹션에서 정의 됨: <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-array-initializer">Array Initializer</a>, <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-argument-lists">Argument Lists</a></td> + </tr> + <tr> + <td>{{SpecName('ES2018', '#sec-object-initializer')}}</td> + <td>{{Spec2('ES2018')}}</td> + <td><a href="http://www.ecma-international.org/ecma-262/9.0/#sec-object-initializer">Object Initializer</a> 에서 정의됨</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array-initializer')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>변동 없음.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object-initializer')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>변동 없음.</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.operators.spread")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/rest_parameters">나머지 매개변수</a> (또한 ‘<code>...</code>’)</li> + <li><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Function/apply">fn.apply</a> (또한 ‘<code>...</code>’)</li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/super/index.html b/files/ko/web/javascript/reference/operators/super/index.html new file mode 100644 index 0000000000..fbcb123c57 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/super/index.html @@ -0,0 +1,176 @@ +--- +title: super +slug: Web/JavaScript/Reference/Operators/super +tags: + - Classes + - JavaScript + - Left-hand-side expressions + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/super +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>super</strong> 키워드는 부모 오브젝트의 함수를 호출할 때 사용됩니다.</p> + +<p><code>super.prop</code> 와 <code>super[expr]</code> 표현식은 <a href="/ko/docs/Web/JavaScript/Reference/Classes">클래스</a> 와 <a href="/ko/docs/Web/JavaScript/Reference/Operators/Object_initializer">객체리터럴</a>의 어떠한 <a href="/ko/docs/Web/JavaScript/Reference/Functions/Method_definitions">메서드 정의</a> 방법에서도 유효합니다.</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox">super([arguments]); // 부모 생성자 호출 +super.functionOnParent([arguments]); +</pre> + +<h2 id="설명">설명</h2> + +<p>생성자에서는 <code>super</code> 키워드 하나만 사용되거나 <code>this</code> 키워드가 사용되기 전에 호출되어야 합니다. 또한 <code>super</code> 키워드는 부모 객체의 함수를 호출하는데 사용될 수 있습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="클래스에서_super_사용하기">클래스에서 <code>super</code> 사용하기</h3> + +<p>이 예제는 옆의 링크에서 발췌하였습니다. <a href="https://github.com/GoogleChrome/samples/blob/gh-pages/classes-es6/index.html">classes sample</a> (<a href="https://googlechrome.github.io/samples/classes-es6/index.html">live demo</a>).</p> + +<pre class="brush: js">class Polygon { + constructor(height, width) { + this.name = 'Polygon'; + this.height = height; + this.width = width; + } + sayName() { + console.log('Hi, I am a ', this.name + '.'); + } +} + +class Square extends Polygon { + constructor(length) { + this.height; // 참조오류가 발생합니다. super가 먼저 호출되어야 합니다. + + // 여기서, 부모클래스의 생성자함수를 호출하여 높이값을 넘겨줍니다. + // Polygon의 길이와 높이를 넘겨줍니다. + super(length, length); + + // 참고: 파생 클래스에서 super() 함수가 먼저 호출되어야 + // 'this' 키워드를 사용할 수 있습니다. 그렇지 않을 경우 참조오류가 발생합니다. + this.name = 'Square'; + } + + get area() { + return this.height * this.width; + } + + set area(value) { + this.area = value; + } +}</pre> + +<h3 id="정적_메서드에서_Super_호출">정적 메서드에서 Super 호출</h3> + +<p><a href="/ko/docs/Web/JavaScript/Reference/Classes/static">static</a> 메서드에서도 super를 호출할 수 있습니다.</p> + +<pre class="brush: js">class Human { + constructor() {} + static ping() { + return 'ping'; + } +} + +class Computer extends Human { + constructor() {} + static pingpong() { + return super.ping() + ' pong'; + } +} +Computer.pingpong(); // 'ping pong' +</pre> + +<h3 id="super의_속성_삭제">super의 속성 삭제</h3> + +<p><a href="/ko/docs/Web/JavaScript/Reference/Operators/delete">delete 연산자</a>를 사용할 수 없으며 <code>super.prop</code> 또는 <code>super[expr]</code> 표현식을 사용하여 부모 클래스의 속성을 삭제할 경우 {{jsxref("ReferenceError")}} 오류가 발생합니다.</p> + +<pre class="brush: js">class Base { + constructor() {} + foo() {} +} +class Derived { + constructor() {} + delete() { + delete super.foo; + } +} + +new Derived().delete(); // 참조오류: 'super'완 관련된 삭제가 유효하지 않습니다. </pre> + +<h3 id="Super.prop은_non-writable_속성을_덮어_쓸_수_없습니다"><code>Super.prop</code>은 non-writable 속성을 덮어 쓸 수 없습니다</h3> + +<p>예를 들어 {{jsxref("Object.defineProperty")}}로 속성을 정의할 때, <code>super</code>의 속성 값을 덮어 쓸 수 없습니다.</p> + +<pre class="brush: js">class X { + constructor() { + Object.defineProperty(this, "prop", { + configurable: true, + writable: false, + value: 1 + }); + } + f() { + super.prop = 2; + } +} + +var x = new X(); +x.f(); +console.log(x.prop); // 1 +</pre> + +<h3 id="객체_리터럴에서_super.prop_사용하기">객체 리터럴에서 <code>super.prop</code> 사용하기</h3> + +<p>Super는 <a href="/ko/docs/Web/JavaScript/Reference/Operators/Object_initializer">object initializer / literal</a> 표기법에서 사용할 수 있습니다. 아래의 예제에서, 두개의 객체는 메서드를 정의합니다. 두번째 객체에서, <code>super</code>는 첫번째 객체의 메서드를 호출합니다. 이 예제는 {{jsxref("Object.setPrototypeOf()")}}를 이용하여 obj2 prototype에 obj1을 세팅하여, <code>super</code>가 obj1의 method1을 찾을 수 있도록 합니다.</p> + +<pre class="brush: js">var obj1 = { + method1() { + console.log("method 1"); + } +} + +var obj2 = { + method2() { + super.method1(); + } +} + +Object.setPrototypeOf(obj2, obj1); +obj2.method2(); // logs "method 1" +</pre> + +<h2 id="명세서">명세서</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-super-keyword', 'super')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-super-keyword', 'super')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.operators.super")}}</p> + +<h2 id="참고">참고</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Reference/Classes">Classes</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/this/index.html b/files/ko/web/javascript/reference/operators/this/index.html new file mode 100644 index 0000000000..8a2807a5d8 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/this/index.html @@ -0,0 +1,398 @@ +--- +title: this +slug: Web/JavaScript/Reference/Operators/this +tags: + - JavaScript + - Operator + - Primary Expressions + - Reference +translation_of: Web/JavaScript/Reference/Operators/this +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>JavaScript에서 <strong>함수의 <code>this</code> 키워드</strong>는 다른 언어와 조금 다르게 동작합니다. 또한 <a href="/ko/docs/Web/JavaScript/Reference/Strict_mode">엄격 모드</a>와 비엄격 모드에서도 일부 차이가 있습니다.</p> + +<p>대부분의 경우 <code>this</code>의 값은 함수를 호출한 방법에 의해 결정됩니다. 실행중에는 할당으로 설정할 수 없고 함수를 호출할 때 마다 다를 수 있습니다. ES5는 {{jsxref('Operators/this', "함수를 어떻게 호출했는지 상관하지 않고 <code>this</code> 값을 설정할 수 있는")}} {{jsxref("Function.prototype.bind()", "bind")}} 메서드를 도입했고, ES2015는 스스로의 <code>this</code> 바인딩을 제공하지 않는 <a href="/ko/docs/Web/JavaScript/Reference/Functions/%EC%95%A0%EB%A1%9C%EC%9A%B0_%ED%8E%91%EC%85%98">화살표 함수</a>를 추가했습니다(이는 렉시컬 컨텍스트안의 <code>this</code>값을 유지합니다).</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-this.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox notranslate">this</pre> + +<h3 id="값">값</h3> + +<p>실행 컨텍스트(global, function 또는 eval)의 프로퍼티는 비엄격 모드에서 항상 객체를 참조하며, 엄격 모드에서는 어떠한 값이든 될 수 있습니다.</p> + +<h2 id="전역_문맥">전역 문맥</h2> + +<p>전역 실행 문맥<sup>global execution context</sup>에서 <code>this</code>는 엄격 모드 여부에 관계 없이 전역 객체를 참조합니다.</p> + +<pre class="brush: js notranslate">// 웹 브라우저에서는 window 객체가 전역 객체 +console.log(this === window); // true + +a = 37; +console.log(window.a); // 37 + +this.b = "MDN"; +console.log(window.b) // "MDN" +console.log(b) // "MDN"</pre> + +<div class="blockIndicator note"> +<p><strong>노트:</strong> global {{jsxref("globalThis")}} 프로퍼티를 사용하여 코드가 실행중인 현재 컨텍스트와 관계없이 항상 전역 객체를 얻을 수 있습니다.</p> +</div> + +<h2 id="함수_문맥">함수 문맥</h2> + +<p>함수 내부에서 <code>this</code>의 값은 함수를 호출한 방법에 의해 좌우됩니다.</p> + +<h3 id="단순_호출">단순 호출</h3> + +<p>다음 예제는 엄격 모드가 아니며 <code>this</code>의 값이 호출에 의해 설정되지 않으므로, 기본값으로 브라우저에서는 {{domxref("Window", "window")}}인 전역 객체를 참조합니다.</p> + +<pre class="brush: js notranslate">function f1() { + return this; +} + +// 브라우저 +f1() === window; // true + +// Node.js +f1() === global; // true</pre> + +<p>반면에 엄격 모드에서 <code>this</code> 값은 실행 문맥에 진입하며 설정되는 값을 유지하므로 다음 예시에서 보여지는 것 처럼 <code>this</code>는 <code>undefined</code>로 남아있습니다.</p> + +<pre class="brush: js notranslate">function f2(){ + "use strict"; // 엄격 모드 참고 + return this; +} + +f2() === undefined; // true +</pre> + +<div class="blockIndicator note"> +<p>두번째 예제에서 <code>f2</code>를 객체의 메서드나 속성(예: <code>window.f2()</code>)으로써가 아닌 직접 호출했기 때문에 <code>this</code>는 {{jsxref("undefined")}}여야 합니다. 그러나 엄격 모드를 처음 지원하기 시작한 초기 브라우저에서는 구현하지 않았고, <code>window</code> 객체를 잘못 반환했습니다.</p> +</div> + +<p><code>this</code>의 값을 한 문맥에서 다른 문맥으로 넘기려면 다음 예시와 같이 {{jsxref("Function.prototype.call()", "call()")}}이나 {{jsxref("Function.prototype.apply", "apply()")}}를 사용하세요.</p> + +<p><strong>예시 1</strong></p> + +<pre class="brush: js notranslate" dir="rtl">// call 또는 apply의 첫 번째 인자로 객체가 전달될 수 있으며 this가 그 객체에 묶임 +var obj = {a: 'Custom'}; + +// 변수를 선언하고 변수에 프로퍼티로 전역 window를 할당 +var a = 'Global'; + +function whatsThis() { + return this.a; // 함수 호출 방식에 따라 값이 달라짐 +} + +whatsThis(); // this는 'Global'. 함수 내에서 설정되지 않았으므로 global/window 객체로 초기값을 설정한다. +whatsThis.call(obj); // this는 'Custom'. 함수 내에서 obj로 설정한다. +whatsThis.apply(obj); // this는 'Custom'. 함수 내에서 obj로 설정한다. +</pre> + +<p><strong>예시 2</strong></p> + +<pre class="brush: js notranslate">function add(c, d) { + return this.a + this.b + c + d; +} + +var o = {a: 1, b: 3}; + +// 첫 번째 인자는 'this'로 사용할 객체이고, +// 이어지는 인자들은 함수 호출에서 인수로 전달된다. +add.call(o, 5, 7); // 16 + +// 첫 번째 인자는 'this'로 사용할 객체이고, +// 두 번째 인자는 함수 호출에서 인수로 사용될 멤버들이 위치한 배열이다. +add.apply(o, [10, 20]); // 34 +</pre> + +<p>비엄격 모드에서 <code>this</code>로 전달된 값이 객체가 아닌 경우, <code>call</code>과 <code>apply</code>는 이를 객체로 변환하기 위한 시도를 합니다. <code>null</code>과 <code>undefined</code> 값은 전역 객체가 됩니다. <code>7</code>이나 <code>'foo'</code>와 같은 원시값은 관련된 생성자를 사용해 객체로 변환되며, 따라서 원시 숫자 <code>7</code>은 <code>new Number(7)</code>에 의해 객체로 변환되고 문자열 <code>'foo'</code>는 <code>new String('foo')</code>에 의해 객체로 변환됩니다.</p> + +<pre class="brush: js notranslate">function bar() { + console.log(Object.prototype.toString.call(this)); +} + +bar.call(7); // [object Number] +bar.call('foo'); // [object String] +bar.call(undefined); // [object global] +</pre> + +<h3 id="bind_메서드"><code>bind</code> 메서드</h3> + +<p>ECMAScript 5는 {{jsxref("Function.prototype.bind")}}를 도입했습니다. <code>f.bind(someObject)</code>를 호출하면 <code>f</code>와 같은 본문(코드)과 범위를 가졌지만 this는 원본 함수를 가진 새로운 함수를 생성합니다. 새 함수의 <code>this</code>는 호출 방식과 상관없이 영구적으로<code>bind()</code>의 첫 번째 매개변수로 고정됩니다.</p> + +<pre class="brush: js notranslate">function f() { + return this.a; +} + +var g = f.bind({a: 'azerty'}); +console.log(g()); // azerty + +var h = g.bind({a: 'yoo'}); // bind는 한 번만 동작함! +console.log(h()); // azerty + +var o = {a: 37, f: f, g: g, h: h}; +console.log(o.a, o.f(), o.g(), o.h()); // 37, 37, azerty, azerty</pre> + +<h3 id="화살표_함수">화살표 함수</h3> + +<p><a href="/ko/docs/Web/JavaScript/Reference/Functions/%EC%95%A0%EB%A1%9C%EC%9A%B0_%ED%8E%91%EC%85%98">화살표 함수</a>에서 <code>this</code>는 자신을 감싼 정적 범위<sup>lexical context</sup>입니다. 전역 코드에서는 전역 객체를 가리킵니다.</p> + +<pre class="brush: js notranslate">var globalObject = this; +var foo = (() => this); +console.log(foo() === globalObject); // true</pre> + +<div class="blockIndicator note"> +<p><strong>참고</strong>: 화살표 함수를 <code>call()</code>, <code>bind()</code>, <code>apply()</code>를 사용해 호출할 때 <code>this</code>의 값을 정해주더라도 무시합니다. 사용할 매개변수를 정해주는 건 문제 없지만, 첫 번째 매개변수(<code>thisArg</code>)는 <code>null</code>을 지정해야 합니다.</p> +</div> + +<pre class="brush: js notranslate">// 객체로서 메서드 호출 +var obj = {func: foo}; +console.log(obj.func() === globalObject); // true + +// call을 사용한 this 설정 시도 +console.log(foo.call(obj) === globalObject); // true + +// bind를 사용한 this 설정 시도 +foo = foo.bind(obj); +console.log(foo() === globalObject); // true</pre> + +<p>어떤 방법을 사용하든 <code>foo</code>의 <code>this</code>는 생성 시점의 것으로 설정됩니다(위 예시에서는 global 객체). 다른 함수 내에서 생성된 화살표 함수에도 동일하게 적용됩니다. <code>this</code>는 싸여진 렉시컬 컨텍스트의 것으로 유지됩니다.</p> + +<pre class="brush: js notranslate">// this를 반환하는 메소드 bar를 갖는 obj를 생성합니다. +// 반환된 함수는 화살표 함수로 생성되었으므로, +// this는 감싸진 함수의 this로 영구적으로 묶입니다. +// bar의 값은 호출에서 설정될 수 있으며, 이는 반환된 함수의 값을 설정하는 것입니다. +var obj = { + bar: function() { + var x = (() => this); + return x; + } +}; + +// obj의 메소드로써 bar를 호출하고, this를 obj로 설정 +// 반환된 함수로의 참조를 fn에 할당 +var fn = obj.bar(); + +// this 설정 없이 fn을 호출하면, +// 기본값으로 global 객체 또는 엄격 모드에서는 undefined +console.log(fn() === obj); // true + +// 호출 없이 obj의 메소드를 참조한다면 주의하세요. +var fn2 = obj.bar; +// 화살표 함수의 this를 bar 메소드 내부에서 호출하면 +// fn2의 this를 따르므로 window를 반환할것입니다. +console.log(fn2()() == window); // true</pre> + +<p>위 예시에서, <code>obj.bar</code>에 할당된 함수(익명 함수 A라고 지칭)는 화살표 함수로 생성된 다른 함수(익명 함수 B라고 지칭)를 반환합니다. 결과로써 함수 B가 호출될 때 B의 <code>this</code>는 영구적으로 <code>obj.bar</code>(함수 A)의 <code>this</code>로 설정됩니다. 반환됨 함수(함수 B)가 호출될 때, <code>this</code>는 항상 초기에 설정된 값일 것입니다. 위 코드 예시에서, 함수 B의 <code>this</code>는 함수 A의 <code>this</code>인 <code>obj</code>로 설정되므로, 일반적으로 <code>this</code>를 <code>undefined</code>나 global 객체로 설정하는 방식으로 호출할 때도(또는 이전 예시에서처럼 global 실행 컨텍스트에서 다른 방법을 사용할 때에도) obj의 설정은 유지됩니다.</p> + +<h3 id="객체의_메서드로서">객체의 메서드로서</h3> + +<p>함수를 어떤 객체의 메서드로 호출하면 <code>this</code>의 값은 그 객체를 사용합니다.</p> + +<p>다음 예제에서 <code>o.f()</code>를 실행할 때 <code>o</code> 객체가 함수 내부의 <code>this</code>와 연결됩니다.</p> + +<pre class="brush: js notranslate">var o = { + prop: 37, + f: function() { + return this.prop; + } +}; + +console.log(o.f()); // 37 +</pre> + +<p>이 행동이 함수가 정의된 방법이나 위치에 전혀 영향을 받지 않는 것에 유의해라. 이전 예제에서, <code>o</code> 의 정의 중 <code>f</code> 함수를 구성원으로 내부에 정의 하였다. 그러나, 간단하게 함수를 먼저 정의하고 나중에 <code>o.f</code>를 추가할 수 있다. 이렇게 하면 동일한 동작 결과 이다 :</p> + +<pre class="brush: js notranslate">var o = {prop: 37}; + +function independent() { + return this.prop; +} + +o.f = independent; + +console.log(o.f()); // logs 37 +</pre> + +<p>이는 함수가 <code>o</code>의 멤버 <code>f</code>로 부터 호출 된 것만이 중요하다는 것을 보여준다.</p> + +<p>마찬가지로, 이 <code>this</code> 바인딩은 가장 즉각으로 멤버 대상에 영향을 받는다. 다음 예제에서, 함수를 실행할 때, 객체 <code>o.b</code>의 메소드 <code>g</code> 로서 호출한다. 이것이 실행되는 동안, 함수 내부의 <code>this</code>는 <code>o.b</code>를 나타낸다. 객체는 그 자신이 <code>o</code>의 멤버 중 하나라는 사실은 중요하지 않다. 가장 즉각적인 참조가 중요한 것이다.</p> + +<pre class="brush: js notranslate">o.b = {g: independent, prop: 42}; +console.log(o.b.g()); // logs 42 +</pre> + +<h4 id="객체의_프로토타입_체인에서의_this">객체의 프로토타입 체인에서의 <code>this</code></h4> + +<p>같은 개념으로 객체의 프로토타입 체인 어딘가에 정의한 메서드도 마찬가지입니다. 메서드가 어떤 객체의 프로토타입 체인 위에 존재하면, <code>this</code>의 값은 그 객체가 메서드를 가진 것 마냥 설정됩니다.</p> + +<pre class="brush: js notranslate">var o = { + f:function() { return this.a + this.b; } +}; +var p = Object.create(o); +p.a = 1; +p.b = 4; + +console.log(p.f()); // 5 +</pre> + +<p>이 예제에서, <code>f</code> 속성을 가지고 있지 않은 변수 <code>p</code>가 할당된 객체는, 프로토타입으로 부터 상속받는다. 그러나 그것은 결국 <code>o</code>에서 <code>f</code> 이름을 가진 멤버를 찾는 되는 문제가 되지 않는다 ; <code>p.f</code>를 찾아 참조하기 시작하므로, 함수 내부의 <code>this</code>는<code> p</code> 처럼 나타나는 객체 값을 취한다. 즉, <code>f</code>는 <code>p</code>의 메소드로서 호출된 이후로, <code>this</code>는 <code>p</code>를 나타낸다. 이것은 JavaScript의 프로토타입 상속의 흥미로운 기능이다.</p> + +<h4 id="접근자와_설정자의_this">접근자와 설정자의 <code>this</code></h4> + +<p>다시 한 번 같은 개념으로, 함수를 접근자와 설정자에서 호출하더라도 동일합니다. 접근자나 설정자로 사용하는 함수의 <code>this</code>는 접근하거나 설정하는 속성을 가진 객체로 묶입니다.</p> + +<pre class="brush: js notranslate">function sum() { + return this.a + this.b + this.c; +} + +var o = { + a: 1, + b: 2, + c: 3, + get average() { + return (this.a + this.b + this.c) / 3; + } +}; + +Object.defineProperty(o, 'sum', { + get: sum, enumerable: true, configurable: true}); + +console.log(o.average, o.sum); // 2, 6 +</pre> + +<h3 id="생성자로서">생성자로서</h3> + +<p>함수를 {{jsxref("Operators/new", "new")}} 키워드와 함께 생성자로 사용하면 <code>this</code>는 새로 생긴 객체에 묶입니다.</p> + +<div class="blockIndicator note"> +<p>While the default for a constructor is to return the object referenced by <code>this</code>, it can instead return some other object (if the return value isn't an object, then the <code>this</code> object is returned).</p> +</div> + +<pre class="brush: js notranslate">/* + * Constructors work like this: + * + * function MyConstructor(){ + * // Actual function body code goes here. + * // Create properties on |this| as + * // desired by assigning to them. E.g., + * this.fum = "nom"; + * // et cetera... + * + * // If the function has a return statement that + * // returns an object, that object will be the + * // result of the |new| expression. Otherwise, + * // the result of the expression is the object + * // currently bound to |this| + * // (i.e., the common case most usually seen). + * } + */ + +function C() { + this.a = 37; +} + +var o = new C(); +console.log(o.a); // 37 + + +function C2() { + this.a = 37; + return {a: 38}; +} + +o = new C2(); +console.log(o.a); // 38 +</pre> + +<h3 id="DOM_이벤트_처리기로서">DOM 이벤트 처리기로서</h3> + +<p>함수를 이벤트 처리기로 사용하면 this는 이벤트를 발사한 요소로 설정됩니다. 일부 브라우저는 {{domxref("EventTarget.addEventListener()", "addEventListener()")}} 외의 다른 방법으로 추가한 처리기에 대해선 이 규칙을 따르지 않습니다.</p> + +<pre class="brush: js notranslate">// 처리기로 호출하면 관련 객체를 파랗게 만듦 +function bluify(e) { + // 언제나 true + console.log(this === e.currentTarget); + // currentTarget과 target이 같은 객체면 true + console.log(this === e.target); + this.style.backgroundColor = '#A5D9F3'; +} + +// 문서 내 모든 요소의 목록 +var elements = document.getElementsByTagName('*'); + +// 어떤 요소를 클릭하면 파랗게 변하도록 +// bluify를 클릭 처리기로 등록 +for (var i = 0; i < elements.length; i++) { + elements[i].addEventListener('click', bluify, false); +}</pre> + +<h3 id="인라인_이벤트_핸들러에서">인라인 이벤트 핸들러에서</h3> + +<p>코드를 인라인 이벤트 처리기로 사용하면 <code>this</code>는 처리기를 배치한 DOM 요소로 설정됩니다.</p> + +<pre class="brush: js notranslate"><button onclick="alert(this.tagName.toLowerCase());"> + this 표시 +</button></pre> + +<p>위의 경고창은 <code>button</code>을 보여줍니다. 다만 바깥쪽 코드만 <code>this</code>를 이런 방식으로 설정합니다.</p> + +<pre class="brush: js notranslate"><button onclick="alert((function() { return this; })());"> + 내부 this 표시 +</button></pre> + +<p>위의 경우, 내부 함수의 this는 정해지지 않았으므로 전역/<code>window</code> 객체를 반환합니다. 즉 비엄격 모드에서 <code>this</code>를 설정하지 않은 경우의 기본값입니다.</p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-this-keyword', 'The this keyword')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-this-keyword', 'The this keyword')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11.1.1', 'The this keyword')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES3', '#sec-11.1.1', 'The this keyword')}}</td> + <td>{{Spec2('ES3')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-11.1.1', 'The this keyword')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.operators.this")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Reference/Strict_mode">엄격 모드</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/typeof/index.html b/files/ko/web/javascript/reference/operators/typeof/index.html new file mode 100644 index 0000000000..acdd2eedbb --- /dev/null +++ b/files/ko/web/javascript/reference/operators/typeof/index.html @@ -0,0 +1,227 @@ +--- +title: typeof +slug: Web/JavaScript/Reference/Operators/typeof +tags: + - JavaScript + - Operator + - Reference + - Unary +translation_of: Web/JavaScript/Reference/Operators/typeof +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong><code>typeof</code></strong> 연산자는 피연산자의 평가 전 자료형을 나타내는 문자열을 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-typeof.html")}}</div> + +<p class="hidden">이 예제 소스는 GitHub repository에 존재합니다. 만약 이 예제에 기여하고 싶다면 <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a>를 클론해서 pull request를 보내주세요.</p> + +<h2 id="구문">구문</h2> + +<p><code>typeof</code> 연산자는 피연산자 앞에 위치합니다.</p> + +<pre>typeof <var>operand</var> +typeof(<var>operand</var>)</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>operand</code></dt> + <dd>자료형을 가져올 객체 또는 {{glossary("Primitive", "원시값")}}을 나타내는 표현식.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p><code>typeof</code>가 반환할 수 있는 값을 아래 표에서 볼 수 있습니다. 자료형과 원시값에 대한 자세한 정보는 <a href="/ko/docs/Web/JavaScript/Data_structures">JavaScript 자료형과 자료구조</a> 페이지를 참고하세요.</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Type</th> + <th scope="col">Result</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{glossary("Undefined")}}</td> + <td><code>"undefined"</code></td> + </tr> + <tr> + <td>{{glossary("Null")}}</td> + <td><code>"object"</code> ({{anch("null", "아래")}} 참고)</td> + </tr> + <tr> + <td>{{glossary("Boolean")}}</td> + <td><code>"boolean"</code></td> + </tr> + <tr> + <td>{{glossary("Number")}}</td> + <td><code>"number"</code></td> + </tr> + <tr> + <td>{{glossary("BigInt")}}</td> + <td><code>"bigint"</code></td> + </tr> + <tr> + <td>{{glossary("String")}}</td> + <td><code>"string"</code></td> + </tr> + <tr> + <td>{{glossary("Symbol")}} (ECMAScript 2015에서 추가)</td> + <td><code>"symbol"</code></td> + </tr> + <tr> + <td>호스트 객체 (JS 환경에서 제공)</td> + <td><em>구현체마다 다름</em></td> + </tr> + <tr> + <td>{{glossary("Function")}} 객체 (ECMA-262 표현으로는 [[Call]]을 구현하는 객체)</td> + <td><code>"function"</code></td> + </tr> + <tr> + <td>다른 모든 객체</td> + <td><code>"object"</code></td> + </tr> + </tbody> +</table> + +<div class="blockIndicator note"> +<p><strong>Note:</strong> ECMAScript 2019 and older permitted implementations to have <code>typeof</code> return any implementation-defined string value for non-callable non-standard exotic objects.</p> + +<p>The only known browser to have actually taken advantage of this is old Internet Explorer (see <a href="#IE-specific_notes">below</a>).</p> +</div> + +<h2 id="예제">예제</h2> + +<pre class="brush:js">// Numbers +typeof 37 === 'number'; +typeof 3.14 === 'number'; +typeof Math.LN2 === 'number'; +typeof Infinity === 'number'; +typeof NaN === 'number'; // Despite being "Not-A-Number" +typeof Number(1) === 'number'; // but never use this form! + +typeof 42n === 'bigint'; + + +// Strings +typeof "" === 'string'; +typeof "bla" === 'string'; +typeof (typeof 1) === 'string'; // typeof always returns a string +typeof String("abc") === 'string'; // but never use this form! + + +// Booleans +typeof true === 'boolean'; +typeof false === 'boolean'; +typeof Boolean(true) === 'boolean'; // but never use this form! + + +// Symbols +typeof Symbol() === 'symbol' +typeof Symbol('foo') === 'symbol' +typeof Symbol.iterator === 'symbol' + + +// Undefined +typeof undefined === 'undefined'; +typeof declaredButUndefinedVariable === 'undefined'; +typeof undeclaredVariable === 'undefined'; + + +// Objects +typeof {a:1} === 'object'; + +// use <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray" title="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray">Array.isArray</a> or Object.prototype.toString.call +// to differentiate regular objects from arrays +typeof [1, 2, 4] === 'object'; + +typeof new Date() === 'object'; + + +// The following is confusing. Don't use! +typeof new Boolean(true) === 'object'; +typeof new Number(1) === 'object'; +typeof new String("abc") === 'object'; + + +// Functions +typeof function(){} === 'function'; +typeof class C {} === 'function'; +typeof Math.sin === 'function'; +</pre> + +<h2 id="추가_정보">추가 정보</h2> + +<h3 id="null"><code>null</code></h3> + +<pre class="brush:js">// This stands since the beginning of JavaScript +typeof null === 'object'; +</pre> + +<p>자바스크립트를 처음 구현할 때, 자바스크립트 값은 타입 태그와 값으로 표시되었습니다. 객체의 타입 태그는 0이었습니다. <code>null</code>은 Null pointer(대부분의 플랫폼에서 <code>0x00</code>)로 표시되었습니다. 그 결과 null은 타입 태그로 0을 가지며, 따라서 <code>typeof</code>는 object를 반환합니다. (<a href="https://2ality.com/2013/10/typeof-null.html">참고 문서</a>)</p> + +<p>ECMAScript에 수정이 제안(opt-in을 통해)되었으나 <a href="https://web.archive.org/web/20160331031419/http://wiki.ecmascript.org:80/doku.php?id=harmony:typeof_null">거절되었습니다</a>. 제안된 것은 다음과 같습니다. <code>typeof null === 'null'.</code></p> + +<h3 id="Regular_expressions">Regular expressions</h3> + +<p>Callable regular expressions were a non-standard addition in some browsers.</p> + +<pre class="brush:js">typeof /s/ === 'function'; // Chrome 1-12 Non-conform to ECMAScript 5.1 +typeof /s/ === 'object'; // Firefox 5+ Conform to ECMAScript 5.1 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-typeof-operator', 'The typeof Operator')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-typeof-operator', 'The typeof Operator')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11.4.3', 'The typeof Operator')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES3', '#sec-11.4.3', 'The typeof Operator')}}</td> + <td>{{Spec2('ES3')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-11.4.3', 'The typeof Operator')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.operators.typeof")}}</p> + +<h2 id="IE_참고사항">IE 참고사항</h2> + +<p>On IE 6, 7, and 8 a lot of host objects are objects and not functions. For example:</p> + +<pre class="brush: js">typeof alert === 'object'</pre> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Operators/instanceof", "instanceof")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/void/index.html b/files/ko/web/javascript/reference/operators/void/index.html new file mode 100644 index 0000000000..79fe2c1837 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/void/index.html @@ -0,0 +1,122 @@ +--- +title: void +slug: Web/JavaScript/Reference/Operators/void +tags: + - JavaScript + - Operator + - Reference + - Unary +translation_of: Web/JavaScript/Reference/Operators/void +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong><code>void</code> 연산자</strong>는 주어진 표현식을 평가하고 {{jsxref("undefined")}}를 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-voidoperator.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">void <em>expression</em></pre> + +<h2 id="설명">설명</h2> + +<p><code>void</code>는 값을 생성하는 표현식을 평가해서 {{jsxref("undefined")}}를 반환합니다.</p> + +<p>오직 <code>undefined</code> 원시값을 얻기 위해 <code>void 0</code> 또는 <code>void(0)</code>처럼 사용하는 경우도 볼 수 있습니다. 이런 경우 전역 {{jsxref("undefined")}}를 대신 사용해도 됩니다.</p> + +<p><code>void</code> 연산자의 <a href="/ko/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">우선순위</a>도 유념해야 합니다. <a href="/ko/docs/Web/JavaScript/Reference/Operators/Grouping">그룹 연산자</a>(괄호)를 사용하면 <code>void</code> 연산자를 사용한 식의 평가 과정을 더 명확하게 보일 수 있습니다.</p> + +<pre class="brush: js">void 2 == '2'; // undefined == '2', false +void (2 == '2'); // void true, undefined +</pre> + +<h2 id="IIFE">IIFE</h2> + +<p>즉시 실행 함수 표현식({{Glossary("IIFE")}})을 사용할 때 <code>void</code>를 사용하면 <code>function</code> 키워드를 선언문이 아니라 표현식처럼 간주하도록 강제할 수 있습니다.</p> + +<pre class="brush: js">void function iife() { + var bar = function () {}; + var baz = function () {}; + var foo = function () { + bar(); + baz(); + }; + var biz = function () {}; + + foo(); + biz(); +}(); +</pre> + +<h2 id="JavaScript_URI">JavaScript URI</h2> + +<p><code>javascript:</code>로 시작하는 URI를 지원하는 브라우저에서는, URI에 있는 코드의 평가 결과가 {{jsxref("undefined")}}가 아니라면 페이지의 콘텐츠를 반환 값으로 대체합니다. <code>void</code> 연산자를 사용하면 <code>undefined</code>를 반환할 수 있습니다. 다음 예제를 확인하세요.</p> + +<pre class="brush: html"><a href="javascript:void(0);"> + 클릭해도 아무 일도 없음 +</a> +<a href="javascript:void(document.body.style.backgroundColor='green');"> + 클릭하면 배경색이 녹색으로 +</a> +</pre> + +<div class="blockIndicator note"> +<p><strong>참고</strong>: <code>javascript:</code> 의사 프로토콜보다 이벤트 처리기와 같은 대체재 사용을 권장합니다.</p> +</div> + +<h2 id="새지_않는_화살표_함수">새지 않는 화살표 함수</h2> + +<p>Arrow functions introduce a short-hand braceless syntax that returns an expression. This can cause unintended side effects by returning the result of a function call that previously returned nothing. To be safe, when the return value of a function is not intended to be used, it can be passed to the void operator to ensure that (for example) changing APIs do not cause arrow functions' behaviors to change.</p> + +<pre class="brush: js">button.onclick = () => void doSomething();</pre> + +<p>This ensures the return value of <code>doSomething</code> changing from <code>undefined</code> to <code>true</code> will not change the behavior of this code.</p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-void-operator', 'The void Operator')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-void-operator', 'The void Operator')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11.4.2', 'The void Operator')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES3', '#sec-11.4.2', 'The void Operator')}}</td> + <td>{{Spec2('ES3')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-11.4.2', 'The void Operator')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.operators.void")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("undefined")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/yield/index.html b/files/ko/web/javascript/reference/operators/yield/index.html new file mode 100644 index 0000000000..ef884816d2 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/yield/index.html @@ -0,0 +1,182 @@ +--- +title: yield +slug: Web/JavaScript/Reference/Operators/yield +tags: + - ECMAScript 2015 + - Generators + - Iterator + - JavaScript + - Operator + - 반복자 + - 생성기 +translation_of: Web/JavaScript/Reference/Operators/yield +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><code>yield </code>키워드는 제너레이터 함수 ({{jsxref("Statements/function*", "function*")}} 또는 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/Legacy_generator_function">레거시 generator </a>함수)를 중지하거나 재개하는데 사용됩니다.</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox">[<em>rv</em>] = <strong>yield</strong> [<em>expression</em>];</pre> + +<dl> + <dt><code>expression</code></dt> + <dd>제너레이터 함수에서 <a href="/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterator">제너레이터 프로토콜</a>을 통해 반환할 값을 정의합니다. 값이 생략되면, <code>undefined를 반환합니다.</code></dd> + <dt><code>rv</code></dt> + <dd> + <p>제너레이터 실행을 재개 하기 위해서, optional value을 제너레이터의 <code>next()</code> 메서드로 전달하여 반환합니다.</p> + </dd> +</dl> + +<h2 id="설명">설명</h2> + +<p><code>yield 키워드</code>는 제너레이터 함수의 실행을 중지시키거나 그리고 <code>yield</code> 키워드 뒤에오는 표현식[expression]의 값은 제너레이터의 caller로 반환된다. 제너레이터 버전의 <code>return</code> 키워드로 생각 할 수 있다.</p> + +<p><code>yield</code> 키워드는 실질적으로 value 와 done 이라는 두 개의 속성을 가진 <code>IteratorResult</code> 객체를 반환한다. <code>value</code> 속성은 <code>yield</code> 표현(expression)의 실행 결과를 나타내고, <code>done</code> 속성은 제너레이터 함수가 완전히 종료되었는지 여부를 불린(Boolean) 형태로 보여줍니다. </p> + +<p>yield 표현식에서 중지되면 ,제너레이터의 next()가 메서드가 호출될 때까지 제너레이터의 코드 실행이 중지된다. 제너레이터의 next()메서드를 호출할 때마다 제너레이터는 실행을 재개하며 그리고 다음의 같은 경우에 진행될 때 실행된다:</p> + +<ul> + <li> <code>yield 는</code> 제너레이터가 한번 멈추게 하고 제너레이터의 새로운 값을 반환한다. 다음번의 next()가 호출된 후, yield 이후에 선언된 코드가 바로 실행된다.</li> + <li>{{jsxref("Statements/throw", "throw")}}는 제네레이터에서 예외를 설정할 때 사용된다. 예외가 발생할 경우 제너레이터의 전체적으로 실행이 중지되고, 그리고 다시 켜는 것이 일반적으로 실행됩니다.</li> + <li> + <p>제너레이터 함수가 종료가 되었다; 이 경우, 제너레이터 실행이 종료되고 <code>IteratorResult는 </code>caller 로 값이 {{jsxref("undefined")}}이고 done의 값이 true 로 리턴한다.</p> + </li> + <li> + <p>{{jsxref("Statements/return", "return")}} 문에 도달했다. 이 경우에는, 이 값이 종료되고 <code>IteratorResult는 </code>caller 로<code> return</code> 문에 의해 반환되는 값과 done의 값이 true 로 리턴한다.</p> + </li> +</ul> + +<p>만약에 optional value가 제너레이터의 next() 메서드로 전달되면, optional value는 제너레이터의 현재 yield의 연산으로 반환되는 값이 된다.</p> + +<p>generator 코드 경로, yield연산자, {{jsxref("Generator.prototype.next()")}}에 이르기까지 새로운 시작 값을 지정할 수 있는 능력과 제네레이터는 커다란 힘과 제어를 제공한다.</p> + +<h2 id="예시">예시</h2> + +<p>다음 코드는 제너레이터 함수의 선언의 예시이다.</p> + +<pre class="brush: js">function* foo(){ + var index = 0; + while (index <= 2) // when index reaches 3, + // yield's done will be true + // and its value will be undefined; + yield index++; +}</pre> + +<p>제너레이터 함수가 정의되면 , 아래 코드와 보여지는 것처럼 iterator로 만들어 사용할 수 있다.</p> + +<pre class="brush: js">var iterator = foo(); +console.log(iterator.next()); // { value: 0, done: false } +console.log(iterator.next()); // { value: 1, done: false } +console.log(iterator.next()); // { value: 2, done: false } +console.log(iterator.next()); // { value: undefined, done: true }</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ES6', '#', 'Yield')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#', 'Yield')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>39</td> + <td>{{CompatGeckoDesktop("26.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>IteratorResult</code> object instead of throwing</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("29.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("26.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{ CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>IteratorResult</code> object instead of throwing</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("29.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Firefox-specific_notes">Firefox-specific notes</h2> + +<ul> + <li>Starting with Gecko 29 {{geckoRelease(29)}}, the completed generator function no longer throws a {{jsxref("TypeError")}} "generator has already finished". Instead, it returns an <code>IteratorResult</code> object like <code>{ value: undefined, done: true }</code> ({{bug(958951)}}).</li> + <li>Starting with Gecko 33 {{geckoRelease(33)}}, the parsing of the <code>yield</code> expression has been updated to conform with the latest ES6 specification ({{bug(981599)}}): + <ul> + <li>The expression after the <code>yield</code> keyword is optional and omitting it no longer throws a {{jsxref("SyntaxError")}}: <code>function* foo() { yield; }</code></li> + </ul> + </li> +</ul> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Guide/The_Iterator_protocol">The Iterator protocol</a></li> + <li>{{jsxref("Statements/function*", "function*")}}</li> + <li>{{jsxref("Operators/function*", "function* expression")}}</li> + <li>{{jsxref("Operators/yield*", "yield*")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/yield_star_/index.html b/files/ko/web/javascript/reference/operators/yield_star_/index.html new file mode 100644 index 0000000000..3bbb10146d --- /dev/null +++ b/files/ko/web/javascript/reference/operators/yield_star_/index.html @@ -0,0 +1,164 @@ +--- +title: yield* +slug: Web/JavaScript/Reference/Operators/yield* +tags: + - ECMAScript 2015 + - Generators + - Iterable + - Iterator + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/yield* +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong><code>yield*</code> 표현식</strong>은 다른 {{jsxref("Statements/function*", "generator")}} 또는 이터러블(iterable) 객체에 yield를 위임할 때 사용됩니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-yieldasterisk.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">yield* [[<em>expression</em>]];</pre> + +<dl> + <dt><code>expression</code></dt> + <dd>이터러블(iterable) 객체를 반환하는 표현식.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p>yield* 표현은 피연산자를 반복하고 반환되는 값을 yield합니다.</p> + +<p>yield* 표현 자체의 값은 반복자(iterator)가 종료될 때 반환되는 값입니다. (i.e., done이 true일 때)</p> + +<h2 id="예제">예제</h2> + +<h3 id="다른_생성기(generator)에_위임하기">다른 생성기(generator)에 위임하기</h3> + +<p>다음 코드는, next() 호출을 통해 g1()으로부터 yield 되는 값을 g2()에서 yield 되는 것처럼 만듭니다.</p> + +<pre class="brush: js">function* g1() { + yield 2; + yield 3; + yield 4; +} + +function* g2() { + yield 1; + yield* g1(); + yield 5; +} + +var iterator = g2(); + +console.log(iterator.next()); // { value: 1, done: false } +console.log(iterator.next()); // { value: 2, done: false } +console.log(iterator.next()); // { value: 3, done: false } +console.log(iterator.next()); // { value: 4, done: false } +console.log(iterator.next()); // { value: 5, done: false } +console.log(iterator.next()); // { value: undefined, done: true } +</pre> + +<h3 id="다른_이터러블(iterable)_객체">다른 이터러블(iterable) 객체</h3> + +<p>생성기 객체 말고도, yield*는 다른 반복 가능한 객체도 yield 할 수 있습니다. e.g. 배열, 문자열 또는 arguments 객체</p> + +<pre class="brush: js">function* g3() { + yield* [1, 2]; + yield* "34"; + yield* Array.from(arguments); +} + +var iterator = g3(5, 6); + +console.log(iterator.next()); // { value: 1, done: false } +console.log(iterator.next()); // { value: 2, done: false } +console.log(iterator.next()); // { value: "3", done: false } +console.log(iterator.next()); // { value: "4", done: false } +console.log(iterator.next()); // { value: 5, done: false } +console.log(iterator.next()); // { value: 6, done: false } +console.log(iterator.next()); // { value: undefined, done: true } +</pre> + +<h3 id="yield*_표현_자체의_값"><code>yield*</code> 표현 자체의 값</h3> + +<p><code>yield*</code> 는 구문이 아닌 표현입니다. 따라서 값으로 평가됩니다.</p> + +<pre class="brush: js">function* g4() { + yield* [1, 2, 3]; + return "foo"; +} + +var result; + +function* g5() { + result = yield* g4(); +} + +var iterator = g5(); + +console.log(iterator.next()); // { value: 1, done: false } +console.log(iterator.next()); // { value: 2, done: false } +console.log(iterator.next()); // { value: 3, done: false } +console.log(iterator.next()); // { value: undefined, done: true }, + // g4() 는 여기서 { value: "foo", done: true }를 반환합니다 + +console.log(result); // "foo" +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ES2015', '#sec-generator-function-definitions-runtime-semantics-evaluation', 'Yield')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-generator-function-definitions-runtime-semantics-evaluation', 'Yield')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.operators.yield_star")}}</p> + +<h2 id="Firefox에_한정된_내용">Firefox에 한정된 내용</h2> + +<ul> + <li>Gecko 33 {{geckoRelease(33)}} 부터, yield 표현 구문 분석이 최신 ES6 표준에 맞추도록 업데이트 되었습니다 ({{bug(981599)}}): + <ul> + <li>개행 제한이 이제 구현되었습니다. 개행이 없는 "yield" 와 "*"만 인정됩니다. 다음과 같은 코드는 {{jsxref("SyntaxError")}}를 발생시킵니다: + <pre class="brush: js">function* foo() { + yield + *[]; +}</pre> + </li> + </ul> + </li> +</ul> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Guide/The_Iterator_protocol">The Iterator protocol</a></li> + <li>{{jsxref("Statements/function*", "function*")}}</li> + <li>{{jsxref("Operators/function*", "function* expression")}}</li> + <li>{{jsxref("Operators/yield", "yield")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/논리_연산자(logical_operators)/index.html b/files/ko/web/javascript/reference/operators/논리_연산자(logical_operators)/index.html new file mode 100644 index 0000000000..2e1140eed5 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/논리_연산자(logical_operators)/index.html @@ -0,0 +1,249 @@ +--- +title: 논리 연산자 +slug: Web/JavaScript/Reference/Operators/논리_연산자(Logical_Operators) +tags: + - JavaScript + - Logic + - Not + - Operator + - Reference + - and + - or + - 논리 +translation_of: Web/JavaScript/Reference/Operators +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>논리 연산자는 보통 {{jsxref("Boolean")}}(논리적) 값과 함께 쓰이며, 불리언 값을 반환합니다. 그런데, <code>&&</code>과 <code>||</code> 연산자는 사실 피연산자 중 하나의 값을 반환합니다. 그러므로 불리언 외의 다른 값과 함께 사용하면 불리언 값이 아닌 것을 반환할 수 있습니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-logicaloperator.html")}}</div> + + + +<h2 id="설명">설명</h2> + +<p>다음 표는 논리 연산자의 종류입니다. (<code><em>expr</em></code>은 불리언을 포함해서 아무 자료형이나 가능합니다)</p> + +<table class="fullwidth-table"> + <tbody> + <tr> + <th>연산자</th> + <th>구문</th> + <th>설명</th> + </tr> + <tr> + <td>논리 AND (<code>&&</code>)</td> + <td><code><em>expr1</em> && <em>expr2</em></code></td> + <td><code>expr1</code>을 <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">true</span></font>로 변환할 수 있는 경우 <code>expr2</code>을 반환하고, 그렇지 않으면 <code>expr1</code>을 반환합니다.</td> + </tr> + <tr> + <td>논리 OR (<code>||</code>)</td> + <td><code><em>expr1</em> || <em>expr2</em></code></td> + <td> + <p><code>expr1</code>을 <code>true</code>로 변환할 수 있으면 <code>expr1</code>을 반환하고, 그렇지 않으면 <code>expr2</code>를 반환합니다.</p> + </td> + </tr> + <tr> + <td>논리 NOT (<code>!</code>)</td> + <td><code>!<em>expr</em></code></td> + <td>단일 피연산자를 <code>true</code>로 변환할 수 있으면 <code>false</code>를 반환합니다. 그렇지 않으면 <code>true</code>를 반환합니다.</td> + </tr> + </tbody> +</table> + +<p>값을 <code>true</code>로 변환하면 값이 {{Glossary("truthy", "참")}}인 것입니다.<br> + 값을 <code>false</code>로 변환할 수 있으면 값이 {{Glossary("falsy", "거짓")}}인 것입니다.</p> + +<p>거짓으로 변환할 수 있는 표현의 예는 다음과 같습니다.</p> + +<ul> + <li><code>null</code></li> + <li><code>NaN</code></li> + <li><code>0</code></li> + <li>빈 문자열 (<code>"",</code> <code>''</code>, <code>``</code>)</li> + <li><code>undefined</code></li> +</ul> + +<p><code>&&</code> 연산자와 <code>||</code> 연산자를 불리언 값이 아닌 피연산자와 함께 사용될 수 있지만, 반환 값을 항상 <a href="/ko/docs/Web/JavaScript/Data_structures#Boolean_%ED%83%80%EC%9E%85">불리언 원시값</a>으로 변환할 수 있으므로 불리언 연산자로 생각할 수 있습니다. 반환 값을 직접 불리언으로 바꾸려면 {{jsxref("Boolean")}} 함수나 이중 부정 연산자를 사용하세요.</p> + +<h3 id="단락_평가">단락 평가</h3> + +<p>논리 표현식을 좌측부터 평가하므로, 아래 규칙에 따라 단락(short-circuit) 평가를 수행합니다.</p> + +<ul> + <li><code>(거짓 표현식) && expr</code>은 거짓 표현식으로 단락 평가됩니다.</li> + <li><code>(참 표현식) || expr</code>은 참 표현식으로 단락 평가됩니다.</li> +</ul> + +<p>"단락"이란, 위 규칙에서 <code>expr</code>을 평가하지 않는다는 뜻입니다. 따라서 평가 중 발생해야 할 부작용(예: <code>expr</code>이 함수 호출이면 절대 호출하지 않음)도 나타나지 않습니다. 단락 평가가 발생하는 원인은 첫 번째 피연산자를 평가한 순간 이미 연산자의 결과가 정해지기 때문입니다. 다음 예제를 살펴보세요.</p> + +<pre>function A(){ console.log('A 호출'); return false; } +function B(){ console.log('B 호출'); return true; } + +console.log( A() && B() ); +// 함수 호출로 인해 콘솔에 "A 호출" 기록 +// 그 후 연산자의 결과값인 "false" 기록 + +console.log( B() || A() ); +// 함수 호출로 인해 콘솔에 "B 호출" 기록 +// 그 후 연산자의 결과인 "true" 기록 +</pre> + +<h3 id="연산자_우선순위">연산자 우선순위</h3> + +<p>다음 두 식은 똑같아 보이지만, <code>&&</code> 연산자는 <code>||</code> 이전에 실행되므로 서로 다릅니다. <a href="/ko/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">연산자 우선순위</a>를 참고하세요.</p> + +<pre class="brush: js">true || false && false // returns true, because && is executed first +(true || false) && false // returns false, because operator precedence cannot apply</pre> + +<h3 id="논리_AND_()"><a name="Logical_AND">논리 AND (<code>&&</code>)</a></h3> + +<p>다음은 <code>&&</code>(논리 AND) 연산자의 예제입니다.</p> + +<pre class="brush: js">a1 = true && true // t && t returns true +a2 = true && false // t && f returns false +a3 = false && true // f && t returns false +a4 = false && (3 == 4) // f && f returns false +a5 = 'Cat' && 'Dog' // t && t returns "Dog" +a6 = false && 'Cat' // f && t returns false +a7 = 'Cat' && false // t && f returns false +a8 = '' && false // f && f returns "" +a9 = false && '' // f && f returns false</pre> + +<h3 id="논리_OR_()"><a name="Logical_OR">논리 OR (<code>||</code>)</a></h3> + +<p>다음은 <code>||</code>(논리 OR) 연산자의 예제입니다.</p> + +<pre class="brush: js">o1 = true || true // t || t returns true +o2 = false || true // f || t returns true +o3 = true || false // t || f returns true +o4 = false || (3 == 4) // f || f returns false +o5 = 'Cat' || 'Dog' // t || t returns "Cat" +o6 = false || 'Cat' // f || t returns "Cat" +o7 = 'Cat' || false // t || f returns "Cat" +o8 = '' || false // f || f returns false +o9 = false || '' // f || f returns "" +o10 = false || varObject // f || object returns varObject +</pre> + +<h3 id="논리_NOT_(!)"><a name="Logical_NOT">논리 NOT (<code>!</code>)</a></h3> + +<p>다음은 <code>!</code>(논리 NOT) 연산자의 예제입니다.</p> + +<pre class="brush: js">n1 = !true // !t returns false +n2 = !false // !f returns true +n3 = !'' // !f returns true +n4 = !'Cat' // !t returns false +</pre> + +<h4 id="이중_NOT_(!!)">이중 NOT (<code>!!</code>)</h4> + +<p>NOT 연산자 다수를 연속해서 사용하면 아무 값이나 불리언 원시값으로 강제 변환할 수 있습니다. 변환 결과는 피연산자 값의 "참스러움"이나 "거짓스러움"에 따릅니다. ({{Glossary("truthy", "참")}}과 {{Glossary("falsy", "거짓")}}을 참고하세요)</p> + +<p>동일한 변환을 {{jsxref("Boolean")}} 함수로도 수행할 수 있습니다.</p> + +<pre class="brush: js">n1 = !!true // !!truthy returns true +n2 = !!{} // !!truthy returns true: any object is truthy... +n3 = !!(new Boolean(false)) // ...even Boolean objects with a false .valueOf()! +n4 = !!false // !!falsy returns false +n5 = !!"" // !!falsy returns false +n6 = !!Boolean(false) // !!falsy returns false +</pre> + +<h3 id="불리언_변환_규칙">불리언 변환 규칙</h3> + +<h4 id="AND에서_OR로_변환">AND에서 OR로 변환</h4> + +<p>불리언 계산에서, 다음 두 코드는 항상 같습니다.</p> + +<pre class="brush: js">bCondition1 && bCondition2 +</pre> + +<pre class="brush: js">!(!bCondition1 || !bCondition2)</pre> + +<h4 id="OR에서_AND로_변환">OR에서 AND로 변환</h4> + +<p>불리언 계산에서, 다음 두 코드는 항상 같습니다.</p> + +<pre class="brush: js">bCondition1 || bCondition2 +</pre> + +<pre class="brush: js">!(!bCondition1 && !bCondition2)</pre> + +<h4 id="NOT_간_변환">NOT 간 변환</h4> + +<p>불리언 계산에서, 다음 두 코드는 항상 같습니다.</p> + +<pre class="brush: js">!!bCondition +</pre> + +<pre class="brush: js">bCondition</pre> + +<h3 id="중첩_괄호_제거">중첩 괄호 제거</h3> + +<p>논리 표현식은 항상 왼쪽에서 오른쪽으로 평가되므로, 몇 가지 규칙을 따르면 복잡한 표현식에서 괄호를 제거할 수 있습니다.</p> + +<h4 id="중첩_AND_제거">중첩 AND 제거</h4> + +<p>불리언의 합성 계산에서, 다음 두 코드는 항상 같습니다.</p> + +<pre class="brush: js">bCondition1 || (bCondition2 && bCondition3) +</pre> + +<pre class="brush: js">bCondition1 || bCondition2 && bCondition3</pre> + +<h4 id="중첩_OR_제거">중첩 OR 제거</h4> + +<p>불리언의 합성 계산에서, 다음 두 코드는 항상 같습니다.</p> + +<pre class="brush: js">bCondition1 && (bCondition2 || bCondition3) +</pre> + +<pre class="brush: js">!(!bCondition1 || !bCondition2 && !bCondition3)</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11.11')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Defined in several sections of the specification: <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-11.4.9">Logical NOT Operator</a>, <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-11.11">Binary Logical Operators</a></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-binary-logical-operators')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Defined in several sections of the specification: <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-logical-not-operator">Logical NOT Operator</a>, <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-binary-logical-operators">Binary Logical Operators</a></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-binary-logical-operators')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Defined in several sections of the specification: <a href="http://tc39.github.io/ecma262/#sec-logical-not-operator">Logical NOT Operator</a>, <a href="http://tc39.github.io/ecma262/#sec-binary-logical-operators">Binary Logical Operators</a></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.operators.logical")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators">비트 연산자</a></li> + <li>{{jsxref("Boolean")}}</li> + <li>{{Glossary("truthy", "참")}}</li> + <li>{{Glossary("falsy", "거짓")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/배열/index.html b/files/ko/web/javascript/reference/operators/배열/index.html new file mode 100644 index 0000000000..4bdd29b61c --- /dev/null +++ b/files/ko/web/javascript/reference/operators/배열/index.html @@ -0,0 +1,200 @@ +--- +title: 배열 내포 +slug: Web/JavaScript/Reference/Operators/배열 +tags: + - JavaScript + - Non-standard + - Obsolete + - Operator + - Reference +translation_of: Archive/Web/JavaScript/Array_comprehensions +--- +<div>{{jsSidebar("Operators")}}</div> + +<div class="warning"><strong>표준이 아닙니다. 사용하지 않는 것을 권장합니다!</strong><br> +Array comprehensions 문법은 비표준이며 Firefox 58부터는 제거됩니다. 향후 사용할 수 없게 되기 때문에 사용하지 않는것을 고려해보세요.<br> +{{jsxref("Array.prototype.map")}}, {{jsxref("Array.prototype.filter")}}, {{jsxref("Functions/Arrow_functions", "arrow functions", "", 1)}}, and {{jsxref("Operators/Spread_operator", "spread syntax", "", 1)}}.</div> + +<div>{{Obsolete_Header(58)}}</div> + +<p><strong>array comprehension </strong>문법은 기존의 배열을 기반으로 새로운 배열을 신속하게 어셈블 할 수 있는 JavaScript 표현식입니다. 그러나 표준 및 Firefox 구현에서 제거되었습니다. 사용하지 마세요!</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">[for (x of iterable) x] +[for (x of iterable) if (condition) x] +[for (x of iterable) for (y of iterable) x + y] +</pre> + +<h2 id="Description">Description</h2> + +<p>배열의 이해로 넘어가서, 다음 두가지의 요소들이 사용가능하다.</p> + +<ul> + <li>{{jsxref("Statements/for...of", "for...of")}} and</li> + <li>{{jsxref("Statements/if...else", "if")}}</li> +</ul> + +<p>for-of 반복문은 항상 첫번째 요소이다. 여러개의 for-of 반복문이나 if 제어문을 사용할 수 있다.</p> + +<p>배열 선언은 ECMAScript 2016에서 이전부터 표준으로 정립되어왔으며, 이는 다른 형태의 데이터(contents)를 이용해서 새로운 배열을 구성할 수 있게 해 준다.</p> + +<p>아래의 선언은 숫자로 이루어진 배열 내 각각의 숫자들을 이용해서 double형의 새로운 배열을 만들어준다.</p> + +<pre class="brush: js">var numbers = [1, 2, 3, 4]; +var doubled = [for (i of numbers) i * 2]; +console.log(doubled); // logs 2,4,6,8 +</pre> + +<p>이것은 {{jsxref("Array.prototype.map", "map()")}} 연산자와 같은 기능을 한다.</p> + +<pre class="brush: js">var doubled = numbers.map(i => i * 2); +</pre> + +<p>배열들은 또한 다양한 표현을 통해 몇몇개의 배열 원소들은 선택할 수 도 있다. 아래의 예제는 바로 홀수만 선택하는 예제이다.</p> + +<pre class="brush: js">var numbers = [1, 2, 3, 21, 22, 30]; +var evens = [for (i of numbers) if (i % 2 === 0) i]; +console.log(evens); // logs 2,22,30 +</pre> + +<p>{{jsxref("Array.prototype.filter", "filter()")}} 또한 같은 목적으로 얼마든지 사용가능하다.</p> + +<pre class="brush: js">var evens = numbers.filter(i => i % 2 === 0); +</pre> + +<p>{{jsxref("Array.prototype.map", "map()")}} 그리고 {{jsxref("Array.prototype.filter", "filter()")}} 스타일과 같은 연산자들은 단한 배열 선언과 결합할 수 있다. 아래는 짝수만 필터링하고, 그 원소들을 2배씩하는 배열들을 만드는 예제이다.</p> + +<pre class="brush: js">var numbers = [1, 2, 3, 21, 22, 30]; +var doubledEvens = [for (i of numbers) if (i % 2 === 0) i * 2]; +console.log(doubledEvens); // logs 4,44,60 +</pre> + +<p>배열에서의 [ ] (꺽쇠괄호) 는 범위의 목적으로 암시적인 괄호를 의미한다. {{jsxref("Statements/let","let")}}를 사용하면서 정의된다면, 예제의 i와 같은 변수들이 사용된다. 이는 배열 밖에서 사용할 수 없음을 나타낸다.</p> + +<p>배열의 원소에 넣어지는 것은 굳이 배열일 필요는 없다 <a href="/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators" title="en-US/docs/JavaScript/Guide/Iterators and Generators">iterators and generators</a> 물론 가능하다.</p> + +<p>심지어 문자열도 배열의 원소로 넣을 수 있다. 필터와 지도 액션과 같은 데에 이용할 수 있다.</p> + +<pre class="brush: js">var str = 'abcdef'; +var consonantsOnlyStr = [for (c of str) if (!(/[aeiouAEIOU]/).test(c)) c].join(''); // 'bcdf' +var interpolatedZeros = [for (c of str) c + '0' ].join(''); // 'a0b0c0d0e0f0' +</pre> + +<p>또한 입력 폼이 유지되지 않으므로, 문자열을 뒤집기 위해 {{jsxref("Array.prototype.join", "join()")}} 를 사용해야 한다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="단순_배열">단순 배열</h3> + +<pre class="brush:js">[for (i of [1, 2, 3]) i * i ]; +// [1, 4, 9] + +var abc = ['A', 'B', 'C']; +[for (letters of abc) letters.toLowerCase()]; +// ["a", "b", "c"]</pre> + +<h3 id="if문에서의_배열">if문에서의 배열</h3> + +<pre class="brush: js">var years = [1954, 1974, 1990, 2006, 2010, 2014]; +[for (year of years) if (year > 2000) year]; +// [ 2006, 2010, 2014 ] +[for (year of years) if (year > 2000) if (year < 2010) year]; +// [ 2006], the same as below: +[for (year of years) if (year > 2000 && year < 2010) year]; +// [ 2006] +</pre> + +<h3 id="map과_filter를_비교한_배열">map과 filter를 비교한 배열</h3> + +<p>배열문법을 가장 쉽게 이해하는 방법은, 배열에서 {{jsxref("Array.map", "map")}} 그리고 {{jsxref("Array.filter", "filter")}}메소드를 비교하는 것이다.</p> + +<pre class="brush: js">var numbers = [1, 2, 3]; + +numbers.map(function (i) { return i * i }); +numbers.map(i => i * i); +[for (i of numbers) i * i]; +// all are [1, 4, 9] + +numbers.filter(function (i) { return i < 3 }); +numbers.filter(i => i < 3); +[for (i of numbers) if (i < 3) i]; +// all are [1, 2] +</pre> + +<h3 id="2개의_배열">2개의 배열</h3> + +<p>2개의 배열과 2개의 for-of 반복문을 살펴본다.</p> + +<pre class="brush: js">var numbers = [1, 2, 3]; +var letters = ['a', 'b', 'c']; + +var cross = [for (i of numbers) for (j of letters) i + j]; +// ["1a", "1b", "1c", "2a", "2b", "2c", "3a", "3b", "3c"] + +var grid = [for (i of numbers) [for (j of letters) i + j]]; +// [ +// ["1a", "1b", "1c"], +// ["2a", "2b", "2c"], +// ["3a", "3b", "3c"] +// ] + +[for (i of numbers) if (i > 1) for (j of letters) if(j > 'a') i + j] +// ["2b", "2c", "3b", "3c"], the same as below: + +[for (i of numbers) for (j of letters) if (i > 1) if(j > 'a') i + j] +// ["2b", "2c", "3b", "3c"] + +[for (i of numbers) if (i > 1) [for (j of letters) if(j > 'a') i + j]] +// [["2b", "2c"], ["3b", "3c"]], not the same as below: + +[for (i of numbers) [for (j of letters) if (i > 1) if(j > 'a') i + j]] +// [[], ["2b", "2c"], ["3b", "3c"]] +</pre> + +<h2 id="명세">명세</h2> + +<p>ECMAScript 2015 초안에 있었지만 개정 27(2014년 8월)에서 삭제되었습니다. specification semantics에 대해서는 ES2015의 이전 버전을 참조하세요.</p> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{Compat("javascript.operators.array_comprehensions")}}</p> + +<h2 id="오래된_JS1.7JS1.8_comprehensions과의_차이점들">오래된 JS1.7/JS1.8 comprehensions과의 차이점들</h2> + +<div class="warning">Gecko에서 JS1.7 / JS1.8 comprehensions가 46 버전부터 제거되었습니다. ({{bug(1220564)}}).</div> + +<p><strong>이전에 사용된 문법입니다. (더 이상 사용되지 않음!):</strong></p> + +<pre class="brush: js example-bad">[X for (Y in Z)] +[X for each (Y in Z)] +[X for (Y of Z)] +</pre> + +<p>차이점:</p> + +<ul> + <li>ESNext comprehensions는 전체comprehension 대신 "for"노드마다 하나의 범위를 만듭니다. + <ul> + <li>Old: <code>[()=>x for (x of [0, 1, 2])][1]() // 2</code></li> + <li>New: <code>[for (x of [0, 1, 2]) ()=>x][1]() // 1, each iteration creates a fresh binding for x. </code></li> + </ul> + </li> + <li>ESNext comprehensions은 assignment expression대신 "for"로 시작합니다. + <ul> + <li>Old: <code>[i * 2 for (i of numbers)]</code></li> + <li>New: <code>[for (i of numbers) i * 2]</code></li> + </ul> + </li> + <li>ESNext comprehensions는 <code>if</code> 및 <code>for</code> 구성 요소를 여러 개 가질 수 있습니다.</li> + <li>ESNext comprehensions <code>{{jsxref("Statements/for...of", "for...of")}}</code>에서만 동작하고 <code>{{jsxref("Statements/for...in", "for...in")}}</code>에서는 동작하지 않습니다.</li> +</ul> + +<p>버그 업데이트에 대한 제안은 <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1220564#c42">Bug 1220564, comment 42</a>를 참조하세요.</p> + +<h2 id="더보기">더보기</h2> + +<ul> + <li>{{jsxref("Statements/for...of", "for...of")}}</li> + <li>{{jsxref("Operators/Generator_comprehensions", "Generator comprehensions", "" ,1)}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/operators/연산자_우선순위/index.html b/files/ko/web/javascript/reference/operators/연산자_우선순위/index.html new file mode 100644 index 0000000000..7a82346d09 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/연산자_우선순위/index.html @@ -0,0 +1,462 @@ +--- +title: 연산자 우선순위 +slug: Web/JavaScript/Reference/Operators/연산자_우선순위 +tags: + - JavaScript + - Operator + - 연산자 + - 우선순위 +translation_of: Web/JavaScript/Reference/Operators/Operator_Precedence +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>연산자 우선순위</strong>는 연산자를 실행하는 순서를 결정합니다. 우선순위가 높은 연산자가 먼저 실행됩니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-operatorprecedence.html")}}</div> + + + +<h2 id="우선순위와_결합성">우선순위와 결합성</h2> + +<p>아래와 같이 표현할 수 있는 표현식을 생각해 봅시다. 연산자<sub>1</sub>과 연산자<sub>2</sub>의 자리에는 아무 연산자를 넣을 수 있습니다.</p> + +<pre class="syntaxbox">a 연산자<sub>1</sub> b 연산자<sub>2</sub> c</pre> + +<p>두 연산자의 우선순위(아래 표 참조)가 다를 경우, 우선순위가 높은 연산자가 먼저 실행되고 결합성은 영향을 미치지 않습니다. 아래 예제에서는 덧셈이 곱셈보다 먼저 쓰였음에도 곱셈의 우선순위가 높기 때문에 먼저 실행됩니다.</p> + +<pre class="brush: js">console.log(3 + 10 * 2); // 23을 출력 +console.log(3 + (10 * 2)); // 23을 출력, 괄호는 불필요함 +console.log((3 + 10) * 2); // 26을 출력, 괄호로 인해 실행 순서가 바뀜 +</pre> + +<p>좌결합성(왼쪽에서 오른쪽으로)은 표현식이 <code>(a 연산자<sub>1</sub> b) 연산자<sub>2</sub> c</code>와 같이, 우결합성(오른쪽에서 왼쪽으로)은 <code>a 연산자<sub>1</sub> (b 연산자<sub>2</sub> c)</code>와 같이 계산된다는 의미입니다. 대입 연산자는 우결합성이므로 다음과 같은 코드를 작성할 수 있습니다.</p> + +<pre class="brush: js">a = b = 5; // a = (b = 5);와 같음 +</pre> + +<p>이때 대입 연산자는 대입된 값을 반환하므로 <code>a</code>와 <code>b</code>의 값이 5가 됨을 예상할 수 있습니다. 우선 <code>b</code>의 값이 5로 설정되고, 그 다음에는 <code>a</code>의 값이 우변인 <code>b = 5</code>의 반환값 5로 설정됩니다.</p> + +<p>다른 예시로, 좌결합성인 다른 산술 연산자와 달리 거듭제곱 연산자 (<code>**</code>)만은 우결합성입니다. 흥미로운 점으로 표현식의 평가는 결합성과 무관하게 항상 왼쪽에서 오른쪽으로 진행됩니다.</p> + +<table class="standard-table"> + <tbody> + <tr> + <td>코드</td> + <td>출력</td> + </tr> + <tr> + <td> + <pre class="brush: js"> +function echo(name, num) { + console.log(name + " 항 평가함"); + return num; +} +// 나눗셈 연산자 (/)에 주목 +console.log(echo("첫째", 6) / echo("둘째", 2)); +</pre> + </td> + <td> + <pre> +첫째 항 평가함 +둘째 항 평가함 +3 +</pre> + </td> + </tr> + <tr> + <td> + <pre class="brush: js"> +function echo(name, num) { + console.log(name + " 항 평가함"); + return num; +} +// 거듭제곱 연산자 (**)에 주목 +console.log(echo("첫째", 2) ** echo("둘째", 3));</pre> + </td> + <td> + <pre> +첫째 항 평가함 +둘째 항 평가함 +8</pre> + </td> + </tr> + </tbody> +</table> + +<p>여러 연산자의 우선순위가 같을 때는 결합성을 고려합니다. 위에서와 같이 연산자가 하나이거나 연산자끼리 우선순위가 다를 경우에는 결합성이 결과에 영향을 미치지 않습니다. 아래의 예제에서 같은 종류의 연산자를 여러 번 사용했을 때 결합성이 결과에 영향을 미치는 것을 확인할 수 있습니다.</p> + +<table class="standard-table"> + <tbody> + <tr> + <td>코드</td> + <td>출력</td> + </tr> + <tr> + <td> + <pre class="brush: js"> +function echo(name, num) { + console.log(name + " 항 평가함"); + return num; +} +// 나눗셈 연산자 (/)에 주목 +console.log(echo("첫째", 6) / echo("둘째", 2) / echo("셋째", 3)); +</pre> + </td> + <td> + <pre> +첫째 항 평가함 +둘째 항 평가함 +셋째 항 평가함 +1 +</pre> + </td> + </tr> + <tr> + <td> + <pre class="brush: js"> +function echo(name, num) { + console.log(name + " 항 평가함"); + return num; +} +// 거듭제곱 연산자 (**)에 주목 +console.log(echo("첫째", 2) ** echo("둘째", 3) ** echo("셋째", 2)); +</pre> + </td> + <td> + <pre> +첫째 항 평가함 +둘째 항 평가함 +셋째 항 평가함 +512 +</pre> + </td> + </tr> + <tr> + <td> + <pre class="brush: js"> +function echo(name, num) { + console.log(name + " 항 평가함"); + return num; +} +// 첫 번째 거듭제곱 연산자 주변의 괄호에 주목 +console.log((echo("첫째", 2) ** echo("둘째", 3)) ** echo("셋째", 2));</pre> + </td> + <td> + <pre> +첫째 항 평가함 +둘째 항 평가함 +셋째 항 평가함 +64</pre> + </td> + </tr> + </tbody> +</table> + +<p>위의 예제에서 나눗셈은 좌결합성이므로 <code>6 / 3 / 2</code>는 <code>(6 / 3) / 2</code>와 같습니다. 한편 거듭제곱은 우결합성이므로 <code>2 ** 3 ** 2</code>는 <code>2 ** (3 ** 2)</code>와 같습니다. 그러므로 <code>(2 ** 3) ** 2</code>는 괄호로 인해 실행 순서가 바뀌기 때문에 위 표와 같이 64로 평가됩니다.</p> + +<p>우선순위는 결합성보다 항상 우선하므로, 거듭제곱과 나눗셈을 같이 사용하면 나눗셈보다 거듭제곱이 먼저 계산됩니다. 예를 들어 <code>2 ** 3 / 3 ** 2</code>는 <code>(2 ** 3) / (3 ** 2)</code>와 같으므로 0.8888888888888888로 계산됩니다.</p> + +<h2 id="예제">예제</h2> + +<pre class="brush: js">3 > 2 && 2 > 1 +// true를 반환 + +3 > 2 > 1 +// 3 > 2는 true인데, 부등호 연산자에서 true는 1로 변환되므로 +// true > 1은 1 > 1이 되고, 이는 거짓이다. +// 괄호를 추가하면 (3 > 2) > 1과 같다.</pre> + +<h2 id="표">표</h2> + +<p>다음 표는 우선순위 내림차순(21부터 1까지)으로 정렬되어 있습니다.</p> + +<table class="fullwidth-table"> + <tbody> + <tr> + <th>우선순위</th> + <th>연산자 유형</th> + <th>결합성</th> + <th>연산자</th> + </tr> + <tr> + <td>21</td> + <td>{{jsxref("Operators/Grouping", "그룹", "", 1)}}</td> + <td>없음</td> + <td><code>( … )</code></td> + </tr> + <tr> + <td colspan="1" rowspan="5">20</td> + <td>{{jsxref("Operators/Property_Accessors", "멤버 접근", "#점_표기법", 1)}}</td> + <td>좌결합성</td> + <td><code>… . …</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/Property_Accessors", "계산된 멤버 접근","#괄호_표기법", "1")}}</td> + <td>좌결합성</td> + <td><code>… [ … ]</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/new","new")}} (매개변수 리스트 존재)</td> + <td>없음</td> + <td><code>new … ( … )</code></td> + </tr> + <tr> + <td> + <p><a href="/ko/docs/Web/JavaScript/Guide/Functions">함수 호출</a></p> + </td> + <td>좌결합성</td> + <td><code>… ( <var>… </var>)</code></td> + </tr> + <tr> + <td><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Optional_chaining">Optional chaining</a></td> + <td>좌결합성</td> + <td><code>?.</code></td> + </tr> + <tr> + <td rowspan="1">19</td> + <td>{{jsxref("Operators/new","new")}} (매개변수 리스트 생략)</td> + <td>우결합성</td> + <td><code>new …</code></td> + </tr> + <tr> + <td rowspan="2">18</td> + <td>{{jsxref("Operators/Arithmetic_Operators","후위 증가","#Increment", 1)}}</td> + <td colspan="1" rowspan="2">없음</td> + <td><code>… ++</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/Arithmetic_Operators","후위 감소","#Decrement", 1)}}</td> + <td><code>… --</code></td> + </tr> + <tr> + <td colspan="1" rowspan="10">17</td> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_NOT">논리 NOT</a></td> + <td colspan="1" rowspan="10">우결합성</td> + <td><code>! …</code></td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_NOT">비트 NOT</a></td> + <td><code>~ …</code></td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus">단항 양부호</a></td> + <td><code>+ …</code></td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_negation">단항 부정</a></td> + <td><code>- …</code></td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment">전위 증가</a></td> + <td><code>++ …</code></td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Decrement">전위 감소</a></td> + <td><code>-- …</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/typeof", "typeof")}}</td> + <td><code>typeof …</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/void", "void")}}</td> + <td><code>void …</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/delete", "delete")}}</td> + <td><code>delete …</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/await", "await")}}</td> + <td><code>await …</code></td> + </tr> + <tr> + <td>16</td> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Exponentiation">거듭제곱</a></td> + <td>우결합성</td> + <td><code>… ** …</code></td> + </tr> + <tr> + <td rowspan="3">15</td> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Multiplication">곱셈</a></td> + <td colspan="1" rowspan="3">좌결합성</td> + <td><code>… * …</code></td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Division">나눗셈</a></td> + <td><code>… / …</code></td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder">나머지</a></td> + <td><code>… % …</code></td> + </tr> + <tr> + <td rowspan="2">14</td> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Addition">덧셈</a></td> + <td colspan="1" rowspan="2">좌결합성</td> + <td><code>… + …</code></td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Subtraction">뺄셈</a></td> + <td><code>… - …</code></td> + </tr> + <tr> + <td rowspan="3">13</td> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators">비트 왼쪽 시프트</a></td> + <td colspan="1" rowspan="3">좌결합성</td> + <td><code>… << …</code></td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators">비트 오른쪽 시프트</a></td> + <td><code>… >> …</code></td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators">비트 부호 없는 오른쪽 시프트</a></td> + <td><code>… >>> …</code></td> + </tr> + <tr> + <td rowspan="6">12</td> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Less_than_operator">미만</a></td> + <td colspan="1" rowspan="6">좌결합성</td> + <td><code>… < …</code></td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Less_than__or_equal_operator">이하</a></td> + <td><code>… <= …</code></td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Greater_than_operator">초과</a></td> + <td><code>… > …</code></td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Greater_than_or_equal_operator">이상</a></td> + <td><code>… >= …</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/in", "in")}}</td> + <td><code>… in …</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/instanceof", "instanceof")}}</td> + <td><code>… instanceof …</code></td> + </tr> + <tr> + <td rowspan="4">11</td> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Equality">동등</a></td> + <td colspan="1" rowspan="4">좌결합성</td> + <td><code>… == …</code></td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Inequality">부등</a></td> + <td><code>… != …</code></td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Identity">일치</a></td> + <td><code>… === …</code></td> + </tr> + <tr> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Nonidentity">불일치</a></td> + <td><code>… !== …</code></td> + </tr> + <tr> + <td>10</td> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_AND">비트 AND</a></td> + <td>좌결합성</td> + <td><code>… & …</code></td> + </tr> + <tr> + <td>9</td> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_XOR">비트 XOR</a></td> + <td>좌결합성</td> + <td><code>… ^ …</code></td> + </tr> + <tr> + <td>8</td> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_OR">비트 OR</a></td> + <td>좌결합성</td> + <td><code>… | …</code></td> + </tr> + <tr> + <td>7</td> + <td><a href="https://wiki.developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator">널 병합 연산자</a></td> + <td>좌결합성</td> + <td><code>… ?? …</code></td> + </tr> + <tr> + <td>6</td> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_AND">논리 AND</a></td> + <td>좌결합성</td> + <td><code>… && …</code></td> + </tr> + <tr> + <td>5</td> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_OR">논리 OR</a></td> + <td>좌결합성</td> + <td><code>… || …</code></td> + </tr> + <tr> + <td>4</td> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Conditional_Operator">조건</a></td> + <td>우결합성</td> + <td><code>… ? … : …</code></td> + </tr> + <tr> + <td rowspan="13">3</td> + <td rowspan="13"><a href="/ko/docs/Web/JavaScript/Reference/Operators/Assignment_Operators">할당</a></td> + <td rowspan="13">우결합성</td> + <td><code>… = …</code></td> + </tr> + <tr> + <td><code>… += …</code></td> + </tr> + <tr> + <td><code>… -= …</code></td> + </tr> + <tr> + <td><code>… **= …</code></td> + </tr> + <tr> + <td><code>… *= …</code></td> + </tr> + <tr> + <td><code>… /= …</code></td> + </tr> + <tr> + <td><code>… %= …</code></td> + </tr> + <tr> + <td><code>… <<= …</code></td> + </tr> + <tr> + <td><code>… >>= …</code></td> + </tr> + <tr> + <td><code>… >>>= …</code></td> + </tr> + <tr> + <td><code>… &= …</code></td> + </tr> + <tr> + <td><code>… ^= …</code></td> + </tr> + <tr> + <td><code>… |= …</code></td> + </tr> + <tr> + <td rowspan="2">2</td> + <td>{{jsxref("Operators/yield", "yield")}}</td> + <td colspan="1" rowspan="2">우결합성</td> + <td><code>yield …</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/yield*", "yield*")}}</td> + <td><code>yield* …</code></td> + </tr> + <tr> + <td>1</td> + <td><a href="/ko/docs/Web/JavaScript/Reference/Operators/Comma_Operator">쉼표 / 시퀀스</a></td> + <td>좌결합성</td> + <td><code>… , …</code></td> + </tr> + </tbody> +</table> diff --git a/files/ko/web/javascript/reference/statements/async_function/index.html b/files/ko/web/javascript/reference/statements/async_function/index.html new file mode 100644 index 0000000000..5a986c8af4 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/async_function/index.html @@ -0,0 +1,243 @@ +--- +title: async function +slug: Web/JavaScript/Reference/Statements/async_function +tags: + - Example + - JavaScript + - Promise + - async + - await +translation_of: Web/JavaScript/Reference/Statements/async_function +--- +<div>{{jsSidebar("Statements")}}</div> + +<p><code><strong>async function</strong></code> 선언은 {{jsxref("Global_Objects/AsyncFunction","AsyncFunction")}}객체를 반환하는 하나의 비동기 함수를 정의합니다. 비동기 함수는 이벤트 루프를 통해 비동기적으로 작동하는 함수로, 암시적으로 {{jsxref("Promise")}}를 사용하여 결과를 반환합니다. 그러나 비동기 함수를 사용하는 코드의 구문과 구조는, 표준 동기 함수를 사용하는것과 많이 비슷합니다.</p> + +<div class="noinclude"> +<p>또한 {{jsxref("Operators/async_function", "async function expression", "", 1)}}을 사용해서 async function을 선언할 수 있습니다.</p> +</div> + +<div>{{EmbedInteractiveExample("pages/js/statement-async.html", "taller")}}</div> + +<div class="hidden"> +<p>이 데모에 대한 소스가 여기에 있다. 기여하고싶다면 다음의 주소에서 Clone하고 pull request하라 : <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a></p> +</div> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox notranslate" dir="rtl">async function <em>name</em>([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { + <em>statements</em> +} +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>name</code></dt> + <dd>함수의 이름.</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>함수에게 전달되기 위한 인자의 이름.</dd> +</dl> + +<dl> + <dt><code>statements</code></dt> + <dd><font face="Consolas, Liberation Mono, Courier, monospace">함수본문을 구성하는 내용.</font></dd> + <dt> + <h3 id="반환_값"><font face="Consolas, Liberation Mono, Courier, monospace">반환 값</font></h3> + + <p>Promise : async 함수에 의해 반환 된 값으로 해결되거나 async함수 내에서 발생하는 캐치되지 않는 예외로 거부되는 값.</p> + </dt> +</dl> + +<h2 id="Description">Description</h2> + +<p><code>async</code> 함수에는 {{jsxref ( "Operators / await", "await")}}식이 포함될 수 있습니다. 이 식은 <code>async</code> 함수의 실행을 일시 중지하고 전달 된 <code>Promise</code>의 해결을 기다린 다음 <code>async</code> 함수의 실행을 다시 시작하고 완료후 값을 반환합니다.</p> + +<div class="blockIndicator note"> +<p><code>await</code> 키워드는 <code>async</code> 함수에서만 유효하다는 것을 기억하십시오. <code>async</code> 함수의 본문 외부에서 사용하면 <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError">SyntaxError</a>가 발생합니다.</p> +</div> + +<div class="note"> +<p>async/await함수의 목적은 사용하는 여러 promise의 동작을 동기스럽게 사용할 수 있게 하고, 어떠한 동작을 여러 promise의 그룹에서 간단하게 동작하게 하는 것이다.<br> + promise가 구조화된 callback과 유사한 것 처럼 async/await또한 제네레이터(generator)와 프로미스(promise)를 묶는것과 유사하다.</p> +</div> + +<p><code>async</code> 함수는 항상 promise를 반환합니다. 만약 <code>async</code> 함수의 반환값이 명시적으로 promise가 아니라면 암묵적으로 promise로 감싸집니다.</p> + +<p>예를 들어</p> + +<pre class="notranslate">async function foo() { + return 1 +}</pre> + +<p>위 코드는 아래와 같습니다.</p> + +<pre class="notranslate">function foo() { + return Promise.resolve(1) +}</pre> + +<p><code>async</code> 함수의 본문은 0개 이상의 <code>await</code> 문으로 분할된 것으로 생각할 수 있습니다. 첫번째 <code>await</code> 문을 포함하는 최상위 코드는 동기적으로 실행됩니다. 따라서 <code>await</code> 문이 없는 <code>async</code> 함수는 동기적으로 실행됩니다. 하지만 <code>await</code> 문이 있다면 <code>async</code> 함수는 항상 비동기적으로 완료됩니다.</p> + +<p>예를 들어</p> + +<pre class="notranslate">async function foo() { + await 1 +}</pre> + +<p>위 코드는 아래와 같습니다.</p> + +<pre class="notranslate">function foo() { + return Promise.resolve(1).then(() => undefined) +} +</pre> + +<h2 id="Examples">Examples</h2> + +<h3 id="Simple_example">Simple example</h3> + +<pre class="notranslate"><code>var resolveAfter2Seconds = function() { + console.log("starting slow promise"); + return new Promise(resolve => { + setTimeout(function() { + resolve(20); + console.log("slow promise is done"); + }, 2000); + }); +}; + +var resolveAfter1Second = function() { + console.log("starting fast promise"); + return new Promise(resolve => { + setTimeout(function() { + resolve(10); + console.log("fast promise is done"); + }, 1000); + }); +}; + +var sequentialStart = async function() { + console.log('==SEQUENTIAL START=='); + + // If the value of the expression following the await operator is not a Promise, it's converted to a resolved Promise. + const slow = await resolveAfter2Seconds(); + console.log(slow); + + const fast = await resolveAfter1Second(); + console.log(fast); +} + +var concurrentStart = async function() { + console.log('==CONCURRENT START with await=='); + const slow = resolveAfter2Seconds(); // starts timer immediately + const fast = resolveAfter1Second(); + + console.log(await slow); + console.log(await fast); // waits for slow to finish, even though fast is already done! +} + +var stillConcurrent = function() { + console.log('==CONCURRENT START with Promise.all=='); + Promise.all([resolveAfter2Seconds(), resolveAfter1Second()]).then((messages) => { + console.log(messages[0]); // slow + console.log(messages[1]); // fast + }); +} + +var parallel = function() { + console.log('==PARALLEL with Promise.then=='); + resolveAfter2Seconds().then((message)=>console.log(message)); + resolveAfter1Second().then((message)=>console.log(message)); +} + +sequentialStart(); // after 2 seconds, logs "slow", then after 1 more second, "fast" +// wait above to finish +setTimeout(concurrentStart, 4000); // after 2 seconds, logs "slow" and then "fast" +// wait again +setTimeout(stillConcurrent, 7000); // same as concurrentStart +// wait again +setTimeout(parallel, 10000); // trully parallel: after 1 second, logs "fast", then after 1 more second, "slow"</code></pre> + +<div class="warning"> +<h4 id="await_와_Promisethen을_혼동하지_마세요"><code>await</code> 와 <code>Promise#then</code>을 혼동하지 마세요</h4> + +<p><code>sequentialStart</code> 에서, 첫 번째 <code>await</code>는 2초의 대기 시간을 갖고, 다시 두 번째 <code>await</code>에서 1초의 대기 시간을 갖습니다. 두 번째 타이머는 첫 번째 타이머가 완료될 때 까지 생성되지 않습니다.</p> + +<p><code>concurrentStart</code> 에서, 두 타이머 모두 생성 된 다음 <code>await</code> 합니다. 타이머가 동시에 실행되고 있지만, <code>await</code> 호출은 여전히 연속적 실행중이므로, 두 번째 <code>await</code> 는 첫 번째 호출이 끝날 때 까지 대기합니다. 이렇게하면 3초가 아니라, 가장 느린 타이머에 필요한 2초가 필요합니다. <code>stillConcurrent</code> 에서도 <code>Promise.all</code> 을 사용하여 같은 일이 발생합니다.</p> + +<p>두 개 이상의 프러미스를 동시에 wait 하고 싶다면, <code>Promise#then</code>을 사용하여 예제와 같이 <code>parallel</code> 를 수행할 수 있습니다.</p> +</div> + +<h3 id="async함수를_사용한_promise_chain_재작성"><code>async</code>함수를 사용한 promise chain 재작성</h3> + +<p>{{jsxref("Promise")}} 를 반환하는 API는 promise chain을 만들며 여러 파트의 함수로 나뉜다.<br> + 아래 코드를 보자.</p> + +<pre class="brush: js notranslate">function getProcessedData(url) { + return downloadData(url) // returns a promise + .catch(e => { + return downloadFallbackData(url) // returns a promise + }) + .then(v => { + return processDataInWorker(v); // returns a promise + }); +} +</pre> + +<p>위의 코드는 하나의 async함수로 아래와 같이 쓰여질 수도 있다.</p> + +<pre class="brush: js notranslate">async function getProcessedData(url) { + let v; + try { + v = await downloadData(url); + } catch (e) { + v = await downloadFallbackData(url); + } + return processDataInWorker(v); +} +</pre> + +<p>위 예제에서는 return 구문에 await 구문이 없다는 것에 주목하자. 이는 async function의 반환값이 암묵적으로 {{jsxref("Promise.resolve")}}로 감싸지기 때문이다.</p> + +<h2 id="Specifications">Specifications</h2> + +<table> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-async-function-definitions', 'async function')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Initial definition in ES2017.</td> + </tr> + <tr> + <td>{{SpecName('ES8', '#sec-async-function-definitions', 'async function')}}</td> + <td>{{Spec2('ES8')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div class="hidden"> +<p>The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>and send us a pull request.</p> +</div> + +<p>{{Compat("javascript.statements.async_function")}}</p> + +<h2 id="함께_보기">함께 보기</h2> + +<ul> + <li>{{jsxref("Operators/async_function", "async function expression")}}</li> + <li>{{jsxref("AsyncFunction")}} object</li> + <li>{{jsxref("Operators/await", "await")}}</li> + <li><a href="http://innolitics.com/10x/javascript-decorators-for-promise-returning-functions/">"Decorating Async Javascript Functions" on "innolitics.com"</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/statements/block/index.html b/files/ko/web/javascript/reference/statements/block/index.html new file mode 100644 index 0000000000..aab5d0dc3f --- /dev/null +++ b/files/ko/web/javascript/reference/statements/block/index.html @@ -0,0 +1,132 @@ +--- +title: block +slug: Web/JavaScript/Reference/Statements/block +tags: + - JavaScript + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/block +--- +<div>{{jsSidebar("Statements")}}</div> + +<p><strong>블록문</strong>(또는 다른 언어에서는 복합문)은 0개 이상의 구문을 묶을 때 사용합니다. 블록은 한 쌍의 중괄호로 구성하며 선택적으로 {{jsxref("Statements/label", "이름", "", 0)}}을 붙일 수 있습니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/statement-block.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<h3 id="블록문">블록문</h3> + +<pre class="syntaxbox">{ + <em>StatementList</em> +}</pre> + +<h3 id="유명_블록문">유명 블록문</h3> + +<pre class="syntaxbox"><em>LabelIdentifier</em>: { + <em>StatementList</em> +} +</pre> + +<dl> + <dt><code>StatementList</code></dt> + <dd>블록문 내의 문.</dd> + <dt><code>LabelIdentifier</code></dt> + <dd>시각적인 구분, 또는 {{jsxref("Statements/break", "break")}}문의 대상으로 쓸 {{jsxref("Statements/label", "label")}}.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p>다른 언어에서 블록문은 <strong>복합문</strong>이라고 부르기도 합니다. 블록문을 쓰면 JavaScript가 하나의 문을 기대하는 곳에서 다수의 문을 실행할 수 있습니다. JavaScript에서 이렇게 문을 묶는건 흔히 쓰이는 기법입니다. 반대 개념으로는 {{jsxref("Statements/empty", "공백문", "", 0)}}이 있으며, 이는 하나의 문을 기대하는 곳에 아무것도 제공하지 않는 것입니다.</p> + +<h3 id="블록_범위_규칙">블록 범위 규칙</h3> + +<h4 id="var_사용_시"><code>var</code> 사용 시</h4> + +<p>{{jsxref("Statements/var", "var")}}로 선언한 변수는 블록 범위를 <strong>가지지 않습니다</strong>. 블록 내에서 선언한 변수의 범위는 함수나 스크립트가 되어, 값 할당의 영향이 블록 바깥까지 미칩니다. 다른 말로는 블록문이 범위를 만들지 않습니다. "독립" 블록문도 유효한 구문이긴 하지만, C와 Java의 블록에 기대하는걸 JavaScript에서도 기대하면 안됩니다. 예를 들어보겠습니다.</p> + +<pre class="brush: js example-bad">var x = 1; +{ + var x = 2; +} +console.log(x); // 2 기록</pre> + +<p>콘솔 출력 결과는 2입니다. 블록 밖의 <code>var x</code>와 블록 안의 <code>var x</code>는 같은 범위에 속하기 때문입니다. C나 Java에서 같은 코드를 작성한다면 1을 출력할 것입니다.</p> + +<h4 id="let과_const_사용_시"><code>let</code>과 <code>const</code> 사용 시</h4> + +<p>반면 {{jsxref("Statements/let", "let")}}과 {{jsxref("Statements/const", "const")}}로 선언한 식별자는 블록 범위를 <strong>가집니다</strong>.</p> + +<pre class="brush: js">let x = 1; +{ + let x = 2; +} +console.log(x); // 1 기록 +</pre> + +<p><code>x = 2</code>는 선언한 블록으로 범위가 제한됩니다.</p> + +<p><code>const</code>도 마찬가지입니다.</p> + +<pre class="brush: js">const c = 1; +{ + const c = 2; +} +console.log(c); // 1 기록, SyntaxError 없음</pre> + +<p>블록 내의 <code>const c = 2</code>가 <code>SyntaxError: Identifier 'c' has already been declared</code>를 던지지 않는 점에 주목하세요. 블록 범위 안이라 별개의 식별자이기 때문입니다.</p> + +<p>ES2015의 <a href="/ko/docs/Web/JavaScript/Reference/Strict_mode">엄격 모드</a>부터, 블록 내의 함수는 해당 블록으로 범위가 제한됩니다. ES2015 이전의 엄격 모드에서는 블록 레벨 함수를 사용할 수 없었습니다.</p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-block', 'Block statement')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-block', 'Block statement')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-12.1', 'Block statement')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES3', '#sec-12.1', 'Block statement')}}</td> + <td>{{Spec2('ES3')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-12.1', 'Block statement')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.statements.block")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Statements/while", "while")}}</li> + <li>{{jsxref("Statements/if...else", "if...else")}}</li> + <li>{{jsxref("Statements/let", "let")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/statements/break/index.html b/files/ko/web/javascript/reference/statements/break/index.html new file mode 100644 index 0000000000..fdbb79e719 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/break/index.html @@ -0,0 +1,119 @@ +--- +title: break +slug: Web/JavaScript/Reference/Statements/break +tags: + - JavaScript + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/break +--- +<div>{{jsSidebar("Statements")}}</div> + +<p><strong><code>break</code> 문</strong>은 현재 반복문, {{jsxref("Statements/switch", "switch")}} 문, 또는 {{jsxref("Statements/label", "label")}} 문을 종료하고, 그 다음 문으로 프로그램 제어를 넘깁니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/statement-break.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">break [<em>label</em>];</pre> + +<dl> + <dt><code>label</code> {{optional_inline}}</dt> + <dd>문의 라벨에 연결한 {{glossary("identifier", "식별자")}}. 반복문이나 {{jsxref("Statements/switch", "switch")}}에서 사용하는게 아니면 필수로 제공해야 합니다.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p><code>break</code> 문은 프로그램이 label 달린 문에서 빠져나오게 하는 선택사항 label을 포함합니다. <code>break</code> 문은 참조되는 label 내에 중첩되어야 합니다. label 달린 문은 어떤 {{jsxref("Statements/block", "block")}} 문이든 될 수 있습니다. 꼭, loop 문을 달 필요가 없습니다.</p> + +<h2 id="예제">예제</h2> + +<p>다음 함수는 <code>i</code>가 3일 때 {{jsxref("Statements/while", "while")}} loop를 종료하는 break 문이 있고, 그러고는 3 * <code>x</code>값을 반환합니다.</p> + +<pre class="brush:js;highlight:[6];">function testBreak(x) { + var i = 0; + + while (i < 6) { + if (i == 3) { + break; + } + i += 1; + } + + return i * x; +}</pre> + +<p>다음 코드는 label 달린 블록이 있는 <code>break</code> 문을 사용합니다. <code>break</code> 문은 자신이 참조하는 label 내에 중첩되어야 합니다. <code>inner_block</code>은 <code>outer_block</code>내에 중첩되어야 함을 주의하세요.</p> + +<pre class="brush:js;highlight:[1,2,4];">outer_block: { + inner_block: { + console.log('1'); + break outer_block; // inner_block과 outer_block 둘다 빠져나옴 + console.log(':-('); // 건너뜀 + } + console.log('2'); // 건너뜀 +} +</pre> + +<p>다음 코드는 또한 label 달린 블록이 있는 break 문을 사용하지만 그 <code>break</code> 문이 <code>block_2</code>를 참조하지만 <code>block_1</code> 내에 있기에 구문 오류(Syntax Error)가 발생합니다. <code>break</code> 문은 항상 자신이 참조하는 label 내에 중첩되어야 합니다.</p> + +<pre class="brush:js;highlight:[1,3,6];">block_1: { + console.log('1'); + break block_2; // SyntaxError: label을 찾을 수 없음 +} + +block_2: { + console.log('2'); +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Unlabeled version.</td> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Labeled version added.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-12.8', 'Break statement')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-break-statement', 'Break statement')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-break-statement', 'Break statement')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.statements.break")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Statements/continue", "continue")}}</li> + <li>{{jsxref("Statements/label", "label")}}</li> + <li>{{jsxref("Statements/switch", "switch")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/statements/class/index.html b/files/ko/web/javascript/reference/statements/class/index.html new file mode 100644 index 0000000000..bfb1c95027 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/class/index.html @@ -0,0 +1,119 @@ +--- +title: class +slug: Web/JavaScript/Reference/Statements/class +tags: + - Classes + - Declaration + - ECMAScript 2015 + - JavaScript + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/class +--- +<div>{{jsSidebar("Statements")}}</div> + +<p><strong><code>class</code> 선언</strong>은 프로토타입 기반 상속을 사용하여, 주어진 이름의 새로운 클래스를 만듭니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/statement-class.html")}}</div> + + + +<div class="noinclude"> +<p>{{jsxref("Operators/class", "클래스 표현", "", 1)}}을 사용하여 클래스를 정의할 수도 있습니다. 표현식과 달리 선언문으로는 같은 클래스를 다시 선언하면 오류가 발생합니다.</p> +</div> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">class <em>name</em> [extends] { + // class body +} +</pre> + +<h2 id="설명">설명</h2> + +<p>클래스 본문은 <a href="/ko/docs/Web/JavaScript/Reference/Strict_mode">엄격 모드</a>에서 실행됩니다. 생성자 속성은 선택 사항입니다..</p> + +<p>클래스 선언은 {{jsxref("Statements/function", "함수 선언", "", 0)}}과 달리 {{Glossary("Hoisting", "호이스팅")}}의 대상이 아닙니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="간단한_클래스_선언">간단한 클래스 선언</h3> + +<p>다음 예제는 우선 <code>Polygon</code> 클래스를 정의하고, <code>Square</code>라는 이름의 새로운 클래스가 <code>Polygon</code>을 상속합니다. 생성자 내부의 <code>super()</code>는 생성자 내에서만, 그리고 {{jsxref("Operators/this", "this")}} 키워드를 사용하기 전에만 쓸 수 있다는 점을 주의하세요.</p> + +<pre class="brush: js">class Polygon { + constructor(height, width) { + this.name = 'Polygon'; + this.height = height; + this.width = width; + } +} + +class Square extends Polygon { + constructor(length) { + super(length, length); + this.name = 'Square'; + } +}</pre> + +<div class="warning"> +<h3 id="같은_클래스를_두_번_선언하려고_시도할_때">같은 클래스를 두 번 선언하려고 시도할 때</h3> + +<p>클래스 선언문으로 같은 클래스를 두 번 선언하면 오류가 발생합니다.</p> + +<pre class="brush: js">class Foo {}; +class Foo {}; // Uncaught SyntaxError: Identifier 'Foo' has already been declared +</pre> + +<p>이전에 표현식으로 정의한 경우에도 오류가 발생합니다.</p> + +<pre class="brush: js">var Foo = class {}; +class Foo {}; // Uncaught TypeError: Identifier 'Foo' has already been declared +</pre> +</div> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES2016', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ES2016')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES2017', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ES2017')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.statements.class")}}</p> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("Statements/function", "function")}} 선언문</li> + <li>{{jsxref("Operators/class", "class")}} 표현식</li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Classes">클래스</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/statements/const/index.html b/files/ko/web/javascript/reference/statements/const/index.html new file mode 100644 index 0000000000..1cbd7ea7aa --- /dev/null +++ b/files/ko/web/javascript/reference/statements/const/index.html @@ -0,0 +1,136 @@ +--- +title: const +slug: Web/JavaScript/Reference/Statements/const +tags: + - ECMAScript 2015 + - JavaScript + - Reference + - Statement + - constants +translation_of: Web/JavaScript/Reference/Statements/const +--- +<div>{{jsSidebar("Statements")}}</div> + +<p><strong><code>const</code> 선언</strong>은 블록 범위의 상수를 선언합니다. 상수의 값은 재할당할 수 없으며 다시 선언할 수도 없습니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/statement-const.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">const <em>name1 = <em>value1 [</em>, <em>name2</em> = <em>value2</em><em> [</em>, ... [</em>, <em>nameN</em> = <em>valueN]]]</em>;</pre> + +<dl> + <dt><code>nameN</code></dt> + <dd>상수의 이름. 아무 유효한 {{Glossary("identifier", "식별자")}}를 사용할 수 있습니다.</dd> + <dt><code>valueN</code></dt> + <dd>상수의 값. 아무 유효한 <a href="/ko/docs/Web/JavaScript/Guide/Expressions_and_Operators#표현식">표현식</a>이나 가능합니다.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p>이 선언은 선언된 함수에 전역 또는 지역일 수 있는 상수를 만듭니다. 상수 초기자(initializer)가 필요합니다. 즉 선언되는 같은 문에 그 값을 지정해야 합니다(이는 나중에 변경될 수 없는 점을 감안하면 말이 됩니다).</p> + +<p>상수는 <code><a href="/ko/docs/Web/JavaScript/Reference/Statements/let">let</a></code> 문을 사용하여 정의된 변수와 마찬가지로 블록 범위(block-scope)입니다. 상수의 값은 재할당을 통해 바뀔 수 없고 재선언될 수 없습니다.</p> + +<p><code><a href="/ko/docs/Web/JavaScript/Reference/Statements/let">let</a></code>에 적용한 "<a href="/ko/docs/Web/JavaScript/Reference/Statements/let#Temporal_dead_zone_and_errors_with_let" title="temporal dead zone">일시적 사각 지대</a>"에 관한 모든 고려는, <code>const</code>에도 적용합니다.</p> + +<p>상수는 같은 범위의 상수 또는 변수와 그 이름을 공유할 수 없습니다.</p> + +<h2 id="예제">예제</h2> + +<p>다음 예제는 상수가 어떻게 동작하는지 보입니다. 브라우저 콘솔에서 따라해보세요.</p> + +<pre class="brush:js">// 주의: 상수 선언에는 대소문자 모두 사용할 수 있지만, +// 일반적인 관습은 모두 대문자를 사용하는 것입니다. + +// MY_FAV를 상수로 정의하고 그 값을 7로 함 +const MY_FAV = 7; + +// 에러가 발생함 +MY_FAV = 20; + +// 7 출력 +console.log("my favorite number is: " + MY_FAV); + +// 상수를 재선언하려는 시도는 오류 발생 - Uncaught SyntaxError: Identifier 'MY_FAV' has already been declared +const MY_FAV = 20; + +// MY_FAV라는 이름은 위에서 상수로 예약되어 있어서 역시 실패함. +var MY_FAV = 20; + +<code>// 역시 오류가 발생함 +let MY_FAV = 20; + +// 블록 범위의 특성을 아는게 중요 +if (MY_FAV === 7) { + // 블록 범위로 지정된 MY_FAV 라는 변수를 만드므로 괜찮습니다 + // (let으로 const 변수가 아닌 블록 범위를 선언하는 것과 똑같이 동작합니다) + let MY_FAV = 20; + + // MY_FAV는 이제 20입니다 + console.log('my favorite number is ' + MY_FAV); + + // 이 선언은 전역으로 호이스트되고 에러가 발생합니다. + var MY_FAV = 20; +} + +// MY_FAV는 여전히 7 +console.log('my favorite number is ' + MY_FAV); + +// const 선언시에 초기값을 생략해서 오류 발생 +const FOO; + +// const는 오브젝트에도 잘 동작합니다 +const MY_OBJECT = {'key': 'value'}; + +// 오브젝트를 덮어쓰면 오류가 발생합니다 +MY_OBJECT = {'OTHER_KEY': 'value'}; + +// 하지만 오브젝트의 키는 보호되지 않습니다. +// 그러므로 아래 문장은 문제없이 실행됩니다 +MY_OBJECT.key = 'otherValue'; // 오브젝트를 변경할 수 없게 하려면 Object.freeze() 를 사용해야 합니다 + +// 배열에도 똑같이 적용됩니다 +const MY_ARRAY = []; +// 배열에 아이템을 삽입하는 건 가능합니다 +MY_ARRAY.push('A'); // ["A"] +// 하지만 변수에 새로운 배열을 배정하면 에러가 발생합니다 +MY_ARRAY = ['B']</code></pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-let-and-const-declarations', 'Let and Const Declarations')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-let-and-const-declarations', 'Let and Const Declarations')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.statements.const")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Reference/Statements/var"><code>var</code></a></li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Statements/let"><code>let</code></a></li> + <li><a href="/ko/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#Constants">JavaScript 안내서의 상수</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/statements/continue/index.html b/files/ko/web/javascript/reference/statements/continue/index.html new file mode 100644 index 0000000000..f0d67deea2 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/continue/index.html @@ -0,0 +1,164 @@ +--- +title: continue +slug: Web/JavaScript/Reference/Statements/continue +translation_of: Web/JavaScript/Reference/Statements/continue +--- +<div>{{jsSidebar("Statements")}}</div> + +<p><strong>continue</strong> 문은 현재 또는 레이블이 지정된 루프의 현재 반복에서 명령문의 실행을 종료하고 반복문의 처음으로 돌아가여 루프문의 다음 코드를 실행합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/statement-continue.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">continue [<em>label</em>];</pre> + +<dl> + <dt><code>label</code></dt> + <dd> + <p>명령문의 레이블과 연관된 식별자.</p> + </dd> +</dl> + +<h2 id="설명">설명</h2> + +<p>{{jsxref ( "Statements / break", "break")}} 문과 달리 <code>continue</code>는 루프의 실행을 완전히 종료하지 않고 <code>for</code>, <code>while</code>문에서 다음과 같이 동작합니다.</p> + +<ul> + <li>{{jsxref ( "Statements / while", "while")}} 루프에서는 다시 조건으로 점프합니다.</li> +</ul> + +<ul> + <li>{{jsxref ( "Statements / for", "for")}} 루프에서는 업데이트 표현식으로 점프합니다.</li> +</ul> + +<p><code>continue</code> 문에는 현재 루프 대신 레이블이 지정된 루프 문의 다음 반복으로 건너 뛰도록하는 선택적 레이블이 포함될 수 있습니다. 이 경우, <code>continue</code> 문은 이 레이블 된 명령문 내에 중첩되어야합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="Using_continue_with_while">Using <code>continue</code> with <code>while</code></h3> + +<p>다음 예제에서는 <code>i</code>의 값이 3일 때 실행되는 <code>continue</code>문을 포함하는 {{jsxref("Statements/while", "while")}}을 보여줍니다. 따라서 n은 1, 3, 7 및 12 값을 갖습니다.</p> + +<pre class="brush: js">var i = 0; +var n = 0; + +while (i < 5) { + i++; + + if (i === 3) { + continue; + } + + n += i; +} +</pre> + +<h3 id="label과_함께_continue_사용하기">label과 함께 <code>continue</code> 사용하기</h3> + +<p>다음 예제에서 <code>checkiandj</code>라는 문에는 <code>checkj</code>라는 문이 있습니다. <code>continue</code>가 발생하면 프로그램은 <code>checkj</code> 문의 맨 위에서 계속됩니다. <code>continue</code>가 발생할 때마다 <code>checkj</code>는 조건이 false를 반환 할 때까지 반복합니다. false가 리턴되면 나머지 <code>checkiandj</code> 문이 완료됩니다.</p> + +<p><code>continue</code>에 <code>checkiandj</code> 레이블이 있으면이 프로그램은 <code>checkiandj</code> 문 맨 위에서 계속됩니다.</p> + +<p>See also {{jsxref("Statements/label", "label")}}.</p> + +<pre class="brush: js">var i = 0; +var j = 8; + +checkiandj: while (i < 4) { + console.log('i: ' + i); + i += 1; + + checkj: while (j > 4) { + console.log('j: ' + j); + j -= 1; + + if ((j % 2) == 0) + continue checkj; + console.log(j + ' is odd.'); + } + console.log('i = ' + i); + console.log('j = ' + j); +} +</pre> + +<p>출력:</p> + +<pre class="brush: js">i: 0 + +// start checkj +j: 8 +7 is odd. +j: 7 +j: 6 +5 is odd. +j: 5 +// end checkj + +i = 1 +j = 4 + +i: 1 +i = 2 +j = 4 + +i: 2 +i = 3 +j = 4 + +i: 3 +i = 4 +j = 4 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Unlabeled version.</td> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Labeled version added.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-12.7', 'Continue statement')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-continue-statement', 'Continue statement')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-continue-statement', 'Continue statement')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.statements.continue")}}</p> + +<h2 id="함께_보기">함께 보기</h2> + +<ul> + <li>{{jsxref("Statements/break", "break")}}</li> + <li>{{jsxref("Statements/label", "label")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/statements/debugger/index.html b/files/ko/web/javascript/reference/statements/debugger/index.html new file mode 100644 index 0000000000..4f081282b9 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/debugger/index.html @@ -0,0 +1,79 @@ +--- +title: debugger +slug: Web/JavaScript/Reference/Statements/debugger +tags: + - JavaScript + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/debugger +--- +<div>{{jsSidebar("Statements")}}</div> + +<p><strong><code>debugger</code> 문</strong>은 중단점 설정 등 현재 사용할 수 있는 디버그 기능을 호출합니다. 사용할 수있는 디버깅 기능이 없으면 아무런 동작도 하지 않습니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">debugger;</pre> + +<h2 id="예제">예제</h2> + +<p>다음 예제에서는 함수가 호출 시 디버거를 활성화하도록 <code>debugger</code>를 삽입한 모습입니다.</p> + +<pre class="brush:js">function potentiallyBuggyCode() { + debugger; + // 버그가 있을 것으로 생각하는 코드를 분석하거나, 한 단계씩 진행해보거나... +}</pre> + +<p>디버거가 활성화되면 디버거 문의 위치에서 실행이 일시중지됩니다. 스크립트 소스의 중단점과 비슷합니다.</p> + +<p><a href="https://mdn.mozillademos.org/files/6963/Screen Shot 2014-02-07 at 9.14.35 AM.png"><img alt="Paused at a debugger statement." src="https://mdn.mozillademos.org/files/6963/Screen%20Shot%202014-02-07%20at%209.14.35%20AM.png" style="height: 371px; width: 700px;"></a></p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-debugger-statement', 'Debugger statement')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-debugger-statement', 'Debugger statement')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-12.15', 'Debugger statement')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition</td> + </tr> + <tr> + <td>{{SpecName('ES3', '#sec-7.5.3', 'Debugger statement')}}</td> + <td>{{Spec2('ES3')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-7.4.3', 'Debugger statement')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Only mentioned as reserved word.</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.statements.debugger")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Mozilla/Debugging/Debugging_JavaScript">JavaScript 디버깅</a></li> + <li><a href="/ko/docs/도구들/Debugger">Firefox 개발자 도구의 디버거</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/statements/default/index.html b/files/ko/web/javascript/reference/statements/default/index.html new file mode 100644 index 0000000000..d8d107e774 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/default/index.html @@ -0,0 +1,121 @@ +--- +title: default +slug: Web/JavaScript/Reference/Statements/default +tags: + - JavaScript + - Keyword + - Reference +translation_of: Web/JavaScript/Reference/Statements/switch +--- +<div>{{jsSidebar("Statements")}}</div> + +<p><code><strong>default</strong></code> 키워드는 {{jsxref("Statements/switch", "switch")}} 구문과 {{jsxref("Statements/export", "export")}} 구문에서 사용할 수 있습니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/statement-default.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<p>{{jsxref("Statements/switch", "switch")}} 구문 내에서는 다음과 같이 사용합니다.</p> + +<pre class="syntaxbox">switch (expression) { + case value1: + //Statements executed when the result of expression matches value1 + [break;] + default: + //Statements executed when none of the values match the value of the expression + [break;] +}</pre> + +<p>{{jsxref("Statements/export", "export")}} 구문 내에서는 다음과 같이 사용합니다.</p> + +<pre class="syntaxbox">export default <em>nameN</em> </pre> + +<h2 id="설명">설명</h2> + +<p>세부사항을 보려면,</p> + +<ul> + <li>{{jsxref("Statements/switch", "switch")}} 구문,</li> + <li>{{jsxref("Statements/export", "export")}} 구문 페이지를 확인하세요.</li> +</ul> + +<h2 id="예제">예제</h2> + +<h3 id="switch에서_default_사용"><code>switch</code>에서 <code>default</code> 사용</h3> + +<p>아래 예제에서 <code>expr</code> 이 "오렌지" 또는 "사과"일 때, 프로그램은 값을 "오렌지" 또는 "사과"와 일치시키고 해당 명령문을 실행합니다. 기본(<code>default</code>) 키워드는 다른 경우에 도움이 되며 연관된 명령문을 실행합니다.</p> + +<pre class="brush: js">switch (expr) { + case '오렌지': + console.log('오렌지는 1000원입니다.'); + break; + case '사과': + console.log('사과는 500원입니다.'); + break; + default: + console.log('죄송합니다. ' + expr + '의 재고가 다 떨어졌습니다.'); +}</pre> + +<h3 id="export에서_default_사용"><code>export</code>에서 <code>default</code> 사용</h3> + +<p>단일 값을 내보내거나 모듈의 기본 값이 필요한 경우, 기본 내보내기를 사용할 수 있습니다.</p> + +<pre class="brush: js">// module "my-module.js" +let cube = function cube(x) { + return x * x * x; +}; +export default cube;</pre> + +<p>다른 스크립트에서 가져오는 건 간단합니다.</p> + +<pre class="brush: js">// module "my-module.js" +import cube from 'my-module'; //default export gave us the liberty to say import cube, instead of import cube from 'my-module' +console.log(cube(3)); // 27 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-switch-statement', 'switch statement')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-exports', 'Exports')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-switch-statement', 'switch statement')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-exports', 'Exports')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.statements.default")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Statements/export", "export")}}</li> + <li>{{jsxref("Statements/switch", "switch")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/statements/do...while/index.html b/files/ko/web/javascript/reference/statements/do...while/index.html new file mode 100644 index 0000000000..f6d2e00c57 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/do...while/index.html @@ -0,0 +1,78 @@ +--- +title: do...while +slug: Web/JavaScript/Reference/Statements/do...while +tags: + - 구문 + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Statements/do...while +--- +<div>{{jsSidebar("Statements")}}</div> + +<p><strong><code>do...while</code> 문은</strong> 테스트 조건이 거짓으로 평가될 때까지 지정된 구문을 실행하는 루프를 만듭니다.<br> + 단, 구문이 실행된 뒤에 테스트 조건이 평가됨으로 구문은 무조건 한 번은 실행됩니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/statement-dowhile.html")}}</div> + +<div class="hidden">이 예제의 소스는 GitHub 저장소에 저장됩니다. 만약 이 프로젝트에 기여하고 싶으시다면, <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> 를 복사하고 저희에게 pull request 를 보내주십시오.</div> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox notranslate">do<em>구문</em> +while (<em>조건식</em>); +</pre> + +<dl> + <dt><code><em>구문</em></code></dt> + <dd>테스트 조건이 참일 때마다 한 번이상 실행되는 구문입니다. 만약 루프 내에서 여러 구문을 반복 실행 시키고 싶으시다면, 다음 명령을 사용합니다.</dd> + <dd>{{jsxref("Statements/block", "block", "", 1)}} 구문을 활용하여 (<code>{ ... }</code>) 이런 식으로 그룹화합니다.</dd> +</dl> + +<dl> + <dt><code><em>조건식</em></code></dt> + <dd>루프가 실행될 때마다 평가되는 식입니다. 만약 조건식이 참으로 평가되었다면, <code>구문</code> 이 다시 실행됩니다. 만약 조건식이 거짓으로 평가되었다면, 자바스크립트는 <code>do...while</code>. 구문 밑에 있는 구문들을 실행시킵니다.</dd> +</dl> + +<h2 id="Examples" name="Examples">예제</h2> + +<h3 id="do...while"><code>do...while</code></h3> + +<p>예제에서 <code>do...while</code> 문은 적어도 한번 반복되고 i 변수가 5 보다 작을 때까지 실행됩니다.</p> + +<pre class="brush: js notranslate">var result = ''; +var i = 0; +do { + i += 1; + result += i + ' '; +} +while (i > 0 && i < 5); +// Despite i == 0 this will still loop as it starts off without the test + +console.log(result);</pre> + +<h2 id="자세한_내용">자세한 내용</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-do-while-statement', 'do-while statement')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div class="hidden">이 페이지의 브라우저 호환성 표는 구조화된 데이터에서 생성되었습니다. 만약 이 문서에 기여하고 싶으시다면, <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> 문서를 확인하고 수정한 뒤 pull request 를 보내주십시오.</div> + +<p>{{Compat("javascript.statements.do_while")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Statements/while", "while")}}</li> + <li>{{jsxref("Statements/for", "for")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/statements/empty/index.html b/files/ko/web/javascript/reference/statements/empty/index.html new file mode 100644 index 0000000000..c986c6232a --- /dev/null +++ b/files/ko/web/javascript/reference/statements/empty/index.html @@ -0,0 +1,102 @@ +--- +title: empty +slug: Web/JavaScript/Reference/Statements/Empty +translation_of: Web/JavaScript/Reference/Statements/Empty +--- +<div>{{jsSidebar("Statements")}}</div> + +<p><strong>empty</strong> 문은 JavaScript 아무것도 동작하지 않습니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/statement-empty.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">; +</pre> + +<h2 id="설명">설명</h2> + +<p>empty statement은 JavaScript구문에 하나가 필요할 때 어떤 문도 실행되지 않을 것이라는 것을 나타내는 세미 콜론(;)입니다. 여러개의 문장을 원하지만 JavaScript는 <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/block">block statement</a>을 사용하여 하나만 허용하며 여러개의 문장을 하나로 결합합니다.</p> + +<h2 id="예제">예제</h2> + +<p>빈 문은 루프 문과 함께 사용되기도합니다. 빈 루프 본문이있는 다음 예제를 참조하십시오.</p> + +<pre class="brush: js">var arr = [1, 2, 3]; + +// Assign all array values to 0 +for (i = 0; i < arr.length; arr[i++] = 0) /* empty statement */ ; + +console.log(arr) +// [0, 0, 0] +</pre> + +<p><strong>참고:</strong> 정상적인 세미 콜론을 구분하는 것이 그리 쉽지 않기 때문에, empty statement를 사용할 때는 의도적으로 주석을 달아주는것이 좋습니다. 다음 예 에서는 의도한대로 코드가 동작하지 않을것입니다. 아마도 killTheUniverse()를 if문 안에서 실행하고자 했던것 같습니다.</p> + +<pre class="brush: js">if (condition); // Caution, this "if" does nothing! + killTheUniverse() // So this always gets executed!!! +</pre> + +<p>다른 예 : 중괄호 ({})가없는 <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/if...else"><code>if...else</code></a> 문에서 <code>three</code>가 <code>true</code>이면 아무 일도 일어나지 않고 <code>four</code>를 건너 뛰고 else case의 launchRocket() 함수도 실행되지 않습니다.</p> + +<pre class="brush: js">if (one) + doOne(); +else if (two) + doTwo(); +else if (three) + ; // nothing here +else if (four) + doFour(); +else + launchRocket();</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-empty-statement', 'Empty statement')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-empty-statement', 'Empty statement')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-12.3', 'Empty statement')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES3', '#sec-12.3', 'Empty statement')}}</td> + <td>{{Spec2('ES3')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-12.3', 'Empty statement')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.statements.empty")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Statements/block", "Block statement")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/statements/export/index.html b/files/ko/web/javascript/reference/statements/export/index.html new file mode 100644 index 0000000000..1c15d4e7f9 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/export/index.html @@ -0,0 +1,199 @@ +--- +title: export +slug: Web/JavaScript/Reference/Statements/export +tags: + - ECMAScript 2015 + - JavaScript + - Modules + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/export +--- +<div>{{jsSidebar("Statements")}}</div> + +<p><strong><code>export</code></strong> 문은 JavaScript 모듈에서 함수, 객체, 원시 값을 내보낼 때 사용합니다. 내보낸 값은 다른 프로그램에서 {{jsxref("Statements/import", "import")}} 문으로 가져가 사용할 수 있습니다.</p> + +<p>내보내는 모듈은 <code>"use strict"</code>의 존재 유무와 상관없이 무조건 <a href="/ko/docs/Web/JavaScript/Reference/Strict_mode">엄격 모드</a>입니다. <code>export</code> 문은 HTML 안에 작성한 스크립트에서는 사용할 수 없습니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">// 하나씩 내보내기 +export let <var>name1</var>, <var>name2</var>, …, <var>nameN</var>; // var, const도 동일 +export let <var>name1</var> = …, <var>name2</var> = …, …, <var>nameN</var>; // var, const도 동일 +export function functionName(){...} +export class ClassName {...} + +// 목록으로 내보내기 +export { <var>name1</var>, <var>name2</var>, …, <var>nameN</var> }; + +// 내보내면서 이름 바꾸기 +export { <var>variable1</var> as <var>name1</var>, <var>variable2</var> as <var>name2</var>, …, <var>nameN</var> }; + +// 비구조화로 내보내기 +export const { <var>name1</var>, <var>name2: bar</var> } = o; + +// 기본 내보내기 +export default <em>expression</em>; +export default function (…) { … } // also class, function* +export default function name1(…) { … } // also class, function* +export { <var>name1</var> as default, … }; + +// 모듈 조합 +export * from …; // does not set the default export +export * as name1 from …; +export { <var>name1</var>, <var>name2</var>, …, <var>nameN</var> } from …; +export { <var>import1</var> as <var>name1</var>, <var>import2</var> as <var>name2</var>, …, <var>nameN</var> } from …; +export { default } from …;</pre> + +<dl> + <dt><code>nameN</code></dt> + <dd>내보낼 식별자 이름. {{jsxref("Statements/import", "import")}}를 사용해 다른 스크립트에서 가져갈 수 있습니다.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p>내보내기에는 두 종류, <strong>유명</strong>(named)과 <strong>기본</strong>(default) 내보내기가 있습니다. 모듈 하나에서, 유명 내보내기는 여러 개 존재할 수 있지만 기본 내보내기는 하나만 가능합니다. 각 종류는 위의 구문 중 하나와 대응합니다.</p> + +<ul> + <li>유명 내보내기 + <pre class="brush: js">// 먼저 선언한 식별자 내보내기 +export { myFunction, myVariable }; + +// 각각의 식별자 내보내기 +// (변수, 상수, 함수, 클래스) +export let myVariable = Math.sqrt(2); +export function myFunction() { ... }; +</pre> + </li> + <li>기본 내보내기 + <pre class="brush: js">// 먼저 선언한 식별자 내보내기 +export { myFunction as default }; + +// 각각의 식별자 내보내기 +export default function () { ... }; +export default class { ... } +</pre> + </li> +</ul> + +<p>유명 내보내기는 여러 값을 내보낼 때 유용합니다. 가져갈 때는 내보낸 이름과 동일한 이름을 사용해야 합니다.</p> + +<p>반면 기본 내보내기는 어떤 이름으로도 가져올 수 있습니다.</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="comment token">// test.js</span> +<span class="keyword token">let</span> k<span class="punctuation token">;</span> <span class="keyword token">export</span> <span class="keyword token">default</span> k <span class="operator token">=</span> <span class="number token">12</span><span class="punctuation token">;</span></code></pre> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="comment token">// 임의의 다른 파일</span> +<span class="keyword token">import</span> m <span class="keyword token">from</span> <span class="string token">'./test'</span><span class="punctuation token">;</span> <span class="comment token">// k가 기본 내보내기이므로, 가져오는 이름으로 k 대신 m을 사용해도 문제 없음</span> +console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span>m<span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// 12 기록</span></code></pre> + +<p>식별자 충돌을 피하기 위해 유명 내보내기 중 이름을 바꿔줄 수도 있습니다.</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">export</span> <span class="punctuation token">{</span> myFunction <span class="keyword token">as</span> function1<span class="punctuation token">,</span> + myVariable <span class="keyword token">as</span> variable <span class="punctuation token">}</span><span class="punctuation token">;</span></code></pre> + +<h3 id="다시_내보내기_조합">다시 내보내기 / 조합</h3> + +<p>부모 모듈이 자식 모듈을 가져와서 다시 내보낼 수도 있습니다. 즉, 여러 개의 모듈을 모아놓을 하나의 모듈을 만들 수 있습니다.</p> + +<pre class="brush: js">export foo from 'bar.js'; +</pre> + +<p>위 구문은 아래와 동일합니다.</p> + +<pre class="brush: js">import foo from 'bar.js'; +export foo; +</pre> + +<h2 id="예제">예제</h2> + +<h3 id="유명_내보내기_사용">유명 내보내기 사용</h3> + +<p>어떤 모듈에서 다음과 같은 코드를 가진다고 해보겠습니다.</p> + +<pre class="brush: js">// module "my-module.js" +function cube(x) { + return x * x * x; +} +const foo = Math.PI + Math.SQRT2; +var graph = { + options: { + color:'white', + thickness:'2px' + }, + draw: function() { + console.log('From graph draw function'); + } +} +export { cube, foo, graph };</pre> + +<p>다른 스크립트에서는 아래와 같이 사용할 수 있습니다.</p> + +<pre class="brush: js">// You should use this script in html with the type module. +// For example: +// <script type="module" src="./demo.js"></script> +// +// Open the page in a http server, otherwise there will be a CORS policy error. +// +// script demo.js + +import { cube, foo, graph } from 'my-module'; +graph.options = { + color:'blue', + thickness:'3px' +}; +graph.draw(); +console.log(cube(3)); // 27 +console.log(foo); // 4.555806215962888</pre> + +<h3 id="기본_내보내기_사용">기본 내보내기 사용</h3> + +<p>단일 값을 내보낼 때나 모듈의 폴백<sup>fallback</sup> 값이 필요할 땐 기본 내보내기를 사용할 수 있습니다.</p> + +<pre class="brush: js">// module "my-module.js" +export default function cube(x) { + return x * x * x; +}</pre> + +<p>그런 다음, 다른 스크립트에서 가져오는건 간단합니다:</p> + +<pre class="brush: js">import cube from './my-module.js'; +console.log(cube(3)); // 27</pre> + +<p><code><font face="Open Sans, arial, sans-serif">e</font>xport default</code>를 사용할 때 <code>var</code>, <code>let</code>, <code>const</code>는 사용하지 못합니다.</p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-exports', 'Exports')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-exports', 'Exports')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.statements.export")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Statements/import", "import")}}</li> + <li><a href="/ko/docs/Web/JavaScript/Guide/Modules">JavaScript 모듈</a> 안내서</li> + <li><a href="https://hacks.mozilla.org/2015/08/es6-in-depth-modules/">ES6 in Depth: Modules</a>, Hacks blog post by Jason Orendorff</li> + <li><a href="https://hacks.mozilla.org/2018/03/es-modules-a-cartoon-deep-dive/">ES modules: A cartoon deep-dive</a>, Hacks blog post by Lin Clark</li> + <li><a href="http://exploringjs.com/es6/ch_modules.html">Axel Rauschmayer's book: "Exploring JS: Modules"</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/statements/for-await...of/index.html b/files/ko/web/javascript/reference/statements/for-await...of/index.html new file mode 100644 index 0000000000..c52d226e27 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/for-await...of/index.html @@ -0,0 +1,144 @@ +--- +title: for await...of +slug: Web/JavaScript/Reference/Statements/for-await...of +tags: + - 구문 + - 반복문 + - 비동기 + - 식 + - 열거 + - 열거자 +translation_of: Web/JavaScript/Reference/Statements/for-await...of +--- +<div>{{jsSidebar("Statements")}}</div> + +<p><strong><code>for await...of</code> 구문</strong>은 보통 비동기에 대응하는 열거자를 나열할 때 쓰이지만, {{jsxref("String")}}, {{jsxref("Array")}}, <code>Array</code> 같은 객체 (e.g., {{jsxref("Functions/arguments", "arguments")}} or <a href="/en-US/docs/Web/API/NodeList" title="NodeList objects are collections of nodes, usually returned by properties such as Node.childNodes and methods such as document.querySelectorAll()."><code>NodeList</code></a>), {{jsxref("TypedArray")}}, {{jsxref("Map")}}, {{jsxref("Set")}} 같은 동기적으로 열거 가능한 객체 또한 가능하며, 사용자가 직접 정의한 동기 또는 비동기 객체도 나열할 수 있도록 해준다. 일반적인 <strong><code>for ...of</code></strong> 문과 마찬가지로 열거자 심볼이 정의한 속성을 실행하게 되어 열거한 값을 변수로 받아 처리한다.</p> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">for await (<var>variable</var> of <var>iterable</var>) { + <var>statement</var> +} +</pre> + +<dl> + <dt><code><var>variable</var></code></dt> + <dd>열거할 때마다 <code><var>variable</var></code>. 문을 통해 변수로 받을 수 있다. <code><var>variable</var></code> 문 안에서는 <code>const</code>, <code>let</code> 및 <code>var</code>. 문으로 선언된 변수 및 상수를 선언할 수 있다.</dd> + <dt><code><var>iterable</var></code></dt> + <dd>열거 가능한 속성이 들어가 있는 객체 및 식을 포함한다.</dd> +</dl> + +<h3 id="비동기_열거_속성을_통한_열거_식">비동기 열거 속성을 통한 열거 식</h3> + +<p>비동기 열거 프로토콜을 담은 객체를 아래와 같이 열거할 수 있다.</p> + +<pre class="brush:js">const asyncIterable = { + [Symbol.asyncIterator]() { + return { + i: 0, + next() { + if (this.i < 3) { + return Promise.resolve({ value: this.i++, done: false }); + } + + return Promise.resolve({ done: true }); + } + }; + } +}; + +(async function() { + for await (let num of asyncIterable) { + console.log(num); + } +})(); + +// 0 +// 1 +// 2 +</pre> + +<h3 id="비동기_생성자를_통한_열거_식">비동기 생성자를 통한 열거 식</h3> + +<p>비동기 생성자는 애초부터 비동기 열거 프로토콜을 탑재한 채로 정의한다.이를 <code>for await...of</code> 식으로 아래와 같이 사용할 수 있다.</p> + +<pre class="brush: js">async function* asyncGenerator() { + let i = 0; + while (i < 3) { + yield i++; + } +} + +(async function() { + for await (let num of asyncGenerator()) { + console.log(num); + } +})(); +// 0 +// 1 +// 2</pre> + +<p>좀 더 상세한 비동기 생성자를 통한 <code>for await...of </code>식의 사용법을 위해 기본 API를 통해 값을 비동기적으로 열거하는 방법을 알아본다.</p> + +<p>아래 예제를 통해 먼저 API를 사용하여 스트림 데이터를 통해 비동기 열거자를 만든 뒤, 스트림에서 응답이 끝나면 최종 응답 데이터 크기를 가져온다.</p> + +<pre class="brush: js">async function* streamAsyncIterator(stream) { + const reader = stream.getReader(); + try { + while (true) { + const { done, value } = await reader.read(); + if (done) { + return; + } + yield value; + } + } finally { + reader.releaseLock(); + } +} +// 주소로부터 데이터를 받아온 뒤, 응답 크기를 구하는 비동기 생성자 함수. +async function getResponseSize(url) { + const response = await fetch(url); + // 여기에 응답 크기를 바이트 단위로 적재한다. + let responseSize = 0; + // for-await-of 문을 통해 응답이 들어올 때마다 열거 프로토콜을 통해 반복문이 작동한다. + for await (const chunk of streamAsyncIterator(response.body)) { + // 총 응답 크기를 지속적으로 누적한다. + responseSize += chunk.length; + } + + console.log(`응답 크기: ${responseSize} 바이트`); + // 예상 출력: "응답 크기: 1071472 바이트" + return responseSize; +} +getResponseSize('https://jsonplaceholder.typicode.com/photos');</pre> + +<h2 id="규격">규격</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-for-in-and-for-of-statements', 'ECMAScript Language: The for-in, for-of, and for-await-of Statements')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.statements.for_await_of")}}</p> + +<h2 id="같이보기">같이보기</h2> + +<ul> + <li>{{jsxref("Global_Objects/Symbol/asyncIterator", "Symbol.asyncIterator")}}</li> + <li>{{jsxref("Statements/for...of", "for...of")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/statements/for...in/index.html b/files/ko/web/javascript/reference/statements/for...in/index.html new file mode 100644 index 0000000000..983e50c91f --- /dev/null +++ b/files/ko/web/javascript/reference/statements/for...in/index.html @@ -0,0 +1,176 @@ +--- +title: for...in +slug: Web/JavaScript/Reference/Statements/for...in +tags: + - JavaScript + - Statement +translation_of: Web/JavaScript/Reference/Statements/for...in +--- +<div>{{jsSidebar("Statements")}}</div> + +<p><code>for...in</code>문은 상속된 열거 가능한 속성들을 포함하여 객체에서 문자열로 키가 지정된 모든 열거 가능한 속성에 대해 반복합니다. (<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol">Symbol</a>로 키가 지정된 속성은 무시합니다.)</p> + +<p>{{EmbedInteractiveExample("pages/js/statement-forin.html")}}</p> + +<h2 id="Syntax" name="Syntax">문법</h2> + +<pre class="syntaxbox notranslate">for (<var>variable</var> in <var>object</var>) {<em> ... </em>}</pre> + +<h3 id="Parameters" name="Parameters">파라미터</h3> + +<dl> + <dt><code>variable</code></dt> + <dd>매번 반복마다 다른 속성이름(Value name)이 변수(<em>variable)</em>로 지정됩니다.</dd> + <dt><code>object</code></dt> + <dd>반복작업을 수행할 객체로 열거형 속성을 가지고 있는 객체.</dd> +</dl> + +<h2 id="Description" name="Description">설명</h2> + +<p><code>for...in</code>문은 열거 가능한 non-Symbol 속성에 대해서만 반복합니다.<br> + <code>Array</code>나 <code>Object</code> 등 내장 constructor를 통해 만들어진 객체는 {{jsxref("String")}}의 {{jsxref("String.indexOf", "indexOf()")}}, {{jsxref("Object")}}의 {{jsxref("Object.toString", "toString()")}}와 같이 <code>Object.prototype</code>, <code>String.prototype</code> 로부터 열거가 가능하지 않은 속성들을 상속해왔습니다. <code>for...in</code>문은 객체 자체의 모든 열거 가능한 속성들과 프로토타입 체인으로부터 상속받은 속성들에 대해 반복할 것입니다. (더 가까운 프로토타입의 속성들이 프로토타입 체인 객체로부터 더 멀리 떨어진 프로토 타입의 속성보다 더 우선합니다.)</p> + +<h3 id="속성의_삭제_추가_수정">속성의 삭제, 추가, 수정 </h3> + +<p><code>for..in</code> 문은 임의의 순서로 객체의 속성들에 대해 반복합니다. (적어도 <code>cross-browser</code> 설정에서는 왜 표면적으로 보이는 반복의 순서를 따를 수 없는지에 대해서 {{jsxref("Operators/delete", "delete")}} 를 참고하십시오.)</p> + +<p>만약 한 반복으로 속성이 수정된 후에 방문하는 경우, 반복문에서의 그 값은 나중의 값으로 정해집니다. 방문하기 전에 삭제된 속성에 대해서는 이후에 방문하지 않습니다. 반복이 발생하는 객체에 추가된 속성은 방문하거나 반복에서 생략할 수 있습니다.</p> + +<p>일반적으로 현재 방문 중인 속성 외에는 반복하는 동안 객체의 속성을 추가, 수정, 제거하지 않는 것이 가장 좋습니다. 추가된 속성을 방문할 것인지, 수정된 속성(현재의 속성 제외)을 수정 이전 혹은 이후에 방문할 것인지, 삭제된 속성을 삭제 이전에 방문할 것인지에 대해서는 보장할 수 없습니다.</p> + +<h3 id="배열의_반복과_for...in">배열의 반복과 for...in</h3> + +<div class="note" id="arrayNote"> +<p><strong>Note: <code>for...in</code>은</strong> 인덱스의 순서가 중요한<strong> </strong>{{jsxref("Array")}}에서 반복을 위해 사용할 수 없습니다.</p> +</div> + +<p>배열 인덱스는 정수로 된 열거 가능한 속성이며, 일반적인 객체의 속성들과 같습니다. <code>for...in</code>은 특정 순서에 따라 인덱스를 반환하는 것을 보장할 수 없습니다. <code>for...in</code>반복문은 정수가 아닌 이름을 가진 속성, 상속된 모든 열거 가능한 속성들을 반환합니다.</p> + +<p>반복되는 순서는 구현에 따라 다르기 때문에, 배열의 반복이 일관된 순서로 요소를 방문하지 못할 수도 있습니다. 그러므로 방문의 순서가 중요한 배열의 반복시에는 숫자 인덱스를 사용할 수 있는 <code>for</code> 반복문을 사용하는 것이 좋습니다.(또는 {{jsxref("Array.prototype.forEach()")}}, {{jsxref("Statements/for...of", "for...of")}}를 권장합니다.)</p> + +<h3 id="자체_속성만_반복">자체 속성만 반복</h3> + +<p>만약 당신이 객체의 프로토타입이 아닌 객체 자체에 연결된 속성만 고려한다면 {{jsxref("Object.getOwnPropertyNames", "getOwnPropertyNames()")}}나 {{jsxref("Object.prototype.hasOwnProperty", "hasOwnProperty()")}}를 사용하십시오.({{jsxref("Object.prototype.propertyIsEnumerable", "propertyIsEnumerable()")}} 또한 가능합니다.) 또는 외부적인 코드 간섭이 없다면 체크 메서드로 내장 프로토타입을 확장할 수 있습니다.</p> + +<h2 id="왜_for...in을_사용합니까">왜 for...in을 사용합니까?</h2> + +<p><code>for...in</code>이 객체의 반복을 위해 만들어졌지만, 배열의 반복을 위해서는 추천되지 않고, <code>Array.prototype.forEach()</code>, <code>for...of</code>가 이미 존재합니다. 그러면 for...in은 어떻게 사용하는 것이 좋을까요?</p> + +<p>이것은 쉽게 객체의 속성을 확인(콘솔이나 다른 방법으로 출력)할 수 있기 때문에 실질적으로 디버깅을 위해 사용될 수 있습니다. 배열이 데이터의 저장에 있어서는 더 실용적이지만, 키-값 쌍이 선호되는 데이터의 경우(속성이 "key"의 역할을 함) 특정 값을 가진 키가 있는지 확인하려는 경우에 for...in을 사용할 수 있습니다.</p> + +<h2 id="Example" name="Example">예제</h2> + +<h3 id="for...in의_사용">for...in의 사용</h3> + +<p>아래의 예는 열거 가능한 non-Symbol속성들을 반복해서 속성의 이름과 그 값을 기록합니다.</p> + +<pre class="notranslate"><code>var obj = {a: 1, b: 2, c: 3}; + +for (const prop in obj) { + console.log(`obj.${prop} = ${obj[prop]}`); +} + +// Output: +// "obj.a = 1" +// "obj.b = 2" +// "obj.c = 3"</code></pre> + +<h3 id="자체_속성_반복">자체 속성 반복</h3> + +<p>아래는 {{jsxref("Object.prototype.hasOwnProperty", "hasOwnProperty()")}} 를 사용하는 예를 보여주고 있습니다. 상속된 속성은 표시되지 않습니다.</p> + +<pre class="brush: js notranslate">var triangle = {a:1, b:2, c:3}; + +function ColoredTriangle() { + this.color = "red"; +} + +ColoredTriangle.prototype = triangle; + +function show_own_props(obj, objName) { + var result = ""; + + for (var prop in obj) { + if( obj.hasOwnProperty( prop ) ) { + result += objName + "." + prop + " = " + obj[prop] + "\n"; + } + } + + return result; +} + +o = new ColoredTriangle(); +alert(show_own_props(o, "o")); /* alerts: o.color = red */ +</pre> + +<h2 id="상세">상세</h2> + +<table> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-for-in-and-for-of-statements', 'for...in statement')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-for-in-and-for-of-statements', 'for...in statement')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-12.6.4', 'for...in statement')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES3', '#sec-12.6.4', 'for...in statement')}}</td> + <td>{{Spec2('ES3')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-12.6.3', 'for...in statement')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.statements.for_in")}}</p> + +<h2 id="Compatibility_Initializer_expressions_in_strict_mode">Compatibility: Initializer expressions in strict mode</h2> + +<p>Prior to SpiderMonkey 40 {{geckoRelease(40)}}, it was possible to use an initializer expression (<code>i=0</code>) in a <code>for...in</code> loop:</p> + +<pre class="notranslate"><code>var obj = {a: 1, b: 2, c: 3}; +for (var i = 0 in obj) { + console.log(obj[i]); +} +// 1 +// 2 +// 3</code></pre> + +<p>This nonstandard behavior is now ignored in version 40 and later, and will present a {{jsxref("SyntaxError")}} ("<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_for-in_initializer">for-in loop head declarations may not have initializers</a>") error in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a> ({{bug(748550)}} and {{bug(1164741)}}).</p> + +<p>Other engines such as v8 (Chrome), Chakra (IE/Edge), and JSC (WebKit/Safari) are investigating whether to remove the nonstandard behavior as well.</p> + +<h2 id="관련_문서">관련 문서</h2> + +<ul> + <li>{{jsxref("Statements/for...of", "for...of")}} – a similar statement that iterates over the property <em>values</em></li> + <li>{{jsxref("Statements/for_each...in", "for each...in")}} {{deprecated_inline}} – a similar but deprecated statement that iterates over the values of an object's properties, rather than the property names themselves</li> + <li>{{jsxref("Statements/for", "for")}}</li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators">Generator expressions</a> (uses the <code>for...in</code> syntax)</li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties">Enumerability and ownership of properties</a></li> + <li>{{jsxref("Object.getOwnPropertyNames()")}}</li> + <li>{{jsxref("Object.prototype.hasOwnProperty()")}}</li> + <li>{{jsxref("Array.prototype.forEach()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/statements/for...of/index.html b/files/ko/web/javascript/reference/statements/for...of/index.html new file mode 100644 index 0000000000..d082763616 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/for...of/index.html @@ -0,0 +1,228 @@ +--- +title: for...of +slug: Web/JavaScript/Reference/Statements/for...of +tags: + - ECMAScript 2015 + - JavaScript + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/for...of +--- +<div>{{jsSidebar("Statements")}}</div> + +<p><strong><code>for...of</code> 명령문</strong>은 <a href="/ko/docs/Web/JavaScript/Reference/Iteration_protocols#iterable">반복가능한 객체</a> ({{jsxref("Array")}}, {{jsxref("Map")}}, {{jsxref("Set")}}, {{jsxref("String")}}, {{jsxref("TypedArray")}}, <a href="/ko/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a> 객체 등을 포함)에 대해서 반복하고 각 개별 속성값에 대해 실행되는 문이 있는 사용자 정의 반복 후크를 호출하는 루프를 생성합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/statement-forof.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">for (<em>variable</em> of <em>iterable</em>) { + <em>statement +</em>} +</pre> + +<dl> + <dt><code>variable</code></dt> + <dd>각 반복에 서로 다른 속성값이 <em>variable</em>에 할당됩니다.</dd> + <dt><code>iterable</code></dt> + <dd>반복되는 열거가능(enumerable)한 속성이 있는 객체.</dd> +</dl> + +<h2 id="예제">예제</h2> + +<h3 id="jsxrefArray에_대해_반복">{{jsxref("Array")}}에 대해 반복:</h3> + +<pre class="brush:js">let iterable = [10, 20, 30]; + +for (let value of iterable) { + console.log(value); +} +// 10 +// 20 +// 30 +</pre> + +<p><a href="/ko/docs/Web/JavaScript/Reference/Statements/let"><code>let</code></a> 대신 <a href="/ko/docs/Web/JavaScript/Reference/Statements/const"><code>const</code></a>도 사용할 수 있습니다, 블록 내부 변수를 수정하지 않는 경우.</p> + +<pre class="brush:js">let iterable = [10, 20, 30]; + +for (const value of iterable) { + console.log(value); +} +// 10 +// 20 +// 30 +</pre> + +<h3 id="jsxrefString에_대해_반복">{{jsxref("String")}}에 대해 반복:</h3> + +<pre class="brush:js">let iterable = "boo"; + +for (let value of iterable) { + console.log(value); +} +// "b" +// "o" +// "o" +</pre> + +<h3 id="jsxrefTypedArray에_대해_반복">{{jsxref("TypedArray")}}에 대해 반복:</h3> + +<pre class="brush:js">let iterable = new Uint8Array([0x00, 0xff]); + +for (let value of iterable) { + console.log(value); +} +// 0 +// 255 +</pre> + +<h3 id="jsxrefMap에_대해_반복">{{jsxref("Map")}}에 대해 반복:</h3> + +<pre class="brush:js">let iterable = new Map([["a", 1], ["b", 2], ["c", 3]]); + +for (let entry of iterable) { + console.log(entry); +} +// [a, 1] +// [b, 2] +// [c, 3] + +for (let [key, value] of iterable) { + console.log(value); +} +// 1 +// 2 +// 3 +</pre> + +<h3 id="jsxrefSet에_대해_반복">{{jsxref("Set")}}에 대해 반복:</h3> + +<pre class="brush:js">let iterable = new Set([1, 1, 2, 2, 3, 3]); + +for (let value of iterable) { + console.log(value); +} +// 1 +// 2 +// 3 +</pre> + +<h3 id="DOM_컬렉션에_대해_반복">DOM 컬렉션에 대해 반복</h3> + +<p>{{domxref("NodeList")}} 같은 DOM 컬렉션에 대해 반복: 다음 예는 article의 직계 자손인 paragraph에 <code>read</code> 클래스를 추가합니다:</p> + +<pre class="brush:js">// 주의: 이는 NodeList.prototype[Symbol.iterator]가 +// 구현된 플랫폼에서만 작동합니다 +let articleParagraphs = document.querySelectorAll("article > p"); + +for (let paragraph of articleParagraphs) { + paragraph.classList.add("read"); +} +</pre> + +<h3 id="생성기에_대해_반복">생성기에 대해 반복</h3> + +<p><a href="/ko/docs/Web/JavaScript/Reference/Statements/function*">생성기</a>에 대해서도 반복할 수 있습니다:</p> + +<pre class="brush:js">function* fibonacci() { // 생성기 함수 + let [prev, curr] = [1, 1]; + while (true) { + [prev, curr] = [curr, prev + curr]; + yield curr; + } +} + +for (let n of fibonacci()) { + console.log(n); + // 1000에서 수열을 자름 + if (n >= 1000) { + break; + } +} +</pre> + +<h3 id="다른_반복가능_객체에_대해_반복">다른 반복가능 객체에 대해 반복</h3> + +<p><a href="/ko/docs/Web/JavaScript/Reference/Iteration_protocols#iterable">iterable</a> 프로토콜을 명시해서 구현하는 객체에 대해서도 반복할 수 있습니다:</p> + +<pre class="brush:js">var iterable = { + [Symbol.iterator]() { + return { + i: 0, + next() { + if (this.i < 3) { + return { value: this.i++, done: false }; + } + return { value: undefined, done: true }; + } + }; + } +}; + +for (var value of iterable) { + console.log(value); +} +// 0 +// 1 +// 2 +</pre> + +<h3 id="for...of와_for...in의_차이"><code>for...of</code>와 <code>for...in</code>의 차이</h3> + +<p><code><a href="/ko/docs/Web/JavaScript/Reference/Statements/for...in">for...in</a></code> 루프는 객체의 모든 열거가능한 속성에 대해 반복합니다.</p> + +<p><code>for...of</code> 구문은 <strong>컬렉션</strong> 전용입니다. 모든 객체보다는, <code>[Symbol.iterator]</code> 속성이 있는 모든 컬렉션 요소에 대해 이 방식으로 반복합니다.</p> + +<p>다음 예는 <code>for...of</code> 루프와 <code>for...in</code> 루프의 차이를 보입니다.</p> + +<pre class="brush:js">Object.prototype.objCustom = function () {}; +Array.prototype.arrCustom = function () {}; + +let iterable = [3, 5, 7]; +iterable.foo = "hello"; + +for (let i in iterable) { + console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom" +} + +for (let i of iterable) { + console.log(i); // logs 3, 5, 7 +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-for-in-and-for-of-statements', 'for...of statement')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-for-in-and-for-of-statements', 'for...of statement')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.statements.for_of")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Reference/Statements/for_each...in">for each...in</a> - 비슷한 문이지만, 속성 이름 자체보다는 객체의 속성값을 반복합니다 (사라짐).</li> + <li>{{jsxref("Array.prototype.forEach()")}}</li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach">Map.prototype.forEach()</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/statements/for/index.html b/files/ko/web/javascript/reference/statements/for/index.html new file mode 100644 index 0000000000..cba49dbba6 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/for/index.html @@ -0,0 +1,160 @@ +--- +title: for +slug: Web/JavaScript/Reference/Statements/for +tags: + - JavaScript + - Loop + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/for +--- +<div>{{jsSidebar("Statements")}}</div> + +<p><strong>for 문</strong>은 괄호로 감싸고 세미콜론으로 구분한 세 개의 선택식과, 반복을 수행할 문(주로 {{jsxref("Statements/block", "블럭문", "", 0)}})으로 이루어져 있습니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/statement-for.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">for ([<em>initialization</em>]; [<em>condition</em>]; [<em>final-expression</em>]) + <em>statement</em> +</pre> + +<dl> + <dt><code>initialization</code></dt> + <dd>식(할당식 포함) 또는 변수 선언. 주로 카운터 변수를 초기화할 때 사용합니다. <code>var</code> 또는 <code>let</code> 키워드를 사용해 새로운 변수를 선언할 수도 있습니다. <code>var</code> 키워드로 선언한 변수는 반복문에 제한되지 않습니다. 즉 <code>for</code> 문과 같은 범위<sup>scope</sup>에 위치합니다. <code>let</code> 키워드로 선언한 변수는 반복문의 지역 변수가 됩니다.<br> + <br> + 식의 결과는 버려집니다.</dd> + <dt><code>condition</code></dt> + <dd>매 반복마다 평가할 식. 평가 결과가 참이라면 <code>statement</code>를 실행합니다. 이 식을 넣지 않았을 때 계산 결과는 언제나 참이 됩니다. 계산 결과가 거짓이라면 <code>for</code> 문의 바로 다음 식으로 건너 뜁니다.</dd> + <dt><code>final-expression</code></dt> + <dd>매 반복 후 평가할 식. 다음번 <code>condition</code> 평가 이전에 발생합니다. 주로 카운터 변수를 증감하거나 바꿀 때 사용합니다.</dd> + <dt><code>statement</code></dt> + <dd>조건의 평가 결과가 참일 때 실행하는 문. 여러 문을 반복 실행하려면 {{jsxref("Statements/block", "블럭문", "", 0)}}(<code>{ ... }</code>)으로 묶어야 합니다. 아무것도 실행하지 않으려면 {{jsxref("Statements/empty", "공백문", "", 0)}} (<code>;</code>)을 사용하세요.</dd> +</dl> + +<h2 id="예제">예제</h2> + +<h3 id="for_사용하기"><code>for</code> 사용하기</h3> + +<p>다음 <code>for</code> 문은 변수 <code>i</code>를 선언하고 0으로 초기화하여 시작합니다. <code>i</code>가 9보다 작은지를 확인하고 맞으면 명령문을 수행한 후 <code>i</code>의 값을 1 높입니다.</p> + +<pre class="brush: js">for (var i = 0; i < 9; i++) { + console.log(i); + // 기타 등등 +} +</pre> + +<h3 id="선택적_식_사용">선택적 식 사용</h3> + +<p><code>for</code> 반복문의 3개 식은 모두 선택 사항입니다.</p> + +<p>예를 들어, 변수를 초기화하려고 <code>initialization</code> 블럭을 사용할 필요는 없습니다.</p> + +<pre class="brush: js">var i = 0; +for (; i < 9; i++) { + console.log(i); + // 기타 등등 +} +</pre> + +<p><code>initialization</code> 블럭처럼 <code>condition</code> 블럭도 선택 사항입니다. 다만 이 경우, 반복문 본문에 무한 반복을 탈출할 수 있는 장치를 추가해야 합니다.</p> + +<pre class="brush: js">for (var i = 0;; i++) { + console.log(i); + if (i > 3) break; + // 기타 등등 +}</pre> + +<p>세 가지 모두 생략할 수도 있습니다. 위와 같이 {{jsxref("Statements/break", "break")}} 문을 사용해 반복을 탈출할 수 있도록 추가하고, 변수를 수정해 탈출 조건이 언젠가 참이 되도록 해야 합니다.</p> + +<pre class="brush: js">var i = 0; + +for (;;) { + if (i > 3) break; + console.log(i); + i++; +} +</pre> + +<h3 id="문_없이_for_사용하기">문 없이 <code>for</code> 사용하기</h3> + +<p>다음 <code>for</code> 반복 사이클은 노드의 위치 오프셋을 <code>final-expression</code>에서 계산해 문이나 블럭문이 필요하지 않으므로 세미콜론을 사용합니다.</p> + +<pre>function showOffsetPos(sId) { + var nLeft = 0, nTop = 0; + + for ( + var oItNode = document.getElementById(sId); /* initialization */ + oItNode; /* condition */ + nLeft += oItNode.offsetLeft, nTop += oItNode.offsetTop, oItNode = oItNode.offsetParent /* final-expression */ + ); /* semicolon */ + + console.log('Offset position of \'' + sId + '\' element:\n left: ' + nLeft + 'px;\n top: ' + nTop + 'px;'); +} + +/* Example call: */ + +showOffsetPos('content'); + +// Output: +// "Offset position of "content" element: +// left: 0px; +// top: 153px;"</pre> + +<div class="note"><strong>참고:</strong> 여기서 쓰인 세미콜론은, JavaScript가 <strong>필수로 요구하는 몇 안되는 세미콜론</strong>입니다. 물론 세미콜론 없이는 반복 사이클 선언의 바로 다음 줄을 반복 본문으로 인식합니다.</div> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-12.6.2', 'for statement')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES3', '#sec-12.6.3', 'for statement')}}</td> + <td>{{Spec2('ES3')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-12.6.3', 'for statement')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-for-statement', 'for statement')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-for-statement', 'for statement')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.statements.for")}}</p> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("Statements/empty", "공백문", "", 0)}}</li> + <li>{{jsxref("Statements/break", "break")}}</li> + <li>{{jsxref("Statements/continue", "continue")}}</li> + <li>{{jsxref("Statements/while", "while")}}</li> + <li>{{jsxref("Statements/do...while", "do...while")}}</li> + <li>{{jsxref("Statements/for...in", "for...in")}}</li> + <li>{{jsxref("Statements/for...of", "for...of")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/statements/for_each...in/index.html b/files/ko/web/javascript/reference/statements/for_each...in/index.html new file mode 100644 index 0000000000..9fa9901aae --- /dev/null +++ b/files/ko/web/javascript/reference/statements/for_each...in/index.html @@ -0,0 +1,85 @@ +--- +title: for each...in +slug: Web/JavaScript/Reference/Statements/for_each...in +tags: + - Deprecated + - E4X + - JavaScript + - Obsolete + - Statement +translation_of: Archive/Web/JavaScript/for_each...in +--- +<div>{{jsSidebar("Statements")}}</div> + +<div class="warning"> +<p>The <code>for each...in</code> statement is deprecated as the part of ECMA-357 (<a href="/en-US/docs/Archive/Web/E4X" title="/en-US/docs/E4X">E4X</a>) standard. E4X support has been removed. Consider using <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a> instead.<br> + <br> + <strong>Firefox now warns about the usage of <code>for each...in</code> and it no longer works starting with Firefox 57.<br> + Please see <a href="/en-US/docs/Web/JavaScript/Reference/Errors/For-each-in_loops_are_deprecated">Warning: JavaScript 1.6's for-each-in loops are deprecated</a> for migration help.</strong></p> +</div> + +<p><code><strong>for each...in</strong></code> 문은 객체의 모든 속성 값에 대해 지정된 변수를 반복합니다. 각각의 고유한 특성에 대해 지정된 명령문이 실행됩니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">for each (<em>variable</em> in <em>object</em>) { + <em>statement</em> +}</pre> + +<dl> + <dt><code>variable</code></dt> + <dd>var 키워드로 선택적으로 선언된 속성 값을 반복하는 변수입니다. 이 변수는 루프가 아니라 함수의 local이 됩니다.</dd> +</dl> + +<dl> + <dt><code>object</code></dt> + <dd>반복될 객체입니다.</dd> +</dl> + +<dl> + <dt><code>statement</code></dt> + <dd>각 속성에 대해 실행할 명령문입니다. 루프 내에서 여러 명령문을 실행하려면 블록 명령문 ({...})을 사용하여 해당 명령문을 그룹화하십시오.</dd> +</dl> + +<h2 id="Description">Description</h2> + +<p>일부 기본 제공 속성은 반복되지 않습니다. 여기에는 객체 기본 제공 메서드 전부가 포함됩니다.</p> + +<p>ex) String의 indexOf 메소드.</p> + +<p>그러나 사용자가 정의한 모든 속성은 반복됩니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_for_each...in">Using <code>for each...in</code></h3> + +<p><strong>Warning:</strong> Never use a loop like this on arrays. Only use it on objects. See <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in"><code>for...in</code></a> for more details.</p> + +<p>The following snippet iterates over an object's properties, calculating their sum:</p> + +<pre class="brush:js">var sum = 0; +var obj = {prop1: 5, prop2: 13, prop3: 8}; + +for each (var item in obj) { + sum += item; +} + +console.log(sum); // logs "26", which is 5+13+8</pre> + +<h2 id="Specifications">Specifications</h2> + +<p>Not part of a current ECMA-262 specification. Implemented in JavaScript 1.6 and deprecated.</p> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.statements.for_each_in")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in">for...in</a></code> - a similar statement that iterates over the property <em>names</em>.</li> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a></code> - a similar statement that iterates over the property <em>values</em> but can only be used for iteratable types, so not for generic objects</li> + <li><code><a href="/en-US/docs/JavaScript/Reference/Statements/for">for</a></code></li> +</ul> diff --git a/files/ko/web/javascript/reference/statements/function/index.html b/files/ko/web/javascript/reference/statements/function/index.html new file mode 100644 index 0000000000..fe1eee366a --- /dev/null +++ b/files/ko/web/javascript/reference/statements/function/index.html @@ -0,0 +1,177 @@ +--- +title: 함수 선언 +slug: Web/JavaScript/Reference/Statements/function +tags: + - Function + - JavaScript + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/function +--- +<div>{{jsSidebar("Statements")}}</div> + +<p><strong>함수 선언(function declaration)</strong>은 지정된 매개변수(parameter)를 갖는 함수를 정의합니다.</p> + +<p>{{jsxref("Function")}} 생성자나 {{jsxref("Operators/function", "함수 표현식(function expression)")}}을 사용해서 정의할 수도 있습니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/statement-function.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">function <em>name</em>([<em>param</em>[, <em>param</em>,[..., <em>param</em>]]]) { [<em>statements</em>] } +</pre> + +<dl> + <dt><code>name</code></dt> + <dd>함수 이름.</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>함수로 전달되는 인수(argument)의 이름. 인수의 최대 개수는 엔진마다 다름.</dd> +</dl> + +<dl> + <dt><code>statements</code></dt> + <dd>함수의 몸통(body)을 구성하는 문(statement).</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p>함수 선언으로 생성된 함수는 <code>Function</code> 객체로, <code>Function</code> 객체의 모든 속성(property), 메서드 및 행위 특성(behavior)을 갖습니다. 함수에 관한 더 자세한 정보는 {{jsxref("Function")}} 참조하시기 바랍니다.</p> + +<p>함수는 또한 표현식({{jsxref("Operators/function", "함수 표현식")}} 참조)을 사용하여 생성될 수 있습니다.</p> + +<p>기본적으로 함수는 <code>undefined</code>를 반환합니다. 다른 값을 반환하기 위해서는, 함수는 반환값을 지정하는 {{jsxref("Statements/return", "return")}} 문이 있어야 합니다.</p> + +<h3 id="조건부로_생성되는_함수">조건부로 생성되는 함수</h3> + +<p>함수는 조건부로 선언될 수 있습니다. 즉, function 문은 <code>if</code> 문 안에 들어갈 수 있습니다. 하지만, 구현에 따라 결과에 일관성이 없으므로 이 패턴은 실제 코드에서는 사용해선 안됩니다. 조건부로 함수를 생성하고자 한다면, 함수 표현식(function expression)을 대신 사용하세요.</p> + +<pre class="brush: js">var hoisted = "foo" in this; +console.log(`'foo' name ${hoisted ? "is" : "is not"} hoisted. typeof foo is ${typeof foo}`); +if (false) { + function foo(){ return 1; } +} + +// In Chrome: +// 'foo' name is hoisted. typeof foo is undefined +// +// In Firefox: +// 'foo' name is hoisted. typeof foo is undefined +// +// In Edge: +// 'foo' name is not hoisted. typeof foo is undefined +// +// In Safari: +// 'foo' name is hoisted. typeof foo is function +</pre> + +<p>결과는 참으로 평가되는 조건과 정확하게 일치합니다.</p> + +<pre class="brush: js">var hoisted = "foo" in this; +console.log(`'foo' name ${hoisted ? "is" : "is not"} hoisted. typeof foo is ${typeof foo}`); +if (true) { + function foo(){ return 1; } +} + +// In Chrome: +// 'foo' name is hoisted. typeof foo is undefined +// +// In Firefox: +// 'foo' name is hoisted. typeof foo is undefined +// +// In Edge: +// 'foo' name is not hoisted. typeof foo is undefined +// +// In Safari: +// 'foo' name is hoisted. typeof foo is function +</pre> + +<h3 id="함수_선언_끌어올리기">함수 선언 끌어올리기</h3> + +<p>자바스크립트에서 함수 선언은 그 선언을 둘러싼 함수의 최상부나 전역 범위(global scope)로 끌어올려집니다.</p> + +<pre class="brush: js">hoisted(); // logs "foo" + +function hoisted() { + console.log("foo"); +} +</pre> + +<p>{{jsxref("Operators/function", "함수 표현식")}}은 끌어올려지지 않으므로 주의하세요:</p> + +<pre class="brush: js">notHoisted(); // TypeError: notHoisted is not a function + +var notHoisted = function() { + console.log("bar"); +}; +</pre> + +<h2 id="예제">예제</h2> + +<h3 id="function_사용하기"><code>function</code> 사용하기</h3> + +<p>다음 코드는 제품 <code>a</code>, <code>b</code> 및 <code>c</code>의 단위 판매량이 주어졌을 때, 총 판매량을 반환하는 함수를 선언합니다.</p> + +<pre class="brush: js">function calc_sales(units_a, units_b, units_c) { + return units_a*79 + units_b * 129 + units_c * 699; +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-13', 'Function definition')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES3', '#sec-13', 'Function definition')}}</td> + <td>{{Spec2('ES3')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-13', 'Function definition')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>초기 정의. JavaScript 1.0에서 구현됨.</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.statements.function")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Functions", "함수 및 함수 범위")}}</li> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("Operators/function", "함수 표현식")}}</li> + <li>{{jsxref("Statements/function*", "function* 문")}}</li> + <li>{{jsxref("Operators/function*", "function* 식")}}</li> + <li>{{jsxref("Functions/Arrow_functions", "화살표 함수")}}</li> + <li>{{jsxref("GeneratorFunction")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/statements/function_star_/index.html b/files/ko/web/javascript/reference/statements/function_star_/index.html new file mode 100644 index 0000000000..9178c28602 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/function_star_/index.html @@ -0,0 +1,159 @@ +--- +title: function* +slug: Web/JavaScript/Reference/Statements/function* +tags: + - ECMAScript6 + - Generator + - Iterator + - JavaScript +translation_of: Web/JavaScript/Reference/Statements/function* +--- +<div>{{jsSidebar("Statements")}}</div> + +<p><code><strong>function*</strong></code> 선언 (끝에 별표가 있는 <code>function</code> keyword) 은 <em>generator function</em> 을 정의하는데, 이 함수는 {{jsxref("Global_Objects/Generator","Generator")}} 객체를 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/statement-functionasterisk.html")}}</div> + + + +<p>generator function 은 {{jsxref("Global_Objects/GeneratorFunction", "GeneratorFunction")}} 생성자와 {{jsxref("Operators/function*", "function* expression")}} 을 사용해서 정의할 수 있습니다.</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox">function* <em>name</em>([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { + <em>statements</em> +} +</pre> + +<dl> + <dt><code>name</code></dt> + <dd>함수명.</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>함수에 전달되는 인수의 이름. 함수는 인수를 255개까지 가질 수 있다.</dd> +</dl> + +<dl> + <dt><code>statements</code></dt> + <dd>함수의 본체를 구성하는 구문들.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p>Generator는 빠져나갔다가 나중에 다시 돌아올 수 있는 함수입니다. 이때 컨텍스트(변수 값)는 출입 과정에서 저장된 상태로 남아 있습니다.</p> + +<p>Generator 함수는 호출되어도 즉시 실행되지 않고, 대신 함수를 위한 <a href="/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterator">Iterator</a> 객체가 반환됩니다. Iterator의 <code>next()</code> 메서드를 호출하면 Generator 함수가 실행되어 <strong>{{jsxref("Operators/yield", "yield")}}</strong> 문을 만날 때까지 진행하고, 해당 표현식이 명시하는 Iterator로부터의 반환값을 반환합니다. <strong>{{jsxref("Operators/yield*", "yield*")}}</strong> 표현식을 마주칠 경우, 다른 Generator 함수가 위임(delegate)되어 진행됩니다.</p> + +<p>이후 <code>next()</code> 메서드가 호출되면 진행이 멈췄던 위치에서부터 재실행합니다. <code>next()</code> 가 반환하는 객체는 <code>yield</code>문이 반환할 값(yielded value)을 나타내는 <code>value</code> 속성과, Generator 함수 안의 모든 <code>yield</code> 문의 실행 여부를 표시하는 boolean 타입의 <code>done</code> 속성을 갖습니다. <code>next()</code> 를 인자값과 함께 호출할 경우, 진행을 멈췄던 위치의 <code>yield</code> 문을 <code>next()</code> 메서드에서 받은 인자값으로 치환하고 그 위치에서 다시 실행하게 됩니다.</p> + +<h2 id="예시">예시</h2> + +<h3 id="간단한_예제">간단한 예제</h3> + +<pre class="brush: js">function* idMaker(){ + var index = 0; + while(index < 3) + yield index++; +} + +var gen = idMaker(); + +console.log(gen.next().value); // 0 +console.log(gen.next().value); // 1 +console.log(gen.next().value); // 2 +console.log(gen.next().value); // undefined +// ... +</pre> + +<h3 id="yield*_를_사용한_예제">yield* 를 사용한 예제</h3> + +<pre class="brush: js">function* anotherGenerator(i) { + yield i + 1; + yield i + 2; + yield i + 3; +} + +function* generator(i){ + yield i; + yield* anotherGenerator(i); + yield i + 10; +} + +var gen = generator(10); + +console.log(gen.next().value); // 10 +console.log(gen.next().value); // 11 +console.log(gen.next().value); // 12 +console.log(gen.next().value); // 13 +console.log(gen.next().value); // 20 +</pre> + +<h3 id="Generator_에_인자값을_넘기는_예제">Generator 에 인자값을 넘기는 예제</h3> + +<pre class="brush: js">function* logGenerator() { + console.log(yield); + console.log(yield); + console.log(yield); +} + +var gen = logGenerator(); + +// the first call of next executes from the start of the function +// until the first yield statement +gen.next(); +gen.next('pretzel'); // pretzel +gen.next('california'); // california +gen.next('mayonnaise'); // mayonnaise +</pre> + +<h3 id="Generator_는_생성자로서_사용될_수_없다">Generator 는 생성자로서 사용될 수 없다</h3> + +<pre><code>function* f() {} +var obj = new f; // throws "TypeError: f is not a constructor"</code></pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ES2015', '#', 'function*')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{Compat("javascript.statements.generator_function")}}</p> + +<h2 id="관련_항목">관련 항목</h2> + +<ul> + <li>{{jsxref("Operators/function*", "function* expression")}}</li> + <li>{{jsxref("GeneratorFunction")}} object</li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/The_Iterator_protocol">The Iterator protocol</a></li> + <li>{{jsxref("Operators/yield", "yield")}}</li> + <li>{{jsxref("Operators/yield*", "yield*")}}</li> + <li>{{jsxref("Function")}} object</li> + <li>{{jsxref("Statements/function", "function declaration")}}</li> + <li>{{jsxref("Operators/function", "function expression")}}</li> + <li>{{jsxref("Functions_and_function_scope", "Functions and function scope")}}</li> + <li>Other web resources: + <ul> + <li><a href="http://facebook.github.io/regenerator/">Regenerator</a> an ES2015 generator compiler to ES5</li> + <li><a href="http://www.youtube.com/watch?v=qbKWsbJ76-s">Forbes Lindesay: Promises and Generators: control flow utopia -- JSConf EU 2013</a></li> + <li><a href="https://www.youtube.com/watch?v=ZrgEZykBHVo&list=PLuoyIZT5fPlG44bPq50Wgh0INxykdrYX7&index=1">Hemanth.HM: The New gen of *gen(){}</a></li> + <li><a href="http://taskjs.org/">Task.js</a></li> + </ul> + </li> +</ul> diff --git a/files/ko/web/javascript/reference/statements/if...else/index.html b/files/ko/web/javascript/reference/statements/if...else/index.html new file mode 100644 index 0000000000..cde42b2a80 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/if...else/index.html @@ -0,0 +1,177 @@ +--- +title: if...else +slug: Web/JavaScript/Reference/Statements/if...else +tags: + - JavaScript + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/if...else +--- +<div>{{jsSidebar("Statements")}}</div> + +<p><strong><code>if</code> 문</strong>은 지정한 조건이 {{glossary("truthy", "참")}}인 경우 명령문(statement)을 실행합니다. 조건이 {{glossary("falsy", "거짓")}}인 경우 또 다른 명령문이 실행 될 수 있습니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/statement-ifelse.html")}}</div> + +<div class="hidden">The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</div> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">if (<em>condition</em>) + <em>statement</em><em>1</em> +[else + <em>statement2</em>] +</pre> + +<dl> + <dt><code>condition</code></dt> + <dd>참 또는 거짓으로 평가되는 <a href="/ko/docs/Web/JavaScript/Guide/Expressions_and_Operators#표현식">표현식</a>입니다.</dd> +</dl> + +<dl> + <dt><code>statement1</code></dt> + <dd>조건이 참으로 평가될 경우 실행되는 문입니다.<br> + 중첩된 if구문을 포함하여 어떤 구문이든 쓸 수 있습니다. 다중구문을 사용할 경우 ({ ... })<a href="/en-US/docs/Web/JavaScript/Reference/Statements/block" title="en/JavaScript/Reference/Statements/block">블럭</a> 구문 으로 그룹화 하고 실행하지 않으려면 <a href="/en-US/docs/Web/JavaScript/Reference/Statements/Empty">빈</a> 구문을 사용합니다.</dd> +</dl> + +<dl> + <dt><code><em>statement</em>2</code></dt> + <dd>이 구문은 조건이 거짓일경우 다른 조항이 있을 때 실행되는 구문입니다. 블록 문과 if문의 중첩을 호함한 모든문이 될 수 있습니다.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p>다중의 if...else 문은 else if 절을 만들기 위해 중첩될 수 있다.<br> + 자바스크립트에서는 elseif (하나의 단어) 키워드가 존재하지 않는다.</p> + +<pre class="eval">if (<em>조건1</em>) + <em>명령문1</em> +else if (<em>조건2</em>) + <em>명령문2</em> +else if (<em>조건3</em>) + <em>명령문3</em> +... +else + <em>명령문N</em> +</pre> + +<p>아래 작업한 것을 보면, if문을 중첩 사용하면 들여쓰기된 것이 제대로 보여집니다.</p> + +<pre class="eval">if (<em>조건1</em>) + <em>명령문1</em> +else + if (<em>조건2</em>) + <em>명령문2</em> + else + if (<em>조건3</em>) +... +</pre> + +<p>하나의 절에서 여러개의 명령문들을 실행하려면, 그 명령문들을 그룹화하는 블록 명령문 ({ ... }) 블럭구문을 사용한다.<br> + 일반적으로, 블럭구문을 항상 사용하는 것은 좋은 연습입니다. 특히 중첩된 if 문과 관련되어<br> + 있는 코드안에서 사용하면 더욱 좋습니다.</p> + +<pre class="eval">if (조건) { + <em>명령문들1</em> +} else { + <em>명령문들2</em> +} +</pre> + +<p>원시 불리언 값인 true (참) 과 false (거짓) 을 불리언 객체의 truthiness (참으로 보이는 것) 과 falsiness (거짓으로 보이는 것)으로 혼동하면 안된다. false, undefined, null, 0, NaN, 또는 빈 스트링 ("") 이 아닌 모든 값, 그리고 false 값인 불리언 객체를 포함하는 모든 객체는 조건으로 사용될 때 <a href="https://developer.mozilla.org/ko/docs/Glossary/Truthy">truthy</a> 로 간주된다. 예:</p> + +<pre class="brush: js">var b = new Boolean(false); +if (b) // 이 조건은 참으로 보이는 것 (truthy) 이다. +</pre> + +<h2 id="예시">예시</h2> + +<h3 id="if...else_사용하기"><code>if...else</code> 사용하기</h3> + +<pre class="brush: js">if (cipher_char === from_char) { + result = result + to_char; + x++; +} else { + result = result + clear_char; +} +</pre> + +<h3 id="else_if_사용하기"><code>else if</code> 사용하기</h3> + +<p>자바스크립트에는 elseif 구문이 없다. 그러나, else if 를 사용할 수 있다.</p> + +<pre class="brush: js">if (x > 5) { + +} else if (x > 50) { + +} else { + +}</pre> + +<h3 id="조건식의_값을_지정하기">조건식의 값을 지정하기</h3> + +<p>조건식을 단순하게 지정하는 것은 좋지 않습니다.<br> + 왜냐하면, 코드를 흘깃 보면 값을 지정한것을 평등한것으로 혼동할 수 있기 때문입니다. 예를들어, 다음코드를 사용하지 마세요:</p> + +<pre class="brush: js example-bad">if (x = y) { + /* do the right thing */ +} +</pre> + +<p>당신이 조건식에 값의 지정을 해야할 경우, 일반적인 관행은 그 할당된 것 주위에 추가 괄호를 넣어야 합니다. 예를들면:</p> + +<pre class="brush: js example-good">if ((x = y)) { + /* do the right thing */ +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-if-statement', 'if statement')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-if-statement', 'if statement')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-12.5', 'if statement')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES3', '#sec-12.5', 'if statement')}}</td> + <td>{{Spec2('ES3')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-12.5', 'if statement')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.statements.if_else")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Statements/block", "block")}}</li> + <li>{{jsxref("Statements/switch", "switch")}}</li> + <li><a href="/ko/docs/Web/JavaScript/Reference/Operators/Conditional_Operator">삼항 조건 연산자</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/statements/import/index.html b/files/ko/web/javascript/reference/statements/import/index.html new file mode 100644 index 0000000000..ce3a1536cb --- /dev/null +++ b/files/ko/web/javascript/reference/statements/import/index.html @@ -0,0 +1,156 @@ +--- +title: import +slug: Web/JavaScript/Reference/Statements/import +tags: + - ECMAScript6 + - Modules + - import +translation_of: Web/JavaScript/Reference/Statements/import +--- +<div>{{jsSidebar("Statements")}}</div> + +<p>정적 <strong><code>import</code></strong> 문은 다른 모듈에서 내보낸 바인딩을 가져올 때 사용합니다.</p> + +<p>가져오는 모듈은 <code>"use strict"</code>의 존재 유무와 상관없이 무조건 <a href="/ko/docs/Web/JavaScript/Reference/Strict_mode">엄격 모드</a>입니다. HTML 안에 작성한 스크립트에서는 <code>import</code>를 사용할 수 없습니다.</p> + +<p>함수형 구문을 가진 동적 <strong><code>import()</code></strong>도 있으며, <code>type="module"</code>을 필요로 하지 않습니다.</p> + +<p>{{htmlelement("script")}} 태그의 <code>nomodule</code> 속성을 사용해 하위호환성을 유지할 수 있습니다.</p> + +<p>동적 가져오기는 모듈을 조건적으로 가져오고 싶거나, 필요할 때에만 가져올 때 유용합니다. 반면 초기 의존성을 불러올 때엔 정적 가져오기가 더 좋고, 정적 코드 분석 도구와 {{glossary("Tree shaking", "트리 셰이킹")}}을 적용하기 쉽습니다.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">import defaultExport from "module-name"; +import * as name from "module-name"; +import { export1 } from "module-name"; +import { export1 as alias1 } from "module-name"; +import { export1 , export2 } from "module-name"; +import { foo , bar } from "module-name/path/to/specific/un-exported/file"; +import { export1 , export2 as alias2 , [...] } from "module-name"; +import defaultExport, { export1 [ , [...] ] } from "module-name"; +import defaultExport, * as name from "module-name"; +import "module-name"; +var promise = import("module-name");</pre> + +<dl> + <dt><code>defaultExport</code></dt> + <dd>모듈에서 가져온 기본 내보내기를 가리킬 이름.</dd> + <dt><code>module-name</code></dt> + <dd>가져올 대상 모듈. 보통, 모듈을 담은 <code>.js</code> 파일로의 절대 또는 상대 경로입니다. 번들러에 따라 확장자를 허용하거나, 필요로 할 수도 있으므로 작업 환경을 확인하세요. 따옴표와 쌍따옴표 문자열만 사용 가능합니다.</dd> + <dt><code>name</code></dt> + <dd>가져온 대상에 접근할 때 일종의 이름공간으로 사용할, 모듈 객체의 이름.</dd> + <dt><code>exportN</code></dt> + <dd>내보낸 대상 중 가져올 것의 이름.</dd> + <dt><code>aliasN</code></dt> + <dd>가져온 유명 내보내기를 가리킬 이름.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p><code>name</code> 파라미터는 export 되는 멤버를 받을 오브젝트의 이름입니다. <code>member</code> 파라미터는 각각의 멤버를 지정하지만, <code>name</code> 파라미터는 모두를 가져옵니다. 모듈에서 <font face="Courier New, Andale Mono, monospace">name</font> 은 멤버 대신 하나의 default 파라미터를 통해 export 하는 경우에도 동작할 수 있습니다. 다음의 명확한 예제 문법을 살펴봅시다.</p> + +<p>모듈 전체를 가져옵니다. export 한 모든 것들을 현재 범위(스크립트 파일 하나로 구분되는 모듈 범위) 내에 <code>myModule</code> 로 바인딩되어 들어갑니다.</p> + +<pre class="brush: js">import * as <em>myModule</em> from "my-module.js"; +</pre> + +<p>모듈에서 하나의 멤버만 가져옵니다. 현재 범위 내에 <code>myMember</code> 이 들어갑니다.</p> + +<pre class="brush: js">import {myMember} from "my-module.js";</pre> + +<p>모듈에서 여러 멤버들을 가져옵니다. 현재 범위 내에 <code>foo</code> 와 <code>bar</code> 이 들어갑니다.</p> + +<pre class="brush: js">import {foo, bar} from "my-module.js";</pre> + +<p>멤버를 가져올 때 좀 더 편리한 별명을 지정해줍니다. 현재 범위 내에 <code>shortName</code> 이 들어갑니다.</p> + +<pre class="brush: js">import {reallyReallyLongModuleMemberName as shortName} from "my-module.js";</pre> + +<p>모듈에서 여러 멤버들을 편리한 별명을 지정하며 가져옵니다.</p> + +<pre>import {reallyReallyLongModuleMemberName as shortName, anotherLongModuleName as short} from "my-module.js";</pre> + +<p>어떠한 바인딩 없이 모듈 전체의 사이드 이펙트만 가져옵니다.</p> + +<pre class="brush: js">import "my-module.js";</pre> + +<h3 id="기본값_가져오기">기본값 가져오기</h3> + +<p>default export 를 통해 내보낸 것을 기본값으로 가져올 수 있습니다. (object, function, class 등). export 와 상반된 <code>import</code> 명령어를 통해 기본값을 가져오는 것이 가능합니다.</p> + +<p>기본값으로 바로 가져오는 가장 간단한 버전:</p> + +<pre class="brush: js">import myModule from "my-module.js";</pre> + +<p>위와 함께 기본 구문도 같이 사용할 수 있습니다 (namespace 가져오기 또는 이름 지정하여 가져오기). 이러한 경우, 기본값 가져오는 부분을 먼저 선언해야 할 것입니다. 예를 들어:</p> + +<pre class="brush: js">import myDefault, * as myModule from "my-module.js"; +// myModule used as a namespace</pre> + +<p>또는</p> + +<pre class="brush: js">import myDefault, {foo, bar} from "my-module.js"; +// specific, named imports +</pre> + +<h2 id="예제">예제</h2> + +<p>AJAX JSON 리퀘스트 처리를 돕는 보조 파일을 가져옵니다.</p> + +<pre class="brush: js; highlight: [14]">// --file.js-- +function getJSON(url, callback) { + let xhr = new XMLHttpRequest(); + xhr.onload = function () { + callback(this.responseText) + }; + xhr.open("GET", url, true); + xhr.send(); +} + +export function getUsefulContents(url, callback) { + getJSON(url, data => callback(JSON.parse(data))); +} + +// --main.js-- +import { getUsefulContents } from "file.js"; +getUsefulContents("http://www.example.com", data => { + doSomethingUseful(data); +});</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-imports', 'Imports')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-imports', 'Imports')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.statements.import")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Statements/export", "export")}}</li> + <li><a href="https://blogs.windows.com/msedgedev/2016/05/17/es6-modules-and-beyond/">Previewing ES6 Modules and more from ES2015, ES2016 and beyond</a></li> + <li><a href="https://hacks.mozilla.org/2015/08/es6-in-depth-modules/">ES6 in Depth: Modules</a>, Hacks blog post by Jason Orendorff</li> + <li><a href="http://exploringjs.com/es6/ch_modules.html">Axel Rauschmayer's book: "Exploring JS: Modules"</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/statements/index.html b/files/ko/web/javascript/reference/statements/index.html new file mode 100644 index 0000000000..cd83b9f1c0 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/index.html @@ -0,0 +1,143 @@ +--- +title: 문 및 선언 +slug: Web/JavaScript/Reference/Statements +tags: + - JavaScript + - Reference + - statements +translation_of: Web/JavaScript/Reference/Statements +--- +<div>{{jsSidebar("Statements")}}</div> + +<p>JavaScript 응용 프로그램은 적절한 구문을 갖는 문으로 구성됩니다. 한 문이 여러 줄에 걸칠 수 있습니다. 여러 문은 각 문이 세미콜론으로 구분된 경우 한 줄에 나올 수 있습니다. 이는 키워드 하나가 아니라, 키워드 그룹입니다.</p> + +<h2 id="항목별_문_및_선언">항목별 문 및 선언</h2> + +<p>알파벳순 목록은 왼쪽 사이드바를 보세요.</p> + +<h3 id="흐름_제어">흐름 제어</h3> + +<dl> + <dt>{{jsxref("Statements/block", "Block")}}</dt> + <dd>블록문은 0개 이상의 문을 묶을 때 쓰입니다. 블록은 중괄호 한 쌍으로 구분됩니다.</dd> + <dt>{{jsxref("Statements/break", "break")}}</dt> + <dd>현재 루프, <code>switch</code> 또는 <code>label</code> 문을 종료하고 프로그램 제어를 종료된 문의 다음 문으로 넘겨줍니다.</dd> + <dt>{{jsxref("Statements/continue", "continue")}}</dt> + <dd>현재 또는 레이블 달린 루프의 현재 반복 중인 문의 실행을 종료하고 루프의 실행은 다음 반복으로 이어집니다.</dd> + <dt>{{jsxref("Statements/Empty", "empty")}}</dt> + <dd>empty 문은 내용이 없는 빈 문을 제공하기 위해 사용됩니다, 비록 JavaScript 구문이 문을 기대할 것이지만.</dd> + <dt>{{jsxref("Statements/if...else", "if...else")}}</dt> + <dd>지정된 조건이 true면 문을 실행. 조건이 false인 경우, 다른 문이 실행될 수 있습니다.</dd> + <dt>{{jsxref("Statements/switch", "switch")}}</dt> + <dd>식의 값이 case 절과 일치하는지 식을 평가하고 case 절과 관련된 문을 실행합니다.</dd> + <dt>{{jsxref("Statements/throw", "throw")}}</dt> + <dd>사용자 정의 예외가 발생합니다.</dd> + <dt>{{jsxref("Statements/try...catch", "try...catch")}}</dt> + <dd>시도(try)할 문 블록을 표시하고 예외가 발생되어야 하는 응답을 지정합니다.</dd> +</dl> + +<h3 id="선언">선언</h3> + +<dl> + <dt>{{jsxref("Statements/var", "var")}}</dt> + <dd>변수를 선언합니다, 변수를 값으로 초기화할 수 있습니다.</dd> + <dt>{{jsxref("Statements/let", "let")}}</dt> + <dd>블록 범위 지역 변수를 선언합니다, 변수를 값으로 초기화할 수 있습니다.</dd> + <dt>{{jsxref("Statements/const", "const")}}</dt> + <dd>읽기 전용 유명(named) 상수를 선언합니다.</dd> +</dl> + +<h3 id="함수_및_클래스">함수 및 클래스</h3> + +<dl> + <dt>{{jsxref("Statements/function", "function")}}</dt> + <dd>지정된 매개변수를 갖는 함수를 선언합니다.</dd> + <dt>{{jsxref("Statements/function*", "function*")}}</dt> + <dd><a href="/ko/docs/Web/JavaScript/Guide/The_Iterator_protocol" title="iterators">반복기</a>를 더 쉽게 작성할 수 있게 하는 생성기 함수.</dd> + <dt>{{jsxref("Statements/return", "return")}}</dt> + <dd>함수에 의해 반환되는 값을 지정합니다.</dd> + <dt>{{jsxref("Statements/class", "class")}}</dt> + <dd>클래스를 선언합니다.</dd> +</dl> + +<h3 id="반복">반복</h3> + +<dl> + <dt>{{jsxref("Statements/do...while", "do...while")}}</dt> + <dd>테스트 조건이 거짓으로 평가될 때까지 지정된 문을 실행하는 루프를 만듭니다. 조건은 문을 실행한 후 평가됩니다, 그 결과 지정된 문은 적어도 한 번 실행됩니다.</dd> + <dt>{{jsxref("Statements/for", "for")}}</dt> + <dd>괄호로 묶이고 세미콜론으로 구분된 선택사항 식 셋으로 구성된 루프를 만듭니다, 루프에서 실행되는 문이 뒤따릅니다.</dd> + <dt>{{jsxref("Statements/for_each...in", "for each...in")}} {{deprecated_inline}} {{non-standard_inline}}</dt> + <dd>객체의 모든 속성값에 대해 지정된 변수를 반복합니다. 각 개별 속성에 대해, 지정된 문이 실행됩니다.</dd> + <dt>{{jsxref("Statements/for...in", "for...in")}}</dt> + <dd>임의의 순서로 객체의 열거 속성을 반복합니다. 각 개별 속성에 대해, 문은 실행될 수 있습니다.</dd> + <dt>{{jsxref("Statements/for...of", "for...of")}}</dt> + <dd>반복 가능한 객체 ({{jsxref("Global_Objects/Array","배열","","true")}}, 배열 같은 객체, <a href="/ko/docs/Web/JavaScript/Guide/Iterators_and_Generators">반복기 및 생성기</a> 포함) 를 반복합니다, 각 개별 속성값에 대해 실행되는 문을 가진 사용자 정의 반복 후크를 호출하는.</dd> + <dt>{{jsxref("Statements/while", "while")}}</dt> + <dd>테스트 조건이 true로 평가되는 한 지정된 문을 실행하는 루프를 만듭니다. 조건은 문을 실행하기 전에 평가됩니다.</dd> +</dl> + +<h3 id="기타">기타</h3> + +<dl> + <dt>{{jsxref("Statements/debugger", "debugger")}}</dt> + <dd>이용 가능한 디버깅 기능을 호출합니다. 이용 가능한 기능이 없는 경우, 이 문은 아무 효과가 없습니다.</dd> + <dt>{{jsxref("Statements/export", "export")}}</dt> + <dd>외부 모듈, 다른 스크립트에 가져올(import) 수 있도록 함수를 내보내(export)는데 사용됩니다.</dd> + <dt>{{jsxref("Statements/import", "import")}}</dt> + <dd>외부 모듈, 다른 스크립트에서 내보낸 함수를 가져오는데 사용됩니다.</dd> + <dt>{{jsxref("Statements/label", "label")}}</dt> + <dd><code>break</code> 또는 <code>continue</code> 문을 사용하여 참조할 수 있는 식별자 있는 문을 제공합니다.</dd> +</dl> + +<dl> + <dt>{{jsxref("Statements/with", "with")}} {{deprecated_inline}}</dt> + <dd>문의 스코프 체인을 확장합니다.</dd> +</dl> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-12', 'Statements')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>초기 정의</td> + </tr> + <tr> + <td>{{SpecName('ES3', '#sec-12', 'Statements')}}</td> + <td>{{Spec2('ES3')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-12', 'Statements')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>신규: function*, let, for...of, yield, class</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.statements")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Reference/Operators">연산자</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/statements/label/index.html b/files/ko/web/javascript/reference/statements/label/index.html new file mode 100644 index 0000000000..49d6054031 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/label/index.html @@ -0,0 +1,241 @@ +--- +title: label +slug: Web/JavaScript/Reference/Statements/label +translation_of: Web/JavaScript/Reference/Statements/label +--- +<div>{{jsSidebar("Statements")}}</div> + +<p><strong>레이블 구문</strong>은 {{jsxref("Statements/break", "break")}}나 {{jsxref("Statements/continue", "continue")}} 구문과 함께 사용할 수 있다. 원하는 식별자로 구문 앞에 레이블을 추가할 수 있다.</p> + +<div class="note"> +<p>레이블을 붙인 반복문이나 블록가 자주 사용되는 것은 아니다. 반복문으로 점프하는 대신에 함수를 호출할 수도 있다.</p> +</div> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox"><em>label</em> : + <em>statement</em> +</pre> + +<dl> + <dt><code>label</code></dt> + <dd>자바스크립트에서 사용할 수 있는 식별자면 모두 가능하다.</dd> + <dt><code>statement</code></dt> + <dd>구문. break는 모든 레이블 구문에서 사용될 수 있으며, continue는 반복 레이블 구문에서만 사용할 수 있다.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p>반복문에 레이블을 붙이고, break나 continue 구문을 사용해 반복문의 어느 위치에서 작업을 멈추고 어느 위치에서 다시 수행할지를 알려줄 수 있다.</p> + +<p>자바스크립트에는 goto 구문이 없다는 것에 주의. break나 continue에서만 레이블을 사용할 수 있다.</p> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a> 코드에서 "let"을 레이블 이름으로 사용할 수 없다. {{jsxref("SyntaxError")}}를 발생시킨다. (let은 허용되지 않는 식별자이다.)</p> + +<h2 id="예제">예제</h2> + +<h3 id="for문에서_레이블_continue_사용하기">for문에서 레이블 continue 사용하기</h3> + +<pre class="brush: js">var i, j; + +loop1: +for (i = 0; i < 3; i++) { //첫번째 for문은 "loop1" 레이블을 붙였다. + loop2: + for (j = 0; j < 3; j++) { //두번째 for문은 "loop2" 레이블을 붙였다. + if (i === 1 && j === 1) { + continue loop1; + } + console.log('i = ' + i + ', j = ' + j); + } +} + +// 출력 결과: +// "i = 0, j = 0" +// "i = 0, j = 1" +// "i = 0, j = 2" +// "i = 1, j = 0" +// "i = 2, j = 0" +// "i = 2, j = 1" +// "i = 2, j = 2" +// 다음 두 경우를 어떻게 스킵하는지 주목 : "i = 1, j = 1", "i = 1, j = 2" +</pre> + +<h3 id="레이블_continue문_사용하기">레이블 continue문 사용하기</h3> + +<p>items, tests 배열을 보면 이 예제는 tests를 통과하는 items의 수를 세고 있다.</p> + +<pre class="brush: js">var itemsPassed = 0; +var i, j; + +top: +for (i = 0; i < items.length; i++) { + for (j = 0; j < tests.length; j++) { + if (!tests[j].pass(items[i])) { + continue top; + } + } + + itemsPassed++; +}</pre> + +<h3 id="for문에_레이블_break문_사용하기">for문에 레이블 break문 사용하기</h3> + +<pre class="brush: js">var i, j; + +loop1: +for (i = 0; i < 3; i++) { //The first for statement is labeled "loop1" + loop2: + for (j = 0; j < 3; j++) { //The second for statement is labeled "loop2" + if (i === 1 && j === 1) { + break loop1; + } + console.log('i = ' + i + ', j = ' + j); + } +} + +// Output is: +// "i = 0, j = 0" +// "i = 0, j = 1" +// "i = 0, j = 2" +// "i = 1, j = 0" +// Notice the difference with the previous continue example</pre> + +<h3 id="레이블_break문_사용하기">레이블 break문 사용하기</h3> + +<p>items, tests 배열을 보면, 다음 예제는 items가 tests를 모두 통과하는지 판단한다.</p> + +<pre class="brush: js">var allPass = true; +var i, j; + +top: +for (i = 0; items.length; i++) + for (j = 0; j < tests.length; i++) + if (!tests[j].pass(items[i])) { + allPass = false; + break top; + }</pre> + +<h3 id="레이블_붙인_블록에_break_사용하기">레이블 붙인 블록에 break 사용하기</h3> + +<p>간단한 블록에도 레이블을 사용할 수 있지만, 반복문 아닌 레이블에는 break문만 사용할 수 있다.</p> + +<pre class="brush: js">foo: { + console.log('face'); + break foo; + console.log('this will not be executed'); +} +console.log('swap'); + +// 로그는 이렇게 출력된다: + +// "face" +// "swap </pre> + +<h3 id="레이블_붙인_함수_선언문">레이블 붙인 함수 선언문</h3> + +<p>ECMAScript 2015에서, 레이블 붙인 함수 선언문은 <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-labelled-function-declarations">web compatibility annex of the specification</a>의 non-strict 모드에서 표준화되어 있다.</p> + +<pre class="brush: js">L: function F() {}</pre> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a> 에서는 {{jsxref("SyntaxError")}}를 발생시킨다.</p> + +<pre class="brush: js">'use strict'; +L: function F() {} +// SyntaxError: functions cannot be labelled</pre> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Statements/function*">Generator functions</a>는 strict code도 non-strict code에서도 레이블 붙일 수 없다.</p> + +<pre class="brush: js">L: function* F() {} +// SyntaxError: generator functions cannot be labelled +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-12.12', 'Labelled statement')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-labelled-statements', 'Labelled statement')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-labelled-statements', 'Labelled statement')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="더_알아보기">더 알아보기</h2> + +<ul> + <li>{{jsxref("Statements/break", "break")}}</li> + <li>{{jsxref("Statements/continue", "continue")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/statements/let/index.html b/files/ko/web/javascript/reference/statements/let/index.html new file mode 100644 index 0000000000..3d02a34fba --- /dev/null +++ b/files/ko/web/javascript/reference/statements/let/index.html @@ -0,0 +1,246 @@ +--- +title: let +slug: Web/JavaScript/Reference/Statements/let +translation_of: Web/JavaScript/Reference/Statements/let +--- +<div>{{jsSidebar("Statements")}}</div> + +<p><strong><code>let</code></strong> 구문은 블록 유효 범위를 갖는 지역 변수를 선언하며, 선언과 동시에 임의의 값으로 초기화할 수도 있다.</p> + +<div>{{EmbedInteractiveExample("pages/js/statement-let.html")}}</div> + + + +<h2 id="Syntax">Syntax</h2> + +<pre class="brush: js">let var1 [= value1] [, var2 [= value2]] [, ..., varN [= valueN]];</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>var1</code>, <code>var2</code>, …, <code>varN</code></dt> + <dd>변수명. 유효한 식별자이면 가능하다.</dd> + <dt><code>value1</code>, <code>value2</code>, …, <code>valueN</code></dt> + <dd>변수의 초기값. 유효한 표현식이면 가능하다.</dd> +</dl> + +<h2 id="Description">Description</h2> + +<p><strong><code>let</code></strong>은 변수가 선언된 블록, 구문 또는 표현식 내에서만 유효한 변수를 선언한다. 이는 <strong><a href="/en-US/docs/JavaScript/Reference/Statements/var"><code>var</code></a></strong> 키워드가 블록 범위를 무시하고 전역 변수나 함수 지역 변수로 선언되는 것과 다른 점이다.</p> + +<p>"<strong>let</strong>"을 사용해야 하는 이유에 대해서는 이어지는 <a href="https://stackoverflow.com/questions/37916940/why-was-the-name-let-chosen-for-block-scoped-variable-declarations-in-javascri">링크</a>를 참조하시오.</p> + +<h3 id="유효_범위_규칙">유효 범위 규칙</h3> + +<p><strong><code>let</code></strong> 으로 선언된 변수는 변수가 선언된 블록 내에서만 유효하며, 당연하지만 하위 블록에서도 유효하다. 이러한 점에서는 <strong><code>let</code></strong> 과 <strong><a href="/en-US/docs/JavaScript/Reference/Statements/var"><code>var</code></a></strong>는 유사하지만, <strong><a href="/en-US/docs/JavaScript/Reference/Statements/var"><code>var</code></a></strong>는 함수 블록 이외의 블록은 무시하고 선언된다는 점이 다르다.</p> + +<pre class="brush:js">function varTest() { + var x = 1; + if (true) { + var x = 2; // 상위 블록과 같은 변수! + console.log(x); // 2 + } + console.log(x); // 2 +} + +function letTest() { + let x = 1; + if (true) { + let x = 2; // 상위 블록과 다른 변수 + console.log(x); // 2 + } + console.log(x); // 1 +} +</pre> + +<p id="Scoping_rules">프로그램이나 함수의 최상위에서는 <strong><code>let</code></strong>과 <strong><a href="/en-US/docs/JavaScript/Reference/Statements/var"><code>var</code></a></strong>은 서로 다르게 행동한다. <strong><code>let</code></strong>은 전역 객체의 속성 값을 생성하지 않는다.</p> + +<pre class="brush:js">var x = 'global'; +let y = 'global'; +console.log(this.x); // "global" 전역 객체의 속성 x를 생성 +console.log(this.y); // undefined 전역 객체의 속성 y를 생성하지 않음 +</pre> + +<h3 id="비공개_변수_모사">비공개 변수 모사</h3> + +<p><a href="/en-US/docs/Glossary/Constructor">생성자</a>와 함께 사용하여 <a href="/en-US/docs/Web/JavaScript/Closures">클로저</a>를 사용하지 않고 비공개 변수를 만들고 접근할 수 있다.</p> + +<pre class="brush:js">var Thing; + +{ + let privateScope = new WeakMap(); + let counter = 0; + + Thing = function() { + this.someProperty = 'foo'; + + privateScope.set(this, { + hidden: ++counter, + }); + }; + + Thing.prototype.showPublic = function() { + return this.someProperty; + }; + + Thing.prototype.showPrivate = function() { + return privateScope.get(this).hidden; + }; +} + +console.log(typeof privateScope); +// "undefined" + +var thing = new Thing(); + +console.log(thing); +// Thing {someProperty: "foo"} + +thing.showPublic(); +// "foo" + +thing.showPrivate(); +// 1 +</pre> + +<h3 id="임시적인_사각_지역과_오류">임시적인 사각 지역과 오류</h3> + +<p>같은 변수를 같은 함수나 블록 범위 내에서 재선언하면 {{jsxref("SyntaxError")}}가 발생한다.</p> + +<pre class="brush: js example-bad">if (x) { + let foo; + let foo; // SyntaxError thrown. +}</pre> + +<p>ECMAScript 2015에서는<strong><code>let</code></strong>은 <strong>선언 끌어올리기</strong>의 적용을 받지 않습니다. 이는 <strong><code>let</code></strong> 선언이 현재 실행되는 구간의 최상위로 옮겨지지 않는다는 것을 의미합니다. 따라서 변수가 초기화(선언)되기 전에 참조할 경우 <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/ReferenceError">ReferenceError</a></code>가 발생합니다.(<strong><a href="/en-US/docs/JavaScript/Reference/Statements/var"><code>var</code></a></strong>로 선언된 변수는 undefined 값을 가지는 것과는 대조적입니다.) "임시적인 사각 지역"은 블록 시작 부분부터 변수 선언이 실행되기 전까지 입니다.</p> + +<p>(<strong><code>let</code></strong>들의 정의가 평가되기까지 초기화가 되지 않는다는 의미이지. 호이스팅이 되지않아 정의가 되지 않는다는 의미와는 다르다고 생각함_헷갈리면 안된다.)</p> + +<pre class="brush: js example-bad">function do_something() { + console.log(bar); // undefined + console.log(foo); // ReferenceError + var bar = 1; + let foo = 2; +}</pre> + +<p><a href="/en-US/docs/JavaScript/Reference/Statements/switch"><code>switch</code></a> 구문을 사용할 때는 실제 블록이 하나 뿐이므로 중복 선언 오류가 발생하기 쉽습니다.</p> + +<pre class="brush: js example-bad">let x = 1; +switch(x) { + case 0: + let foo; + break; + + case 1: + let foo; // 재선언에 의한 SyntaxError. + break; +}</pre> + +<p>하지만 case 조건을 새로운 블록으로 감싸면 위의 코드와는 다르게 재선언 오류가 발생하지 않습니다.</p> + +<pre class="brush: js">let x = 1; + +switch(x) { + case 0: { + let foo; + break; + } + case 1: { + let foo; + break; + } +}</pre> + +<h3 id="임시적인_사각_지역과_typeof">임시적인 사각 지역과 <code>typeof</code></h3> + +<p>선언되지 않은 변수와 <code>undefined</code> 값을 지닌 변수와는 다르게, 임시적인 사각 지역에 있는 변수에 변수형 확인을 위해 <code>typeof</code>을 사용하면 <code>ReferenceError</code>가 발생합니다:</p> + +<pre class="brush: js">// 'undefined' 출력 +console.log(typeof undeclaredVariable); +// 'ReferenceError' 발생 +console.log(typeof i); +let i = 10;</pre> + +<h3 id="정적_유효_범위와_결합된_임시적인_사각_지역_예시">정적 유효 범위와 결합된 임시적인 사각 지역 예시</h3> + +<p>정적 유효 범위로 인해, 표현 <code>(foo + 55)</code> 내부의 "<strong>foo</strong>"는 33을 값으로 가지는 <u>상위 블록의 foo</u>가 아니라 <u>if 블록의 foo</u>로 해석됩니다. 해당 행에서 <u>if 블록의 "foo"</u>는 이미 정적 유효 범위에 생성되었지만, 선언의 초기화가 완료(선언 구문의 <strong>종료</strong>)되지 않았습니다. 따라서 여전히 임시적인 사각 지역에 해당됩니다.</p> + +<pre class="brush: js example-bad">function test(){ + var foo = 33; + if (true) { + let foo = (foo + 55); // ReferenceError + } +} +test();</pre> + +<p>이 현상은 다음과 같은 상황에서 혼란을 유발할 수 있습니다. 지시 구문 <code>let n of n.a</code>은 이미 for loop 블록에 속해 있으며, 구문자 "<strong>n.a</strong>"는 속성 'a'를 지시 구문 자기자신의 앞부분에 위치한 객체 'n'에서 참조하려 합니다. 해당 객체 'n'은 위와 마찬가지로 선언이 <strong>종료</strong>되지 않았기에 임시적인 사각 지역에 해당합니다.</p> + +<pre class="brush: js example-bad">function go(n) { + // 정의되어 있는 n! + console.log(n); // Object {a: [1,2,3]} + + for (let n of n.a) { // ReferenceError + console.log(n); + } +} + +go({a: [1, 2, 3]}); +</pre> + +<h2 id="그_외_상황들">그 외 상황들</h2> + +<p>블록을 사용할 때, <strong><code>let</code></strong>은 변수의 유효 범위를 블록으로 제한합니다. 함수 내 또는 전역을 유효 범위로 가지는 <code><strong>var</strong></code>와의 차이점을 숙지하세요.</p> + +<pre class="brush: js">var a = 1; +var b = 2; + +if (a === 1) { + var a = 11; // 전역 변수 + let b = 22; // if 블록 변수 + + console.log(a); // 11 + console.log(b); // 22 +} + +console.log(a); // 11 +console.log(b); // 2</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-let-and-const-declarations', 'Let and Const Declarations')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition. Does not specify let expressions or let blocks.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-let-and-const-declarations', 'Let and Const Declarations')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.statements.let")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/var"><code>var</code></a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/const"><code>const</code></a></li> + <li><a href="https://hacks.mozilla.org/2015/07/es6-in-depth-let-and-const/">ES6 In Depth: <code>let</code> and <code>const</code></a></li> + <li><a href="https://blog.mozilla.org/addons/2015/10/14/breaking-changes-let-const-firefox-nightly-44/">Breaking changes in <code>let</code> and <code>const</code> in Firefox 44</a></li> + <li><a href="https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch3.md">You Don't Know JS: Scope & Closures: Chapter 3: Function vs. Block Scope</a></li> + <li><a href="https://stackoverflow.com/a/33198850/1125029">StackOverflow: What is the Temporal Dead Zone. </a></li> + <li><a href="https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable">StackOverflow: What is the difference between using let and var?</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/statements/return/index.html b/files/ko/web/javascript/reference/statements/return/index.html new file mode 100644 index 0000000000..e865cb9a65 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/return/index.html @@ -0,0 +1,159 @@ +--- +title: return +slug: Web/JavaScript/Reference/Statements/return +tags: + - JavaScript + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/return +--- +<div>{{jsSidebar("Statements")}}</div> + +<p><strong><code>return</code> 명령문</strong>은 함수 실행을 종료하고, 주어진 값을 함수 호출 지점으로 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/statement-return.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">return [[expression]]; </pre> + +<dl> + <dt><code>expression</code></dt> + <dd>반환할 값으로 사용할 표현식. 생략할 경우 {{jsxref("undefined")}}를 대신 반환합니다.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p>함수 본문에서 <code>return</code> 명령문에 도달하면 함수의 실행은 그 지점에서 중단됩니다. 값을 제공한 경우 함수를 호출한 곳에 그 값을 반환합니다. 예를 들어, 다음 함수는 숫자 매개변수 <code>x</code>의 제곱을 반환합니다.</p> + +<pre class="brush: js">function square(x) { + return x * x; +} +var demo = square(3); +// demo는 9</pre> + +<p>값을 명시하지 않으면 대신 <code>undefined</code>를 반환합니다.</p> + +<p>다음 <code>return</code> 명령문 모두 함수 실행을 끊습니다.</p> + +<pre class="brush: js">return; +return true; +return false; +return x; +return x + y / 3; +</pre> + +<h3 id="자동_세미콜론_삽입">자동 세미콜론 삽입</h3> + +<p><code>return</code> 명령문은 <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion">자동 세미콜론 삽입(ASI)</a>의 영향을 받습니다. <code>return</code> 키워드와 표현식 사이에는 줄바꿈 문자가 올 수 없습니다.</p> + +<pre class="brush: js">return +a + b; +</pre> + +<p>위 코드는 ASI로 인해 아래처럼 처리됩니다.</p> + +<pre class="brush: js">return; +a + b; +</pre> + +<p>콘솔이 "unreachable code after return statement" 경고를 출력할 것입니다.</p> + +<div class="note">Gecko 40 {{geckoRelease(40)}}부터, <code>return</code> 이후에 위치하여 도달할 수 없는 코드를 발견하면 콘솔에 경고를 출력합니다.</div> + +<p>문제를 해결하려면 괄호를 사용해 ASI를 방지해야 합니다.</p> + +<pre class="brush: js">return ( + a + b +); +</pre> + +<h2 id="예제">예제</h2> + +<h3 id="함수_중단">함수 중단</h3> + +<p>함수는 <code>return</code>을 호출하는 지점에서 즉시 실행을 멈춥니다.</p> + +<pre class="brush: js">function counter() { + for (var count = 1; ; count++) { // 무한 반복 + console.log(count + "A"); // 5까지 + if (count === 5) { + return; + } + console.log(count + "B"); // 4까지 + } + console.log(count + "C"); // 절대 나타나지 않음 +} + +counter(); + +// 출력: +// 1A +// 1B +// 2A +// 2B +// 3A +// 3B +// 4A +// 4B +// 5A +</pre> + +<h3 id="함수_반환하기">함수 반환하기</h3> + +<p><a href="/ko/docs/Web/JavaScript/Guide/Closures">클로저</a>에 대해서도 더 알아보세요.</p> + +<pre class="brush: js">function magic(x) { + return function calc(x) { return x * 42 }; +} + +var answer = magic(); +answer(1337); // 56154 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-12.9', 'Return statement')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-return-statement', 'Return statement')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-return-statement', 'Return statement')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.statements.return")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Reference/Functions">함수</a></li> + <li><a href="/ko/docs/Web/JavaScript/Guide/Closures">클로저</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/statements/switch/index.html b/files/ko/web/javascript/reference/statements/switch/index.html new file mode 100644 index 0000000000..b4eb68e5a7 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/switch/index.html @@ -0,0 +1,306 @@ +--- +title: switch +slug: Web/JavaScript/Reference/Statements/switch +translation_of: Web/JavaScript/Reference/Statements/switch +--- +<div>{{jsSidebar("Statements")}}</div> + +<p><span class="seoSummary">The <strong><code>switch</code> statement</strong> evaluates an <a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators">expression</a>, matching the expression's value to a <code>case</code> clause, and executes <a href="/en-US/docs/Web/JavaScript/Reference/Statements">statements</a> associated with that case, as well as statements in cases that follow the matching case.</span></p> + +<div>{{EmbedInteractiveExample("pages/js/statement-switch.html")}}</div> + + + +<h2 id="문법">문법</h2> + +<pre class="brush: js">switch (expression) { + case value1: + //Statements executed when the + //result of expression matches value1 + [break;] + case value2: + //Statements executed when the + //result of expression matches value2 + [break;] + ... + case valueN: + //Statements executed when the + //result of expression matches valueN + [break;] + [default: + //Statements executed when none of + //the values match the value of the expression + [break;]] +}</pre> + +<dl> + <dt><code>expression</code></dt> + <dd><br> + 각각의 case 절에 맞추어볼 결과에 대한 <code>expression</code></dd> + <dt><code>case valueN</code> {{optional_inline}}</dt> + <dd>어떤 <code>case</code> 절은 <code>expression</code>와 맞추어보는데 사용된다. 만약 <code>expression</code> 이 특정 <code>valueN</code>과 일치 된다면, <code>switch</code> statement 문이 끝나거나 <code>break</code>가 오떄까지 case 절 내부가 실행된다.</dd> + <dt><code>default</code> {{optional_inline}}</dt> + <dd><code>default</code> 절; 만약 있다면, 어떤 <code>case</code>의 절도 <code>expression</code> 값과 일치되지 않는다면, default 절이 실행된다.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p>A switch statement first evaluates its expression. It then looks for the first <code>case</code> clause whose expression evaluates to the same value as the result of the input expression (using the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">strict comparison</a>, <code>===</code>) and transfers control to that clause, executing the associated statements. (If multiple cases match the provided value, the first case that matches is selected, even if the cases are not equal to each other.)</p> + +<p>If no matching <code>case</code> clause is found, the program looks for the optional <code>default</code> clause, and if found, transfers control to that clause, executing the associated statements. If no <code>default</code> clause is found, the program continues execution at the statement following the end of <code>switch</code>. By convention, the <code>default</code> clause is the last clause, but it does not need to be so.</p> + +<p>The optional <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/break" title="JavaScript/Reference/Statements/break">break</a></code> statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If <code>break</code> is omitted, the program continues execution at the next statement in the <code>switch</code> statement.</p> + +<h2 id="예제">예제</h2> + +<h3 id="Using_switch">Using <code>switch</code></h3> + +<p>In the following example, if <code>expr</code> evaluates to "Bananas", the program matches the value with case "Bananas" and executes the associated statement. When <code>break</code> is encountered, the program breaks out of <code>switch</code> and executes the statement following <code>switch</code>. If <code>break</code> were omitted, the statement for case "Cherries" would also be executed.</p> + +<pre class="brush: js">switch (expr) { + case 'Oranges': + console.log('Oranges are $0.59 a pound.'); + break; + case 'Apples': + console.log('Apples are $0.32 a pound.'); + break; + case 'Bananas': + console.log('Bananas are $0.48 a pound.'); + break; + case 'Cherries': + console.log('Cherries are $3.00 a pound.'); + break; + case 'Mangoes': + case 'Papayas': + console.log('Mangoes and papayas are $2.79 a pound.'); + break; + default: + console.log('Sorry, we are out of ' + expr + '.'); +} + +console.log("Is there anything else you'd like?"); +</pre> + +<h3 id="break를_쓰지않으면_어떻게_되는가">break를 쓰지않으면 어떻게 되는가?</h3> + +<p>If you forget a break then the script will run from the case where the criterion is met and will run the case after that regardless if criterion was met. See example here:</p> + +<pre class="brush: js">var foo = 0; +switch (foo) { + case -1: + console.log('negative 1'); + break; + case 0: // foo is 0 so criteria met here so this block will run + console.log(0); + // NOTE: the forgotten break would have been here + case 1: // no break statement in 'case 0:' so this case will run as well + console.log(1); + break; // it encounters this break so will not continue into 'case 2:' + case 2: + console.log(2); + break; + default: + console.log('default'); +}</pre> + +<h3 id="Can_I_put_a_default_between_cases">Can I put a default between cases?</h3> + +<p>Yes, you can! JavaScript will drop you back to the default if it can't find a match:</p> + +<pre class="brush: js">var foo = 5; +switch (foo) { + case 2: + console.log(2); + break; // it encounters this break so will not continue into 'default:' + default: + console.log('default') + // fall-through + case 1: + console.log('1'); +} +</pre> + +<p>It also works when you put default before all other cases.</p> + +<h3 id="Methods_for_multi-criteria_case">Methods for multi-criteria case</h3> + +<p>Source for this technique is here:</p> + +<p><a href="http://stackoverflow.com/questions/13207927/switch-statement-multiple-cases-in-javascript">Switch statement multiple cases in JavaScript (Stack Overflow)</a></p> + +<h4 id="Multi-case_-_single_operation">Multi-case - single operation</h4> + +<p>This method takes advantage of the fact that if there is no break below a case statement it will continue to execute the next case statement regardless if the case meets the criteria. See the section titled "What happens if I forgot a break?"</p> + +<p>This is an example of a single operation sequential switch statement, where four different values perform exactly the same.</p> + +<pre class="brush: js">var Animal = 'Giraffe'; +switch (Animal) { + case 'Cow': + case 'Giraffe': + case 'Dog': + case 'Pig': + console.log('This animal will go on Noah\'s Ark.'); + break; + case 'Dinosaur': + default: + console.log('This animal will not.'); +}</pre> + +<h4 id="Multi-case_-_chained_operations">Multi-case - chained operations</h4> + +<p>This is an example of a multiple-operation sequential switch statement, where, depending on the provided integer, you can receive different output. This shows you that it will traverse in the order that you put the case statements, and it does not have to be numerically sequential. In JavaScript, you can even mix in definitions of strings into these case statements as well.</p> + +<pre class="brush: js">var foo = 1; +var output = 'Output: '; +switch (foo) { + case 0: + output += 'So '; + case 1: + output += 'What '; + output += 'Is '; + case 2: + output += 'Your '; + case 3: + output += 'Name'; + case 4: + output += '?'; + console.log(output); + break; + case 5: + output += '!'; + console.log(output); + break; + default: + console.log('Please pick a number from 0 to 5!'); +}</pre> + +<p>이 예제의 결과:</p> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Value</th> + <th scope="col">Log text</th> + </tr> + <tr> + <td>foo is NaN or not 1, 2, 3, 4, 5 or 0</td> + <td>Please pick a number from 0 to 5!</td> + </tr> + <tr> + <td>0</td> + <td>Output: So What Is Your Name?</td> + </tr> + <tr> + <td>1</td> + <td>Output: What Is Your Name?</td> + </tr> + <tr> + <td>2</td> + <td>Output: Your Name?</td> + </tr> + <tr> + <td>3</td> + <td>Output: Name?</td> + </tr> + <tr> + <td>4</td> + <td>Output: ?</td> + </tr> + <tr> + <td>5</td> + <td>Output: !</td> + </tr> + </tbody> +</table> + +<h3 id="Block-scope_variables_within_switch_statements">Block-scope variables within <code>switch</code> statements</h3> + +<p>With ECMAScript 2015 (ES6) support made available in most modern browsers, there will be cases where you would want to use <a href="/en-US/docs/Web/JavaScript/Reference/Statements/let">let</a> and <a href="/en-US/docs/Web/JavaScript/Reference/Statements/const">const</a> statements to declare block-scoped variables.</p> + +<p>Take a look at this example:</p> + +<pre class="brush: js">const action = 'say_hello'; +switch (action) { + case 'say_hello': + let message = 'hello'; + console.log(message); + break; + case 'say_hi': + let message = 'hi'; + console.log(message); + break; + default: + console.log('Empty action received.'); + break; +}</pre> + +<p>This example will output the error <code>Uncaught SyntaxError: Identifier 'message' has already been declared</code> which you were not probably expecting.</p> + +<p>This is because the first <code>let message = 'hello';</code> conflicts with second let statement <code>let message = 'hi';</code> even they're within their own separate case statements <code>case 'say_hello':</code> and <code>case 'say_hi':</code>; ultimately this is due to both <code>let</code> statements being interpreted as duplicate declarations of the same variable name within the same block scope.</p> + +<p>We can easily fix this by wrapping our case statements with brackets:</p> + +<pre class="brush: js">const action = 'say_hello'; +switch (action) { + case 'say_hello': <strong>{ // added brackets</strong> + let message = 'hello'; + console.log(message); + break; + <strong>} // added brackets</strong> + case 'say_hi': <strong>{ // added brackets</strong> + let message = 'hi'; + console.log(message); + break; + <strong>} // added brackets</strong> + default: <strong>{ // added brackets</strong> + console.log('Empty action received.'); + break; + <strong>} // added brackets</strong> +}</pre> + +<p>This code will now output <code>hello</code> in the console as it should, without any errors at all.</p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-12.11', 'switch statement')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-switch-statement', 'switch statement')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-switch-statement', 'switch statement')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.statements.switch")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/if...else"><code>if...else</code></a></li> +</ul> diff --git a/files/ko/web/javascript/reference/statements/throw/index.html b/files/ko/web/javascript/reference/statements/throw/index.html new file mode 100644 index 0000000000..ff5ccb2333 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/throw/index.html @@ -0,0 +1,198 @@ +--- +title: throw +slug: Web/JavaScript/Reference/Statements/throw +translation_of: Web/JavaScript/Reference/Statements/throw +--- +<div>{{jsSidebar("Statements")}}</div> + +<p><strong><code>throw</code> </strong>문은 사용자 정의 예외를 던질 수 있습니다. 현재 함수의 실행이 중지되고 (<code>throw</code> 이후의 명령문은 실행되지 않습니다.), 컨트롤은 콜 스택의 첫 번째 <a href="/en-US/docs/Web/JavaScript/Reference/Statements/try...catch"><code>catch</code></a> 블록으로 전달됩니다. 호출자 함수 사이에 <code>catch</code> 블록이 없으면 프로그램이 종료됩니다. </p> + +<div>{{EmbedInteractiveExample("pages/js/statement-throw.html")}}</div> + + + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">throw <em>expression</em>; </pre> + +<dl> + <dt><code>expression</code></dt> + <dd>예외를 던지는 구문</dd> +</dl> + +<h2 id="Description">Description</h2> + +<p>예외를 발생하기 위해 <code>throw</code> 문을 사용하세요. <br> + 예외를 던지면 <code>expression</code>은 예외 값을 지정합니다.<br> + 다음 각각은 예외를 던집니다:</p> + +<pre class="brush: js">throw 'Error2'; // generates an exception with a string value +throw 42; // generates an exception with the value 42 +throw true; // generates an exception with the value true</pre> + +<p>또한 <code>throw</code> 문은 <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion">자동 세미콜론 삽입</a> (ASI)에 의해 영향을 받으며 <code>throw</code> 키워드와 표현식 사이에 줄 종결자는 허용되지 않으므로 주의해야합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="객체_throw_하기">객체 throw 하기</h3> + +<p>예외를 던질 때 객체를 지정할 수 있습니다. 그러면 <code>catch</code> 블록에서 객체의 속성을 참조 할 수 있습니다.<br> + 다음 예제에서는 <code>UserException</code> 유형의 객체를 만들고 <code>throw</code> 구문에서 이 객체를 사용합니다.</p> + +<pre class="brush: js">function UserException(message) { + this.message = message; + this.name = 'UserException'; +} +function getMonthName(mo) { + mo = mo - 1; // Adjust month number for array index (1 = Jan, 12 = Dec) + var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', + 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + if (months[mo] !== undefined) { + return months[mo]; + } else { + throw new UserException('InvalidMonthNo'); + } +} + +try { + // statements to try + var myMonth = 15; // 15 is out of bound to raise the exception + var monthName = getMonthName(myMonth); +} catch (e) { + monthName = 'unknown'; + console.log(e.message, e.name); // pass exception object to err handler +} +</pre> + +<h3 id="객체를_throw_하는_다른_예제">객체를 throw 하는 다른 예제</h3> + +<p>다음 예제는 입력 문자열에서 미국 우편 번호를 테스트합니다.<br> + 우편 번호가 잘못된 형식을 사용하는 경우 throw 문은 <code>ZipCodeFormatException</code> 유형의 개체를 만들어 예외를 던집니다.</p> + +<pre class="brush: js">/* + * Creates a ZipCode object. + * + * Accepted formats for a zip code are: + * 12345 + * 12345-6789 + * 123456789 + * 12345 6789 + * + * If the argument passed to the ZipCode constructor does not + * conform to one of these patterns, an exception is thrown. + */ + +function ZipCode(zip) { + zip = new String(zip); + pattern = /[0-9]{5}([- ]?[0-9]{4})?/; + if (pattern.test(zip)) { + // zip code value will be the first match in the string + this.value = zip.match(pattern)[0]; + this.valueOf = function() { + return this.value + }; + this.toString = function() { + return String(this.value) + }; + } else { + throw new ZipCodeFormatException(zip); + } +} + +function ZipCodeFormatException(value) { + this.value = value; + this.message = 'does not conform to the expected format for a zip code'; + this.toString = function() { + return this.value + this.message; + }; +} + +/* + * This could be in a script that validates address data + * for US addresses. + */ + +const ZIPCODE_INVALID = -1; +const ZIPCODE_UNKNOWN_ERROR = -2; + +function verifyZipCode(z) { + try { + z = new ZipCode(z); + } catch (e) { + if (e instanceof ZipCodeFormatException) { + return ZIPCODE_INVALID; + } else { + return ZIPCODE_UNKNOWN_ERROR; + } + } + return z; +} + +a = verifyZipCode(95060); // returns 95060 +b = verifyZipCode(9560); // returns -1 +c = verifyZipCode('a'); // returns -1 +d = verifyZipCode('95060'); // returns 95060 +e = verifyZipCode('95060 1234'); // returns 95060 1234 +</pre> + +<h3 id="Rethrow_an_exception">Rethrow an exception</h3> + +<p><code>throw</code>를 사용하여 예외를 잡은 후에 예외를 다시 던질 수 있습니다.<br> + 다음 예제에서는 숫자 값으로 예외를 잡고 값이 50 이상이면 예외를 다시 throw합니다.<br> + 반환 된 예외는 둘러싸는 함수 또는 최상위 수준으로 전파되어 사용자가 볼 수 있도록합니다</p> + +<pre class="brush: js">try { + throw n; // throws an exception with a numeric value +} catch (e) { + if (e <= 50) { + // statements to handle exceptions 1-50 + } else { + // cannot handle this exception, so rethrow + throw e; + } +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.4</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-12.13', 'throw statement')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-throw-statement', 'throw statement')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-throw-statement', 'throw statement')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.statements.throw")}}</p> + +<h2 id="추가적으로_볼_것">추가적으로 볼 것</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/try...catch"><code>try...catch</code></a></li> +</ul> diff --git a/files/ko/web/javascript/reference/statements/try...catch/index.html b/files/ko/web/javascript/reference/statements/try...catch/index.html new file mode 100644 index 0000000000..c7cdf05b1f --- /dev/null +++ b/files/ko/web/javascript/reference/statements/try...catch/index.html @@ -0,0 +1,273 @@ +--- +title: try...catch +slug: Web/JavaScript/Reference/Statements/try...catch +translation_of: Web/JavaScript/Reference/Statements/try...catch +--- +<div> +<p>{{jsSidebar("Statements")}}</p> + +<p><strong><code>try...catch</code></strong> 문은 실행할 코드블럭을 표시하고 예외(exception)가 발생(throw)할 경우의 응답을 지정합니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/statement-trycatch.html")}}</p> +</div> + +<h2 id="문법">문법</h2> + +<pre class="notranslate">try { + <em>try_statements</em> +} +[catch (<em>exception_var</em>) { + <em>catch_statements</em> +}] +[finally { + <em>finally_statements</em> +}]</pre> + +<dl> + <dt><code>try_statements</code></dt> + <dd>실행될 선언들</dd> +</dl> + +<dl> + <dt><code>catch_statements</code></dt> + <dd>try 블록에서 예외가 발생했을 때 실행될 선언들</dd> +</dl> + +<dl> + <dt><code>exception_var</code></dt> + <dd>catch 블록과 관련된 예외 객체를 담기 위한 식별자</dd> +</dl> + +<dl> + <dt><code>finally_statements</code></dt> + <dd>try 선언이 완료된 이후에 실행된 선언들. 이 선언들은 예외 발생 여부와 상관없이 실행된다.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p>try 선언의 구성은 하나 혹은 그 이상의 선언을 포함한 try 블록 및 catch 항목이나 finally 항목 중 최소한 하나 혹은 둘 다 포함하여 이루어진다. 즉, try 선언에는 세 가지 형식이 존재한다.</p> + +<ol> + <li><code>try...catch</code></li> + <li><code>try...finally</code></li> + <li><code>try...catch...finally</code></li> +</ol> + +<p><code>catch</code> 블록은 <code>try</code> 블록 안에서 예외가 발생(throw)하는 경우 무엇을 할지 명시하는 코드를 포함합니다. <code>try</code> 블록 (또는 <code>try</code> 블록 내에서 호출된 함수) 내의 명령문이 예외를 throw 하면 제어가 <code>catch</code> 블록으로 이동합니다. <code>try</code> 블록에 예외가 발생하지 않으면 <code>catch</code> 블록을 건너뜁니다.</p> + +<p><code>finally</code> 블록은 <code>try</code> 블록과 <code>catch</code> 블록(들)이 실행을 마친 후 항상 실행됩니다. 예외가 발생했는지에 관계없이 항상 실행됩니다.</p> + +<p>하나 이상의 <code>try</code> 문을 중첩 할 수 있습니다. 내부의 <code>try</code> 문에 <code>catch</code> 블록이 없으면, 둘러싼 <code>try</code> 문의 <code>catch</code> 블록이 입력됩니다.</p> + +<p>또한 <code>try</code> 문을 사용하여 예외처리를 합니다. 예외처리에 대해 더 알고 싶다면, <a href="/en-US/docs/Web/JavaScript/Guide" title="en/JavaScript/Guide">JavaScript Guide</a> 를 참고하세요.</p> + +<h3 id="무조건적_catch_문">무조건적 <code>catch</code> 문</h3> + +<p><code>try</code>-block 내에서 예외가 발생하면 <code>catch</code>-block이 실행됩니다. 예를 들어, 다음 코드에서 예외가 발생하면 제어가 <code>catch</code> 블록으로 전송됩니다.</p> + + + +<pre class="brush: js notranslate">try { + throw "myException"; // generates an exception +} +catch (e) { + // statements to handle any exceptions + logMyErrors(e); // pass exception object to error handler +} +</pre> + +<h3 id="조건적_catch_문">조건적 <code>catch</code> 문</h3> + +<p>다음과 같이 <code>try...catch</code>블록을 <code>if...else if...else</code> 구조와 결합하여 '조건부 <code>catch</code>-blocks'을 만들 수 있습니다.</p> + + + +<pre class="notranslate">try { + myroutine(); // may throw three types of exceptions +} catch (e) { + if (e instanceof TypeError) { + // statements to handle TypeError exceptions + } else if (e instanceof RangeError) { + // statements to handle RangeError exceptions + } else if (e instanceof EvalError) { + // statements to handle EvalError exceptions + } else { + // statements to handle any unspecified exceptions + logMyErrors(e); // pass exception object to error handler + } +} +</pre> + + + +<p>이에 대한 일반적인 사용 사례는 예상 오류의 작은 하위 집합 만 포착 (및 침묵) 한 다음 다른 경우에 오류를 다시 발생시키는 것입니다.</p> + +<pre class="notranslate">try { + myRoutine(); +} catch (e) { + if (e instanceof RangeError) { + // statements to handle this very common expected error + } else { + throw e; // re-throw the error unchanged + } +}</pre> + +<h3 id="The_exception_identifier">The exception identifier</h3> + +<p><code>try</code>-block에서 예외가 발생하면 <code>exception_var</code> (즉, <code>catch (e)</code>내부의 <code>e</code>)가 예외 값을 보유합니다. 이 식별자를 사용하여 발생한 예외에 대한 정보를 얻을 수 있습니다. 이 식별자는 <code>catch</code>-block의 {{Glossary("Scope", "scope")}}에서만 사용할 수 있습니다.</p> + + + +<pre class="notranslate">function isValidJSON(text) { + try { + JSON.parse(text); + return true; + } catch { + return false; + } +}</pre> + +<h3 id="The_finally-block">The finally-block</h3> + +<p>The <code>finally</code>-block contains statements to execute after the <code>try</code>-block and <code>catch</code>-block(s) execute, but before the statements following the <code>try...catch...finally</code>-block. Note that the <code>finally</code>-block executes regardless of whether an exception is thrown. Also, if an exception is thrown, the statements in the <code>finally</code>-block execute even if no <code>catch</code>-block handles the exception.</p> + + + +<p>The following example shows one use case for the <code>finally</code>-block. The code opens a file and then executes statements that use the file; the <code>finally</code>-block makes sure the file always closes after it is used even if an exception was thrown.</p> + +<pre class="notranslate">openMyFile(); +try { + // tie up a resource + writeMyFile(theData); +} +finally { + closeMyFile(); // always close the resource +}</pre> + +<h2 id="Examples">Examples</h2> + +<h3 id="Nested_try-blocks">Nested try-blocks</h3> + +<p>First, let's see what happens with this:</p> + +<pre class="notranslate">try { + try { + throw new Error('oops'); + } + finally { + console.log('finally'); + } +} +catch (ex) { + console.error('outer', ex.message); +} + +// Output: +// "finally" +// "outer" "oops" +</pre> + +<p>Now, if we already caught the exception in the inner <code>try</code>-block by adding a <code>catch</code>-block</p> + +<pre class="notranslate">try { + try { + throw new Error('oops'); + } + catch (ex) { + console.error('inner', ex.message); + } + finally { + console.log('finally'); + } +} +catch (ex) { + console.error('outer', ex.message); +} + +// Output: +// "inner" "oops" +// "finally" +</pre> + +<p>And now, let's rethrow the error.</p> + +<pre class="notranslate">try { + try { + throw new Error('oops'); + } + catch (ex) { + console.error('inner', ex.message); + throw ex; + } + finally { + console.log('finally'); + } +} +catch (ex) { + console.error('outer', ex.message); +} + +// Output: +// "inner" "oops" +// "finally" +// "outer" "oops" +</pre> + +<p>Any given exception will be caught only once by the nearest enclosing <code>catch</code>-block unless it is rethrown. Of course, any new exceptions raised in the "inner" block (because the code in <code>catch</code>-block may do something that throws), will be caught by the "outer" block.</p> + +<h3 id="Returning_from_a_finally-block">Returning from a finally-block</h3> + +<p>If the <code>finally</code>-block returns a value, this value becomes the return value of the entire <code>try-catch-finally</code> statement, regardless of any <code>return</code> statements in the <code>try</code> and <code>catch</code>-blocks. This includes exceptions thrown inside of the <code>catch</code>-block:</p> + +<pre class="notranslate">(function() { + try { + try { + throw new Error('oops'); + } + catch (ex) { + console.error('inner', ex.message); + throw ex; + } + finally { + console.log('finally'); + return; + } + } + catch (ex) { + console.error('outer', ex.message); + } +})(); + +// Output: +// "inner" "oops" +// "finally"</pre> + +<p>The outer "oops" is not thrown because of the return in the <code>finally</code>-block. The same would apply to any value returned from the <code>catch</code>-block.</p> + +<h2 id="Specifications">Specifications</h2> + +<table> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-try-statement', 'try statement')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.statements.try_catch")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Error")}}</li> + <li>{{jsxref("Statements/throw", "throw")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/statements/var/index.html b/files/ko/web/javascript/reference/statements/var/index.html new file mode 100644 index 0000000000..4366c3ed73 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/var/index.html @@ -0,0 +1,195 @@ +--- +title: var +slug: Web/JavaScript/Reference/Statements/var +tags: + - JavaScript + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/var +--- +<div>{{jsSidebar("Statements")}}</div> + +<p><code><strong>var</strong></code>문은 변수를 선언하고, 선택적으로 초기화할 수 있습니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/statement-var.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox">var <em>varname1 [</em>= <em>value1 [</em>, <em>varname2 [</em>, <em>varname3 ... [</em>, <em>varnameN]]]]</em>;</pre> + +<dl> + <dt><code>varnameN</code></dt> + <dd>변수 이름. 어떤 유효한 식별자도 될 수 있습니다.</dd> +</dl> + +<dl> + <dt><code>valueN</code></dt> + <dd>변수의 초기값. 어떤 유효한 표현도 될 수 있습니다.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p>어디에 선언이 되어있든 간에 변수들은 어떠한 코드가 실행되기 전에 처리가 됩니다. var로 선언된 변수의 범위는 현재 실행 문맥인데, 그 문맥은 둘러싼 함수, 혹은 함수의 외부에 전역으로 선언된 변수도 될 수 있습니다.</p> + +<p>선언된 변수들의 값 할당은 할당이 실행될 때 전역변수(이것은 전역 오브젝트의 프로퍼티가 됩니다)처럼 생성이 됩니다. 선언된 변수들과 선언되지 않은 변수들의 차이점은 다음과 같습니다:</p> + +<p>1. 선언된 변수들은 변수가 선언된 실행 콘텍스트(execution context) 안에서 만들어집니다. 선언되지 않은 변수들은 항상 전역변수 입니다.</p> + +<pre class="brush: js">function x() { + y = 1; // strict 모드에서는 ReferenceError를 출력합니다. + var z = 2; +} + +x(); + +console.log(y); // 로그에 "1" 출력합니다. +console.log(z); // ReferenceError: z is not defined outside x를 출력합니다. +</pre> + +<p>2. 선언된 변수들은 어떠한 코드가 실행되기 전에 만들어집니다. 선언되지 않은 변수들은 변수들을 할당하는 코드가 실행되기 전까지는 존재하지 않습니다.</p> + +<pre class="brush: js">console.log(a); // ReferenceError를 출력합니다. +console.log('still going...'); // 결코 실행되지 않습니다.</pre> + +<pre class="brush: js">var a; +console.log(a); // 브라우저에 따라 로그에 "undefined" 또는 "" 출력합니다. +console.log('still going...'); // 로그에 "still going..." 출력합니다.</pre> + +<p>3. 선언된 변수들은 변수들의 실행 콘텍스트(execution context)의 프로퍼티를 변경되지 않습니다. 선언되지 않은 변수들은 변경 가능합니다. (e.g 삭제 될 수도 있습니다.)</p> + +<pre class="brush: js">var a = 1; +b = 2; + +delete this.a; // strict 모드에서는 TypeError를 출력합니다. 그렇지 않으면 자동적으로 실패합니다. +delete this.b; + +console.log(a, b); // ReferenceError를 출력합니다. +// 'b' 프로퍼티는 삭제되었고, 어디에도 존재하지 않습니다.</pre> + +<p>이러한 세가지 다른점 때문에, 변수 선언 오류는 예기치않은 결과로 이어질 가능성이 높습니다. 그러므로 <strong>함수 또는 전역 범위인지 여부와 상관없이, 항상 변수를 선언 하는 것을 추천합니다.</strong> 그리고 ECMAScript 5 안에 <a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode">strict mode</a>, 선언되지 않은 변수에 할당하면 오류를 출력합니다.</p> + +<h3 id="var_호이스팅(hoisting)">var 호이스팅(hoisting)</h3> + +<p>변수 선언들 (그리고 일반적인 선언)은 어느 코드가 실행 되기 전에 처리하기 때문에, 코드 안에서 어디서든 변수 선언은 최상위에 선언한 것과 동등합니다. 이것은 변수가 선언되기 전에 사용 될 수 있다는 것을 의미합니다. 변수 선언이 함수 또는 전역 코드의 상단에 이동하는 것과 같은 행동을 "호이스팅(hoisting)"이라고 불립니다.</p> + +<pre class="brush: js">bla = 2 +var bla; +// ... + +// 위 선언을 다음과 같이 암묵적으로 이해하면 됩니다: + +var bla; +bla = 2; +</pre> + +<p>이러한 이유로, 그들의 범위(전역 코드의 상단 그리고 함수 코드의 상단) 상단에 변수를 항상 선언하기를 권장합니다. 그러면 변수는 함수 범위 (지역)이 되며, 스코프 체인으로 해결될 것이 분명합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="두_변수들의_선언_및_초기화">두 변수들의 선언 및 초기화</h3> + +<pre class="brush: js">var a = 0, b = 0; +</pre> + +<h3 id="단일_문자열_값으로_두_변수들_할당">단일 문자열 값으로 두 변수들 할당</h3> + +<pre class="brush: js">var a = "A"; +var b = a; + +// 다음과 같음: + +var a, b = a = "A"; +</pre> + +<p>순서에 유의:</p> + +<pre class="brush: js">var x = y, y = 'A'; +console.log(x + y); // undefinedA +</pre> + +<p>여기, x와 y는 어떠한 코드 실행하기 전에 선언되었다, 할당은 후에 발생하였다. "<code>x = y</code>"가 실행될 때, <code>y<font face="Open Sans, Arial, sans-serif">는 존재하여 </font></code><code>ReferenceError를 출력하진 않고</code> 값은 '<code>undefined</code>' 입니다. 그래서, <code>x는</code> undefined 값이 할당 됩니다. 그리고나서, <code>y는 </code>'A' 값이 할당 됩니다. 결과적으로, 첫번째 줄 이후에, <code>x === undefined && y === 'A'</code>, 이와 같은 결과가 됩니다.</p> + +<h3 id="다수의_변수들의_초기화">다수의 변수들의 초기화</h3> + +<pre class="brush: js">var x = 0; + +function f(){ + var x = y = 1; // x는 지역변수로 선언됩니다. y는 아닙니다! +} +f(); + +console.log(x, y); // 0, 1 +// x는 예상대로 전역이다 +// y leaked outside of the function, though! </pre> + +<h3 id="암묵적인_전역변수와_외부_함수_범위">암묵적인 전역변수와 외부 함수 범위</h3> + +<p>암묵적인 전역변수가 될 것으로 보이는 변수는 함수 범위 밖에서 변수들을 참조할 수 있다.</p> + +<pre class="brush: js">var x = 0; // x는 전역으로 선언되었고, 0으로 할당됩니다. + +console.log(typeof z); // undefined, z는 아직 존재하지 않습니다. + +function a() { // a 함수를 호출했을 때, + var y = 2; // y는 함수 a에서 지역변수로 선언되었으며, 2로 할당됩니다. + + console.log(x, y); // 0 2 + + function b() { // b 함수를 호출하였을때, + x = 3; // 존재하는 전역 x값에 3을 할당, 새로운 전역 var 변수를 만들지 않습니다. + y = 4; // 존재하는 외부 y값에 4를 할당, 새로운 전역 var 변수를 만들지 않습니다. + z = 5; // 새로운 전역 z 변수를 생성하고 5를 할당 합니다. + } // (strict mode에서는 ReferenceError를 출력합니다.) + + b(); // 호출되는 b는 전역 변수로 z를 생성합니다. + console.log(x, y, z); // 3 4 5 +} + +a(); // 호출되는 a는 또한 b를 호출합니다. +console.log(x, z); // 3 5 +console.log(typeof y); // undefined y는 function a에서 지역 변수입니다.</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">비고</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-12.2', 'var statement')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-variable-statement', 'variable statement')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-variable-statement', 'variable statement')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.statements.var")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Statements/let", "let")}}</li> + <li>{{jsxref("Statements/const", "const")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/statements/while/index.html b/files/ko/web/javascript/reference/statements/while/index.html new file mode 100644 index 0000000000..5509404ed6 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/while/index.html @@ -0,0 +1,142 @@ +--- +title: while +slug: Web/JavaScript/Reference/Statements/while +tags: + - 반복문 + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Statements/while +--- +<div>{{jsSidebar("Statements")}}</div> + +<p><strong>while문</strong>은 조건문이 참일 때 실행되는 반복문이다. 조건은 문장안이 실행되기 전에 참, 거짓을 판단한다.</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox">while (<em>condition</em>) + <em>statement</em> +</pre> + +<dl> + <dt><code>조건</code></dt> + <dd>반복이 시작되기 전에 조건문은 참,거짓을 판단받게 된다. 만약 조건문이 참이라면, while문 안의 문장들이 실행된다. 거짓이라면, 문장은 그냥 while 반복문 후로 넘어간다.</dd> + <dt><code>문장</code></dt> + <dd>조건문이 참일 때만 while문 속의 문장들이 실행된다. 반복문 속에 여러개의 문장을 사용하고 싶다면 중괄호 { } 를 통해 문장들을 하나로 묶어야 한다.</dd> +</dl> + +<h2 id="예제">예제</h2> + +<p>다음의 while문은 n이 3보다 작을 때까지 반복한다.</p> + +<pre class="brush:js">var n = 0; +var x = 0; + +while (n < 3) { + n++; + x += n; +}</pre> + +<p>반복을 살펴보면, n을 x에 계속 더하게 된다. 그러므로 x와 n 변수는 다음의 값을 갖는다.</p> + +<ul> + <li>첫번째 반복; n=1 과 x=1</li> + <li>두번째 반복; n=2 과 x=3</li> + <li>세번째 반복; n=3 과 x=6</li> +</ul> + +<p>세번째 반복후, n<3 이라는 초건은 더 이상 참이아니가 되므로 반복은 종료된다</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-while-statement', 'while statement')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-while-statement', 'while statement')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-12.6.2', 'while statement')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES3', '#sec-12.6.2', 'while statement')}}</td> + <td>{{Spec2('ES3')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-12.6.1', 'while statement')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/do...while"><code>do...while</code></a></li> + <li>{{jsxref("Statements/for", "for")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/statements/with/index.html b/files/ko/web/javascript/reference/statements/with/index.html new file mode 100644 index 0000000000..30940cc297 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/with/index.html @@ -0,0 +1,127 @@ +--- +title: with +slug: Web/JavaScript/Reference/Statements/with +translation_of: Web/JavaScript/Reference/Statements/with +--- +<div class="warning">Use of the <code>with</code> statement is not recommended, as it may be the source of confusing bugs and compatibility issues. See the "Ambiguity Contra" paragraph in the "Description" section below for details.</div> + +<div>{{jsSidebar("Statements")}}</div> + +<p><strong>with statement</strong> 는 명령문의 범위 체인을 확장합니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">with (expression) + <em>statement</em> +</pre> + +<dl> + <dt><code>expression</code></dt> + <dd>명령문을 평가할 때 사용되는 범위 체인에 지정된 표현식을 추가합니다. 표현식을 중괄호로 감싸는 것은 필수입니다.</dd> + <dt><code>statement</code></dt> + <dd>모든 구문을 말합니다. 여러개의 명령문을 실행하려면 <a href="/en-US/docs/Web/JavaScript/Reference/Statements/block" title="JavaScript/Reference/Statements/block">블록</a>명령문 ({...})을 사용하여 해당 명령문을 그룹화 하세요.</dd> +</dl> + +<h2 id="Description">Description</h2> + +<p>JavaScript는 규정되지 않은 이름을 포함하는 스크립트 또는 함수의 실행 컨텍스트와 연관된 범위 체인을 검색하여 규정되지 않은 이름을 찾습니다. 'with'문은 해당 개체를 평가하는 동안 이 개체를 해당 범위 체인의 머리글에 추가합니다. 본문에 사용된 규정되지 않은 이름이 범위 체인의 속성과 일치하는 경우 이름은 속성과 속성이 포함 된 개체에 바인딩 됩니다. 그렇지 않으면, {{jsxref("ReferenceError")}} 가 발생됩니다.</p> + +<div class="note"><code>with</code> 를 사용하는 것은 권장하지 않으며, ECMAScript 5 <a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode" title="JavaScript/Strict mode">strict mode</a>에서는 금지되어 있습니다. 임시 변수에 액세스 하려는 속성이 있는 객체를 할당하는 것이 좋습니다.</div> + +<h3 id="Performance_pro_contra">Performance pro & contra</h3> + +<p><strong>Pro:</strong> <code>with</code> 구문은 성능저하 없이 긴 객체 참조를 반복해야할 필요를 줄여서 파일 크기를 감소 시킬 수 있습니다. 'with'에 필요한 스코프 체인 변경은 연산 비용이 들지 않습니다. 'with'를 사용하면 반복되는 객체 참조를 파싱하는 인터프리터가 해소됩니다. 하지만 대게의 경우에 이 이점은 임시변수를 사용하여 원하는 객체에 대한 참조를 저장함으로써 얻을 수 있습니다.</p> + +<p><strong>Contra:</strong> The <code>with</code> statement forces the specified object to be searched first for all name lookups. Therefore all identifiers that aren't members of the specified object will be found more slowly in a 'with' block. Where performance is important, 'with' should only be used to encompass code blocks that access members of the specified object.</p> + +<h3 id="Ambiguity_contra">Ambiguity contra</h3> + +<p><strong>Contra:</strong> The <code>with</code> statement makes it hard for a human reader or JavaScript compiler to decide whether an unqualified name will be found along the scope chain, and if so, in which object. So given this example:</p> + +<pre class="brush: js">function f(x, o) { + with (o) { + console.log(x); + } +}</pre> + +<p>Only when <code>f</code> is called is <code>x</code> either found or not, and if found, either in <code>o</code> or (if no such property exists) in <code>f</code>'s activation object, where <code>x</code> names the first formal argument. If you forget to define <code>x</code> in the object you pass as the second argument, or if there's some similar bug or confusion, you won't get an error -- just unexpected results.</p> + +<p><strong>Contra: </strong>Code using <code>with</code> may not be forward compatible, especially when used with something other than a plain object. Consider this example:</p> + +<div> +<pre class="brush:js">function f(foo, values) { + with (foo) { + console.log(values); + } +} +</pre> + +<p>If you call <code>f([1,2,3], obj)</code> in an ECMAScript 5 environment, then the <code>values</code> reference inside the <code>with</code> statement will resolve to <code>obj</code>. However, ECMAScript 6 introduces a <code>values</code> property on {{jsxref("Array.prototype")}} (so that it will be available on every array). So, in a JavaScript environment that supports ECMAScript 6, the <code>values</code> reference inside the <code>with</code> statement could resolve to <code>[1,2,3].values</code>. However, in this particular example, {{jsxref("Array.prototype")}} has been defined with <code>values</code> in its {{jsxref("Symbol.unscopables")}} object. If it were not, one can see how this would be a difficult issue to debug.</p> +</div> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_with">Using <code>with</code></h3> + +<p>The following <code>with</code> statement specifies that the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math" title="JavaScript/Reference/Global_Objects/Math"><code>Math</code></a> object is the default object. The statements following the <code>with</code> statement refer to the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/PI" title="JavaScript/Reference/Global_Objects/Math/PI"><code>PI</code></a> property and the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/cos" title="JavaScript/Reference/Global_Objects/Math/cos"><code>cos</code></a> and <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sin" title="JavaScript/Reference/Global_Objects/Math/sin"><code>sin</code></a> methods, without specifying an object. JavaScript assumes the <code>Math</code> object for these references.</p> + +<pre class="brush:js">var a, x, y; +var r = 10; + +with (Math) { + a = PI * r * r; + x = r * cos(PI); + y = r * sin(PI / 2); +}</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-with-statement', 'with statement')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-with-statement', 'with statement')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-12.10', 'with statement')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Now forbidden in strict mode.</td> + </tr> + <tr> + <td>{{SpecName('ES3', '#sec-12.10', 'with statement')}}</td> + <td>{{Spec2('ES3')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-12.10', 'with statement')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.statements.with")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Statements/block", "block")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode">Strict mode</a></li> + <li>{{jsxref("Symbol.unscopables")}}</li> + <li>{{jsxref("Array.@@unscopables", "Array.prototype[@@unscopables]")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/strict_mode/index.html b/files/ko/web/javascript/reference/strict_mode/index.html new file mode 100644 index 0000000000..50cac47a52 --- /dev/null +++ b/files/ko/web/javascript/reference/strict_mode/index.html @@ -0,0 +1,383 @@ +--- +title: Strict mode +slug: Web/JavaScript/Reference/Strict_mode +tags: + - ECMAScript 5 + - JavaScript + - 엄격모드 +translation_of: Web/JavaScript/Reference/Strict_mode +--- +<div>{{JsSidebar("More")}}</div> + +<div class="callout-box">가끔 엄격하지 않은 기본값을 "<strong><a href="https://developer.mozilla.org/ko/docs/Glossary/Sloppy_mode">느슨한 모드</a></strong>(sloppy mode)"라고 부르기도 합니다. 공식적인 용어는 아니지만 혹시 모르니 알아두세요.</div> + +<div><a class="external" href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">ECMAScript 5</a> 에서 소개된 JavaScript 의 엄격모드는 JavaScript 의 제한된 버전을 선택하여 암묵적인 "<strong><a href="https://developer.mozilla.org/ko/docs/Glossary/Sloppy_mode">느슨한 모드</a></strong>(sloppy mode)" 를 해제하기 위한 방법입니다. 엄격 모드는 단지 부분적인 것이 아니며, 이것은 <em>고의적으로 </em>일반 코드와 다른 시멘틱을 가지고 있습니다. 엄격모드를 지원하지 않는 브라우저에서는 엄격 모드의 코드가 다른 방식으로 동작할 것입니다, 그 때문에 엄격 모드가 적절하게 적용된 피쳐 테스트 없이 엄격 모드에 의존하면 안됩니다. 엄격 모드의 코드와 비-엄격 모드의 코드는 공존할 수 있으며, 때문에 스크립트의 엄격 모드를 취사 선택하는 것이 점진적으로 가능하게 되었습니다.</div> + +<div></div> + +<p>엄격 모드는 평범한 JavaScript 시멘틱스에 몇가지 변경이 일어나게 합니다.</p> + +<ol> + <li>기존에는 조용히 무시되던 에러들을 throwing합니다.</li> + <li>JavaScript 엔진의 최적화 작업을 어렵게 만드는 실수들을 바로잡습니다. 가끔씩 엄격 모드의 코드는 비-엄격 모드의 동일한 코드보다 더 빨리 작동하도록 만들어집니다.</li> + <li>엄격 모드는 ECMAScript의 차기 버전들에서 정의 될 문법을 금지합니다.</li> +</ol> + +<p>코드를 JavaScript의 변형이 제한된 환경에서 동작하도록 하고 싶다면, 엄격 모드로의 변환(<a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode/Transitioning_to_strict_mode">transitioning to strict mode</a>)을 참고하세요.</p> + +<h2 id="엄격모드_적용하기">엄격모드 적용하기</h2> + +<p>엄격모드는 <em>전체 스크립트</em> 또는 <em>부분 함수</em>에 적용가능합니다. 단, <code>{}</code> 괄호로 묶여진 블럭문에는 적용되지 않습니다. 컨텍스트와 같은곳에 적용을 시도하면 동작하지 않습니다. <code>eval</code> 코드, <code>Function</code> 코드, 이벤트 핸들러 속성, {{domxref("WindowTimers.setTimeout()")}} 과 연관된 함수들에 전달된 문자열이 전체 스크립트이며 여기에서 엄격모드가 예상대로 동작합니다. </p> + +<h3 id="스크립트_엄격_모드">스크립트 엄격 모드</h3> + +<p>엄격모드를 전체 스크립트에 적용하기 위해, 정확한 구문 <code>"use strict";</code>(또는 <code>'use strict';</code>) 을 다른 구문 작성 전에 삽입합니다.</p> + +<pre class="brush: js notranslate">// 전체 스크립트 엄격 모드 구문 +'use strict'; +var v = "Hi! I'm a strict mode script!"; +</pre> + +<p><span style='background-color: transparent; color: #333333; display: inline !important; float: none; font-family: "Open Sans",arial,x-locale-body,sans-serif; font-size: 16px; font-style: normal; font-variant: normal; font-weight: 400; letter-spacing: normal; text-align: left; text-decoration: none; text-indent: 0px; text-transform: none; white-space: normal;'>이 구문은 이미 <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=627531">유명한 웹사이트</a>에서 <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=579119">문제를 일으킨 전적</a>이 있습니다. </span>상충되지 않는 스크립트들 끼리 맹목적인 연결이 불가능하기 때문입니다. 엄격 모드의 스크립트와 비-엄격 모드의 스크립트의 연결은 심사숙고 하시기를 바랍니다. 이렇게 되면 전체 연결은 엄격으로 보입니다! 엄격 모드에 다른 엄격모드 들을 결합하는 것은 괜찮습니다. 그리고, 비-엄격 스크립트 사이의 결합도 괜찮습니다. 분명한건, 스크립트를 결합하는 것이 절대 이상적인 것이 아니라는 것이지만, 그래야 한다면 함수를 기준으로 엄격모드 사용을 고려하시기 바랍니다.</p> + +<p>또한 함수 내부의 전체 스크립트 내용에 접근할 수 있으며, 엄격모드를 사용하는 외부 함수를 가질 수 있습니다. 이는 결합 문제를 없애주기도 하지만, 이것이 스코프 바깥에 위치한 어떤 전역 변수든 확실하게 밖으로 추출할 수 있음을 의미합니다 . </p> + +<h3 id="함수에_strict_mode_적용">함수에 strict mode 적용</h3> + +<p>마찬가지로, 함수에 strict mode를 적용하기 위해, 함수 본문 처음에 다음의 구문을 넣습니다. <code>"use strict";</code> (또는 <code>'use strict';</code>).</p> + +<pre class="brush: js notranslate">function strict() { + // 함수-레벨 strict mode 문법 + 'use strict'; + function nested() { return "And so am I!"; } + return "Hi! I'm a strict mode function! " + nested(); +} +function notStrict() { return "I'm not strict."; } +</pre> + +<h3 id="모듈에_strict_mode_적용">모듈에 strict mode 적용</h3> + +<p>ECMAScript 2015 는 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export">JavaScript 모듈</a>을 소개했습니다. 따라서, 이는 엄격 모드를 적용할 수 있는 3번 째 방법입니다. JavaScript 모듈의 전체 컨텐츠는 엄격 모드 시작을 위한 구문 없이도 자동으로 엄격모드입니다.</p> + +<pre class="notranslate"><code>function strict() { + // 모듈이기때문에 기본적으로 엄격합니다 +} +export default strict;</code> +</pre> + +<h2 id="엄격한_모드_변경">엄격한 모드 변경</h2> + +<p>엄격한 모드는 구문과 런타임 동작을 모두 변경합니다.<br> + 일반적으로 이러한 유형의 변화가 발생합니다: 변환 실수를 오류로 해석하거나(문법 오류 또는 런타임에 오류 발생), 특정 이름의 특정 용도에 대한 특정 변수를 계산하는 방법을 단순화하며, <code>eval</code> 과 <code>arguments</code> 를 단순화하고,"안전한 "자바 스크립트를 작성하도록 돕고, 미래 ECMAScript의 진화에 대비합니다.</p> + +<h3 id="실수를_에러로_바꾸는_것">실수를 에러로 바꾸는 것</h3> + +<p>엄격한 모드는 일부 이전에 허용되었던 실수를 오류로 바꿔 놓습니다. 자바 스크립트는 초보 개발자에게 쉬운 것이 되도록 설계되었으며, 때로는 오류를 일으킬만한 동작을 에러없이 시행합니다. 때때로 이것은 즉각적인 문제를 해결하지만, 때때로 이것은 더 심각한 문제를 만들어 냅니다. 엄격한 모드는 이러한 실수를 <span style='background-color: transparent; color: #333333; display: inline !important; float: none; font-family: "Open Sans",arial,x-locale-body,sans-serif; font-size: 16px; font-style: normal; font-variant: normal; font-weight: 400; letter-spacing: normal; text-align: left; text-decoration: none; text-indent: 0px; text-transform: none; white-space: normal;'>오류로 처리해서</span> 그것을 발견하고 즉시 고칠 수 있도록 합니다.</p> + +<p>첫째로, 엄격모드는 실수로 글로벌 변수를 생성하는 것을 불가능하게 만듭니다. 일반적인 JavaScript에서 변수를 잘못 입력하면 전역 객체에 대한 새 속성이 만들어지고 그대로 "동작" (미래의 오류가 발생할 수 있음: modern 자바 스크립트처럼) 합니다. 전역 변수를 생성하는 할당은 엄격 모드에선 오류를 발생시킵니다.</p> + +<pre class="brush: js notranslate">"use strict"; + // 전역 변수 mistypedVariable 이 존재한다고 가정 +mistypedVaraible = 17; // 변수의 오타때문에 이 라인에서 ReferenceError 를 발생시킴 +</pre> + +<p>둘째로, 엄격모드는 예외를 발생시키는 실패를 조용히 넘어가는 대신 작업을 만듭니다. 예를 들어, <code>NaN</code> 은 쓸 수 없는 전역 변수입니다. <code>NaN</code> 에 할당하는 일반적인 코드는 아무 것도 하지 않습니다. 개발자도 아무런 실패 피드백을 받지 않습니다. 엄격 모드에서 <code>NaN</code> 에 할당하는 것은 예외를 발생시킵니다. 일반 코드에서 조용히 넘어가는 모든 실패에 대해 (쓸 수 없는 전역 또는 프로퍼티에 할당, getter-only 프로퍼티에 할당, <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Object/preventExtensions" title="en-US/JavaScript/Reference/Global Objects/Object/preventExtensions">확장 불가</a> 객체에 새 프로퍼티 할당) 엄격 모드에서는 예외를 발생시킵니다.</p> + +<pre class="brush: js notranslate">"use strict"; + +// 쓸 수 없는 프로퍼티에 할당 +var undefined = 5; // TypeError 발생 +var Infinity = 5; // TypeError 발생 + +// 쓸 수 없는 프로퍼티에 할당 +var obj1 = {}; +Object.defineProperty(obj1, "x", { value: 42, writable: false }); +obj1.x = 9; // TypeError 발생 + +// getter-only 프로퍼티에 할당 +var obj2 = { get x() { return 17; } }; +obj2.x = 5; // TypeError 발생 + +// 확장 불가 객체에 새 프로퍼티 할당 +var fixed = {}; +Object.preventExtensions(fixed); +fixed.newProp = "ohai"; // TypeError 발생 +</pre> + +<p>셋째로, 엄격 모드는 삭제할 수 없는 프로퍼티를 삭제하려할 때 예외를 발생시킵니다(시도가 어떤 효과도 없을 때).</p> + +<pre class="brush: js notranslate">"use strict"; +delete Object.prototype; // TypeError 발생 +</pre> + +<p>넷째로, Gecko 34 이전의 엄격모드는 객체 리터럴의 모든 프로퍼티의 이름이 유니크해도록 요구합니다. 일반 코드는 프로퍼티의 값이 나중에 정해진 프로퍼티 이름으로 중복할 것입니다. 하지만 마지막 인스턴스 만 변경했기 때문에 코드를 수정하여 마지막 인스턴스를 변경하는 것 이외의 속성 값을 변경하면 복제는 버그의 벡터가됩니다. 엄격모드에서는 프로퍼티 이름을 중복하는 것은 구문 에러입니다.</p> + +<div class="note"> +<p>ECMAScript 2015부터는 에러가 아닙니다. ({{bug(1041128)}}).</p> +</div> + +<pre class="brush: js notranslate">"use strict"; +var o = { p: 1, p: 2 }; // !!! 구문 에러 +</pre> + +<p>다섯째로, 엄격모드는 유니크한 함수 파라미터 이름을 요구합니다. 일반 코드에서는 마지막으로 중복된 인수가 이전에 지정된 인수를 숨깁니다. 이러한 이전의 인수들은 <code>arguments[i]</code> 를 통해 여전히 남아 있을 수 있으므로, 완전히 접근 불가한 것이 아닙니다. 여전히, 이런 숨김 처리는 이치에 맞지 않으며 원했던 것이 아닐 수 있습니다(예를 들면 오타를 숨길 수도 있습니다). 따라서 엄격 모드에서는 중복 인수명은 구문 에러입니다.</p> + +<pre class="brush: js notranslate">function sum(a, a, c){ // !!! 구문 에러 + "use strict"; + return a + b + c; // 코드가 실행되면 잘못된 것임 +} +</pre> + +<p>여섯째로, ECMAScript 5 에서의 엄격 모드는 8진 구문을 금지합니다. 8진 구문은 ES5의 문법이 아니지만, 모든 브라우저에서 앞에 0을 붙여 지원됩니다(<code>0644 === 420</code> 와 <code>"\045" === "%"</code>). ECMAScript 2015 에서는 접두사 "<code>0o</code>"를 붙여 8진수를 지원합니다.</p> + +<pre class="brush: js notranslate">var a = 0o10; // ES6: 8진수</pre> + +<p>초보 개발자들은 가끔 앞에 붙은 0 이 무의미하다고 생각하여, 이를 정렬용으로 사용합니다 — 하지만 이는 숫자의 의미를 바꿔버립니다! 이 8진수 문법은 거의 무용하며 잘못 사용될 수 있으므로 엄격모드에서 이 구문은 에러입니다.</p> + +<pre class="brush: js notranslate">"use strict"; +var sum = 015 + // !!! 구문 에러 + 197 + + 142; +</pre> + +<p>일곱째로, ECMAScript 6 의 엄격모드는 {{Glossary("primitive")}} 값에 프로퍼티를 설정하는 것을 금지합니다. 엄격모드가 아닐 때에는 프로퍼티 설정이 간단하게 무시되지만(no-op), 엄격모드에서는 {{jsxref("TypeError")}} 를 발생시킵니다.</p> + +<pre class="brush: js notranslate">(function() { +"use strict"; + +false.true = ""; // TypeError +(14).sailing = "home"; // TypeError +"with".you = "far away"; // TypeError + +})();</pre> + +<h3 id="변수_사용_단순화">변수 사용 단순화</h3> + +<p>엄격모드는 코드상의 변수 이름을 특정 변수 정의로 매핑하는 방법을 단순화합니다. 많은 컴파일러 최적화는 변수 X 가 어떤 위치에 저장되어 있는지를 말해주는 능력에 의존하고 있습니다. 이는 자바스크립트 코드를 완전히 최적화하는데 중요합니다. 자바스크립트는 때때로 이름을 코드상의 변수 정의로 기본 매핑하는 것을 런타임때까지 실행이 불가하게합니다. 엄격모드는 이것이 발생하는 대부분의 경우를 제거하여 컴파일러가 엄격모드 코드를 더 잘 최적화 할 수 있게합니다.</p> + +<p>첫째로, 엄격모드는 <code>with</code> 를 사용하지 못하게합니다. <code>with</code> 사용의 문제는 런타임중에 블록안의 모든 이름이 전달된 객체의 프로퍼티나 인근 (또는 심지어 전역) 스코프 내의 변수로 매핑될 수도 있다는 것입니다. 이는 사전에 아는 것이 불가합니다. 엄격 모드는 <code>with</code> 를 구문 에러로 만들어, <code>with</code> 의 이름이 런타임에 알 수 없는 위치를 참조하지 않도록합니다.</p> + +<pre class="brush: js notranslate">"use strict"; +var x = 17; +with (obj) // !!! 구문 에러 +{ + // 엄격모드가 아니라면, 이는 var x 가 되어야 하나요, + // obj.x 가 되어야 하나요? + // 일반적으로는 코드를 실행하지 않고 이를 말하는 것은 불가하므로, + // 이름을 최적화 할 수 없습니다. + x; +} +</pre> + +<p>이름이 짧은 변수에 객체를 할당한 후, 변수에 해당하는 프로퍼티에 접근하는 간단한 대안은 <code>with</code> 를 대체할 준비가 되었습니다.</p> + +<p>둘째로, <a class="external" href="http://whereswalden.com/2011/01/10/new-es5-strict-mode-support-new-vars-created-by-strict-mode-eval-code-are-local-to-that-code-only/">엄격모드 코드의 <code>eval</code> 은 새로운 변수를 주위 스코프에 추가하지 않습니다</a>. 일반적인 코드에서 <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">eval("var x;")</span></font> 는 변수 <code>x</code> 를 주위 함수나 전역 스코프에 추가합니다. 이는, 일반적으로 <code>eval</code> 호출을 포함하는 함수에서 인수나 지역 변수를 참조하지 않는 모든 이름은 런타임에 특정 정의에 반드시 매핑되어야 함을 의미합니다(<code>eval</code> 이 외부 변수를 숨기는 새로운 변수를 추가했기 때문입니다). 엄격모드에서 <code>eval</code> 은 evaluated 된 코드에서만 변수를 생성하므로, 외부 변수나 일부 로컬 변수에 참조하는지에 영향을 주지 않습니다.</p> + +<pre class="brush: js notranslate">var x = 17; +var evalX = eval("'use strict'; var x = 42; x"); +console.assert(x === 17); +console.assert(evalX === 42); +</pre> + +<p>이와 관련해서, <code>eval</code> 함수가 엄격모드 코드 내에서 <code>eval(...)</code> 형태의 표현으로 적용되었다면, 코드는 엄격모드 코드로 evaluated 됩니다. 코드는 명시적으로 엄격모드를 적용할 수 있지만, 필수적인 것은 아닙니다.</p> + +<pre class="brush: js notranslate">function strict1(str){ + "use strict"; + return eval(str); // str 은 엄격모드 코드로 다뤄짐 +} +function strict2(f, str){ + "use strict"; + return f(str); // eval(...) 이 아님: + // str 은 엄격모드를 적용한 경우에만 엄격함 +} +function nonstrict(str){ + return eval(str); // str 은 엄격모드를 적용한 경우에만 엄격함 +} + +strict1("'엄격모드 코드!'"); +strict1("'use strict'; '엄격모드 코드!'"); +strict2(eval, "'느슨한 코드.'"); +strict2(eval, "'use strict'; '엄격모드 코드!'"); +nonstrict("'느슨한 코드.'"); +nonstrict("'use strict'; '엄격모드 코드!'"); +</pre> + +<p>따라서 엄격모드 <code>eval</code> 코드 내의 이름은 엄격모드 코드 내의 이름이 <code>eval</code> 의 결과로 evaluated 되지 않은 것과 동일하게 동작합니다.</p> + +<p>셋째로, 엄격모드는 일반 이름을 제거하는 것을 금지합니다. 엄격 모드에서 <code>delete name</code> 은 구문 에러입니다.</p> + +<pre class="brush: js notranslate">"use strict"; + +var x; +delete x; // !!! 구문 에러 + +eval("var y; delete y;"); // !!! syntax error</pre> + +<h3 id="eval_과_arguments_를_더_간단하게_하기"><code>eval</code> 과 <code>arguments</code> 를 더 간단하게 하기</h3> + +<p>엄격모드는 <code>arguments</code> 와 <code>evel</code> 을 덜 기괴하고 마법적으로 만듭니다. 둘은 일반 코드에서 상당히 많은 마법적인 동작들을 갖고 있습니다: 바인딩을 추가하거나 삭제하고 바인딩 값을 변경하기위한 <code>eval</code>, 명명된 인수를 앨리어스하는 인덱싱된 프로퍼티 <code>arguments</code>. 엄격모드는 ECMAScript 의 미래 버전까지는 모든 수정이 이루지지는 않겠지만 <code>eval</code> 과 <code>arguments</code> 를 키워드로 다루기 위한 훌륭한 큰 걸음을 내딛었습니다.</p> + +<p>첫째로, 변수명 eval 과 arguments 는 언어 문법에 바운드되거나 할당될 수 없습니다. 다음 시도들은 모두 구문 에러입니다.</p> + +<pre class="brush: js notranslate">"use strict"; +eval = 17; +arguments++; +++eval; +var obj = { set p(arguments) { } }; +var eval; +try { } catch (arguments) { } +function x(eval) { } +function arguments() { } +var y = function eval() { }; +var f = new Function("arguments", "'use strict'; return 17;"); +</pre> + +<p>둘째로, 엄격모드 코드는 <code>arguments</code> 객체가 생성한 프로퍼티를 앨리어스하지 않습니다. 함수의 첫 번째 인수가 <code>arg</code> 인 일반 코드에서는 <code>arg</code> 를 설정하는 것은 <code>arguments[0]</code> 를 설정하기도 하며, 그 반대도 그렇습니다(인수가 제공되지 않거나, <code>arguments[0]</code> 이 삭제된 경우는 제외). 엄격모드 함수의 <code>arguments</code> 객체는 함수가 호출될 때 원본 인수들을 저장합니다. <code><em>arguments[i]</em></code> 는 명명된 인수에 해당하는 값을 추적하지 않으며, 명명된 인수도 <code>arguments[i]</code> 에 해당하는 값을 추적하지 않습니다.</p> + +<pre class="brush: js notranslate">function f(a){ + "use strict"; + a = 42; + return [a, arguments[0]]; +} +var pair = f(17); +console.assert(pair[0] === 42); +console.assert(pair[1] === 17); +</pre> + +<p>셋째로, <code>arguments.callee</code> 는 더 이상 지원되지 않습니다. 일반 코드의 <code>arguments.callee</code> 는 바깥 함수를 참조합니다. 이런 유즈 케이스는 중요하지 않습니다. 간단히 바깥 함수의 이름을 사용하면됩니다. 더욱이, <code>arguments.callee</code> 는 인라인 함수와 같은 최적화를 상당히 방해하므로, <code>arguments.callee</code> 가 접근하는 함수는 인라인이 아닌 함수를 참조하도록 제공해야 했습니다. 엄격모드 함수의 <code>arguments.callee</code> 는 삭제할 수 없는 프로퍼티이며, 설정이나 반환할때 에러를 발생합니다.</p> + +<pre class="brush: js notranslate">"use strict"; +var f = function() { return arguments.callee; }; +f(); // TypeError +</pre> + +<h3 id="JavaScript_보안">JavaScript "보안"</h3> + +<p>엄격모드는 "보안된" 자바스크립트를 작성하기 쉽게 해줍니다. 일부 웹사이트들은 사용자가 다른 사용자들을 대신하여 웹사이트에서 실행시키는자바스크립트를 작성하는 방법을 제공합니다. 브라우저에서 자바스크립트는 사용자의 개인정보에 접근할수 있기 때문에, 자바스크립트는 금지된 기능에 대한 검열을 하기위해 반드시 실행전에 부분적으로 변경되어야 합니다. 자바스크립트의 유연성으로 인해 많은 런타임 체크없이 이것을 수행하는것은 사실상 불가능합니다. 특정 언어의 기능들이 너무 광범위하여 런타임 검사 수행은 상당한 성능비용이 생깁니다. 엄격모드의 작은 수정과 사용자가 제출한 자바스크립트가 엄격모드가 되면 특정 방식으로 호출되므로 런타임 검사의 필요성이 크게 줄어 듭니다. </p> + +<p>첫째, 엄격모드에서는 <code>this</code> 로 함수에 전달된 값은 강제로 객체가 되지 않습니다 (a.k.a. "boxed"). 보통 함수의 경우, <code>this</code> 는 언제나 객체입니다: 객체값 <code>this</code> 와 함께 호출된 경우 제공된 객체이거나 ; 부울값, 문자 또는 숫자 <code>this</code> 로 호출된 경우 그 값은 Boxed 입니다; 또는 <code>undefined</code> 또는 <code>null</code> <code>this</code> 로 호출되면 전역객체입니다. (특정된 <code>this</code> 명세를 위해서는 <a href="/en-US/Web/JavaScript/Reference/Global_Objects/Function/call" title="en-US/JavaScript/Reference/Global_Objects/Function/call"><code>call</code></a>, <a href="/en-US/Web/JavaScript/Reference/Global_Objects/Function/apply" title="en-US/JavaScript/Reference/Global_Objects/Function/apply"><code>apply</code></a>, 또는 <a href="/en-US/Web/JavaScript/Reference/Global_Objects/Function/bind" title="en-US/JavaScript/Reference/Global_Objects/Function/bind"><code>bind</code></a> 를 사용하십시요) 자동 박싱은 성능 비용뿐 아니라 전역 객체가 브라우저에 노출되는것은 보안상 위험합니다. 전역객체들은 자바스크립트 환경의 "보안" 기능에 접근하는것을 제공하기때문에 제한되어야 합니다. 따라서 엄격모드의 함수는, 정의된 <code>this</code> 는 박스드 객체가 되지 않으며, 정의되지 않은경우 <code>this</code> 는 <code>undefined</code> 가 됩니다:</p> + +<pre class="brush: js notranslate">"use strict"; +function fun() { return this; } +console.assert(fun() === undefined); +console.assert(fun.call(2) === 2); +console.assert(fun.apply(null) === null); +console.assert(fun.call(undefined) === undefined); +console.assert(fun.bind(true)() === true); +</pre> + +<p>즉, 브라우저에서 엄격모드의 함수내 에서는 더 이상 <code>window</code> 객체를 <code>this</code> 를 통해 참조할 수 없습니다.</p> + +<p>둘째로, 엄격모드에서는 ECMAScript의 일반적으로 구현된 확장을 통해 자바스크립트 스택을 "걷는"것이 불가능합니다. 이러한 일반적인 확장 코드는, 함수 <code>fun</code> 이 호출되는 중간에, <code>fun.caller</code> 는 가장 최근에 <code>fun</code> 을 호출한 함수이고 <code>fun.arguments</code> 는 <code>fun</code>을 호출하기 위한 <code>인</code><font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">수</span></font> 입니다. "권한있는"함수와 (잠재적으로 보안되지 않은) 인수에 접근을 허용하기때문에 두가지 확장 모두 자바스크립트의 "보안" 문제가 됩니다. <code>fun</code> 이 엄격모드인경우, both <code>fun.caller</code> 와 <code>fun.arguments</code> 모두 설정 또는 검색될때 삭제 불가능한 속성이 됩니다.</p> + +<pre class="brush: js notranslate">function restricted() +{ + "use strict"; + restricted.caller; // throws a TypeError + restricted.arguments; // throws a TypeError +} +function privilegedInvoker() +{ + return restricted(); +} +privilegedInvoker(); +</pre> + +<p>셋째, 엄격모드의 <code>인수</code> 는 더이상 해당 함수의 호출 변수에 대한 접근을 제공하지 않습니다. 일부 이전 ECMAScript에서 <code>arguments.caller</code> 해당 함수에 별명이 지정된 객체였습니다. 이것은 함수의 추상화를 통해 권한이 있는 값을 숨길수 있는 기능을 차단하여 <a class="external" href="http://stuff.mit.edu/iap/2008/facebook/">보안의 위협</a>이 됩니다; 이것은 또한 대부분의 최적화를 배제시킵니다. 이러한 이유로 최신 브라우저들은 이를 구현하지 않습니다. 하지만 이것들의 이전 기능들 때문에, 엄격모드함수에서 <code>arguments.caller</code> 설정이나 검색시 삭제 불가능한 요소가 됩니다:</p> + +<pre class="brush: js notranslate">"use strict"; +function fun(a, b) +{ + "use strict"; + var v = 12; + return arguments.caller; //TypeError 가 발생. +} +fun(1, 2); // doesn't expose v (or a or b) +</pre> + +<h3 id="미래의_ECMAScript_버전을_위한_준비">미래의 ECMAScript 버전을 위한 준비</h3> + +<p>새롭게 선보일 ECMAScript 버전은 새로운 구문을 소개할 것이고, ECMAScript5에서의 엄격 모드는 변환을 쉽게 하기 위해 몇 가지의 제한을 적용할 것으로 예상되고 있습니다. 만약 이 변화들이 엄격 모드에서의 제한을 기반으로 한다면, 더 바꾸기 쉬워질 것입니다.</p> + +<p>첫번째로, 엄격 모드에서의 식별자 후보들은 예약어가 됩니다. 이 예약어들은 <code>implements</code>, <code>interface</code>, <code>let</code>, <code>package</code>, <code>private</code>, <code>protected</code>, <code>public</code>, <code>static</code>, <code>yield</code>입니다. 그럼, 엄격 모드에서는 이 예약어와 똑같은 이름을 사용하거나, 변수명 또는 아규먼트명으로도 사용할 수 없습니다. </p> + +<pre class="brush: js notranslate">function package(protected){ // !!! + "use strict"; + var implements; // !!! + + interface: // !!! + while (true){ + break interface; // !!! + } + + function private() { } // !!! +} +function fun(static) { 'use strict'; } // !!! + +</pre> + +<p>Mozilla의 특별 지시 두 가지 : 먼저, 코드가 JavaScript 1.7 또는 그보다 높고 (예를 들어, 크롬 코드 또는 <code><script type=""></code> 를 바로 사용할 때) 엄격 모드의 코드라면, <code>let</code> 와 <code>yield</code>는 처음 소개되었을 때의 그 기능을 가진다. 그러나 웹에서의 엄격 모드 코드는, <code><script src=""></code>나 <code><script>...</script></code>로 로딩되지, <code>let</code>/<code>yield</code>를 식별자로 사용할 수가 없을 것이다. 그리고 나서는, ES5 가 <code>class</code>, <code>enum</code>, <code>export</code>, <code>extends</code>, <code>import</code>, and <code>super</code> 와 같은 예약어들을 무조건 리저브함에도 불구하고, 먼저 Firefox 5 Mozilla 는 그것들을 엄격 모드에서만 리저브한다.</p> + +<p>다음은, 엄격 모드는 스크립트나 함수의 탑 레벨이 아닌 곳에서의 함수 내용 정의를 제한합니다. (<a class="external" href="http://whereswalden.com/2011/01/24/new-es5-strict-mode-requirement-function-statements-not-at-top-level-of-a-program-or-function-are-prohibited/">strict mode prohibits function statements not at the top level of a script or function</a>). 브라우저에서 일반적인 코드는 함수 내용 정의가 "어디에서든" 허용됩니다. <em>이것은 ES5의 부분이 아닙니다!(심지어 ES3도 아니다.) </em>이건 다른 브라우저에서 공존할 수 없는 시멘틱의 확장입니다. 앞으로의 ECMAScript 에디션은 바라건대, 스크립트나 함수의 탑 레벨이 아닌 곳에서의 함수 내용 정의를 위해, 새로운 시멘틱을 명시할 것입니다. 엄격 모드에서 이러한 함수 정의를 금지하는 것(<a class="external" href="http://wiki.ecmascript.org/doku.php?id=conventions:no_non_standard_strict_decls">Prohibiting such function statements in strict mode</a>)은 앞으로 출시될 ECMAScript의 사양을 위한 "준비"입니다. :</p> + +<pre class="brush: js notranslate">"use strict"; +if (true){ + function f() { } // !!! syntax error + f(); +} + +for (var i = 0; i < 5; i++){ + function f2() { } // !!! syntax error + f2(); +} + +function baz(){ // kosher + function eit() { } // also kosher +} +</pre> + +<p>이 규제는 엄밀히 말하면 엄격 모드가 아닌데, 저런 함수 표현식들은 기본 ECMAScript5의 확장이기 때문입니다. 그러나 이것이 ECMAScript 협회가 권장하는 방식이며, 브라우저들이 이를 지원할 것입니다. </p> + +<h2 id="브라우저에서의_엄격_모드">브라우저에서의 엄격 모드</h2> + +<p>현재 주류의 브라우저들은 엄격 모드를 지원하고 있습니다. 하지만, 아직도 현실에서 사용되는 수 많은 브라우저의 버전들은 엄격 모드를 부분적으로만 지원하거나(<a href="http://caniuse.com/use-strict" rel="external" title="caniuse.com availability of strict mode">Browser versions used in the wild that only have partial support for strict mode</a>), 아예 지원을 하지 않고 있기 때문에, 맹목적으로 여기에 의지할 수는 없습니다. (예를 들면, Internet Explorer 10 버전 이하!) <em>엄격 모드는 시멘틱을 바꿉니다. </em>이 변화들에 의지하는 것은 실수와 엄격 모드를 지원하지 않는 브라우저의 에러를 야기할 것입니다. 엄격 모드를 사용하는 데에 주의하는 것을 익히세요, 그리고 피쳐 테스트로 엄격 모드를 사용하기에 적절한 부분인지 확인하고 보완하세요. 마지막으로, <em>엄격 모드를 지원하는 브라우저와 그렇지 않은 브라우저에서 작성한 코드의 테스트를 확실히 하도록 하세요.</em> </p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-10.1.1', 'Strict Mode Code')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>초기 정의. 참조 : <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-C">Strict mode restriction and exceptions</a></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-strict-mode-code', 'Strict Mode Code')}}</td> + <td>{{Spec2('ES6')}}</td> + <td><a href="http://www.ecma-international.org/ecma-262/6.0/#sec-strict-mode-of-ecmascript">Strict mode restriction and exceptions</a></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-strict-mode-code', 'Strict Mode Code')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td><a href="https://tc39.github.io/ecma262/#sec-strict-mode-of-ecmascript">Strict mode restriction and exceptions</a></td> + </tr> + </tbody> +</table> + +<h2 id="함께_보기">함께 보기</h2> + +<ul> + <li><a class="external" href="http://whereswalden.com/2010/09/08/new-es5-strict-mode-support-now-with-poison-pills/" title="http://whereswalden.com/2010/09/08/new-es5-strict-mode-support-now-with-poison-pills/">Where's Walden? » New ES5 strict mode support: now with poison pills!</a></li> + <li><a class="external" href="http://whereswalden.com/2011/01/24/new-es5-strict-mode-requirement-function-statements-not-at-top-level-of-a-program-or-function-are-prohibited/" title="http://whereswalden.com/2011/01/24/new-es5-strict-mode-requirement-function-statements-not-at-top-level-of-a-program-or-function-are-prohibited/">Where's Walden? » New ES5 strict mode requirement: function statements not at top level of a program or function are prohibited</a></li> + <li><a class="external" href="http://whereswalden.com/2011/01/10/new-es5-strict-mode-support-new-vars-created-by-strict-mode-eval-code-are-local-to-that-code-only/" title="http://whereswalden.com/2011/01/10/new-es5-strict-mode-support-new-vars-created-by-strict-mode-eval-code-are-local-to-that-code-only/">Where's Walden? » New ES5 strict mode support: new vars created by strict mode eval code are local to that code only</a></li> + <li><a href="http://qnimate.com/javascript-strict-mode-in-nutshell/">JavaScript "use strict" tutorial for beginners.</a></li> + <li><a class="external" href="http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/" title="http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/">John Resig - ECMAScript 5 Strict Mode, JSON, and More</a></li> + <li><a class="external" href="http://dmitrysoshnikov.com/ecmascript/es5-chapter-2-strict-mode/">ECMA-262-5 in detail. Chapter 2. Strict Mode.</a></li> + <li><a class="external" href="http://kangax.github.io/compat-table/es5/#Strict_mode">Strict mode compatibility table</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode/Transitioning_to_strict_mode">Transitioning to strict mode</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/strict_mode/transitioning_to_strict_mode/index.html b/files/ko/web/javascript/reference/strict_mode/transitioning_to_strict_mode/index.html new file mode 100644 index 0000000000..bc45f85cac --- /dev/null +++ b/files/ko/web/javascript/reference/strict_mode/transitioning_to_strict_mode/index.html @@ -0,0 +1,137 @@ +--- +title: Transitioning to strict mode(엄격모드로 전환) +slug: Web/JavaScript/Reference/Strict_mode/Transitioning_to_strict_mode +translation_of: Web/JavaScript/Reference/Strict_mode/Transitioning_to_strict_mode +--- +<div>{{jsSidebar("More")}}</div> + +<div>ECMAScript 5에서 <a href="/en-US/docs/JavaScript/Strict_mode" title="/en-US/docs/JavaScript/Strict_mode">strict mode</a>이 도입이 되었다. 이제는 모든 주요 브라우저에서 사용이 가능하다(IE10 포함) 웹 브라우저가 엄격한 코드를 해석하도록 만들어준다. (소스 코드의 맨 위에 'use strict'를 추가하는 것만으로), 기존 코드 기반을 엄격 모드로 전환하는 것은 좀 더 많은 작업을 한다.</div> + +<div> </div> + +<div>이 글은 개발자의 안내서에 초점이 맞춰져있다.</div> + +<h2 id="Gradual_transition">Gradual transition</h2> + +<p>Strict 모드는 점진적으로 전환 할 수 있도록 설계되었다. 개별 파일을 개별적으로 변경하거나 코드를 엄격 모드에서 함수 단위로 전환 할 수도 있다.</p> + +<h2 id="strict_와_non-strict의_차이점">strict 와 non-strict의 차이점</h2> + +<h3 id="Syntax_errors">Syntax errors</h3> + +<p><code>'use strict';</code> 를 추가하게 되면, 아래의 경우에는 스크립트가 실행되기 전에{{jsxref("SyntaxError")}} 에러를 던진다.</p> + +<ul> + <li>Octal syntax <code>var n = 023;</code></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/with" title="/en-US/docs/JavaScript/Reference/Statements/with"><code>with</code></a> statement</li> + <li>Using <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete" title="/en-US/docs/JavaScript/Reference/Operators/delete">delete</a></code> on a variable name <code>delete myVariable</code>;</li> + <li>Using <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval"><code>eval</code></a> or <a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments"><code>arguments</code></a> as variable or function argument name</li> + <li>Using one of the newly <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords">reserved keywords</a> (in prevision for ECMAScript 2015): <code>implements</code>, <code>interface</code>, <code>let</code>, <code>package</code>, <code>private</code>, <code>protected</code>, <code>public</code>, <code>static</code>, and <code>yield</code></li> + <li>Declaring function in blocks <code>if (a < b) { function f() {} }</code></li> + <li>Obvious errors + <ul> + <li>Declaring twice the same name for a property name in an object literal <code>{a: 1, b: 3, a: 7}</code> This is no longer the case in ECMAScript 2015 ({{bug(1041128)}}).</li> + <li>Declaring two function parameters with the same name <code>function f(a, b, b) {}</code></li> + </ul> + </li> +</ul> + +<p>우리들의 명백한 에러나 나쁜 실수들이 드러나기 때문에 이러한 에러들은 좋다. 이러한 것들은 코드가 실행되기 전에 실행이 된다.</p> + +<h3 id="New_runtime_errors">New runtime errors</h3> + +<p>JavaScript는 컨테스트에서 조용한 실패에 익숙해져 있다. Strict mode는 이 같은 경우에는 던졌다. 만약 너의 코드베이스에 이 같은 경우가 포함되어있다면, 잘못된 것이 있는지 확인하기 위해 테스트가 필요할 것이다. 다시 한번, 함수 세분화된 단계에서 발생할 수 있다.</p> + +<h4 id="값을_선언되지_않은_변수로_설정하기">값을 선언되지 않은 변수로 설정하기</h4> + +<pre class="brush: js">function f(x) { + 'use strict'; + var a = 12; + b = a + x * 35; // error! +} +f(42); +</pre> + +<p>이것은 예상된 효과가 드문 전역객체의 변수를 변경하는 데 사용된다. 만약에 정말로 전역객체의 변수를 부여하고 싶다면, 그것을 인수, 그것을 argument로 넘기고 property로 명시적 할당을 한다.</p> + +<pre class="brush: js">var global = this; // in the top-level context, "this" always + // refers to the global object +function f(x) { + 'use strict'; + var a = 12; + global.b = a + x * 35; +} +f(42); +</pre> + +<h4 id="구성할_수_없는_속성을_삭제하려고_한다.">구성할 수 없는 속성을 삭제하려고 한다.</h4> + +<pre class="brush: js">'use strict'; +delete Object.prototype; // error! +</pre> + +<p>비-엄격모드에서는 조용한 실패였으나 사용자의 기대에는 맞지 않다.</p> + +<h4 id="중독_된_인수_및_함수_속성">중독 된 인수 및 함수 속성</h4> + +<p>엄격모드에서 <code>arguments.callee</code>, <code>arguments.caller</code>, <code>anyFunction.caller</code>, or <code>anyFunction.arguments</code> 접근하려고 하면 에러를 던진다. 합법적인 사용 사례는 다음과 같은 함수를 다시 사용하는 것이다 : </p> + +<pre class="brush: js">// example taken from vanillajs: http://vanilla-js.com/ +var s = document.getElementById('thing').style; +s.opacity = 1; +(function() { + if ((s.opacity-=.1) < 0) + s.display = 'none'; + else + setTimeout(arguments.callee, 40); +})();</pre> + +<p>이것을다음과 같이 재 작성할 수 있다 :</p> + +<pre class="brush: js">'use strict'; +var s = document.getElementById('thing').style; +s.opacity = 1; +(function fadeOut() { // name the function + if((s.opacity-=.1) < 0) + s.display = 'none'; + else + setTimeout(fadeOut, 40); // use the name of the function +})();</pre> + +<h3 id="문법적_차이">문법적 차이</h3> + +<p>매우 미묘한 차이점들이 있다. 테스트 단위가 이런 종류의 미묘한 차이를 잡지 못할 수 있다. 이러한 차이점이 너의 코드의 의미에 영향을 주지 않도록, 코드 기반을 신중하게 검토해야 할 것이다. 다행히도,이 세심한 검토는 함수 세분성을 점차적으로 줄일 수 있다.</p> + +<h4 id="함수내부에서_불리는_this">함수내부에서 불리는 <code>this</code></h4> + +<p><code>f()</code> 라는 함수가 있을 때, <code>this</code> 값은 당연히 전역객체이다. stict mode에서는 <code>undefined</code> 이다. 값은 원시값이고, 함수가 <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call" title="/en-US/docs/Core_JavaScript_1.5_Reference/Global_Objects/Function/call">call</a></code> 나 <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply" title="/en-US/docs/Core_JavaScript_1.5_Reference/Global_Objects/Function/apply">apply</a></code> 화 함께 불리게 된다면 값은 이것은 하나의 객체이다.(또는 <code>undefined</code> , <code>null</code> 인 전역객체). stict mode에서, 값은 변환이나 대체없이 직접 전달된다.</p> + +<h4 id="arguments_명명_된_함수_인수를_별명으로_지정하지_않습니다."><code>arguments</code> 명명 된 함수 인수를 별명으로 지정하지 않습니다.</h4> + +<p>비-엄격모드에서, <code>arguments</code>객체의 값을 수정하면 해당 명명 된 인수가 수정된다. 이로 인해 자바 스크립트 엔진에 대한 최적화가 복잡해지고 코드를 읽기 / 이해하기가 더 어려워졌다. 엄격모드에서, arguments 객체는 명명 된 인수와 동일한 값으로 만들어지고 초기화되지만 arguments 객체 또는 명명 된 인수에 대한 변경 사항은 서로 반영되지 않는다.</p> + +<h4 id="eval바꾸기"><code>eval</code>바꾸기</h4> + +<p>엄격모드에서, <code>eval</code> 은 그것이 불린 범위안에서 새로운 변수를 만들지 않는다. 또한 물론 엄격모드에서, 문자열은 엄격모드 규칙으로 평가된다. 아무 문제가 없는지 확인하기 위해서는 철저한 테스트를 수행해야 한다. 정말로 필요하지 않다면 eval을 사용하지 않는 것이 실용적인 해결책이 될 수 있다.</p> + +<h2 id="Strictness-neutral_code">Strictness-neutral code</h2> + +<p>A potential "downside" of moving strict code to strict mode is that the semantics may be different in legacy browsers which do not implement strict mode. In some rare occasions (like bad concatenation or minification), your code also may not run in the mode you wrote and tested it in. Here are the rules to make your code strictness-neutral:</p> + +<ol> + <li>코드를 엄격하게 작성하고 (위의 "New runtime errors" 섹션의) 엄격한 오류가 발생하지 않았는지 확인하십시오.</li> + <li>semantic 차이점으로 부터 멀리하라 + <ol> + <li><code>eval</code>: 당신이 하는 일을 안다면, 그것을 사용해라</li> + <li><code>arguments</code>: 함수의 첫 번째 줄로 이름을 통해 항상 함수 인수에 액세스하거나 인수 객체의 복사본을 수행합니다 :<br> + <code>var args = Array.prototype.slice.call(arguments)</code></li> + <li><code>this</code>: <code>this</code> 당신이 만든 대상을 가리킬 때 사용해라</li> + </ol> + </li> +</ol> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">Strict mode</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/template_literals/index.html b/files/ko/web/javascript/reference/template_literals/index.html new file mode 100644 index 0000000000..3eaf2beb13 --- /dev/null +++ b/files/ko/web/javascript/reference/template_literals/index.html @@ -0,0 +1,254 @@ +--- +title: Template literals +slug: Web/JavaScript/Reference/Template_literals +tags: + - Template +translation_of: Web/JavaScript/Reference/Template_literals +--- +<div>{{JsSidebar("More")}}</div> + +<p>템플릿 리터럴은 내장된 표현식을 허용하는 문자열 리터럴입니다. 여러 줄로 이뤄진 문자열과 문자 보간기능을 사용할 수 있습니다. 이전 버전의 ES2015사양 명세에서는 "template strings" (템플릿 문자열) 라고 불려 왔습니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox notranslate">`string text` + +`string text line 1 + string text line 2` + +`string text ${expression} string text` + +tag `string text ${expression} string text` +</pre> + +<h2 id="Description">Description</h2> + +<p>템플릿 리터럴은 이중 따옴표 나 작은 따옴표 대신 백틱(` `) (<a href="http://en.wikipedia.org/wiki/Grave_accent">grave accent</a>) 을 이용합니다. 템플릿 리터럴은 또한 플레이스 홀더를 이용하여 표현식을 넣을 수 있는데, 이는 $와 중괄호( <code>$ {expression}</code> ) 로 표기할 수 있습니다. 플레이스 홀더 안에서의 표현식과 그 사이의 텍스트는 함께 함수로 전달됩니다. 기본 함수는 단순히 해당 부분을 단일 문자열로 연결시켜 줍니다. 템플릿 리터럴 앞에 어떠한 표현식이 있다면(여기에서는 태그), 템플릿 리터럴은 "태그가 지정된 템플릿"이라고 불리게 됩니다. 이 때, 태그 표현식 (주로 함수)이 처리된 템플릿 리터럴과 함께 호출되면, 출력하기 전에 조작할 수 있습니다. 템플릿 리터럴 안에서 백틱 문자를 사용하려면 백틱 앞에 백슬러쉬(\)를 넣으십시오.</p> + +<pre class="brush: js notranslate">`\`` === "`" // --> true</pre> + +<h3 id="Multi-line_strings">Multi-line strings</h3> + +<p>source 내에 삽입되는 newline characters(\n)은 template literal의 일부가 됩니다.</p> + +<p>일반 string 들을 사용하여, multi-line strings 들을 얻기 위해서는 아래와 같은 문법을 사용해야 할 것입니다.</p> + +<pre class="brush: js notranslate">console.log("string text line 1\n"+ +"string text line 2"); +// "string text line 1 +// string text line 2"</pre> + +<p>같은 효과를 template literal을 통해 얻기 위해서는, 아래와 같이 적을 수 있습니다.</p> + +<pre class="brush: js notranslate">console.log(`string text line 1 +string text line 2`); +// "string text line 1 +// string text line 2"</pre> + +<h3 id="Expression_interpolation표현식_삽입법">Expression interpolation(표현식 삽입법)</h3> + +<p>표현식(expression)을 일반 문자열(normal strings)에 삽입하기 위해서, 당신은 다음의 문법을 사용할 수 있을 것입니다.</p> + +<pre class="brush: js notranslate">var a = 5; +var b = 10; +console.log("Fifteen is " + (a + b) + " and\nnot " + (2 * a + b) + "."); +// "Fifteen is 15 and +// not 20."</pre> + +<p>template literals을 이용하면, 이를 더욱 읽기 쉽도록 다음과 같은 문법 설탕(syntactic sugar) 을 활용할 수 있습니다.</p> + +<pre class="brush: js notranslate">var a = 5; +var b = 10; +console.log(`Fifteen is ${a + b} and +not ${2 * a + b}.`); +// "Fifteen is 15 and +// not 20."</pre> + + + +<h3 id="Nesting_templates">Nesting templates</h3> + +<p>특정한 경우 템플릿을 중첩하는 것이 구성 가능한 문자열을 읽는 읽기 가장 쉬운 방법입니다. 백 스페이스 템플릿 내에서 템플릿 내의 자리 표시자<code>${}</code>에 내부 백틱을 사용하는 것이 쉽습니다. 예를 들어, 조건 a가 참이면:이 템플릿을 문자 그대로 반환합니다.</p> + +<p>In ES5:</p> + +<pre class="notranslate"><code>var classes = 'header' +classes += (isLargeScreen() ? + '' : item.isCollapsed ? + ' icon-expander' : ' icon-collapser');</code></pre> + +<p>ES2015에서 중첩(nesting)없이 템플릿 리터럴 사용한 경우:</p> + +<pre class="notranslate"><code>const classes = `header ${ isLargeScreen() ? '' : + (item.isCollapsed ? 'icon-expander' : 'icon-collapser') }`;</code></pre> + +<p>ES2015에서 중첩된(nested) 템플릿 리터럴을 사용한 경우:</p> + +<pre class="notranslate"><code>const classes = `header ${ isLargeScreen() ? '' : + `icon-${item.isCollapsed ? 'expander' : 'collapser'}` }`;</code></pre> + + + +<h3 id="Tagged_templates">Tagged templates</h3> + +<p>template literals 의 더욱 발전된 한 형태는 <em>tagged</em> templates 입니다. 태그를 사용하면 템플릿 리터럴을 함수로 파싱 할 수 있습니다. 태그 함수의 첫 번째 인수는 문자열 값의 배열을 포함합니다. 나머지 인수는 표현식과 관련됩니다. 결국 함수는 조작 된 문자열을 반환 할 수 있습니다 (또는 다음 예제에서 설명하는 것과 완전히 다른 결과를 반환 할 수 있습니다). function 이름은 원하는 어떤 것이든 가능합니다.</p> + +<pre class="notranslate"><code>var person = 'Mike'; +var age = 28; + +function myTag(strings, personExp, ageExp) { + + var str0 = strings[0]; // "that " + var str1 = strings[1]; // " is a " + + // 사실 이 예제의 string에서 표현식이 두 개 삽입되었으므로 + // ${age} 뒤에는 ''인 string이 존재하여 + // 기술적으로 strings 배열의 크기는 3이 됩니다. + // 하지만 빈 string이므로 무시하겠습니다. + // var str2 = strings[2]; + + var ageStr; + if (ageExp > 99){ + ageStr = 'centenarian'; + } else { + ageStr = 'youngster'; + } + + // 심지어 이 함수내에서도 template literal을 반환할 수 있습니다. + return str0 + personExp + str1 + ageStr; + +} + +var output = myTag`that ${ person } is a ${ age }`; + +console.log(output); +// that Mike is a youngster</code></pre> + +<p>다음 예시에서 보여지듯이, Tag function 들은 string 을 반환할 필요는 없습니다.</p> + +<pre class="brush: js notranslate">function template(strings, ...keys) { + return (function(...values) { + var dict = values[values.length - 1] || {}; + var result = [strings[0]]; + keys.forEach(function(key, i) { + var value = Number.isInteger(key) ? values[key] : dict[key]; + result.push(value, strings[i + 1]); + }); + return result.join(''); + }); +} + +var t1Closure = template`${0}${1}${0}!`; +t1Closure('Y', 'A'); // "YAY!" +var t2Closure = template`${0} ${'foo'}!`; +t2Closure('Hello', {foo: 'World'}); // "Hello World!" +</pre> + +<h3 id="Raw_strings">Raw strings</h3> + +<p>태그 지정된 템플릿의 첫 번째 함수 인수에서 사용할 수있는 특별한 <code>raw</code> property을 사용하면 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Using_special_characters_in_strings">escape sequences</a> 처리하지 않고 원시 문자열을 입력 한대로 액세스 할 수 있습니다.</p> + +<pre class="notranslate"><code>function tag(strings) { + console.log(strings.raw[0]); +} + +tag`string text line 1 \n string text line 2`; +// logs "string text line 1 \n string text line 2" , +// including the two characters '\' and 'n'</code></pre> + +<p>추가로, default template function 과 string 병합으로 생성될 것 같은 raw string 을 생성하기 위한 {{jsxref("String.raw()")}} method가 존재합니다.</p> + +<pre class="notranslate"><code>var str = String.raw`Hi\n${2+3}!`; +// "Hi\n5!" + +str.length; +// 6 + +str.split('').join(','); +// "H,i,\,n,5,!"</code></pre> + + + +<h3 id="Tagged_templates_and_escape_sequences">Tagged templates and escape sequences</h3> + +<h4 id="ES2016_behavior">ES2016 behavior</h4> + +<p>ECMAScript 2016에서 tagged templates은 다음 escape sequences의 규칙을 따릅니다.</p> + +<ul> + <li>Unicode escapes started by "\u", for example <code>\u00A9</code></li> + <li>Unicode code point escapes indicated by "\u{}", for example <code>\u{2F804}</code></li> + <li>Hexadecimal escapes started by "\x", for example <code>\xA9</code></li> + <li>Octal literal escapes started by "\" and (a) digit(s), for example <code>\251</code></li> +</ul> + +<p>이는 다음과 같은 tagged template이 문제가 된다는 것을 의미하는데, ECMAScript문법에 따라, parser는 유효한 유니 코드 탈출 시퀀스가 있는지 확인하지만 형식이 잘못되었기 때문에 오류가 발생합니다.</p> + +<pre class="notranslate"><code>latex`\unicode` +// Throws in older ECMAScript versions (ES2016 and earlier) +// SyntaxError: malformed Unicode character escape sequence</code></pre> + +<h4 id="ES2018_revision_of_illegal_escape_sequences">ES2018 revision of illegal escape sequences</h4> + +<p>Tagged templates은 다른 escapes sequences가 일반적으로 사용되는 언어 (예 : <a href="https://en.wikipedia.org/wiki/Domain-specific_language">DSLs</a> 또는 <a href="https://en.wikipedia.org/wiki/LaTeX">LaTeX</a>)의 임베딩을 허용해야합니다. ECMAScript proposal <a href="https://tc39.github.io/proposal-template-literal-revision/">Template Literal Revision</a> (4 단계, ECMAScript 2018 표준에 통합됨)은 tagged templates에서 ECMAScript escape sequences의 구문 제한을 제거합니다.</p> + +<p>그러나 illegal escape sequences는 여전히 "cooked"라고 표현되어야합니다. "cooked"배열의 {{jsxref ( "undefined")}} 요소로 나타납니다 :</p> + +<pre class="notranslate"><code>function latex(str) { + return { "cooked": str[0], "raw": str.raw[0] } +} + +latex`\unicode` + +// { cooked: undefined, raw: "\\unicode" }</code></pre> + +<p>escape sequence 제한은 <em>tagged</em> templates에만 적용되며 <em>untagged</em> template literals에는 적용되지 않습니다.</p> + +<div class="warning"> +<p>let bad = `bad escape sequence: \unicode`;</p> +</div> + +<h2 id="Specifications">Specifications</h2> + +<table> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-template-literals', 'Template Literals')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition. Defined in several section of the specification: <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-template-literals">Template Literals</a>, <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-tagged-templates">Tagged Templates</a></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-template-literals', 'Template Literals')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Defined in several section of the specification: <a href="https://tc39.github.io/ecma262/#sec-template-literals">Template Literals</a>, <a href="https://tc39.github.io/ecma262/#sec-tagged-templates">Tagged Templates</a></td> + </tr> + <tr> + <td><a href="https://tc39.github.io/proposal-template-literal-revision/">Template Literal Revision</a></td> + <td>Stage 4 draft</td> + <td>Drops escape sequence restriction from tagged templates</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div class="hidden"> +<p>The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> +</div> + +<p>{{Compat("javascript.grammar.template_literals")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("String")}}</li> + <li>{{jsxref("String.raw()")}}</li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar">Lexical grammar</a></li> + <li><a href="https://gist.github.com/WebReflection/8f227532143e63649804">Template-like strings in ES3 compatible syntax</a></li> + <li><a href="https://hacks.mozilla.org/2015/05/es6-in-depth-template-strings-2/">"ES6 in Depth: Template strings" on hacks.mozilla.org</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/trailing_commas/index.html b/files/ko/web/javascript/reference/trailing_commas/index.html new file mode 100644 index 0000000000..aeaded7640 --- /dev/null +++ b/files/ko/web/javascript/reference/trailing_commas/index.html @@ -0,0 +1,185 @@ +--- +title: Trailing commas +slug: Web/JavaScript/Reference/Trailing_commas +tags: + - Comma + - ECMAScript + - ECMAScript2017 + - ECMAScript5 + - JavaScript + - Language feature + - Syntax + - Trailing comma + - 구문 + - 자바스크립트 + - 콤마 + - 트레일링 콤마 +translation_of: Web/JavaScript/Reference/Trailing_commas +--- +<div>{{JsSidebar("More")}}</div> + +<p><strong>Trailing commas</strong> ("final commas"라고도 불립니다)는 새로운 엘리먼트나 매개변수, 속성을 JavaScript 코드에 추가할 때 유용합니다. 새로운 속성을 추가할 때, 마지막 줄에 trailing comma가 있다면 그 줄을 수정 없이 그대로 복사해 쓸 수 있습니다. 이외에도 버전 관리 이력이 간단해지고 코드 편집이 더 편해진다는 장점이 있습니다.</p> + +<p>JavaScript는 초기부터 배열 리터럴에 trailing comma를 허용했으며, ECMAScript 5부터는 객체 리터럴, ECMAScript 2017부터는 함수의 매개변수에도 허용하기 시작했습니다.</p> + +<p>그러나 {{Glossary("JSON")}}에서는 trailing comma를 허용하지 않습니다.</p> + +<h2 id="리터럴에서의_trailing_comma">리터럴에서의 trailing comma</h2> + +<h3 id="배열">배열</h3> + +<p>JavaScript는 배열에 나타나는 trailing comma를 무시합니다.</p> + +<pre class="brush: js notranslate">var arr = [ + 1, + 2, + 3, +]; + +arr; // [1, 2, 3] +arr.length; // 3</pre> + +<p>trailing comma가 여러 개 있을 경우 빈 슬롯("구멍")이 생깁니다. 구멍이 있는 배열을 성기다<sup>sparse</sup>고 합니다(조밀한<sup>dense</sup> 배열에는 구멍이 없습니다). {{jsxref("Array.prototype.forEach()")}}나 {{jsxref("Array.prototype.map()")}}을 이용해 배열을 순회할 때는 빈 슬롯을 무시합니다.</p> + +<pre class="brush: js notranslate">var arr = [1, 2, 3,,,]; +arr.length; // 5 +</pre> + +<h3 id="객체">객체</h3> + +<p>ECMAScript 5부터는 객체 리터럴에도 trailing comma를 사용할 수 있습니다.</p> + +<pre class="brush: js notranslate">var object = { + foo: "bar", + baz: "qwerty", + age: 42, +};</pre> + +<h2 id="함수에서의_trailing_comma">함수에서의 trailing comma</h2> + +<p>ECMAScript 2017에서는 함수의 매개변수 목록에 trailing comma를 허용합니다.</p> + +<h3 id="매개변수_정의">매개변수 정의</h3> + +<p>아래의 두 함수 정의는 모두 유효하며, 서로 같습니다. Trailing comma는 함수 정의의 <code>length</code> 속성이나 <code>arguments</code> 객체에 영향을 주지 않습니다.</p> + +<pre class="brush: js notranslate">function f(p) {} +function f(p,) {} + +(p) => {}; +(p,) => {}; +</pre> + +<p>Trailing comma는 클래스나 객체의 <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions">메소드 정의</a>에도 사용할 수 있습니다.</p> + +<pre class="brush: js notranslate">class C { + one(a,) {}, + two(a, b,) {}, +} + +var obj = { + one(a,) {}, + two(a, b,) {}, +}; +</pre> + +<h3 id="함수_호출">함수 호출</h3> + +<p>아래의 두 함수 호출은 모두 유효하며, 서로 같습니다.</p> + +<pre class="brush: js notranslate">f(p); +f(p,); + +Math.max(10, 20); +Math.max(10, 20,); +</pre> + +<h3 id="잘못된_trailing_comma">잘못된 trailing comma</h3> + +<p>함수의 매개변수 정의나 호출에 쉼표만 있을 경우 {{Jsxref("SyntaxError")}}가 발생합니다. 또한, <a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest 매개변수</a>를 사용할 때는 trailing comma를 사용할 수 없습니다.</p> + +<pre class="brush: js example-bad notranslate">function f(,) {} // SyntaxError: missing formal parameter +(,) => {}; // SyntaxError: expected expression, got ',' +f(,) // SyntaxError: expected expression, got ',' + +function f(...p,) {} // SyntaxError: parameter after rest parameter +(...p,) => {} // SyntaxError: expected closing parenthesis, got ',' +</pre> + +<h2 id="구조_분해_할당에서의_trailing_comma">구조 분해 할당에서의 trailing comma</h2> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">구조 분해 할당</a>의 좌변에도 trailing comma를 사용할 수 있습니다.</p> + +<pre class="brush: js notranslate">// Trailing comma가 있는 배열 구조 분해 +[a, b,] = [1, 2]; + +// Trailing comma가 있는 객체 구조 분해 +var o = { + p: 42, + q: true, +}; +var {p, q,} = o; +</pre> + +<p>Rest 원소가 있을 경우 역시 {{jsxref("SyntaxError")}}가 발생합니다.</p> + +<pre class="brush: js example-bad notranslate">var [a, ...b,] = [1, 2, 3]; +// SyntaxError: rest element may not have a trailing comma</pre> + +<h2 id="JSON에서의_trailing_comma">JSON에서의 trailing comma</h2> + +<p>객체 안에서의 trailing comma는 ECMAScript 5에 와서야 추가되었습니다. JSON은 ES5 이전의 JavaScript 문법을 기초로 하므로 <strong>JSON에서는 trailing comma를 사용할 수 없습니다</strong>.</p> + +<p>아래의 두 줄 모두 <code>SyntaxError</code>를 발생합니다.</p> + +<pre class="brush: js example-bad notranslate">JSON.parse('[1, 2, 3, 4, ]'); +JSON.parse('{"foo" : 1, }'); +// SyntaxError JSON.parse: unexpected character +// at line 1 column 14 of the JSON data +</pre> + +<p>JSON을 올바르게 파싱하려면 trailing comma를 제거해야 합니다.</p> + +<pre class="brush: js example-good notranslate">JSON.parse('[1, 2, 3, 4 ]'); +JSON.parse('{"foo" : 1 }');</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">비고</th> + </tr> + <tr> + <td>{{SpecName('ES5.1')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>객체 리터럴 trailing comma 추가</td> + </tr> + <tr> + <td>{{SpecName('ES6')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>변화 없음</td> + </tr> + <tr> + <td>{{SpecName('ESDraft')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>ES2017에서 함수 trailing comma 추가</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div> + + +<p>{{Compat("javascript.grammar.trailing_commas")}}</p> +</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>Initial ECMAScript proposal: <a href="https://github.com/tc39/proposal-trailing-function-commas">trailing function commas</a> by Jeff Morrison</li> +</ul> diff --git a/files/ko/web/javascript/typed_arrays/index.html b/files/ko/web/javascript/typed_arrays/index.html new file mode 100644 index 0000000000..814ae7c885 --- /dev/null +++ b/files/ko/web/javascript/typed_arrays/index.html @@ -0,0 +1,222 @@ +--- +title: JavaScript 형식화 배열 +slug: Web/JavaScript/Typed_arrays +tags: + - Guide + - JavaScript +translation_of: Web/JavaScript/Typed_arrays +--- +<div>{{JsSidebar("Advanced")}}</div> + +<p>JavaScript 형식화 배열(typed array)은 배열같은 객체이고 원시(raw) 이진 데이터에 액세스하기 위한 메커니즘을 제공합니다. 이미 아시다시피, {{jsxref("Array")}} 객체는 동적으로 늘었다 줄고 어떤 JavaScript 값이든 가질 수 있습니다. JavaScript 엔진은 이러한 배열이 빨라지도록 최적화를 수행합니다. 그러나, audio 및 video 조작과 같은 기능 추가, WebSocket을 사용한 원시 데이터에 액세스 등 웹 어플리케이션이 점점 더 강력해짐에 따라, 빠르고 쉽게 형식화 배열의 원시 이진 데이터를 조작할 수 있게 하는 것이 JavaScript 코드에 도움이 될 때가 있음이 분명해 졌습니다.</p> + +<p>그러나, 형식화 배열은 보통 배열과 혼동되지는 않습니다, 형식화 배열에 {{jsxref("Array.isArray()")}} 호출은 <code>false</code>를 반환하기에. 게다가, 보통 배열에 이용할 수 있는 모든 메서드가 형식화 배열에 의해 지원되지는 않습니다(가령 push 및 pop).</p> + +<h2 id="버퍼_및_뷰_형식화_배열_구조">버퍼 및 뷰: 형식화 배열 구조</h2> + +<p>최대 유연성 및 효율을 달성하기 위해, JavaScript 형식화 배열은 구현을 <strong>버퍼</strong> 및 <strong>뷰</strong>로 나눕니다. 버퍼 ({{jsxref("ArrayBuffer")}} 객체에 의해 구현됨)는 데이터 부분(chunk, 덩어리)을 나타내는 객체입니다; 이야기 할 형식이 없으며, 그 콘텐츠에 액세스하기 위한 메커니즘을 제공하지 않습니다. 버퍼에 포함된 메모리에 액세스하기 위해, 뷰를 사용할 필요가 있습니다. 뷰는 문맥(context, 즉 데이터 형, 시작 오프셋 및 요소 수)을 제공해 데이터를 실제 형식화 배열로 바꿉니다.</p> + +<p><img alt="Typed arrays in an ArrayBuffer" src="https://mdn.mozillademos.org/files/8629/typed_arrays.png" style="height: 278px; width: 666px;"></p> + +<h3 id="ArrayBuffer">ArrayBuffer</h3> + +<p>{{jsxref("ArrayBuffer")}}는 일반 고정 길이 이진 데이터 버퍼를 나타내는 데 사용되는 데이터 형입니다. <code>ArrayBuffer</code> 콘텐츠를 직접 조작할 수는 없습니다; 대신에, 형식화 배열 뷰 또는 특정 형식으로 버퍼를 나타내는 {{jsxref("DataView")}}를 만들어 버퍼의 콘텐츠를 읽고 쓰기 위해 사용합니다.</p> + +<h3 id="형식화_배열_뷰">형식화 배열 뷰</h3> + +<p>형식화 배열 뷰는 자체 설명형 이름이 있으며 <code>Int8</code>, <code>Uint32</code>, <code>Float64</code> 등과 같은 모든 일반 숫자 형을 위한 뷰를 제공합니다. 특별한 형식화 배열 뷰가 하나 있습니다, <code>Uint8ClampedArray</code>. 값은 0에서 255 사이로 단속(제한)합니다. 예를 들어, 이는 <a href="/ko/docs/Web/API/ImageData">Canvas 데이터 처리</a>에 유용합니다.</p> + +<p>{{page("/ko/docs/Web/JavaScript/Reference/Global_Objects/TypedArray", "TypedArray_객체")}}</p> + +<h3 id="DataView">DataView</h3> + +<p>{{jsxref("DataView")}}는 버퍼에 임의 데이터를 읽고 쓰기 위해 getter/setter API를 제공하는 저레벨 인터페이스입니다. 예를 들어, 서로 다른 유형의 데이터를 처리하는 경우 유용합니다. 형식화 배열 뷰는 플랫폼의 본디(native) 바이트 순서(byte-order, {{Glossary("Endianness")}} 참조)에 속합니다. <code>DataView</code>로 바이트 순서를 제어할 수 있습니다. 기본으로 big-endian이고 getter/setter 메서드로 little-endian으로 설정될 수 있습니다.</p> + +<h2 id="형식화_배열을_사용하는_웹_API">형식화 배열을 사용하는 웹 API</h2> + +<dl> + <dt><a href="/ko/docs/Web/API/FileReader#readAsArrayBuffer()"><code>FileReader.prototype.readAsArrayBuffer()</code></a></dt> + <dd><code>FileReader.prototype.readAsArrayBuffer()</code> 메서드는 지정된 <a href="/ko/docs/Web/API/Blob"><code>Blob</code></a> 또는 <a href="/ko/docs/Web/API/File"><code>File</code></a>의 콘텐츠를 읽기 시작합니다.</dd> + <dt><a href="/ko/docs/Web/API/XMLHttpRequest#send()"><code>XMLHttpRequest.prototype.send()</code></a></dt> + <dd><code>XMLHttpRequest</code> 인스턴스의 <code>send()</code> 메서드는 이제 형식화 배열 및 인수로 {{jsxref("ArrayBuffer")}} 객체를 지원합니다.</dd> + <dt><code><a href="/ko/docs/Web/API/ImageData">ImageData.data</a></code></dt> + <dd><code>0</code>에서 <code>255</code>까지 정수값으로 RGBA 순 데이터를 포함하는 1차원 배열을 나타내는 {{jsxref("Uint8ClampedArray")}}입니다.</dd> +</dl> + +<h2 id="예">예</h2> + +<h3 id="버퍼와_뷰_사용하기">버퍼와 뷰 사용하기</h3> + +<p>우선, 여기서 16바이트 고정 길이로 버퍼를 만들어야 합니다:</p> + +<pre class="brush:js">var buffer = new ArrayBuffer(16); +</pre> + +<p>이 시점에서, 바이트가 모두 0으로 미리 초기화된 메모리 덩어리가 있습니다. 그렇지만 이거 가지고 할 수 있는 게 많지 않습니다. 실제 16바이트 길이인지 확인할 수 있고 대략 그런 정도입니다:</p> + +<pre class="brush:js">if (buffer.byteLength === 16) { + console.log("Yes, it's 16 bytes."); +} else { + console.log("Oh no, it's the wrong size!"); +} +</pre> + +<p>정말 이 버퍼로 작업할 수 있기 전에, 뷰를 만들어야 합니다. 32비트 부호있는 정수 배열로 버퍼의 데이터를 다루는 뷰를 만듭시다:</p> + +<pre class="brush:js">var int32View = new Int32Array(buffer); +</pre> + +<p>이제 보통 배열처럼 배열 내 필드에 액세스할 수 있습니다:</p> + +<pre class="brush:js">for (var i = 0; i < int32View.length; i++) { + int32View[i] = i * 2; +} +</pre> + +<p>이는 배열의 4항목을 값 0, 2, 4 및 6으로 채웁니다 (4항목이 각각 4바이트에 총 16바이트가 됩니다).</p> + +<h3 id="같은_데이터에_여러_뷰">같은 데이터에 여러 뷰</h3> + +<p>상황은 당신이 같은 데이터에 여러 뷰를 만들 수 있음을 고려하는 경우 정말 흥미로워지기 시작합니다. 예를 들어, 위 코드가 주어지면 다음과 같이 계속할 수 있습니다:</p> + +<pre class="brush:js">var int16View = new Int16Array(buffer); + +for (var i = 0; i < int16View.length; i++) { + console.log("Entry " + i + ": " + int16View[i]); +} +</pre> + +<p>여기서 우리는 기존 32비트 뷰와 같은 버퍼를 공유하는 16비트 정수 뷰를 만들고 16비트 정수로 버퍼 내 모든 값을 출력합니다. 이제 우리는 출력 0, 0, 2, 0, 4, 0, 6, 0을 얻습니다.</p> + +<p>그렇지만 한 단계 더 앞으로 갈 수 있습니다. 다음을 생각해 보세요:</p> + +<pre class="brush:js">int16View[0] = 32; +console.log("Entry 0 in the 32-bit array is now " + int32View[0]); +</pre> + +<p>이로부터 출력은 "Entry 0 in the 32-bit array is now 32"입니다. 즉, 두 배열은 확실히 그저 같은 데이터 버퍼 상의 뷰입니다, 버퍼를 서로 다른 형식으로 다루는. 모든 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#TypedArray_objects" title="Typed array subclasses">뷰 유형</a>으로 이를 할 수 있습니다.</p> + +<h3 id="복잡한_데이터_구조(체)와_작업하기">복잡한 데이터 구조(체)와 작업하기</h3> + +<p>단일 버퍼를 서로 다른 형인 여러 뷰(버퍼 내 서로 다른 오프셋에서 시작하는)와 결합시켜, 여러 데이터 형을 포함하는 데이터 객체와 상호 작용할 수 있습니다. 예를 들어, 이는 <a href="/ko/docs/Web/WebGL" title="WebGL">WebGL</a>, 데이터 파일 또는 <a href="/ko/docs/Mozilla/js-ctypes" title="js-ctypes">js-ctypes</a>를 쓰는 동안 사용해야 하는 C 구조체에서 복잡한 데이터 구조와 상호 작용케 합니다.</p> + +<p>이 C 구조체를 생각해 보세요:</p> + +<pre class="brush:cpp">struct someStruct { + unsigned long id; + char username[16]; + float amountDue; +};</pre> + +<p>이 같은 형식으로 데이터를 포함하는 버퍼에 액세스할 수 있습니다:</p> + +<pre class="brush:js">var buffer = new ArrayBuffer(24); + +// ... 버퍼 내의 데이터를 읽어들임 ... + +var idView = new Uint32Array(buffer, 0, 1); +var usernameView = new Uint8Array(buffer, 4, 16); +var amountDueView = new Float32Array(buffer, 20, 1);</pre> + +<p>그런 뒤, 예를 들어 <code>amountDueView[0]</code>로 지불할 요금(amount due)을 액세스할 수 있습니다.</p> + +<div class="note"><strong>주의:</strong> C 구조체에서 <a href="http://en.wikipedia.org/wiki/Data_structure_alignment" title="data structure alignment">데이터 구조 정렬</a>은 플랫폼에 의존합니다. 이러한 패딩(padding) 차이에 대해 조심하고 고려하세요.</div> + +<h3 id="보통_배열로_변환">보통 배열로 변환</h3> + +<p>형식화 배열을 처리한 뒤, 때때로 {{jsxref("Array")}} 프로토타입의 도움을 받기 위해 보통 배열로 다시 변환하는 게 유용합니다. 이는 {{jsxref("Array.from")}} 또는 <code>Array.from</code>이 지원되지 않는 경우 다음 코드를 사용하여 수행할 수 있습니다.</p> + +<pre class="brush:js">var typedArray = new Uint8Array([1, 2, 3, 4]), + normalArray = Array.prototype.slice.call(typedArray); +normalArray.length === 4; +normalArray.constructor === Array; +</pre> + +<h2 id="스펙">스펙</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">스펙</th> + <th scope="col">상태</th> + <th scope="col">설명</th> + </tr> + <tr> + <td>{{SpecName('Typed Array')}}</td> + <td>{{Spec2('Typed Array')}}</td> + <td>ECMAScript 6로 대체됨.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-typedarray-objects', 'TypedArray Objects')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>ECMA 표준에서 초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-typedarray-objects', 'TypedArray Objects')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>7.0</td> + <td>{{ CompatGeckoDesktop("2") }}</td> + <td>10</td> + <td>11.6</td> + <td>5.1</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>4.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{ CompatGeckoMobile("2") }}</td> + <td>10</td> + <td>11.6</td> + <td>4.2</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="참조">참조</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Base64_encoding_and_decoding#Appendix.3A_Decode_a_Base64_string_to_Uint8Array_or_ArrayBuffer" title="Decode_a_Base64_string_to_Uint8Array_or_ArrayBuffer"><em>Base64</em>로 인코딩된 문자열에서 <code>ArrayBuffer</code> 또는 형식화 배열 얻기</a></li> + <li><a href="/ko/docs/Code_snippets/StringView"><code>StringView</code> - 형식화 배열에 기반을 둔 문자열의 C-like 표현</a></li> + <li><a href="https://hacks.mozilla.org/2011/12/faster-canvas-pixel-manipulation-with-typed-arrays" title="Faster Canvas Pixel Manipulation with Typed Arrays">형식화 배열로 빠른 Canvas 픽셀 조작</a></li> + <li><a href="http://www.html5rocks.com/en/tutorials/webgl/typed_arrays">형식화 배열: 브라우저에서 이진 데이터</a></li> + <li>{{Glossary("Endianness")}}</li> +</ul> diff --git a/files/ko/web/javascript/쉘/index.html b/files/ko/web/javascript/쉘/index.html new file mode 100644 index 0000000000..718fa8bdc2 --- /dev/null +++ b/files/ko/web/javascript/쉘/index.html @@ -0,0 +1,40 @@ +--- +title: JavaScript 쉘 +slug: Web/JavaScript/쉘 +translation_of: Web/JavaScript/Shells +--- +<div>{{JsSidebar}}</div> + +<p>여러분은 JavaScript 쉘을 통해 웹페이지 새로고침하지 않고 빠르게 <a href="/en-US/docs/Web/JavaScript">JavaScript</a> 의 코드를 테스트해볼 수 있습니다. 코드를 개발하고 디버깅하는데 매우 유용한 도구입니다.</p> + +<h2 id="독립적으로_사용할_수_있는_JavaScript_쉘">독립적으로 사용할 수 있는 JavaScript 쉘</h2> + +<p>아래의 Javascript 쉘은 펄과 파이썬과 같이 독립적인 환경을 제공합니다.</p> + +<ul> + <li><a href="http://nodejs.org/">Node.js</a> - Node.js는 빠르고 확장 가능한 네트워크 어플리케이션을 쉽게 만들 수 있는 플랫폼입니다.</li> + <li><a class="external" href="http://www.jsdb.org/">JSDB</a> - Windows, Mac, Linux 환경에 맞는 컴파일된 바이너리를 제공하는 독립적인 독립적인 Javascript 쉘입니다.</li> + <li><a class="external" href="http://javalikescript.free.fr/">JavaLikeScript</a> - 네이티브와 JavaScript 라이브러리 모두를 제공하는 독립적이고 확장 가능한 JavaScript 쉘입니다.</li> + <li><a class="external" href="http://gluescript.sourceforge.net/">GLUEscript</a> - 크로스-플랫폼 JavaScript 어플리케이션을 제작하기 위한 독립적인 JavaScript 쉘입니다. GUI 앱을 위한 wxWidgets(구 wxJavaScript)를 사용할 수 있습니다.</li> + <li><a class="external" href="http://jspl.msg.mx/">jspl</a> - Perl의 영향을 받은 독립적인 JavaScript 쉘입니다. JavaScript에서 직접 perl 모듈을 사용할 수 있습니다: 데이터베이스 통합을 위한 DBI, GUI 앱을 위한 GTK2, 시스템 프로그래밍을 위한 POSIX, 기타 등등. 현재로서는 JavaScript 프로그래머를 위한 최고의 CPAN입니다.</li> + <li><a class="external" href="http://shelljs.org">ShellJS</a> - Node.js를 위한 포터블 Unix 쉘 명령도구입니다.</li> +</ul> + +<h2 id="JavaScript_쉘_리스트">JavaScript 쉘 리스트</h2> + +<p>아래는 Mozilla에서 사용할 수 있는 JavaScript Shell입니다.</p> + +<ul> + <li>Firefox는 <a href="/ko/docs/Tools/Scratchpad">Scratchpad</a>라 불리는 자바스크립트 내장 콘솔을 가지고있습니다.(version6 이후)</li> + <li><a href="/ko/docs/Mozilla/Projects/SpiderMonkey/Introduction_to_the_JavaScript_shell">JavaScript Shell</a> (<code>js</code>) - JavaScript를 위한 command line인터프리터입니다.</li> + <li><a href="/en-US/docs/Mozilla/Tech/XPCOM/Language_bindings/XPConnect">XPConnect</a>인 <a href="/en-US/docs/Mozilla/XPConnect/xpcshell">xpcshell</a> - Mozilla개발자는 위한 유용한 쉘 입니다. (가끔 필요할거에요.)</li> + <li><a href="http://babeljs.io/repl">Babel REPL</a> - 최신 자바스크립트를 시험해 볼 수 있는 브라우저 기반 <a href="https://en.wikipedia.org/wiki/REPL">REPL</a>입니다.</li> + <li><a href="http://es6console.com/">ES6Console.com</a> - 브라우저에서 ECMAScript 2015 코드를 테스트 해보기위한 open-source JavaScript 콘솔 입니다.</li> + <li><a href="http://jsconsole.com/">jsconsole.com</a> -- 웹에서 빠른속도록 JavaScript 코드를 테스트 해 볼 수 있는 open-source JavaScript 콘솔 입니다.</li> + <li><a class="external" href="http://www.squarefree.com/shell/">JavaScript Shell (web page)</a> - <a class="link-https" href="https://addons.mozilla.org/en-US/firefox/addon/7434">Extension Developer's Extension</a>의 일부 기능으로 사용 가능합니다.</li> + <li><a class="external" href="http://www.billyreisinger.com/jash/">Jash: JavaScript Shell</a> - 웹에서 커맨드라인접속이 가능한 <a href="https://ko.wikipedia.org/wiki/DHTML">DHTML</a> 기반 쉘 입니다.</li> + <li><a class="external" href="http://hyperstruct.net/projects/mozrepl">MozRepl</a> - Firefox 및 기타 Mozilla 응용 프로그램에 연결하고 코드를 실행하는 중에 코드내용을 다루거나 확인 할 수 있습니다.</li> + <li><a class="external" href="https://addons.mozilla.org/en-US/firefox/addon/execute-js/">Execute JS</a> - (더이상 지원되지않음) - 확장 된 JavaScript 콘솔을 제공하는 Firefox 확장 기능입니다. 임의의 JavaScript 코드 및 수정 기능을 편안하게 입력하고 실행할 수 있습니다.</li> + <li><a class="link-https" href="https://addons.mozilla.org/addon/159546">xqjs</a> - Firefox를 위한 간단한 콘솔</li> + <li><a class="link-https" href="https://addons.mozilla.org/en-US/firefox/addon/firebug/">Firebug</a> - 콘솔을 포함한 Firefox 개발자도구입니다.</li> +</ul> diff --git a/files/ko/web/javascript/시작하기/index.html b/files/ko/web/javascript/시작하기/index.html new file mode 100644 index 0000000000..cfe47e1ec5 --- /dev/null +++ b/files/ko/web/javascript/시작하기/index.html @@ -0,0 +1,327 @@ +--- +title: 시작하기 (자바스크립트 튜토리얼) +slug: Web/JavaScript/시작하기 +translation_of: Learn/Getting_started_with_the_web/JavaScript_basics +--- +<h2 id="Why_JavaScript.3F" name="Why_JavaScript.3F">왜 자바스크립트인가?</h2> +<p>자바스크립트는 종종 오해할 수 있는 강력하고 복잡한 컴퓨터 언어이다. 사용자가 쉽게 데이터를 입력하고 결과를 볼 수 있게 어플리케이션을 빠르게 개발 할 수 있다.</p> +<p> 웹브라우저를 중심으로 또한 ECMAScript로 알려진 자바스크립트의 주요 장점은 이와 같이 브라우저를 지원하는 모든 플랫폼에 동일한 결과를 만들 수 있다. 이 페이지의 예제는 구글 맵스처럼 맥 OS와 윈도우, 리눅스에서 실행한다. 수많은 자바스크립트 라이브러리의 최근 성장과 함께 AJax 어플리케이션을 개발하거나 이벤트 처리하기, 에니메이션 만들기, DOM 엘리먼트 선택하기, 도큐먼트 탐색하기가 이제 더욱 쉬워졌다. 다양한 소유권의 이익에 의해 추진된 다른 기술의 과대 광고와는 달리 자바스크립트는 모두 무료이면서 보편적으로 채택된 클라이언트 사이드 프로그래밍 언어이면서 정말이지 유일한 크로스 플래폼이다.</p> +<h2 id="What_you_should_already_know" name="What_you_should_already_know">당신이 이미 알아야 하는 것</h2> +<p>자바스크립트는 프로그래밍을 같이 시작하기 위해 매우 쉬운 언어이다. 시작하기 위해서 당신이 필요한 모든 것은 텍스트 에디터와 웹브라우저이다. </p> +<p>이 문서의 범위를 벗어나는 자바스크립트와 함께 개발되고 통합 할 수 있는 다른 기술은 많이 있다. 첫날부터 구글맵스과 같이 완전한 어플리케이션을 만들 것이라고 기대하지 마라!</p> +<p>시작하기</p> +<p>자바스크립트로 시작하기는 매우 쉽다. 당신은 복잡한 개발 프로그램 설치가 필요가 없다. 컴파일러를 사용하거나 프로그램 만들기, 쉘을 어떻게 사용하는지 알 필요가 없다. 자바스크립트는 당신의 웹 브라우저에서 해석 된다. 당신이 해야 할 모든 일은 텍스트 파일에 당신의 프로그램을 저장하고 당신의 웹브라우저를 연다. 단지 그 것이다!</p> +<p>자바스크립트는 입문 컴퓨터 언어로서 최고의 프로그래밍 언어이다. 새로운 학생에게 즉시 피드백 할 수 있게 하고 그들이 아마도 그들의 실생활에 유용한 것을 발견할 수 있는 도구들에 관한 것을 그들에게 가르친다. 이것은 전용 소프트웨어 개발자를 위해 정말 유용한 C, C++, JAVA 와는 뚜렷하게 대조적이다. </p> +<h2 id="Browser_Compatibility_Issues" name="Browser_Compatibility_Issues">브라우저 호환성 이슈들</h2> +<p>다른 브라우저에서 사용이 가능한 어떤 기능 중에는 차이가 있다. Mozilla, Chrome, Microsoft IE, Apple Safari, Opera에서 가동하는 것에 따라 변동될 수 있다. 이런 <a href="/en-US/docs/JavaScript/Compatibility">변동사항</a>을 문서화 하려고 한다. 사용 가능한 다양한 크로스 플랫폼 자바스크립트 API 사용하여 이런 이슈들을 완하시킬 수 있다. 이런 API는 공통 기능으로 제공하고 이 브라우저의 변동된 것을 숨긴다. </p> +<h2 id="How_to_try_the_Examples" name="How_to_try_the_Examples">예제를 시도하는 방법</h2> +<p>아래의 예제들은 몇가지 샘플 코드를 가지고 있다. 이 예제들을 시도하는 방법은 여러가지가 있다. 만약 당신이 이미 당신의 웹사이트를 가지고 있다면 당신은 당신의 웹사이트에 새로운 웹 페이지로써 이 예제들을 저장할 수 있어야 한다.</p> +<p>만약 당신이 당신의 웹사이트를 가지고 있지 않다면 당신의 컴퓨터에 파일로써 이 예제들을 저장할 수 있고 당신이 현재 사용하고 있는 웹브라우저를 통해 예제들을 열 수 있다. 자바스크립트는 이런 이유로 시작하려는 프로그래머가 사용하기 매운 쉬운 언어이다. 당신은 컴파일러 또는 개발 환경이 필요하지 않다. 그리고 당신과 당신의 브라우저가 시작하기 위해서 필요한 모든 것이다!</p> +<h2 id="Example:_Catching_a_mouse_click" name="Example:_Catching_a_mouse_click">예제 : 마우스 클릭 잡기</h2> +<p>이벤트 핸들링(이벤트 타입들, 핸들러 등록, 전파 등)의 특성은 이 간단한 예제들을 완전히 적용하기에는 너무 광범위하다. 그런데 이 예제는 자바스크립트 이벤트 시스템에 대한 조금의 탐구도 없이 마우스 클릭을 잡기를 설명할 수 없다. 이 예제는 자바스크립트 이벤트에 관해 전체 자세한 내용을 가볍게 스쳐 지나 갈 것이고 만약 당신이 여기 설명된 기본 기능의 범위를 넘어서고 싶다면 자바스크립트 이벤트 시스템에 관해 더 자세히 읽어야 함을 명심하라.</p> +<p>'마우스'이벤트들은 사용자 동작에 반응한 웹브라우저에 의해 발생된 전체 이벤트의 집합이다.<span style="line-height: 1.5;">다음은 사용자의 마우스 동작에 대한 응답으로 방출되는 이벤트의 목록이다.</span></p> +<ul> + <li>Click - 사용자가 마우스를 클릭했을 때 발생</li> + <li>DblClick - 사용자가 마우스를 더블 클릭했을 때 발생</li> + <li>MouseDown - 사용자가 마우스 버튼을 눌렀을 때 발생(클릭의 전반부)</li> + <li>MouseUp - 사용자가 마우스 버튼을 해제했을 때 발생(클릭의 후반후)</li> + <li>MouseOut - 마우스 포인터가 객체의 그래픽 범위를 떠나려고 할때 발생</li> + <li>MouseOver - 마우스 포인터가 객체의 그래픽 범위를 진입하려고 할때 발생</li> + <li>MouseMove - 마우스 포인터가 객체의 그래픽 범위 안에서 마우스 포인터를 움직이려 할때 발생</li> + <li>ContextMenu - 사용자가 오른쪽 마우스 버튼을 클릭했을 때 발생</li> +</ul> +<p>인라인 이벤트 핸들러, HTML의 최신버전에서 주의할 것은 다시 말하면 하나가 태그 애트리뷰트들로써 추가 되었다는 것은 모두 소문자 이고 스크립트의 이벤트 핸들러가 항상 모든 소문자이어야 하는 것을 예상된다.</p> +<p>이벤트 핸들러를 등록하려는 이러한 이벤트들을 캡처하기 위해 가장 간단한 방법은 HTML을 사용하여 당신의 엘리먼트의 애트리뷰트들로서 개별적인 이벤트들을 지정하는 것이다.</p> +<p>예제:</p> +<pre class="brush:js"> <span onclick="alert('Hello World!');">Click Here</span></pre> +<p>당신이 실행하기 원하는 자바스크립트 코드를 애트리뷰트 값으로서 그때마다 처리할 수 있다. 또는 당신은 HTML 페이지안에 <script> 블록에 정의되어진 함수를 호출 할 수 있다 :</p> +<pre class="brush:js"><script> + function clickHandler() { + alert("Hello, World!"); + } +</script> +<span onclick="clickHandler();">Click Here</span></pre> +<p>또한 발생된 이벤트 객체는 캡처하거나 참조할 수 있으며 <span style="line-height: 1.5;">객체가 이벤트를 받거나 이벤트 타입 그리고 마우스가 클릭됐을 때 그러한 이벤트에 관한 특성을 접근하는 무언가 개발하는 것을 제공할 수 있다. </span><span style="line-height: 1.5;">인라인 예제를 다시 사용 하라:</span></p> +<pre class="brush:js"><script> + function clickHandler(event) { + var eType = event.type; + /* 다음은 호환성을 위한 것이다. */ + /* Moz는 이벤트 객체의 target 프로퍼티로 채운다. */ + /* IE는 <span style="font-size: 1rem;">srcElement 프로퍼티로 채운다.</span><span style="font-size: 1rem;">*/</span> + var eTarget = event.target || event.srcElement; + + alert( "Captured Event (type=" + eType + ", target=" + eTarget ); + } +</script> +<span onclick="clickHandler(event);">Click Here</span></pre> +<p>당신의 HTML안에 이벤트를 수신 등록 이외에 당신은 당신의 자바스크립트에 의해 생성된 어떠한 HTML엘리먼트 객체의 똑같은 이름으로 애트리뷰트들을 마찬가지로 설정할 수 있다. 아래의 예는 span 객체를 인스터트화하고 페이지의 body에 추가하고 mouse-over, mouse-out, mouse-down, mouse-up 이벤트들을 수신하기위해 span 객체를 등록한다. </p> +<pre class="brush:js"><body></body> +<script> + function mouseeventHandler(event) { + /*<span style="font-size: 1rem;">다음은 호환성을 위한 것이다.</span><span style="font-size: 1rem;"> */</span> + /* IE는 기본적으로 이벤트 객체를 전달하지 않는다. */ + if (!event) event = window.event; + + /* 미리 이벤트 타입과 타켓 얻기 */ + var eType = event.type; + var eTarget = event.target || event.srcElement; + alert(eType +' event on element with id: '+ eTarget.id); + } + + function onloadHandler() { + /* 페이지의 body 엘리먼트를 참조하여 얻기 */ + var body = document.body; + /* 클릭되기 위한 span 엘리먼트 생성하기 */ + var span = document.createElement('span'); + span.id = 'ExampleSpan'; + span.appendChild(document.createTextNode ('Click Here!')); + + /* 특정 마우스 이벤트를 받기 위해 spna 객체 등록하기 - 이벤트들의 소문자에 유의하라 그러나 당신이 그것을 치환하기 위한 이름의 선택은 자유다. + */ + span.onmousedown = mouseeventHandler; + span.onmouseup = mouseeventHandler; + span.onmouseover = mouseeventHandler; + span.onmouseout = mouseeventHandler; + + /* 페이지에 span 보여주기 */ + body.appendChild(span); +} + +window.onload = onloadHandler; // 우리가 핸들러를 치환한 이후에는 우리는 함수 이름 뒤에 ()을 붙여서는 안된다. +</script></pre> +<h2 id="Example:_Catching_a_keyboard_event" name="Example:_Catching_a_keyboard_event">예제: 키보드 이벤트 잡기</h2> +<p>위의 예제인 "마우스 이벤트 잡기"와 유사하게 키보드 이벤트 잡기는 자바스크립트 이벤트 시스템 탐험에 의존한다. 키보드 이벤트들은 어떤 키든 키보드에서 사용될 때마다 발생한다.</p> +<p>키보드 동작에 반응하여 방출 가능한 키보드 이벤트 목록들은 마으스로 사용 가능한 것보다 상당히 작다. </p> +<ul> + <li>KeyPress - 키보드를 누르거나 해제할때 발생</li> + <li>KeyDown - 키보드를 눌렀지만 아직 해제 않지 않았을때 발생</li> + <li>KeyUp - 키보드가 해제 되었을때 발생</li> + <li>TextInput (글을 썼던 시점에는 웹킷 브라우저에서만 가능) - 텍스트에 붙여넣기나 말하기를 하거나 또는 키보드로 입력했을 때 발생. 이 이벤트는 이 문서에 포함하지 않을 것이다.</li> +</ul> +<p><a class="new " href="/en-US/docs/DOM/event/keypress" rel="internal">keypress</a> 이벤트는 키를 눌렀을 때의 Unicode값이 keycode나 <a href="/en-US/docs/DOM/event.charCode" rel="internal" style="line-height: 1.5; font-family: 'Courier New', 'Andale Mono', monospace;">charCode</a> 프로퍼티에 둘다 저장되어 있다. 만약 키가 문자로 생성되어 눌러졌을때 (예를 들어 'a') <code style="font-style: normal; line-height: 1.5;">charCode는 문자의 경우를 반영하여 문자의 코드를 설정한다.(즉, charCode은 Shift 키를 누르고 있는지 여부를 고려한다)그렇지 않으면, 누른 키의 코드가 keyCode에 저장된다.</code></p> +<p>키보드 이벤트들을 캡쳐하기 위한 가장 간단한 방법은 당신의 엘리먼트를 애트리뷰트들로써 개별적인 이벤트들을 지정한 HTML안에 이벤트 핸들러들을 다시 저장하는 것이다.</p> +<p>예:</p> +<pre class="brush:js"> <input type="text" onkeypress="alert ('Hello World!');"> +</pre> +<p>마우스 이벤트들과 마찬가지로 당신이 실행하기 원하는 자바스크립트 코드는 그때마다 처리할 수 있다. 또는 당신은 HTML 페이지안에 <script> 블록에 정의되어진 함수를 호출 할 수 있다 :</p> +<pre class="brush:js"><script> + function keypressHandler() { + alert ("Hello, World!"); + } +</script> + +<input onkeypress="keypressHandler();" /> +</pre> +<p>타겟을 참조하거나 이벤트를 캡쳐 하는 것은 (즉, 눌러진 실제 키) 마우스 이벤트를 비슷한 방법으로 이룰 수 있다.</p> +<p> <span style="font-family: 'Courier New', 'Andale Mono', monospace; font-size: 1rem; line-height: 19px; background-color: rgb(246, 246, 242);"><script type="text/javascript"></span></p> +<pre class="brush:js"> function keypressHandler(evt) { + var eType = evt.type; // 이벤트 타입으로써 <span style="font-size: 1rem;">"keypress"를 반환할 것이다.</span></pre> +<pre class="brush:js"> + /* <span style="font-size: 1rem;">여기에 우리는 </span><span style="font-size: 1rem;">which 나 다른 </span><span style="font-size: 1rem;">keyCode로 반환되는 모질라 기반으로 된 브라우저를 크로스 브라우저 방법으로 사용할 필요가 있다. </span><a href="/en-US/docs/JavaScript/Reference/Operators/Conditional_Operator" style="font-size: 1rem;" title="/en-US/docs/JavaScript/Reference/Operators/Conditional_Operator">조건 연산자</a><span style="font-size: 1rem;"> 또는 삼항식이 </span><span style="font-size: 1rem;">좋은 방법이다.</span> + var keyCode = evt.which?evt.which:evt.keyCode; + var eCode = 'keyCode is ' + keyCode; + var eChar = 'charCode is ' + .fromCharCode(keyCode); // 또는 evt.charCode + alert ("Captured Event (type=" + eType + ", key Unicode value=" + eCode + ", ASCII value=" + eChar + ")"); + } +</script> +<input onkeypress="keypressHandler(event);" /></pre> +<p>페이지로 부터 어떤 키 이벤트를 캡처하기 위해서는 문서 레벨에서 이벤트를 등록하거나 함수안에서 처리하여 마칠 수 있다. </p> +<pre class="brush:js"><script> + document.onkeypress = keypressHandler; + document.onkeydown = keypressHandler; + document.onkeyup = keypressHandler; +</script></pre> +<p><span style="line-height: 1.5;">여기에 키 이벤트 처리하기 보여주는 완벽한 예제가 있다.</span></p> +<pre class="brush:js"><!DOCTYPE html> +<html> +<head> + <script> + var metaChar = false; + var exampleKey = 16; + function keyEvent(event) { + var key = event.keyCode || event.which; // alternative to ternary - if there is no keyCode, use which + var keychar = String.fromCharCode(key); + if (key == exampleKey) { + metaChar = true; + } + if (key != exampleKey) { + if (metaChar) { + alert("Combination of metaKey + " + keychar) + metaChar = false; + } else { + alert("Key pressed " + key); + } + } + } + function metaKeyUp(event) { + var key = event.keyCode || event.which; + if (key == exampleKey) { metaChar = false; } + } + </script> +</head> +<body onkeydown="keyEvent(event)" onkeyup="metaKeyUp(event)"> + Try pressing any key! +</body> +</html></pre> +<h3 id="브라우저_버그들과_이상한_점">브라우저 버그들과 이상한 점</h3> +<p>키 이벤트를 통해서 사용 가능하게 만들어진 두개의 프로퍼티들은 keycode와 charCode이다. 단순한 용어로 keyCode는 사용자에 의해 눌러진 실제 키보드 키를 의미하는데 반하여 charCode는 키의 ASCII 값을 반환한다. 이 두 값들은 반드시 동일하지 않을 수 있다. 예를 들어 소문자 'a'와 대문자 'A'는 같은 keyCode를 가지고 있다. 왜냐하면 사용자는 같은 키를 누르기 때문이다. 하지만 다른 charCode를 가지는 것은 왜냐하면 결과 문자가 다르기 때문이다.</p> +<p>charCode가 해석되는 브라우저의 방법은 일관되게 적용되는 방법이 아니다. 예를 들어 Internet Explorer 와 Opera는 charCode를 지원하지 않는다. 그런데 그들은 keyCode안에 문자 정보를 준다. onkeypress만 아니라 onkeydown 와 onkeyup의 keyCode가 키 정보를 가지고 있다. Firefox 는 "which", 문자를 구별하기 위해 다른 단어를 사용한다. </p> +<p>더 나아가 키 이벤트들을 다루는 것에 관해서는 <span style="line-height: 1.5;"> </span><a href="/en-US/docs/DOM/Event/UIEvent/KeyboardEvent" style="line-height: 1.5;" title="https://developer.mozilla.org/en-US/docs/DOM/Event/UIEvent/KeyEvent">Keyboard Events</a>에 대한<span style="line-height: 1.5;"> </span><span style="line-height: 1.5;">Mozilla 문서를 참조하시오.</span></p> +<p>{{ draft() }}</p> +<h2 id="Example:_Dragging_images_around" name="Example:_Dragging_images_around">예제: 이미지 주변에 드래그하기</h2> +<p>다음 예제는 페이지 근처의 firefox의 이미지를 이동할 수 있다.</p> +<pre class="brush:js"><!DOCTYPE html> +<html> +<head> +<style> +img { position: absolute; } +</style> + +<script> +window.onload = function() { + + movMeId = document.getElementById("ImgMov"); + movMeId.style.top = "80px"; + movMeId.style.left = "80px"; + + document.onmousedown = coordinates; + document.onmouseup = mouseup; + + function coordinates(e) { + if (e == null) { e = window.event;} + + // <span style="font-size: 1rem;">e.srcElement은 IE에서 타겟 엘리먼트로 가지고 있고 반면 </span><span style="font-size: 1rem;">e.target은 firefox에서 타겟 엘리먼트로 가지고 있다.</span> +// 두 프로퍼티들은 이벤트가 일어난 HTML 엘리먼트를 반환한다. + var sender = (typeof( window.event ) != "undefined" ) ? e.srcElement : e.target; + + if (sender.id=="ImgMov") { + mouseover = true; + pleft = parseInt(movMeId.style.left); + ptop = parseInt(movMeId.style.top); + xcoor = e.clientX; + ycoor = e.clientY; + document.onmousemove = moveImage; + return false; + } + return false; + } + + function moveImage(e) { + if (e == null) { e = window.event; } + movMeId.style.left = pleft+e.clientX-xcoor+"px"; + movMeId.style.top = ptop+e.clientY-ycoor+"px"; + return false; + } + + function mouseup(e) { + document.onmousemove = null; + } +} +</script> +</head> + +<body> + <img id="ImgMov" src="http://placehold.it/100x100&text=JS" width="64" height="64"> + <p>Drag and drop around the image in this page.</p> +</body> + +</html></pre> +<h2 id="Example:_Resizing_things" name="Example:_Resizing_things">예제: 크기 조정하기</h2> +<div> + <p>이미지 크기 조정하는 예제(실제 이미지가 크기가 조정되는 것이 아니고, 이미지의 랜더링만 되는 것이다.)</p> + <pre class="brush:js"> <!DOCTYPE html> + <html> + <head> + <style> + #resizeImage { + margin-left: 100px; + } + </style> + <script> + window.onload = function() { + + var resizeId = document.getElementById("resizeImage"); + var resizeStartCoordsX, + resizeStartCoordsY, + resizeEndCoordsX, + resizeEndCoordsY; + + var resizeEndCoords; + var resizing = false; + + document.onmousedown = coordinatesMousedown; + document.onmouseup = coordinatesMouseup; + + function coordinatesMousedown(e) { + if (e == null) { + e = window.event; + } + + var element = (typeof( window.event ) != 'undefined' ) ? e.srcElement : e.target; + + if (element.id == "resizeImage") { + resizing = true; + resizeStartCoordsX = e.clientX; + resizeStartCoordsY = e.clientY; + } + return false; + } + + function coordinatesMouseup(e) { + if (e == null) { + e = window.event; + } + + if (resizing === true) { + var currentImageWidth = parseInt(resizeId.width); + var currentImageHeight = parseInt(resizeId.height); + + resizeEndCoordsX = e.clientX; + resizeEndCoordsY = e.clientY; + + resizeId.style.height = currentImageHeight - (resizeStartCoordsY - resizeEndCoordsY) + 'px'; + resizeId.style.width = currentImageWidth - (resizeStartCoordsX - resizeEndCoordsX) + 'px'; + + resizing = false; + } + return false; + } + } + </script> + </head> + + <body> + <img id="resizeImage" src="http://upload.wikimedia.org/wikipedia/commons/e/e7/Mozilla_Firefox_3.5_logo_256.png" +width="64" height="64"> + <p>Click on the image and drag for resizing.</p> + </body> + + </html></pre> +</div> +<h2 id="Example:_Drawing_Lines" name="Example:_Drawing_Lines">예제: 라인 그리기</h2> +<pre class="brush: html"><!DOCTYPE html> +<html> +<head> +<script> +function linedraw(ax,ay,bx,by) +{ + if(ay>by) + { + bx=ax+bx; + ax=bx-ax; + bx=bx-ax; + by=ay+by; + ay=by-ay; + by=by-ay; + } + var calc=Math.atan((ay-by)/(bx-ax)); + calc=calc*180/Math.PI; + var length=Math.sqrt((ax-bx)*(ax-bx)+(ay-by)*(ay-by)); + document.body.innerHTML += "<div id='line' style='height:" + length + "px;width:1px;background-color:black;position:absolute;top:" + (ay) + "px;left:" + (ax) + "px;transform:rotate(" + calc + "deg);-ms-transform:rotate(" + calc + "deg);transform-origin:0% 0%;-moz-transform:rotate(" + calc + "deg);-moz-transform-origin:0% 0%;-webkit-transform:rotate(" + calc + "deg);-webkit-transform-origin:0% 0%;-o-transform:rotate(" + calc + "deg);-o-transform-origin:0% 0%;'></div>" +} +</script> +</head> +<body onload="linedraw(200,400,500,900);"> <!--당신의 좌표 교체하기 --> +</body> +</html></pre> +<p> </p> diff --git a/files/ko/web/javascript/언어_리소스/index.html b/files/ko/web/javascript/언어_리소스/index.html new file mode 100644 index 0000000000..5743a54e24 --- /dev/null +++ b/files/ko/web/javascript/언어_리소스/index.html @@ -0,0 +1,155 @@ +--- +title: 자바스크립트 언어 자료 +slug: Web/JavaScript/언어_리소스 +tags: + - Advanced + - 자바스크립트 +translation_of: Web/JavaScript/Language_Resources +--- +<div>{{JsSidebar}}</div> + +<p><strong>ECMAScript</strong>는 <a href="/ko/docs/Web/JavaScript">자바스크립트</a>의 토대를 구성하는 스크립트 언어입니다. ECMAScript는 <a href="http://www.ecma-international.org/" title="http://www.ecma-international.org/">ECMA International</a> 표준화 기구에 의해서 <strong>ECMA-262 및 ECMA-402 스펙</strong>에서 표준화되었습니다. 다음은 현재까지 승인됐거나 작업 중인 ECMAScript 표준입니다:</p> + +<table class="standard-table"> + <tbody> + <tr> + <th>이름</th> + <th>링크</th> + <th>출시 날짜</th> + <th>설명</th> + </tr> + <tr> + <th colspan="4">현재판</th> + </tr> + <tr> + <td>ECMA-262 10<sup>th</sup> Edition</td> + <td><a href="https://tc39.github.io/ecma262/">Working draft</a></td> + <td>2019</td> + <td>ECMAScript 2019 (제 10판), 명세 작업 중</td> + </tr> + <tr> + <td>ECMA-262 9<sup>th</sup> Edition</td> + <td><a href="http://ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf">PDF</a>, <a href="http://ecma-international.org/ecma-262/9.0/index.html#Title">HTML</a>, <br> + <a href="https://tc39.github.io/ecma262/">Working draft</a>, <a href="https://github.com/tc39/ecma262">repository</a></td> + <td>2018</td> + <td>ECMAScript 2018 (제 9판)</td> + </tr> + <tr> + <td>ECMA-402 5<sup>th</sup> Edition</td> + <td><a href="http://tc39.github.io/ecma402/">Working draft</a>, <a href="https://github.com/tc39/ecma402">repository</a></td> + <td>2018</td> + <td>ECMAScript 2018 국제화 API 표준</td> + </tr> + <tr> + <th colspan="4">폐기(Obsolete)/역사판</th> + </tr> + <tr> + <td>ECMA-262 (ES 1)</td> + <td><a href="http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%201st%20edition,%20June%201997.pdf">PDF</a></td> + <td>June 1997</td> + <td>ECMAScript 표준 원본.</td> + </tr> + <tr> + <td>ECMA-262 (ES 2)</td> + <td><a href="http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%202nd%20edition,%20August%201998.pdf">PDF</a></td> + <td>August 1998</td> + <td>ECMAScript 표준 제2판; 또한 ISO 표준 16262.</td> + </tr> + <tr> + <td>ECMA-262 (ES 3)</td> + <td><a href="http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%203rd%20edition,%20December%201999.pdf">PDF</a></td> + <td>December 1999</td> + <td>ECMAScript 표준 제3판; JavaScript 1.5에 해당.<br> + <a href="http://www.mozilla.org/js/language/E262-3-errata.html">errata</a> 참조</td> + </tr> + <tr> + <td>ECMA-262 (ES 5)</td> + <td><a href="http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262%205th%20edition%20December%202009.pdf">PDF</a></td> + <td>December 2009</td> + <td>ECMAScript 제5판<br> + <a href="http://wiki.ecmascript.org/doku.php?id=es3.1:es3.1_proposal_working_draft">ES5 errata</a> 및 <a href="/en-US/docs/JavaScript/ECMAScript_5_support_in_Mozilla" title="JavaScript/ECMAScript 5 support in Mozilla">ECMAScript 5 support in Mozilla</a> 참조</td> + </tr> + <tr> + <td>ECMA-357</td> + <td><a href="http://www.ecma-international.org/publications/files/ECMA-ST-WITHDRAWN/ECMA-357,%201st%20edition,%20June%202004.pdf">PDF</a></td> + <td>June 2004</td> + <td><a href="/en-US/docs/E4X" title="E4X">ECMAScript for XML (E4X)</a>.<br> + <a class="link-https" href="https://bugzilla.mozilla.org/attachment.cgi?id=169406">E4X errata</a> 참조.</td> + </tr> + <tr> + <td>ECMA-357 Edition 2</td> + <td><a href="http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-357.pdf">PDF</a></td> + <td>December 2005</td> + <td><a href="/en-US/docs/E4X" title="E4X">ECMAScript for XML (E4X)</a>.</td> + </tr> + <tr> + <td>ECMA-262 (ES 5.1)</td> + <td><a href="http://www.ecma-international.org/ecma-262/5.1/Ecma-262.pdf">PDF</a>, <a href="http://www.ecma-international.org/ecma-262/5.1/">HTML</a></td> + <td>June 2011</td> + <td>이 판은 국제화 표준 <a href="http://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=55755">ISO/IEC 16262:2011</a> 제3판과 완전히 정렬됨.<br> + ES5 errata 수정 포함, 새로운 기능은 없음.</td> + </tr> + <tr> + <td>ECMA-402 1.0</td> + <td><a href="http://ecma-international.org/ecma-402/1.0/ECMA-402.pdf">PDF</a>, <a href="http://ecma-international.org/ecma-402/1.0/index.html">HTML</a></td> + <td>December 2012</td> + <td>ECMAScript 국제화 API 1.0.</td> + </tr> + <tr> + <td>ECMA-262 2015 (ES 6)</td> + <td><a href="http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf">PDF</a>, <a href="http://www.ecma-international.org/ecma-262/6.0/index.html">HTML</a></td> + <td>June 2015</td> + <td>ECMAScript 2015 (제6판).</td> + </tr> + <tr> + <td>ECMA-402 2.0</td> + <td><a href="http://www.ecma-international.org/ecma-402/2.0/ECMA-402.pdf">PDF</a></td> + <td>June 2015</td> + <td>ECMAScript 국제화 API 2.0.</td> + </tr> + <tr> + <td>ECMA-262 2016 (ES 7)</td> + <td><a href="http://tc39.github.io/ecma262/2016/">HTML</a></td> + <td>June 2016</td> + <td>ECMAScript 2016 (제7판).</td> + </tr> + <tr> + <td>ECMA-402 3.0</td> + <td><a href="http://tc39.github.io/ecma402/2016/">HTML</a></td> + <td>June 2016</td> + <td>ECMAScript 국제화 API 3.0. 나중(올해 6월)에 승인될.</td> + </tr> + <tr> + <td>ECMA-262 2017 (ES 8)</td> + <td><a href="http://www.ecma-international.org/ecma-262/8.0">HTML</a></td> + <td>June 2017</td> + <td>ECMAScript 2017 (제8판).</td> + </tr> + <tr> + <td>ECMA-402 4<sup>th</sup> Edition</td> + <td><a href="http://www.ecma-international.org/ecma-402/4.0">HTML</a></td> + <td>June 2017</td> + <td>ECMAScript 국제화 API 4.0.</td> + </tr> + </tbody> +</table> + +<p>ECMAScript의 역사에 대한 자세한 정보는 <a href="http://en.wikipedia.org/wiki/ECMAScript" title="http://en.wikipedia.org/wiki/ECMAScript">Wikipedia ECMAScript entry</a>를 살펴보세요.</p> + +<p>여러분은 코드네임 "Harmony"로 불리우는 ECMAScript의 다음 개정에 참여하거나 그냥 진행상황을 확인할 수도 있습니다. 또한 ECMAScript 국제화 API 스펙도 공개 위키와<span style="line-height: 1.5;"> </span><a href="http://www.ecmascript.org/community.php" style="line-height: 1.5;" title="http://www.ecmascript.org/community.php">ecmascript.org</a> 에 연결된<span style="line-height: 1.5;"> </span><a class="link-https" href="https://mail.mozilla.org/listinfo/es-discuss" style="line-height: 1.5;" title="https://mail.mozilla.org/listinfo/es-discuss">es-discuss mailing list</a>에서도 확인할 수 있습니다.</p> + +<h2 id="구현">구현</h2> + +<ul> + <li><a href="/en-US/docs/SpiderMonkey" title="SpiderMonkey">SpiderMonkey</a> - 파이어폭스 포함 여러 Mozilla 제품에 사용되는 자바스크립트 엔진;</li> + <li><a href="/en-US/docs/Rhino" title="Rhino">Rhino</a> - 자바로 작성된 자바스크립트 엔진;</li> + <li><a href="/en-US/docs/Tamarin" title="Tamarin">Tamarin</a> - (어도비® 플래쉬® 재생기에서 사용되는) 액션스크립트 가상머신;</li> + <li><a href="http://en.wikipedia.org/wiki/List_of_ECMAScript_engines" title="http://en.wikipedia.org/wiki/List_of_ECMAScript_engines">Other implementations</a> (위키피디아).</li> +</ul> + +<h2 id="관련_항목">관련 항목</h2> + +<ul> + <li><a href="http://brendaneich.com/" title="http://brendaneich.com/">Brendan Eich's blog</a>. Brendan은 자바스크립트와 SpiderMonkey JS 엔진을 만든 사람입니다. 그는 여전히 ECMA 실행그룹과 함께 자바스크립트 언어를 발전시키는데 함께 하고 있습니다.</li> + <li><a href="http://dmitrysoshnikov.com/" title="http://dmitrysoshnikov.com/">Dmitry Soshnikov의 ECMA-262 Edition 3와 5에 대한 분석</a></li> +</ul> |