diff options
Diffstat (limited to 'files/tr/web/javascript/reference')
82 files changed, 17152 insertions, 0 deletions
diff --git a/files/tr/web/javascript/reference/classes/index.html b/files/tr/web/javascript/reference/classes/index.html new file mode 100644 index 0000000000..77a29ab167 --- /dev/null +++ b/files/tr/web/javascript/reference/classes/index.html @@ -0,0 +1,276 @@ +--- +title: Classes +slug: Web/JavaScript/Reference/Classes +tags: + - Classes + - Constructors + - ECMAScript6 + - Inheritance + - Intermediate + - JavaScript + - Kalıtım + - NeedsTranslation + - TopicStub + - sınıf +translation_of: Web/JavaScript/Reference/Classes +--- +<div>{{JsSidebar("Classes")}}</div> + +<p id="ECMAScript_2015_ile_tanıtılan_Javascript_sınıfları_aslında_halihazırdaki_prototype_temelli_kalıtımın_sözdizi_daha_kolaylaştırılmış_halidir._Class_sözdizimi_yeni_bir_nesne_tabanlı_Javascript_modeli_sunmamaktadır.">ECMAScript 2015 ile tanıtılan Javascript sınıfları, aslında halihazırdaki prototype temelli kalıtımın, sözdizi daha kolaylaştırılmış halidir. Class sözdizimi yeni bir nesne tabanlı Javascript modeli <u>sunmamaktadır</u>.</p> + +<h2 id="Sınıf_tanımlama">Sınıf tanımlama</h2> + +<p><br> + Aslında sınıflar class oluşturmak için kullanılan özel <a href="/tr/docs/Web/JavaScript/Reference/Functions">fonksiyonlar</a>dır. Javascript sınıfları <a href="/tr/docs/Web/JavaScript/Reference/Operators/function">klasik fonksiyon tanımladığınız</a> gibi tanımlayabilir veya fonksiyonlar ile yapabildiğiniz gibi bir <a href="/tr/docs/Web/JavaScript/Reference/Statements/class">değişkene atayabilirsiniz</a>.</p> + +<h3 id="Sınıf_Tanımları">Sınıf Tanımları</h3> + +<p>Bir sınıf tanımlamanın bir yolu <code>class</code> ifadesini sınıf adınızla birlikte kullanmaktır. (Örn: Dikdortgen)</p> + +<pre class="brush: js">class Dikdortgen { + constructor(yukseklik, genislik) { + this.yukseklik = yukseklik; + this.genislik = genislik; + } +}</pre> + +<h4 id="Erişim">Erişim</h4> + +<p>Sınıf tanımları ve fonksiyon tanımları arasındaki önemli bir fark, fonksiyonlara tanımlandığı satırdan önce {{Glossary("Hoisting", "erişim sağlanabilir")}}. Sınıflara tanımlandığı satırdan önce erişilemezler. Önce sınıfları tanımlamanız ve ardından ona erişmeniz gerekir. Aksi halde aşağıdakine benzer bir hatayla karşılaşırsınız. {{jsxref("ReferenceError")}}:</p> + +<pre class="brush: js example-bad">var p = new Galeri(); // ReferenceError + +class Galeri {} +</pre> + +<h3 id="Class_expressions">Class expressions</h3> + +<p>Bir class'ı tanımlamanın bir başka yolu ise <strong>"class"</strong> ifadesidir. Class ifadelerine isim verilebilir. İsimli olan bir class ifadesi class body'sinin localidir.</p> + +<p> </p> + +<pre class="brush: js">// isimsiz class +var Dikdortgen = class { + constructor(yukseklik, genislik) { + this.yukseklik= yukseklik; + this.genislik= genislik; + } +}; + +// isimli class +var Dikdortgen = class Dikdortgen { + constructor(yukseklik, genislik) { + this.yukseklik= yukseklik; + this.genislik= genislik; + } +}; +</pre> + +<h2 id="Class_body_and_method_definitions">Class body and method definitions</h2> + +<p>The body of a class is the part that is in curly brackets <code>{}</code>. This is where you define class members, such as methods or constructors.</p> + +<h3 id="Strict_mode">Strict mode</h3> + +<p>The bodies of <em>class declarations</em> and <em>class expressions</em> are executed in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>.</p> + +<h3 id="Constructor">Constructor</h3> + +<p>The <code><a href="/en-US/docs/Web/JavaScript/Reference/Classes/constructor">constructor</a></code> method is a special method for creating and initializing an object created with a <code>class</code>. There can only be one special method with the name "constructor" in a class. A {{jsxref("SyntaxError")}} will be thrown if the class contains more than one occurrence of a <code>constructor</code> method.</p> + +<p>A constructor can use the <code>super</code> keyword to call the constructor of a parent class.</p> + +<h3 id="Prototype_methods">Prototype methods</h3> + +<p>See also <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions">method definitions</a>.</p> + +<pre class="brush: js">class Polygon { + constructor(height, width) { + this.height = height; + this.width = width; + } + + get area() { + return this.calcArea(); + } + + calcArea() { + return this.height * this.width; + } +}</pre> + +<h3 id="Static_methods">Static methods</h3> + +<p>The <code><a href="/en-US/docs/Web/JavaScript/Reference/Classes/static">static</a></code> keyword defines a static method for a class. Static methods are called without <a href="https://developer.mozilla.org/en-US/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>their class and are also <strong>not </strong>callable when the class is instantiated. Static methods are often used to create utility functions for an application.</p> + +<pre class="brush: js">class Point { + constructor(x, y) { + this.x = x; + this.y = y; + } + + static distance(a, b) { + const dx = a.x - b.x; + const dy = a.y - b.y; + + return Math.sqrt(dx*dx + dy*dy); + } +} + +const p1 = new Point(5, 5); +const p2 = new Point(10, 10); + +console.log(Point.distance(p1, p2));</pre> + +<h2 id="Sub_classing_with_extends">Sub classing with <code>extends</code></h2> + +<p>The <code><a href="/en-US/docs/Web/JavaScript/Reference/Classes/extends">extends</a></code> keyword is used in <em>class declarations</em> or <em>class expressions</em> to create a class as a child of another class.</p> + +<pre class="brush: js">class Animal { + constructor(name) { + this.name = name; + } + + speak() { + console.log(this.name + ' makes a noise.'); + } +} + +class Dog extends Animal { + speak() { + console.log(this.name + ' barks.'); + } +} +</pre> + +<h2 id="Super_class_calls_with_super">Super class calls with <code>super</code></h2> + +<p>The <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/super">super</a></code> keyword is used to call functions on an object's parent.</p> + +<pre class="brush: js">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.'); + } +} +</pre> + +<h2 id="Mix-ins">Mix-ins</h2> + +<p>Abstract subclasses or <em>mix-ins</em> are templates for classes. An ECMAScript class can only have a single superclass, so multiple inheritance from tooling classes, for example, is not possible. The functionality must be provided by the superclass.</p> + +<p>A function with a superclass as input and a subclass extending that superclass as output can be used to implement mix-ins in ECMAScript:</p> + +<pre class="brush: js">var CalculatorMixin = Base => class extends Base { + calc() { } +}; + +var RandomizerMixin = Base => class extends Base { + randomize() { } +}; +</pre> + +<p>A class that uses these mix-ins can then be written like this:</p> + +<pre class="brush: js">class Foo { } +class Bar extends CalculatorMixin(RandomizerMixin(Foo)) { }</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-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="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>Edge</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(42.0)}}<sup>[1]</sup><br> + {{CompatChrome(49.0)}}</td> + <td>45</td> + <td>13</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatSafari(9.0)}}</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> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>45</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>9</td> + <td>{{CompatChrome(42.0)}}<sup>[1]</sup><br> + {{CompatChrome(49.0)}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Requires strict mode. Non-strict mode support is behind the flag "Enable Experimental JavaScript", disabled by default.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions">Functions</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/Operators/class"><code>class</code> expression</a></li> + <li>{{jsxref("Operators/super", "super")}}</li> + <li><a href="https://hacks.mozilla.org/2015/07/es6-in-depth-classes/">Blog post: "ES6 In Depth: Classes"</a></li> +</ul> diff --git a/files/tr/web/javascript/reference/classes/static/index.html b/files/tr/web/javascript/reference/classes/static/index.html new file mode 100644 index 0000000000..2214e7e227 --- /dev/null +++ b/files/tr/web/javascript/reference/classes/static/index.html @@ -0,0 +1,127 @@ +--- +title: static +slug: Web/JavaScript/Reference/Classes/static +tags: + - metod + - statik + - sınıf + - tanım +translation_of: Web/JavaScript/Reference/Classes/static +--- +<div>{{jsSidebar("Classes")}}</div> + +<p><strong>static </strong>anahtar kelimesi, bir sınıf için statik bir metod tanımlar.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">static metodAdi() { ... }</pre> + +<h2 id="Description">Description</h2> + +<p>Statik metodlar, kendi sınıfları gerçeklenmeden çağırılır ve aynı zamanda sınıf gerçeklendiği anda çağrılabilir olma özelliklerini yitirirler. Statik metodlar, bir uygulama için yardımcı fonksiyonlar tanımlamak için kullanılırlar.</p> + +<h2 id="Examples">Examples</h2> + +<p>Aşağıdaki örnek, bir statik metodun sınıfa nasıl entegre edildiğini ve statik metodu olan başka bir sınıfın onun içerisinde nasıl kullanıldığını gösteriyor. Son olarak, statik bir metodun nasıl çağırıldığını ve çağrılma özelliğini nasıl yitirdiğini gösteriyor. </p> + +<pre class="brush: js">class Triple { + static triple(n) { + n = n || 1; //should not be a bitwise operation + 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 (not affected by parent's instantiation) +console.log(tp.triple()); // 'tp.triple is not a function'.</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-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="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</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(42.0)}}</td> + <td>{{CompatGeckoDesktop(45)}}</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> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile(45)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatChrome(42.0)}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</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/tr/web/javascript/reference/errors/index.html b/files/tr/web/javascript/reference/errors/index.html new file mode 100644 index 0000000000..c295fccea6 --- /dev/null +++ b/files/tr/web/javascript/reference/errors/index.html @@ -0,0 +1,31 @@ +--- +title: JavaScript error reference +slug: Web/JavaScript/Reference/Errors +tags: + - Debugging + - Error + - Errors + - Exception + - JavaScript + - NeedsTranslation + - TopicStub + - exceptions +translation_of: Web/JavaScript/Reference/Errors +--- +<p>{{jsSidebar("Errors")}}</p> + +<p>Below, you'll find a list of errors which are thrown by JavaScript. These errors can be a helpful debugging aid, but the reported problem isn't always immediately clear. The pages below will provide additional details about these errors. Each error is an object based upon the {{jsxref("Error")}} object, and has a <code>name</code> and a <code>message</code>.</p> + +<p>Errors displayed in the Web console may include a link to the corresponding page below to help you quickly comprehend the problem in your code.</p> + +<h2 id="List_of_errors">List of errors</h2> + +<p>In this list, each page is listed by name (the type of error) and message (a more detailed human-readable error message). Together, these two properties provide a starting point toward understanding and resolving the error. For more information, follow the links below!</p> + +<p>{{ListSubPages("/en-US/docs/Web/JavaScript/Reference/Errors")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong">What went wrong? Troubleshooting JavaScript</a>: Beginner's introductory tutorial on fixing JavaScript errors.</li> +</ul> diff --git a/files/tr/web/javascript/reference/errors/missing_semicolon_before_statement/index.html b/files/tr/web/javascript/reference/errors/missing_semicolon_before_statement/index.html new file mode 100644 index 0000000000..2a811725bf --- /dev/null +++ b/files/tr/web/javascript/reference/errors/missing_semicolon_before_statement/index.html @@ -0,0 +1,71 @@ +--- +title: 'SyntaxError: missing ; before statement' +slug: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement +tags: + - JavaScript + - Noktalı virgül + - Sentaks Hatası +translation_of: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement +--- +<div> +<p>{{jsSidebar("Errors")}}</p> + +<h2 id="Mesaj">Mesaj</h2> + +<pre>Syntax Error: Missing ; before statement +//Sentaks Hatası: ifadeden önce ; eksik +</pre> + +<h2 id="Hata_Tipi">Hata Tipi</h2> + +<p>{{jsxref("SyntaxError")}}.</p> + +<h2 id="Ne_Ters_Gitti">Ne Ters Gitti?</h2> + +<p>Kodunuzda bir yerlerde noktalı virgül (<code>;</code>) eksik. <a href="/en-US/docs/Web/JavaScript/Reference/Statements">JavaScript ifadeleri</a> noktalı virgül ile sonlandırılmalıdır. Bu ifadelerden bazılarına <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion">otomatik noktalı virgül eklenmektedir (ASI)</a>, fakat bu durumda, JavaScript'in kaynak kodunu doğru bir şekilde çözümleyebilmesi için noktalı virgülü sizin eklemeniz gerekmektedir. </p> + +<p>Bununla birlikte, çoğunlukla bu hata, başka bir hatanın sonucudur, <code>var</code> ifadesinin yanlış kullanımı, string ifadelerinin yazımında tırnakların yanlış kullanımı sebebiyle olabilir, belki de bir yerlerde fazladan bir parantez unuttunuz. Bu hata ile karşılaştığınızda, sentaksınızı kontrol edin, yazım hatalarınızı gözden geçirin.<br> + </p> + +<h2 id="Örnekler">Örnekler</h2> + +<h3 id="Kaçınılan_metin_ifadeleri">Kaçınılan metin ifadeleri</h3> + +<p>Metin ifadelerindeki tırnak kullanımında, metin içinde yer almakta olan tırnakları görüntülemek için önlerine \ yatay çizgi koymalısınız ki JavaScript motoru, sizin metin ifadenizin çoktan bitmiş olduğu izlenimine kapılmasın. Örnek olarak:</p> + +<pre>var foo = 'Tomris'in barı'; +Sentaks Hatası: ifadeden önce ; eksik</pre> + +<p>Çift tırnak kullanarak tek tırnağın yanlış kullanımından kaçınabilirsiniz. </p> + +<pre>var foo = "Tomris'in barı"; +var foo = 'Tomris\'in barı'; +</pre> + +<h3 id="var_ile_Özellikleri_Deklare_Etmek">var ile Özellikleri Deklare Etmek</h3> + +<p>var ile bir nesneye veya diziye ait bir özellik <strong>tanımlayamazsınız</strong>. </p> + +<pre>var nesne = {}; +var nesne.foo = 'hey'; Sentaks Hatası: ifadeden önce ; eksik + +var dizi = []; +var dizi[0] = 'selam'; Sentaks Hatası: ifadeden önce ; eksik +</pre> + +<p>Bunun yerine, <code>var</code> anahtar sözcüğünü kaldırın:</p> + +<pre>var nesne = {}; +nesne.foo = 'hey'; + +var dizi= []; +dizi[0] = 'selam'; +</pre> + +<h2 id="Ayrıca_Göz_Atın">Ayrıca Göz Atın</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion">Otomatik noktalı virgül eklenmesi (ASI)</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements">JavaScript ifadeleri</a></li> +</ul> +</div> diff --git a/files/tr/web/javascript/reference/functions/arrow_functions/index.html b/files/tr/web/javascript/reference/functions/arrow_functions/index.html new file mode 100644 index 0000000000..68d6fb3cc7 --- /dev/null +++ b/files/tr/web/javascript/reference/functions/arrow_functions/index.html @@ -0,0 +1,359 @@ +--- +title: Arrow functions +slug: Web/JavaScript/Reference/Functions/Arrow_functions +translation_of: Web/JavaScript/Reference/Functions/Arrow_functions +--- +<div>{{jsSidebar("Functions")}}</div> + +<div>Arrow fonksiyonlar normal fonksiyonların kısa yoldan yazılabilen türüdür ve kendi içerisinde <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">this</a></code>, <a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a>, <a href="/en-US/docs/Web/JavaScript/Reference/Operators/super">super</a>, ya da <a href="/en-US/docs/Web/JavaScript/Reference/Operators/new.target">new.target</a> erişimine sahip değildir. Bu fonksiyon tanımlaması özellikle methodsuz fonksiyonlar için çok uygundur. Constructor olarak kullanılamaz. </div> + +<h2 id="Söz_Dizimi">Söz Dizimi</h2> + +<h3 id="Temel_Söz_Dizimi">Temel Söz Dizimi</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> +// buna eşittir: <strong>(</strong><em>param1</em>, <em>param2</em>, …, <em>paramN</em><strong>)</strong> => { return <em>expression</em>; } + +// Eğer tek parametre var ise parantezsiz kullanılabilir: +<em>(singleParam)</em> <strong>=> {</strong> <em>statements</em> <strong>}</strong> +<em>singleParam</em> <strong>=></strong> { <em>statements </em>} +<em>singleParam</em> <strong>=></strong> <em>expression</em> + + +// Parametre beklenmeyen durumlarda parantez çifti kullanılmalıdır +() => { <em>statements</em> } +</pre> + +<h3 id="İleri_Düzey_Söz_Dizimi">İleri Düzey Söz Dizimi</h3> + +<pre class="syntaxbox notranslate">// Parantez çifti kullanılarak obje tipi veri dönüşü yapılır. +<em>params</em> => ({<em>foo: bar</em>}) + +// <a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">Rest parameters</a> ve <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters">default parameters</a> desteklenmektedir +(<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="/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">Destructuring</a> parametre listesi içinde de desteklenir +let f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c; +f(); +// 6 +</pre> + +<h2 id="Description">Description</h2> + +<p>Şunu da inceleyin <a href="https://hacks.mozilla.org/2015/06/es6-in-depth-arrow-functions/">"ES6 In Depth: Arrow functions" on hacks.mozilla.org</a>.</p> + +<p>Arrow fonksiyonlarının iki dikkat çekici özelliği vardır: daha kısa fonksiyonlara ihtiyaç ve <code>this</code> anahtar kelimesinin kullanımı.</p> + +<h3 id="Kısa_fonksiyonlar">Kısa fonksiyonlar</h3> + +<pre class="brush: js notranslate">var materials = [ + 'Hydrogen', + 'Helium', + 'Lithium', + 'Beryllium' +]; + +materials.<a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a>(function(material) { + return material.length; +}); // [8, 6, 7, 9] + +materials.<a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a>((material) => { + return material.length; +}); // [8, 6, 7, 9] + +materials.<a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a>(({length}) => length); // [8, 6, 7, 9] +</pre> + +<h3 id="No_separate_this">No separate <code>this</code></h3> + +<p>Arrow fonksiyonlara kadar, her yeni fonksiyon nasıl çağrıldığına bağlı olarak kendi this değerini belirlerdi:</p> + +<p>Constructor durumunda yeni bir nesne.<br> + Strict mode fonksiyon çağrılması durumunda undefined.<br> + Eğer fonksiyon "nesne metodu" olarak çağrılmışsa temel nesne.<br> + etc.<br> + <br> + Bu kullanım nesne-yönelimli programla içerisinde ideal kullanım değildi.</p> + +<pre class="brush: js notranslate">function Person() { + // The Person() fonksiyonu kendini temsil eden this değerini oluşturuyor + this.age = 0; + + setInterval(function growUp() { + // non-strict modda, growUp() fonksiyonuda her fonksiyon gibi + // kendi this değerini tanımlar + // bu sayede bir üstteki this değerine artık ulaşamıyor oluruz + this.age++; //bu işlem Person() fonksiyonundaki age değerine işlemez. + }, 1000); +} + +var p = new Person();</pre> + +<p>ECMAScript 3/5'te bu <code>this</code> sorunu this değerinin başka bir değişkene atanarak aşılabilmekteydi.</p> + +<pre class="brush: js notranslate">function Person() { + var that = this; + that.age = 0; + + setInterval(function growUp() { + // 'that' bir üstteki this değerine etki eder. + that.age++; + }, 1000); +}</pre> + +<p>Alternatif olarak, <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">bound function</a> tanımlaması yaparak önceden atanmış <code>this</code> değeri <code>growUp() </code>fonksiyonuna bu işlevi kazandırabilir.</p> + +<p>Fakat arrow fonksiyonlar kendi <code>this</code> değerine sahip değildir; kapsayıcı yürütme fonksiyonunun <code>this</code> değeri kullanılır. Böylelikle aşağıdaki örnekte olduğu gibi <code>setInterval</code>'e atanmış arrow fonksiyon kendi <code>this</code> değeri olmadığı için <code>Person()</code> fonksiyonunun this değerine etki eder.</p> + +<pre class="brush: js notranslate">function Person(){ + this.age = 0; + + setInterval(() => { + this.age++; // |this| person objesine atıfta bulunur + }, 1000); +} + +var p = new Person();</pre> + +<h4 id="Strict_mode_ile_ilişkisi">Strict mode ile ilişkisi</h4> + +<p>Kapsayıcı sözcüksel bağlamından gelen <code>this</code> değeri, <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a> kuralları uygulandığında görmezden gelinir</p> + +<pre class="brush: js notranslate">var f = () => { 'use strict'; return this; }; +f() === window; // or the global object</pre> + +<p>Diğer strict mode kuralları normal olarak geçerlidir.</p> + +<h4 id="Invoked_through_call_or_apply">Invoked through call or apply</h4> + +<p>Arrow fonksiyonların <code>this</code> değeri olmadığı için, <code>call()</code> ve <code>apply()</code> methotları sadece parametre verilebilir. <code>thisArg</code> görmezden gelinir.</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)); // This would log to 2 +console.log(adder.addThruCall(1)); // This would log to 2 still</pre> + +<h3 id="No_binding_of_arguments">No binding of <code>arguments</code></h3> + +<p>Arrow functions do not have their own <a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments"><code>arguments</code> object</a>. Thus, in this example, <code>arguments</code> is simply a reference to the the arguments of the enclosing scope:</p> + +<pre class="brush: js notranslate">var arguments = [1, 2, 3]; +var arr = () => arguments[0]; + +arr(); // 1 + +function foo(n) { + var f = () => arguments[0] + n; // <em>foo</em>'s implicit arguments binding. arguments[0] is n + return f(10); +} + +foo(1); // 2</pre> + +<p>Çoğu durumda <a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest parametreleri</a>, <code>arguments</code> nesnesinin iyi bir alternatifidir.</p> + +<pre class="brush: js notranslate">function foo(n) { + var f = (...args) => args[0] + n; + return f(10); +} + +foo(1); // 11</pre> + +<h3 id="Method_olarak_kullanılan_Arrow_fonksiyonları">Method olarak kullanılan Arrow fonksiyonları</h3> + +<p>As stated previously, arrow function expressions are best suited for non-method functions. Let's see what happens when we try to use them as methods:</p> + +<pre class="brush: js notranslate">'use strict'; +var obj = { + 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 {...}</pre> + +<p>Arrow functions do not have their own <code>this</code>. Another example involving {{jsxref("Object.defineProperty()")}}:</p> + +<pre class="brush: js notranslate">'use strict'; +var obj = { + a: 10 +}; + +Object.defineProperty(obj, 'b', { + get: () => { + console.log(this.a, typeof this.a, this); + return this.a + 10; // represents global object 'Window', therefore 'this.a' returns 'undefined' + } +}); +</pre> + +<h3 id="new_operatörü_kullanımı"><code>new</code> operatörü kullanımı</h3> + +<p>Arrow functions cannot be used as constructors and will throw an error when used with <code>new</code>.</p> + +<pre class="brush: js notranslate">var Foo = () => {}; +var foo = new Foo(); // TypeError: Foo is not a constructor</pre> + +<h3 id="prototype_özelliği_kullanımı"><code>prototype</code> özelliği kullanımı</h3> + +<p>Arrow fonksiyonlarının <code>prototype</code> özelliği yoktur.</p> + +<pre class="brush: js notranslate">var Foo = () => {}; +console.log(Foo.prototype); // undefined +</pre> + +<h3 id="yield_anahtarının_kullanımı"><code>yield</code> anahtarının kullanımı</h3> + +<p>The <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/yield">yield</a></code> keyword may not be used in an arrow function's body (except when permitted within functions further nested within it). As a consequence, arrow functions cannot be used as generators.</p> + +<h2 id="Function_body">Function body</h2> + +<p>Arrow functions can have either a "concise body" or the usual "block body".</p> + +<p>In a concise body, only an expression is specified, which becomes the explicit return value. In a block body, you must use an explicit <code>return</code> statement.</p> + +<pre class="brush: js notranslate">var func = x => x * x; +// concise body syntax, implied "return" + +var func = (x, y) => { return x + y; }; +// with block body, explicit "return" needed +</pre> + +<h2 id="Returning_object_literals">Returning object literals</h2> + +<p>Keep in mind that returning object literals using the concise body syntax <code>params => {object:literal}</code> will not work as expected.</p> + +<pre class="brush: js notranslate">var func = () => { foo: 1 }; +// Calling func() returns undefined! + +var func = () => { foo: function() {} }; +// SyntaxError: function statement requires a name</pre> + +<p>This is because the code inside braces ({}) is parsed as a sequence of statements (i.e. <code>foo</code> is treated like a label, not a key in an object literal).</p> + +<p>Remember to wrap the object literal in parentheses.</p> + +<pre class="brush: js notranslate">var func = () => ({foo: 1});</pre> + +<h2 id="Line_breaks">Line breaks</h2> + +<p>An arrow function cannot contain a line break between its parameters and its arrow.</p> + +<pre class="brush: js notranslate">var func = () + => 1; +// SyntaxError: expected expression, got '=>'</pre> + +<h2 id="Parsing_order">Parsing order</h2> + +<p>Although the arrow in an arrow function is not an operator, arrow functions have special parsing rules that interact differently with <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">operator precedence</a> compared to regular functions.</p> + +<pre class="brush: js notranslate">let callback; + +callback = callback || function() {}; // ok + +callback = callback || () => {}; +// SyntaxError: invalid arrow-function arguments + +callback = callback || (() => {}); // ok +</pre> + +<h2 id="More_examples">More examples</h2> + +<pre class="brush: js notranslate">// An empty arrow function returns undefined +let empty = () => {}; + +(() => 'foobar')(); +// Returns "foobar" +// (this is an Immediately Invoked Function Expression +// see 'IIFE' in glossary) + +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] + +// More concise promise chains +promise.then(a => { + // ... +}).then(b => { + // ... +}); + +// Parameterless arrow functions that are visually easier to parse +setTimeout( () => { + console.log('I happen sooner'); + setTimeout( () => { + // deeper code + console.log('I happen later'); + }, 1); +}, 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('ES2015', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.functions.arrow_functions")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="https://hacks.mozilla.org/2015/06/es6-in-depth-arrow-functions/">"ES6 In Depth: Arrow functions" on hacks.mozilla.org</a></li> +</ul> diff --git a/files/tr/web/javascript/reference/functions/index.html b/files/tr/web/javascript/reference/functions/index.html new file mode 100644 index 0000000000..0b67f9aa30 --- /dev/null +++ b/files/tr/web/javascript/reference/functions/index.html @@ -0,0 +1,596 @@ +--- +title: Functions +slug: Web/JavaScript/Reference/Functions +tags: + - Constructor + - Function + - Functions + - JavaScript + - NeedsTranslation + - Parameter + - TopicStub + - parameters +translation_of: Web/JavaScript/Reference/Functions +--- +<div>{{jsSidebar("Functions")}}</div> + +<p>Generally speaking, a function is a "subprogram" that can be <em>called</em> by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the <em>function body</em>. Values can be <em>passed</em> to a function, and the function will <em>return</em> a value.</p> + +<p>In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function">Function</a></code> objects.</p> + +<p>For more examples and explanations, see also the <a href="/en-US/docs/Web/JavaScript/Guide/Functions">JavaScript guide about functions</a>.</p> + +<h2 id="Description">Description</h2> + +<p>Every function in JavaScript is a <code>Function</code> object. See {{jsxref("Function")}} for information on properties and methods of <code>Function</code> objects.</p> + +<p>To return a value other than the default, a function must have a <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/return">return</a></code> statement that specifies the value to return. A function without a return statement will return a default value. In the case of a <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor">constructor</a> called with the <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/new">new</a></code> keyword, the default value is the value of its <code>this</code> parameter. For all other functions, the default return value is {{jsxref("undefined")}}.</p> + +<p>The parameters of a function call are the function's <em>arguments</em>. Arguments are passed to functions <em>by value</em>. If the function changes the value of an argument, this change is not reflected globally or in the calling function. However, object references are values, too, and they are special: if the function changes the referred object's properties, that change is visible outside the function, as shown in the following example:</p> + +<pre class="brush: js">/* Declare the function 'myFunc' */ +function myFunc(theObject) { + theObject.brand = "Toyota"; +} + +/* + * Declare variable 'mycar'; + * create and initialize a new Object; + * assign reference to it to 'mycar' + */ +var mycar = { + brand: "Honda", + model: "Accord", + year: 1998 +}; + +/* Logs 'Honda' */ +console.log(mycar.brand); + +/* Pass object reference to the function */ +myFunc(mycar); + +/* + * Logs 'Toyota' as the value of the 'brand' property + * of the object, as changed to by the function. + */ +console.log(mycar.brand); +</pre> + +<p>The <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this"><code>this</code> keyword</a> does not refer to the currently executing function, so you must refer to <code>Function</code> objects by name, even within the function body.</p> + +<h2 id="Defining_functions">Defining functions</h2> + +<p>There are several ways to define functions:</p> + +<h3 id="The_function_declaration_(function_statement)">The function declaration (<code>function</code> statement)</h3> + +<p>There is a special syntax for declaring functions (see <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function">function statement</a> for details):</p> + +<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>The function name.</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd> +</dl> + +<dl> + <dt><code>statements</code></dt> + <dd>The statements comprising the body of the function.</dd> +</dl> + +<h3 id="The_function_expression_(function_expression)">The function expression (<code>function</code> expression)</h3> + +<p>A function expression is similar to and has the same syntax as a function declaration (see <a href="/en-US/docs/Web/JavaScript/Reference/Operators/function">function expression</a> for details). A function expression may be a part of a larger expression. One can define "named" function expressions (where the name of the expression might be used in the call stack for example) or "anonymous" function expressions. Function expressions are not <em>hoisted</em> onto the beginning of the scope, therefore they cannot be used before they appear in the code.</p> + +<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>The function name. Can be omitted, in which case the function becomes known as an anonymous function.</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd> + <dt><code>statements</code></dt> + <dd>The statements comprising the body of the function.</dd> +</dl> + +<p>Here is an example of an <strong>anonymous</strong> function expression (the <code>name</code> is not used):</p> + +<pre class="brush: js">var myFunction = function() { + statements +}</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">var myFunction = function namedFunction(){ + statements +} +</pre> + +<p>One of the benefit of creating a named function expression is that in case we encounted 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 <strong>IIFE (<em>Immediately Invokable Function Expression</em>)</strong>.</p> + +<pre class="brush: js">(function() { + statements +})();</pre> + +<p>IIFE are function expressions that are invoked as soon as the function is declared.</p> + +<h3 id="The_generator_function_declaration_(function*_statement)">The generator function declaration (<code>function*</code> statement)</h3> + +<p>There is a special syntax for generator function declarations (see {{jsxref('Statements/function*', 'function* statement')}} for details):</p> + +<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>The function name.</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd> +</dl> + +<dl> + <dt><code>statements</code></dt> + <dd>The statements comprising the body of the function.</dd> +</dl> + +<h3 id="The_generator_function_expression_(function*_expression)">The generator function expression (<code>function*</code> expression)</h3> + +<p>A generator function expression is similar to and has the same syntax as a generator function declaration (see {{jsxref('Operators/function*', 'function* expression')}} for details):</p> + +<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>The function name. Can be omitted, in which case the function becomes known as an anonymous function.</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd> + <dt><code>statements</code></dt> + <dd>The statements comprising the body of the function.</dd> +</dl> + +<h3 id="The_arrow_function_expression_(>)">The arrow function expression (=>)</h3> + +<p>An arrow function expression has a shorter syntax and lexically binds its <code>this</code> value (see <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow functions</a> for details):</p> + +<pre class="syntaxbox">([param[, param]]) => { + statements +} + +param => expression +</pre> + +<dl> + <dt><code>param</code></dt> + <dd>The name of an argument. Zero arguments need to be indicated with <code>()</code>. For only one argument, the parentheses are not required. (like <code>foo => 1</code>)</dd> + <dt><code>statements or expression</code></dt> + <dd>Multiple statements need to be enclosed in brackets. A single expression requires no brackets. The expression is also the implicit return value of the function.</dd> +</dl> + +<h3 id="The_Function_constructor">The <code>Function</code> constructor</h3> + +<div class="note"> +<p><strong>Note:</strong> Using the <code>Function</code> constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.</p> +</div> + +<p>As all other objects, {{jsxref("Function")}} objects can be created using the <code>new</code> operator:</p> + +<pre class="syntaxbox">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>Zero or more names to be used by the function as formal parameters. Each must be a proper JavaScript identifier.</dd> +</dl> + +<dl> + <dt><code>functionBody</code></dt> + <dd>A string containing the JavaScript statements comprising the function body.</dd> +</dl> + +<p>Invoking the <code>Function</code> constructor as a function (without using the <code>new</code> operator) has the same effect as invoking it as a constructor.</p> + +<h3 id="The_GeneratorFunction_constructor">The <code>GeneratorFunction</code> constructor</h3> + +<div class="note"> +<p><strong>Note:</strong> <code>GeneratorFunction</code> is not a global object, but could be obtained from generator function instance (see {{jsxref("GeneratorFunction")}} for more detail).</p> +</div> + +<div class="note"> +<p><strong>Note:</strong> Using the <code>GeneratorFunction</code> constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.</p> +</div> + +<p>As all other objects, {{jsxref("GeneratorFunction")}} objects can be created using the <code>new</code> operator:</p> + +<pre class="syntaxbox">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>Zero or more names to be used by the function as formal argument names. Each must be a string that conforms to the rules for a valid JavaScript identifier or a list of such strings separated with a comma; for example "<code>x</code>", "<code>theValue</code>", or "<code>a,b</code>".</dd> +</dl> + +<dl> + <dt><code>functionBody</code></dt> + <dd>A string containing the JavaScript statements comprising the function definition.</dd> +</dl> + +<p>Invoking the <code>Function</code> constructor as a function (without using the <code>new</code> operator) has the same effect as invoking it as a constructor.</p> + +<h2 id="Function_parameters">Function parameters</h2> + +<h3 id="Default_parameters">Default parameters</h3> + +<p>Default function parameters allow formal parameters to be initialized with default values if no value or <code>undefined</code> is passed. For more details, see<a href="/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters"> default parameters</a>.</p> + +<h3 id="Rest_parameters">Rest parameters</h3> + +<p>The rest parameter syntax allows to represent an indefinite number of arguments as an array. For more details, see <a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest parameters</a>.</p> + +<h2 id="The_arguments_object">The <code>arguments</code> object</h2> + +<p>You can refer to a function's arguments within the function by using the <code>arguments</code> object. See <a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a>.</p> + +<ul> + <li><code><a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments">arguments</a></code>: An array-like object containing the arguments passed to the currently executing function.</li> + <li><code><a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/callee">arguments.callee</a></code> {{Deprecated_inline}}: The currently executing function.</li> + <li><code><a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/caller">arguments.caller</a></code> {{Obsolete_inline}} : The function that invoked the currently executing function.</li> + <li><code><a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/length">arguments.length</a></code>: The number of arguments passed to the function.</li> +</ul> + +<h2 id="Defining_method_functions">Defining method functions</h2> + +<h3 id="Getter_and_setter_functions">Getter and setter functions</h3> + +<p>You can define getters (accessor methods) and setters (mutator methods) on any standard built-in object or user-defined object that supports the addition of new properties. The syntax for defining getters and setters uses the object literal syntax.</p> + +<dl> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Functions/get">get</a></dt> + <dd> + <p>Binds an object property to a function that will be called when that property is looked up.</p> + </dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Functions/set">set</a></dt> + <dd>Binds an object property to a function to be called when there is an attempt to set that property.</dd> +</dl> + +<h3 id="Method_definition_syntax">Method definition syntax</h3> + +<p>Starting with ECMAScript 2015, you are able to define own methods in a shorter syntax, similar to the getters and setters. See <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions">method definitions</a> for more information.</p> + +<pre class="brush: js">var obj = { + foo() {}, + bar() {} +};</pre> + +<h2 id="Constructor_vs._declaration_vs._expression">Constructor vs. declaration vs. expression</h2> + +<p>Compare the following:</p> + +<p>A function defined with the <code>Function</code> <em>constructor</em> assigned to the variable <code>multiply:</code></p> + +<pre class="brush: js">var multiply = new Function('x', 'y', 'return x * y');</pre> + +<p>A <em>function declaration</em> of a function named <code>multiply</code>:</p> + +<pre class="brush: js">function multiply(x, y) { + return x * y; +} // there is no semicolon here +</pre> + +<p>A <em>function expression</em> of an anonymous function assigned to the variable <code>multiply:</code></p> + +<pre class="brush: js">var multiply = function(x, y) { + return x * y; +}; +</pre> + +<p>A <em>function expression</em> of a function named <code>func_name</code> assigned to the variable <code>multiply:</code></p> + +<pre class="brush: js">var multiply = function func_name(x, y) { + return x * y; +}; +</pre> + +<h3 id="Differences">Differences</h3> + +<p>All do approximately the same thing, with a few subtle differences:</p> + +<p>There is a distinction between the function name and the variable the function is assigned to. The function name cannot be changed, while the variable the function is assigned to can be reassigned. The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or <code>undefined</code> if the function name was previously declared via a <code>var</code> statement). For example:</p> + +<pre class="brush: js">var y = function x() {}; +alert(x); // throws an error +</pre> + +<p>The function name also appears when the function is serialized via <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString"><code>Function</code>'s toString method</a>.</p> + +<p>On the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope in which the function is declared.</p> + +<p>As the 4th example shows, the function name can be different from the variable the function is assigned to. They have no relation to each other. A function declaration also creates a variable with the same name as the function name. Thus, unlike those defined by function expressions, functions defined by function declarations can be accessed by their name in the scope they were defined in:</p> + +<p>A function defined by '<code>new Function'</code> does not have a function name. However, in the <a href="/en-US/docs/Mozilla/Projects/SpiderMonkey">SpiderMonkey</a> JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, <code>alert(new Function())</code> outputs:</p> + +<pre class="brush: js">function anonymous() { +} +</pre> + +<p>Since the function actually does not have a name, <code>anonymous</code> is not a variable that can be accessed within the function. For example, the following would result in an error:</p> + +<pre class="brush: js">var foo = new Function("alert(anonymous);"); +foo(); +</pre> + +<p>Unlike functions defined by function expressions or by the <code>Function</code> constructor, a function defined by a function declaration can be used before the function declaration itself. For example:</p> + +<pre class="brush: js">foo(); // alerts FOO! +function foo() { + alert('FOO!'); +} +</pre> + +<p>A function defined by a function expression or by a function declaration inherits the current scope. That is, the function forms a closure. On the other hand, a function defined by a <code>Function</code> constructor does not inherit any scope other than the global scope (which all functions inherit).</p> + +<pre class="brush: js">/* + * 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) + */ +</pre> + +<p>Functions defined by function expressions and function declarations are parsed only once, while those defined by the <code>Function</code> constructor are not. That is, the function body string passed to the <code>Function</code> constructor must be parsed each and every time the constructor is called. Although a function expression creates a closure every time, the function body is not reparsed, so function expressions are still faster than "<code>new Function(...)</code>". Therefore the <code>Function</code> constructor should generally be avoided whenever possible.</p> + +<p>It should be noted, however, that function expressions and function declarations nested within the function generated by parsing a <code>Function constructor</code> 's string aren't parsed repeatedly. For example:</p> + +<pre class="brush: js">var foo = (new Function("var bar = \'FOO!\';\nreturn(function() {\n\talert(bar);\n});"))(); +foo(); // The segment "function() {\n\talert(bar);\n}" of the function body string is not re-parsed.</pre> + +<p>A function declaration is very easily (and often unintentionally) turned into a function expression. A function declaration ceases to be one when it either:</p> + +<ul> + <li>becomes part of an expression</li> + <li>is no longer a "source element" of a function or the script itself. A "source element" is a non-nested statement in the script or a function body:</li> +</ul> + +<pre class="brush: js">var x = 0; // source element +if (x === 0) { // source element + x = 10; // not a source element + function boo() {} // not a source element +} +function foo() { // source element + var y = 20; // source element + function bar() {} // source element + while (y === 10) { // source element + function blah() {} // not a source element + y++; // not a source element + } +} +</pre> + +<h3 id="Examples">Examples</h3> + +<pre class="brush: js">// function declaration +function foo() {} + +// function expression +(function bar() {}) + +// function expression +x = function hello() {} + + +if (x) { + // function expression + function world() {} +} + + +// function declaration +function a() { + // function declaration + function b() {} + if (0) { + // function expression + function c() {} + } +} +</pre> + +<h2 id="Block-level_functions">Block-level functions</h2> + +<p>In <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>, starting with ES2015, functions inside blocks are now scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.</p> + +<pre class="brush: js">'use strict'; + +function f() { + return 1; +} + +{ + function f() { + return 2; + } +} + +f() === 1; // true + +// f() === 2 in non-strict mode +</pre> + +<h3 id="Block-level_functions_in_non-strict_code">Block-level functions in non-strict code</h3> + +<p>In a word: Don't.</p> + +<p>In non-strict code, function declarations inside blocks behave strangely. For example:</p> + +<pre class="brush: js">if (shouldDefineZero) { + function zero() { // DANGER: compatibility risk + console.log("This is zero."); + } +} +</pre> + +<p>ES2015 says that if <code>shouldDefineZero</code> is false, then <code>zero</code> should never be defined, since the block never executes. However, it's a new part of the standard. Historically, this was left unspecified, and some browsers would define <code>zero</code> whether the block executed or not.</p> + +<p>In <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>, all browsers that support ES2015 handle this the same way: <code>zero</code> is defined only if <code>shouldDefineZero</code> is true, and only in the scope of the <code>if</code>-block.</p> + +<p>A safer way to define functions conditionally is to assign a function expression to a variable:</p> + +<pre class="brush: js">var zero; +if (shouldDefineZero) { + zero = function() { + console.log("This is zero."); + }; +} +</pre> + +<h2 id="Examples_2">Examples</h2> + +<h3 id="Returning_a_formatted_number">Returning a formatted number</h3> + +<p>The following function returns a string containing the formatted representation of a number padded with leading zeros.</p> + +<pre class="brush: js">// This function returns a string padded with leading zeros +function padZeros(num, totalLen) { + var numStr = num.toString(); // Initialize return value as string + var numZeros = totalLen - numStr.length; // Calculate no. of zeros + for (var i = 1; i <= numZeros; i++) { + numStr = "0" + numStr; + } + return numStr; +} +</pre> + +<p>The following statements call the padZeros function.</p> + +<pre class="brush: js">var result; +result = padZeros(42,4); // returns "0042" +result = padZeros(42,2); // returns "42" +result = padZeros(5,4); // returns "0005" +</pre> + +<h3 id="Determining_whether_a_function_exists">Determining whether a function exists</h3> + +<p>You can determine whether a function exists by using the <code>typeof</code> operator. In the following example, a test is performed to determine if the <code>window</code> object has a property called <code>noFunc</code> that is a function. If so, it is used; otherwise some other action is taken.</p> + +<pre class="brush: js"> if ('function' === typeof window.noFunc) { + // use noFunc() + } else { + // do something else + } +</pre> + +<p>Note that in the <code>if</code> test, a reference to <code>noFunc</code> is used—there are no brackets "()" after the function name so the actual function is not called.</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-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>New: Arrow functions, Generator functions, default parameters, rest parameters.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.functions")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <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("Function")}}</li> + <li>{{jsxref("GeneratorFunction")}}</li> + <li>{{jsxref("Functions/Arrow_functions", "Arrow functions")}}</li> + <li>{{jsxref("Functions/Default_parameters", "Default parameters")}}</li> + <li>{{jsxref("Functions/rest_parameters", "Rest parameters")}}</li> + <li>{{jsxref("Functions/arguments", "Arguments object")}}</li> + <li>{{jsxref("Functions/get", "getter")}}</li> + <li>{{jsxref("Functions/set", "setter")}}</li> + <li>{{jsxref("Functions/Method_definitions", "Method definitions")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope">Functions and function scope</a></li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/array/concat/index.html b/files/tr/web/javascript/reference/global_objects/array/concat/index.html new file mode 100644 index 0000000000..dbeaff447e --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/array/concat/index.html @@ -0,0 +1,167 @@ +--- +title: Array.prototype.concat +slug: Web/JavaScript/Reference/Global_Objects/Array/concat +tags: + - Array + - JavaScript + - Method + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Array/concat +--- +<div>{{JSRef("Global_Objects", "Array")}}</div> + +<h2 id="Summary" name="Summary">Özet</h2> + +<p><code><strong>concat()</strong></code> metodu eklendigi dizi ile parametre olarak aldığı dizi(leri) birleştirerek yeni bir dizi döndürür.</p> + +<h2 id="Syntax" name="Syntax">Söz Dizimi</h2> + +<pre class="syntaxbox"><code>var <var>new_array</var> = <var>old_array</var>.concat(<var>value1</var>[, <var>value2</var>[, ...[, <var>valueN</var>]]])</code></pre> + +<h3 id="Parameters" name="Parameters">Parmetreler</h3> + +<dl> + <dt><code>value<em>N</em></code></dt> + <dd>Yeni diziye eklenecek dizi ve/veya değerler. Detaylar için aşağıdaki açıklamayı okuyunuz.</dd> +</dl> + +<h2 id="Description" name="Description">Açıklama</h2> + +<p><code>concat</code> çağırılan nesnelerin elemanlarını içeren yeni bir dizi oluşturur. Çağırılma sırasıyla, diziyse elemanlarını, değerse kendisini ekler.</p> + +<p><code>concat</code> , <code>this</code> veya çağırılan dizilerden herhangi birini değiştirmez. Onları kopyalayarak yeni bir dizi oluşturur. Orjinal dizilerin öğeleri yeni diziye aşağıdaki gibi kopyalanır:</p> + +<ul> + <li>Nesne referansı (nesnenin kendisi değil): <code>concat</code> nesne referanslarını yeni diziye kopyalar. Hem orjinal hem de yeni dizi aynı nesneye karşılık gelir. Yani, bir başvurulan nesne değiştirilirse, değişiklikler hem yeni hem de orijinal diziler tarafından görülebilir.</li> + <li>Metinler ve sayılar ({{jsxref("Global_Objects/String", "String")}} ve {{jsxref("Global_Objects/Number", "Number")}} nesneleri değil): <code>concat</code> metin ve sayıların değerlerini yeni dizinin içine kopyalar.</li> +</ul> + +<div class="note"> +<p><strong>Not: </strong>Dizi/değerlerin birleştirilmesi orjinallerini değiştirmez. Ayrıca, yeni dizi (eleman nesne referansı değilse) üzerindeki herhangi bir operasyon orjinal dizileri etkilemez. Tam tersi de geçerlidir.</p> +</div> + +<h2 id="Examples" name="Examples">Örnekler</h2> + +<h3 id="Example:_Concatenating_two_arrays" name="Example:_Concatenating_two_arrays">Örnek: İki diziyi birleştirme</h3> + +<p>Aşağıdaki kod iki diziyi birleştiriyor:</p> + +<pre class="brush: js">var alpha = ['a', 'b', 'c'], + numeric = [1, 2, 3]; + +var alphaNumeric = alpha.concat(numeric); + +console.log(alphaNumeric); // Result: ['a', 'b', 'c', 1, 2, 3] +</pre> + +<h3 id="Example:_Concatenating_three_arrays" name="Example:_Concatenating_three_arrays">Örnek: Üç diziyi birleştirme</h3> + +<p>Aşağıdaki kod üç diziyi birleştiriyor:</p> + +<pre class="brush: js">var num1 = [1, 2, 3], + num2 = [4, 5, 6], + num3 = [7, 8, 9]; + +var nums = num1.concat(num2, num3); + +console.log(nums); // Result: [1, 2, 3, 4, 5, 6, 7, 8, 9] +</pre> + +<h3 id="Example:_Concatenating_values_to_an_array" name="Example:_Concatenating_values_to_an_array">Örnek: Değerleri dizi ile birleştirme</h3> + +<p>Aşağıdaki kod değerler ile diziyi birleştiriyor:</p> + +<pre class="brush: js">var alpha = ['a', 'b', 'c']; + +var alphaNumeric = alpha.concat(1, [2, 3]); + +console.log(alphaNumeric); // Result: ['a', 'b', 'c', 1, 2, 3] +</pre> + +<h2 id="Specifications" name="Specifications">Özellikler</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Özellikler</th> + <th scope="col">Durum</th> + <th scope="col">Yorumlar</th> + </tr> + <tr> + <td>ECMAScript 3rd Edition</td> + <td>Standard</td> + <td>Initial definition. Implemented in 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> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Tarayıcı Uyumluluğu</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Özellik</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Temel destek</td> + <td>{{CompatChrome("1.0")}}</td> + <td>{{CompatGeckoDesktop("1.7")}}</td> + <td>{{CompatIE("5.5")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Özellik</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>Temel destek</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">Ayrıca Bakınız</h2> + +<ul> + <li>{{jsxref("Array.push", "push")}} / {{jsxref("Array.pop", "pop")}} — dizinin sonundan eleman ekleme/çıkarma</li> + <li>{{jsxref("Array.unshift", "unshift")}} / {{jsxref("Array.shift", "shift")}} — dizinin başından eleman ekleme/çıkarma</li> + <li>{{jsxref("Array.splice", "splice")}} — dizinin belirli bir kısmından eleman ekleme/çıkarma</li> + <li>{{jsxref("String.prototype.concat()")}}</li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/array/entries/index.html b/files/tr/web/javascript/reference/global_objects/array/entries/index.html new file mode 100644 index 0000000000..7e2d7b6a82 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/array/entries/index.html @@ -0,0 +1,129 @@ +--- +title: Array.prototype.entries() +slug: Web/JavaScript/Reference/Global_Objects/Array/entries +tags: + - Dizi + - döngü + - gezinilebilir +translation_of: Web/JavaScript/Reference/Global_Objects/Array/entries +--- +<div>{{JSRef}}</div> + +<p><code><strong>entries()</strong></code> metodu, içerisinde, her bir elemanı için anahtar/değer çifti içeren yeni bir <code><strong>Gezinilebilir Dizi </strong></code>nesnesi döndürür.</p> + +<pre class="brush:js">var a = ['a', 'b', 'c']; +var iterator = a.entries(); + +console.log(iterator.next().value); // [0, 'a'] +console.log(iterator.next().value); // [1, 'b'] +console.log(iterator.next().value); // [2, 'c'] +</pre> + +<h2 id="Söz_dizimi">Söz dizimi</h2> + +<pre class="syntaxbox"><var>a</var>.entries()</pre> + +<h3 id="Dönüş_değeri">Dönüş değeri</h3> + +<p>Yeni bir gezinilebilir {{jsxref("Array")}} nesnesi.</p> + +<h2 id="Örnekler">Örnekler</h2> + +<h3 id="Bir_for…of_döngüsü_kullanımı">Bir <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for…of</a> döngüsü kullanımı</h3> + +<pre class="brush:js">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="Tanımlamalar">Tanımlamalar</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Tanımlama</th> + <th scope="col">Durum</th> + <th scope="col">Yorum</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-array.prototype.entries', 'Array.prototype.entries')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.entries', 'Array.prototype.entries')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tarayıcı_uyumluluğu">Tarayıcı uyumluluğu</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Özellik</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Temel destekli</td> + <td>{{CompatChrome("38")}}</td> + <td>{{CompatGeckoDesktop("28")}}</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>Temel destekli</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile("28")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>8.0</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ayrıca_bknz.">Ayrıca bknz.</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/tr/web/javascript/reference/global_objects/array/every/index.html b/files/tr/web/javascript/reference/global_objects/array/every/index.html new file mode 100644 index 0000000000..1cab33d6fe --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/array/every/index.html @@ -0,0 +1,189 @@ +--- +title: Array.prototype.every() +slug: Web/JavaScript/Reference/Global_Objects/Array/every +translation_of: Web/JavaScript/Reference/Global_Objects/Array/every +--- +<div>{{JSRef}}</div> + +<div><code><strong>every()</strong></code> metodu bir dizideki tüm elemanların verilen fonksiyonun testini geçip geçmediği kontrol eder. Bu metot true (doğru) yada false (yanlış) olarak ikilik değer döndürür. </div> + +<div class="note"> +<p><strong>Note</strong>: Test edilen array boş ise bu metot true deger döndürür.</p> +</div> + +<div>{{EmbedInteractiveExample("pages/js/array-every.html")}}</div> + + + +<h2 id="Söz_dizimi">Söz dizimi</h2> + +<pre class="syntaxbox">arr.every(callback(element[, index[, array]])[, thisArg])</pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>Her elemanı test eden üç değişken alan bir fonksiyon: + <dl> + <dt><code>element</code></dt> + <dd>İşlemde olan geçerli dizi elemanı.</dd> + <dt><code>index</code>{{Optional_inline}}</dt> + <dd>İşlemde olan geçerli dizi elemanın indeksi .</dd> + <dt><code>array</code>{{Optional_inline}}</dt> + <dd><code>every</code> tarafından çağrılan dizi.</dd> + </dl> + </dd> + <dt><code>thisArg</code>{{Optional_inline}}</dt> + <dd>Geri dönüş yapıldığında <code>this</code> olarak kullanıcak bir değer.</dd> +</dl> + +<h3 id="Dönüş_değeri">Dönüş değeri</h3> + +<p>Geri dönüş fonksiyonu her bir dizi elemanı için bir {{Glossary("truthy")}} deger dondürse <code><strong>true</strong></code>. Aksi takdirde, <code><strong>false</strong></code>.</p> + +<h2 id="Description">Description</h2> + +<p>The <code>every</code> method executes the provided <code>callback</code> function once for each element present in the array until it finds the one where <code>callback</code> returns a {{Glossary("falsy")}} value. If such an element is found, the <code>every</code> method immediately returns <code>false</code>. Otherwise, if <code>callback</code> returns a {{Glossary("truthy")}} value for all elements, <code>every</code> returns <code>true</code>. <code>callback</code> is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.</p> + +<p><code>callback</code> is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.</p> + +<p>If a <code>thisArg</code> parameter is provided to <code>every</code>, it will be used as callback's <code>this</code> value. Otherwise, the value <code>undefined</code> will be used as its <code>this</code> value. The <code>this</code> value ultimately observable by <code>callback</code> is determined according to <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">the usual rules for determining the <code>this</code> seen by a function</a>.</p> + +<p><code>every</code> does not mutate the array on which it is called.</p> + +<p>The range of elements processed by <code>every</code> is set before the first invocation of <code>callback</code>. Therefore, <code>callback</code> will not run on elements that are appended to the array after the call to <code>every</code> begins. If existing elements of the array are changed, their value as passed to <code>callback</code> will be the value at the time <code>every</code> visits them. Elements that are deleted are not visited.</p> + +<p><code>every</code> acts like the "for all" quantifier in mathematics. In particular, for an empty array, it returns true. (It is <a href="http://en.wikipedia.org/wiki/Vacuous_truth">vacuously true</a> that all elements of the <a href="https://en.wikipedia.org/wiki/Empty_set#Properties">empty set</a> satisfy any given condition.)</p> + +<h2 id="Örnekler">Örnekler</h2> + +<h3 id="Tüm_dizi_elemanlarının_büyüklüğünün_test_edilmesi">Tüm dizi elemanlarının büyüklüğünün test edilmesi</h3> + +<p>Aşağıdaki örnekte tüm dizi elemanlarının 10'dan büyük yada eşit olma durumu test edilir.</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="Ok_fonksiyonlarını_kullanma">Ok fonksiyonlarını kullanma</h3> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">Ok fonksiyonları</a> aynı testin daha kısa söz dizimi ile yapılmasını sağlar.</p> + +<pre class="brush: js">[12, 5, 8, 130, 44].every(x => x >= 10); // false +[12, 54, 18, 130, 44].every(x => x >= 10); // true</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p><code>every</code> was added to the ECMA-262 standard in the 5th edition, and it may not be present in other implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of <code>every</code> in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming <code>Object</code> and <code>TypeError</code> have their original values and that <code>callbackfn.call</code> evaluates to the original value of {{jsxref("Function.prototype.call")}}</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="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.4.4.16', 'Array.prototype.every')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in 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="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.every")}}</p> +</div> + +<h2 id="See_also">See also</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/tr/web/javascript/reference/global_objects/array/filter/index.html b/files/tr/web/javascript/reference/global_objects/array/filter/index.html new file mode 100644 index 0000000000..4dfc8eaeae --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/array/filter/index.html @@ -0,0 +1,243 @@ +--- +title: Array.prototype.filter() +slug: Web/JavaScript/Reference/Global_Objects/Array/filter +tags: + - Dizi + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - ployfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/filter +--- +<div>{{JSRef}}</div> + +<div> </div> + +<p><code><strong>filter()</strong></code> metotu sağlanan işlev tarafından uygulanan testi geçen tüm öğelerle birlikte yeni bir dizi oluşturur.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-filter.html")}}</div> + +<p class="hidden">Bu etkileşimli örneğin kaynağı bir GitHub deposunda saklanır. İnteraktif örnekler projesine katkıda bulunmak istiyorsanız, lütfen https://github.com/mdn/interactive-examples klonlayın ve bize bir istek gönderin.</p> + +<h2 id="Söz_Dizimi">Söz Dizimi</h2> + +<pre class="syntaxbox"><var>var newArray = arr</var>.filter(<var>callback(element[, index[, array]])</var>[, <var>thisArg</var>])</pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>Function , dizinin her öğesini sınamak için bir yordamdır. Öğeyi saklamak için <code>true</code> , aksi takdirde <code>false</code> değerini döndürün. Üç argümanı kabul eder:</dd> + <dd> + <dl> + <dt><code>element</code></dt> + <dd>Dizide işlenen mevcut elementtir.</dd> + <dt><code>index</code>{{optional_inline}}</dt> + <dd>Dizide işlenen geçerli öğenin dizini</dd> + <dt><code>array</code>{{optional_inline}}</dt> + <dd>The array <code>filter</code> was called upon.</dd> + </dl> + </dd> + <dt><code>thisArg</code>{{optional_inline}}</dt> + <dd><code>callback</code> çalıştığı zaman <code>this</code> olarak kullanmak için değerdir.</dd> +</dl> + +<h3 id="Dönüş_değer">Dönüş değer</h3> + +<p>Testi geçen öğeler içeren yeni bir dizi. Hiçbir öğe testi geçemezse, boş bir dizi döndürülür.</p> + +<h2 id="Açıklama">Açıklama</h2> + +<p><code>filter ()</code>, bir dizideki her öğe için sağlanan bir geri çağırma işlevini çağırır ve geri çağrmanın (callback) doğru olan bir değer döndürdüğü tüm değerler için yeni bir dizisini oluşturur. Geri çağırma (callback), yalnızca atanmış değerleri olan dizinin dizinleri için çağrılır; silinmiş veya hiçbir zaman değer atanmamış indeksler için çağrılmaz. Filtre testini geçmeyen dizi öğeleri basitçe atlanır ve yeni diziye dahil edilmez.</p> + +<p><code>Geri Çağırma (callback)</code> 3 argüman ile çağırılır.</p> + +<ol> + <li>elementin değeri</li> + <li>elementin indeksi</li> + <li>Array nesnesinin geçişi</li> +</ol> + +<p>Filtrelemek için bir thisArg parametresi varsa, geri çağırma (callback) bu değer olarak kullanılacaktır. Aksi halde undefined değeri bu değer olarak kullanılacaktır. <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">Sonuçta geri çağırma ile gözlenebilen this değeri, bir işlev tarafından görülenlerin belirlenmesi için kullanılan genel kurallara göre belirlenir.</a></p> + +<p><code>filter()</code> çağrıldığı diziyi değiştirmez.</p> + +<p><code>filter()</code> tarafından işlenen elemanların aralığı, ilk geri çağırma <code>callback</code> çağrısından önce ayarlanır. <code>filter()</code> çağrısı başladıktan sonra diziye eklenen öğeler, geri çağırma <code>callback</code> tarafından ziyaret edilmeyecektir. Dizinin mevcut elemanları değiştirilir veya silinirse, geri çağırmaya <code>callback</code> iletilen değerleri <code>filter()</code> tarafından ziyaret edilen zamanın değeri olacaktır; silinen öğeler ziyaret edilmez.</p> + +<h2 id="Örnekler">Örnekler</h2> + +<h3 id="Tüm_küçük_değerleri_filtrelemek">Tüm küçük değerleri filtrelemek</h3> + +<p>Aşağıdaki örnek, tüm öğeleri 10'dan daha küçük değerlere sahip filtreli bir dizi oluşturmak için <code>filter()</code> kullanır.</p> + +<pre class="brush: js">function isBigEnough(value) { + return value >= 10; +} + +var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); +// filtered is [12, 130, 44] +</pre> + +<h3 id="JSON'dan_geçersiz_girişleri_filtrelemek">JSON'dan geçersiz girişleri filtrelemek</h3> + +<p>Aşağıdaki örnek, 0 olmayan,numeric <code>id</code> olan tüm öğelerin filtrelenmiş bir jsonunu oluşturmak için <code>filter()</code> işlevini kullanır. </p> + +<pre class="brush: js">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 +</pre> + +<h3 id="Array_içinde_arama_yapmak">Array içinde arama yapmak</h3> + +<p> </p> + +<p>Aşağıdaki örnek, arama keriterlerine göre dizi içeriğini filtrelemek için filter() işlevini kullanır</p> + +<p> </p> + +<pre class="brush: js">var fruits = ['apple', 'banana', 'grapes', 'mango', 'orange']; + +/** + * Array filters items based on search criteria (query) + */ +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']</pre> + +<h3 id="ES2015_İmplementasyonu">ES2015 İmplementasyonu</h3> + +<pre class="brush: js">const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange']; + +/** + * Array filters items based on search criteria (query) + */ +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'] + +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>5. basımda ECMA-262 standardına filter () eklenmiştir; bu nedenle standardın tüm uygulamalarında bulunmayabilir. Bu kodu, komut dosyalarınızın başına aşağıdaki kodu ekleyerek ve doğal olarak desteklemeyen ECMA-262 uygulamalarında filter() kullanımına izin vererek çözebilirsiniz. Bu algoritma, fn.call öğesinin {{jsxref ("Function.prototype.bind ()")}} özgün değerini değerlendirdiğini varsayarsak, ECMA-262, 5. basımda belirtilene tamamen eşdeğerdir ve bu {{jsxref ("Array.prototype.push ()")}} orijinal değerine sahiptir</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> + +<p> </p> + +<h2 id="Özellikler">Özellikler</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Özellikler</th> + <th scope="col">Statüler</th> + <th scope="col">Yorumlar</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.20', 'Array.prototype.filter')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>İlk tanım JavaScript 1.6'da uygulanmıştır.</td> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-array.prototype.filter', 'Array.prototype.filter')}}</td> + <td>{{Spec2('ES2015')}}</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="Tarayıcı_uyumluluğu">Tarayıcı uyumluluğu</h2> + +<div> +<div class="hidden">Bu sayfadaki uyumluluk tablosu yapılandırılmış verilerden üretilmiştir. Verilere katkıda bulunmak istiyorsanız, lütfen https://github.com/mdn/browser-compat-data adresini ziyaret edin ve bize bir istek gönderin.</div> + +<p>{{Compat("javascript.builtins.Array.filter")}}</p> +</div> + +<h2 id="Ayrıca_bakınız">Ayrıca bakınız</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/tr/web/javascript/reference/global_objects/array/find/index.html b/files/tr/web/javascript/reference/global_objects/array/find/index.html new file mode 100644 index 0000000000..76d5e38687 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/array/find/index.html @@ -0,0 +1,205 @@ +--- +title: Array.prototype.find() +slug: Web/JavaScript/Reference/Global_Objects/Array/find +translation_of: Web/JavaScript/Reference/Global_Objects/Array/find +--- +<div>{{JSRef}}</div> + +<p><code><strong>find()</strong></code> metodu parametre olarak verilen, true/false değer döndüren test fonksiyonunu karşılayan dizi içerisindeki ilk elemanın <strong>değerini</strong> döndürür. Aksi halde {{jsxref("undefined")}} döndürür.</p> + +<pre class="brush: js">function yeterinceBuyuk(eleman) { + return eleman >= 15; +} + +[12, 5, 8, 130, 44].find(yeterinceBuyuk); // 130</pre> + +<p>Ayrıca {{jsxref("Array.findIndex", "findIndex()")}} metoduna bakınız, bu metod dizi içerisinde bulunan elemanın değeri yerine <strong>indeksini</strong> döndürür.</p> + +<p>Dizi içerisindeki elemanın pozizyonunu bulmak ya da var olup olmadığına bakmak için {{jsxref("Array.prototype.indexOf()")}} veya {{jsxref("Array.prototype.includes()")}} kullanabilirsiniz.</p> + +<h2 id="Sözdizim">Sözdizim</h2> + +<pre class="syntaxbox"><em>arr</em>.find(<var>gericagrim</var>[, <var>thisArg</var>])</pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt><code>gericagrim</code></dt> + <dd>Dizi içerisindeki her bir değer için çalıştırılacak fonksiyon, üç parametre alır: + <dl> + <dt><code>eleman</code></dt> + <dd>Dizideki işlenen mevcut eleman.</dd> + <dt><code>indeks</code></dt> + <dd>Dizideki işlenen mevcut elemanın indeksi.</dd> + <dt><code>dizi</code></dt> + <dd><code>find</code> metodunun çağırıldığı dizi.</dd> + </dl> + </dd> + <dt><code>thisArg</code> <code>{{Optional_inline}}</code></dt> + <dd> <code>gericagrim</code> çalıştığında <code>this</code> olarak kullanılan nesne.</dd> +</dl> + +<h3 id="Dönüş_değeri">Dönüş değeri</h3> + +<p>Eğer test doğrulanırsa dizi içerisindeki bir değer; değilse, {{jsxref("undefined")}}.</p> + +<h2 id="Açıklama">Açıklama</h2> + +<p><code>find</code> metodu <code>gericagrim</code> fonksiyonu doğru bir değer döndürene kadar her bir indeks için bir sefer <code>gericagrim</code> fonksiyonunu çalıştırır. Eğer böyle bir eleman bulunduysa, <code>find</code> derhal bu elemanın değerini döndürür. Aksi halde, <code>find</code> {{jsxref("undefined")}} döndürür. <code>gericagrim</code> <code>0</code> dan <code>length - 1</code> dahil olmak üzere değer atanan ya da atanmayan dizinin her bir elemanı için çağırılır. Bu, aralıklı diziler için sadece değer atanan indeksleri ziyaret eden diğer metodlardan daha verimsiz olduğu anlamına gelmektedir. </p> + +<p><code>gericagrim</code> üç parametre ile çağırılır: dizi elemanının değeri, dizi elemanının indeksi, ve geçilen dizi nesnesi.</p> + +<p>Eğer bir <code>thisArg</code> parametresi <code>find</code> için sağlanırsa, bu parametre <code>gericagrim</code> fonksiyonunun her çağırılışı için <code>this</code> olarak kullanılacaktır. Eğer sağlanmazsa, {{jsxref("undefined")}} kullanılır.</p> + +<p><code>find</code> üzerinde çağırıldığı diziyi değiştirmez.</p> + +<p><code>find</code> tarafından işlenilen elemanların aralığı <code>gericagrim</code> fonksiyonunun ilk çağırılışından önce atanır. <code>find</code> çağırılmaya başlandığından sonra diziye eklenen elemanlar <code>gericagrim</code> tarafından ziyaret edilmeyecektir. Eğer varolan, ziyaret edilmeyen eleman <code>gericagrim</code> tarafından değiştirilirse, bu elemanı ziyaret eden <code>gericagrim</code> fonkisyonuna aktarılan değeri <code>find</code> metodunun bu elemanın indeksini ziyaret edeceği andaki değer olacaktır; silenen elemanlar yine de ziyaret edilecektir.</p> + +<h2 id="Örnekler">Örnekler</h2> + +<h3 id="Dizi_içerisindeki_nesneyi_bir_özelliğinden_bulmak">Dizi içerisindeki nesneyi bir özelliğinden bulmak</h3> + +<pre class="brush: js">var envanter = [ + {isim: 'elma', miktar: 2}, + {isim: 'muz', miktar: 0}, + {isim: 'kiraz', miktar: 5} +]; + +function kirazlariBul(meyve) { + return meyve.isim === 'kiraz'; +} + +console.log(envanter.find(kirazlariBul)); +// { isim: 'kiraz', miktar: 5 }</pre> + +<h3 id="Dizi_içerisindeki_bir_asal_sayıyı_bulmak">Dizi içerisindeki bir asal sayıyı bulmak</h3> + +<p>Aşağıdaki örnek dizi içerisindeki bir asal sayı olan elemanı bulur (ya da eğer asal sayı yoksa {{jsxref("undefined")}} döndürür).</p> + +<pre class="brush: js">function asalMi(eleman, indeks, dizi) { + var baslangic = 2; + while (baslangic <= Math.sqrt(eleman)) { + if (eleman % baslangic++ < 1) { + return false; + } + } + return eleman > 1; +} + +console.log([4, 6, 8, 12].find(asalMi)); // undefined, bulunamadı +console.log([4, 5, 8, 12].find(asalMi)); // 5 +</pre> + +<p>Aşağıdaki örnek varolmayan ve silinen elemanların ziyaret edildiğini ve gericağrım fonksiyonuna gönderilen değerin ziyaret edildikleri andaki değerleri olduğunu gösterir.</p> + +<pre class="brush: js">// İndeks 2, 3 ve 4 için elemanı bulunmayan bir dizi tanımlar +var a = [0,1,,,,5,6]; + +// Sadece değer atanmış olanlar değil, tüm indeksleri gösterir +a.find(function(deger, indeks) { + console.log('Ziyaret edilen indeks ' + indeks + ' ve değeri ' + deger); +}); + +// Silinenler dahil, bütün indeksleri gösterir +a.find(function(deger, indeks) { + + // İndeksi 5 olan elamanı birinci iterasyonda siler + if (indeks == 0) { + console.log('a[5] siliniyor ve değeri ' + a[5]); + delete a[5]; + } + // İndeksi 5 olan elaman silinse bile yine de ziyaret edilir + console.log('Ziyaret edilen indeks ' + indeks + ' ve değeri ' + deger); +}); + +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>Bu metod ECMAScript 2015 spesifikasyonuna eklenmiştir ve tüm JavaScript implementasyonlarında kullanıma hazır olmayabilir. Fakat, aşağıdaki kod parçacığı ile <code>Array.prototype.find</code> polyfill yapabilirsiniz:</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; + } + }); +} +</pre> + +<p>Eğer <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty</a></code> desteği bulunmayan tamamen eskimiş JavaScript motorları için ihtiyacınız varsa, <code>Array.prototype</code> metodlarını polyfill yapmamanız en doğrusudur, çünkü bu metodlar numaralandırılabilir olmayan metodlardır.</p> + +<h2 id="Spesifikasyonlar">Spesifikasyonlar</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Spesifikasyon</th> + <th scope="col">Durum</th> + <th scope="col">Açıklama</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-array.prototype.find', 'Array.prototype.find')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>İlk tanım.</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="Tarayıcı_uyumluluğu">Tarayıcı uyumluluğu</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.find")}}</p> +</div> + +<h2 id="Ayrıca_bakınız">Ayrıca bakınız</h2> + +<ul> + <li>{{jsxref("Array.prototype.findIndex()")}} – bulur ve indeksi döndürür</li> + <li>{{jsxref("Array.prototype.filter()")}} – eşleşen bütün elemanları bulur</li> + <li>{{jsxref("Array.prototype.every()")}} – bütün elemanları birlikte test eder</li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/array/findindex/index.html b/files/tr/web/javascript/reference/global_objects/array/findindex/index.html new file mode 100644 index 0000000000..409222cf45 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/array/findindex/index.html @@ -0,0 +1,177 @@ +--- +title: Array.prototype.findIndex() +slug: Web/JavaScript/Reference/Global_Objects/Array/findIndex +translation_of: Web/JavaScript/Reference/Global_Objects/Array/findIndex +--- +<div>{{JSRef}}</div> + +<p>FindIndex () yöntemi, sağlanan test işlevini karşılayan dizideki ilk öğenin dizinini döndürür. Aksi takdirde -1 iade edilir.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-findindex.html")}}</div> + +<p class="hidden">Bu interaktif örneğin için kaynak bir GitHub deposunda saklanır. Etkileşimli örnek projesine katkıda bulunmak isterseniz, lütfen https://github.com/mdn/interactive-examples klonlayın ve bize bir çekme isteği gönderin.</p> + +<div> </div> + +<p>Ayrıca, dizinde bulunan dizinin yerine bulunan bir öğenin değerini döndüren {{jsx ref ("Array.find", "find ()")}} yöntemine de bakın.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><var>arr</var>.findIndex(<var>callback</var>[, <var>thisArg</var>])</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>Function to execute on each value in the array, taking three arguments: + <dl> + <dt><code>element</code></dt> + <dd>The current element being processed in the array.</dd> + <dt><code>index</code>{{optional_inline}}</dt> + <dd>The index of the current element being processed in the array.</dd> + <dt><code>array</code>{{optional_inline}}</dt> + <dd>The array <code>findIndex</code> was called upon.</dd> + </dl> + </dd> + <dt><code>thisArg</code>{{optional_inline}}</dt> + <dd>Optional. Object to use as <code>this</code> when executing <code>callback</code>.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>An index in the array if an element passes the test; otherwise, <strong>-1</strong>.</p> + +<h2 id="Description">Description</h2> + +<p>The <code>findIndex</code> method executes the <code>callback</code> function once for every array index <code>0..length-1</code> (inclusive) in the array until it finds one where <code>callback</code> returns a truthy value (a value that coerces to <code>true</code>). If such an element is found, <code>findIndex</code> immediately returns the index for that iteration. If the callback never returns a truthy value or the array's <code>length</code> is 0, <code>findIndex</code> returns -1. Unlike some other array methods such as Array#some, in sparse arrays the <code>callback</code> <strong>is</strong> called even for indexes of entries not present in the array.</p> + +<p><code>callback</code> is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.</p> + +<p>If a <code>thisArg</code> parameter is provided to <code>findIndex</code>, it will be used as the <code>this</code> for each invocation of the <code>callback</code>. If it is not provided, then {{jsxref("undefined")}} is used.</p> + +<p><code>findIndex</code> does not mutate the array on which it is called.</p> + +<p>The range of elements processed by <code>findIndex</code> is set before the first invocation of <code>callback</code>. Elements that are appended to the array after the call to <code>findIndex</code> begins will not be visited by <code>callback</code>. If an existing, unvisited element of the array is changed by <code>callback</code>, its value passed to the visiting <code>callback</code> will be the value at the time that <code>findIndex</code> visits that element's index; elements that are deleted are still visited.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Find_the_index_of_a_prime_number_in_an_array">Find the index of a prime number in an array</h3> + +<p>The following example finds the index of an element in the array that is a prime number (or returns -1 if there is no prime number).</p> + +<pre class="brush: js">function isPrime(element, index, array) { + var start = 2; + while (start <= Math.sqrt(element)) { + if (element % start < 1) { + return false; + } else { + start++; + } + } + return element > 1; +} + +console.log([4, 6, 8, 12].findIndex(isPrime)); // -1, not found +console.log([4, 6, 7, 12].findIndex(isPrime)); // 2 +</pre> + +<h3 id="Find_index_using_arrow_function">Find index using arrow function</h3> + +<p>The following example finds the index of a fruit using an arrow function.</p> + +<pre class="brush: js">const fruits = ["apple", "banana", "cantaloupe", "blueberries", "grapefruit"]; + +const index = fruits.findIndex(fruit => fruit === "blueberries"); + +console.log(index); // 3 +console.log(fruits[index]); // blueberries +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js">// https://tc39.github.io/ecma262/#sec-array.prototype.findIndex +if (!Array.prototype.findIndex) { + Object.defineProperty(Array.prototype, 'findIndex', { + 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 k. + var kValue = o[k]; + if (predicate.call(thisArg, kValue, k, o)) { + return k; + } + // e. Increase k by 1. + k++; + } + + // 7. Return -1. + return -1; + }, + configurable: true, + writable: true + }); +} +</pre> + +<p>If you need to support truly obsolete JavaScript engines that don't support <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty</a></code>, it's best not to polyfill <code>Array.prototype</code> methods at all, as you can't make them non-enumerable.</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-array.prototype.findindex', 'Array.prototype.findIndex')}}</td> + <td>{{Spec2('ES2015')}}</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="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.findIndex")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Array.prototype.find()")}}</li> + <li>{{jsxref("Array.prototype.indexOf()")}}</li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/array/foreach/index.html b/files/tr/web/javascript/reference/global_objects/array/foreach/index.html new file mode 100644 index 0000000000..46d677f17a --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/array/foreach/index.html @@ -0,0 +1,308 @@ +--- +title: Array.prototype.forEach() +slug: Web/JavaScript/Reference/Global_Objects/Array/forEach +translation_of: Web/JavaScript/Reference/Global_Objects/Array/forEach +--- +<div>{{JSRef}}</div> + +<p><code><strong>forEach()</strong></code> metodu dizideki her eleman için verilen metodu çalıştırır.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-foreach.html")}}</div> + +<p class="hidden">Bu interaktif örneğin kaynağını GitHub deposunda bulabilirsiniz. Eğer bu interaktif projelere katkı sağlamak isterseni, <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> adresindeki depoyu klonlayın ve bize pull request'i gönderin.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><var>arr</var>.forEach(function <var>callback(currentValue[, index[, array]]) { + //your iterator +}</var>[, <var>thisArg</var>]);</pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>Aşağıdaki üç parametreyi alan ve dizinin her elemanı için çalışan fonksiyon.</dd> + <dd> + <dl> + <dt><code>currentValue</code>{{optional_inline}}</dt> + <dd>İşlenmekte olan dizi elemanı.</dd> + <dt><code>index</code>{{optional_inline}}</dt> + <dd>İşlenmekte olan dizi elemanının indeksi, yani dizideki sırası.</dd> + <dt><code>array</code>{{optional_inline}}</dt> + <dd><code>forEach()</code> in uygulanmakta olduğu dizi.</dd> + </dl> + </dd> + <dt><code>thisArg</code> {{Optional_inline}}</dt> + <dd> + <p><code>callback</code> fonksiyonu çağırılırken, fonksiyon içerisinde <code><strong>this</strong></code> yerine kullanılılabilecek değer.</p> + </dd> +</dl> + +<h3 id="Dönüş_Değeri">Dönüş Değeri</h3> + +<p>{{jsxref("undefined")}}.</p> + +<h2 id="Tanım">Tanım</h2> + +<p><code>forEach()</code> tanımlanmış olan <code>callback</code> fonksiyonunu dizideki her eleman için bir kere olmak üzere, indeks sırasına göre artan şekilde çalıştırır. Silinmiş ya da tanımsız olan elemanlar için fonksiyon çalışmaz (örnek: seyrek diziler).</p> + +<p>Dizinin</p> + +<p><code>callback</code> çağırılırken aşağıdaki <strong>üç parametre kullanılır</strong>:</p> + +<ul> + <li>Dizi elemanının değeri</li> + <li>Dizi elemanının indeksi</li> + <li>Döngünün gerçekleştiği dizinin kendisi</li> +</ul> + +<p>If a <code>thisArg</code> parameter is provided to <code>forEach()</code>, it will be used as callback's <code>this</code> value. Otherwise, the value {{jsxref("undefined")}} will be used as its <code>this</code> value. The <code>this</code> value ultimately observable by <code>callback</code> is determined according to <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">the usual rules for determining the <code>this</code> seen by a function</a>.</p> + +<p>The range of elements processed by <code>forEach()</code> is set before the first invocation of <code>callback</code>. Elements that are appended to the array after the call to <code>forEach()</code> begins will not be visited by <code>callback</code>. If the values of existing elements of the array are changed, the value passed to <code>callback</code> will be the value at the time <code>forEach()</code> visits them; elements that are deleted before being visited are not visited. If elements that are already visited are removed (e.g. using {{jsxref("Array.prototype.shift()", "shift()")}}) during the iteration, later elements will be skipped - see example below.</p> + +<p><code>forEach()</code> executes the <code>callback</code> function once for each array element; unlike {{jsxref("Array.prototype.map()", "map()")}} or {{jsxref("Array.prototype.reduce()", "reduce()")}} it always returns the value {{jsxref("undefined")}} and is not chainable. The typical use case is to execute side effects at the end of a chain.</p> + +<p><code>forEach()</code> does not mutate the array on which it is called (although <code>callback</code>, if invoked, may do so).</p> + +<div class="note"> +<p>There is no way to stop or break a <code>forEach()</code> loop other than by throwing an exception. If you need such behavior, the <code>forEach()</code> method is the wrong tool.</p> + +<p>Early termination may be accomplished with:</p> + +<ul> + <li>A simple loop</li> + <li>A <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a> loop</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>The other Array methods: {{jsxref("Array.prototype.every()", "every()")}}, {{jsxref("Array.prototype.some()", "some()")}}, {{jsxref("Array.prototype.find()", "find()")}}, and {{jsxref("Array.prototype.findIndex()", "findIndex()")}} test the array elements with a predicate returning a truthy value to determine if further iteration is required.</p> +</div> + +<h2 id="Examples">Examples</h2> + +<h3 id="Converting_a_for_loop_to_forEach">Converting a for loop to forEach</h3> + +<p>before</p> + +<pre class="brush:js">const items = ['item1', 'item2', 'item3']; +const copy = []; + +for (let i=0; i<items.length; i++) { + copy.push(items[i]) +} +</pre> + +<p>after</p> + +<pre class="brush:js">const items = ['item1', 'item2', 'item3']; +const copy = []; + +items.forEach(function(item){ + copy.push(item) +}); + +</pre> + +<p> </p> + +<h3 id="Printing_the_contents_of_an_array">Printing the contents of an array</h3> + +<p>The following code logs a line for each element in an array:</p> + +<pre class="brush:js">function logArrayElements(element, index, array) { + console.log('a[' + index + '] = ' + element); +} + +// Notice that index 2 is skipped since there is no item at +// that position in the array. +[2, 5, , 9].forEach(logArrayElements); +// logs: +// a[0] = 2 +// a[1] = 5 +// a[3] = 9 +</pre> + +<h3 id="Using_thisArg">Using <code>thisArg</code></h3> + +<p>The following (contrived) example updates an object's properties from each entry in the array:</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); + // ^---- Note +}; + +const obj = new Counter(); +obj.add([2, 5, 9]); +obj.count; +// 3 +obj.sum; +// 16 +</pre> + +<p>Since the <code>thisArg</code> parameter (<code>this</code>) is provided to <code>forEach()</code>, it is passed to <code>callback</code> each time it's invoked, for use as its <code>this</code> value.</p> + +<div class="note"> +<p>If passing the function argument using an <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow function expression</a> the <code>thisArg</code> parameter can be omitted as arrow functions lexically bind the {{jsxref("Operators/this", "this")}} value.</p> +</div> + +<h3 id="An_object_copy_function">An object copy function</h3> + +<p>The following code creates a copy of a given object. There are different ways to create a copy of an object; the following is just one way and is presented to explain how <code>Array.prototype.forEach()</code> works by using ECMAScript 5 <code>Object.*</code> meta property functions.</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="If_the_array_is_modified_during_iteration_other_elements_might_be_skipped.">If the array is modified during iteration, other elements might be skipped.</h3> + +<p>The following example logs "one", "two", "four". When the entry containing the value "two" is reached, the first entry of the whole array is shifted off, which results in all remaining entries moving up one position. Because element "four" is now at an earlier position in the array, "three" will be skipped. <code>forEach()</code> does not make a copy of the array before iterating.</p> + +<pre class="brush:js">var words = ['one', 'two', 'three', 'four']; +words.forEach(function(word) { + console.log(word); + if (word === 'two') { + words.shift(); + } +}); +// one +// two +// four +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p><code>forEach()</code> was added to the ECMA-262 standard in the 5th edition; as such it may not be present in other implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of <code>forEach()</code> in implementations that don't natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming {{jsxref("Object")}} and {{jsxref("TypeError")}} have their original values and that <code>callback.call()</code> evaluates to the original value of {{jsxref("Function.prototype.call()")}}.</p> + +<pre class="brush: js">// Production steps of ECMA-262, Edition 5, 15.4.4.18 +// Reference: http://es5.github.io/#x15.4.4.18 +if (!Array.prototype.forEach) { + + Array.prototype.forEach = function(callback/*, thisArg*/) { + + 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(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 = arguments[1]; + } + + // 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. Call the Call internal method of callback with T as + // the this value and argument list containing kValue, k, and O. + callback.call(T, kValue, k, O); + } + // d. Increase k by 1. + k++; + } + // 8. return 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('ES5.1', '#sec-15.4.4.18', 'Array.prototype.forEach')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.6.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.forEach")}}</p> +</div> + +<h2 id="See_also">See also</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/tr/web/javascript/reference/global_objects/array/from/index.html b/files/tr/web/javascript/reference/global_objects/array/from/index.html new file mode 100644 index 0000000000..d0d45add78 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/array/from/index.html @@ -0,0 +1,258 @@ +--- +title: Array.from() +slug: Web/JavaScript/Reference/Global_Objects/Array/from +translation_of: Web/JavaScript/Reference/Global_Objects/Array/from +--- +<div>{{JSRef}}</div> + +<p><code><strong>Array.from()</strong></code> metodu bir dizi-benzeri veya gezinilebilir bir nesneden yeni bir Dizi örneği oluşturur.</p> + +<pre class="brush: js">Array.from("birşey"); +// ["b", "i", "r", "ş", "e", "y"]</pre> + +<h2 id="Söz_dizimi">Söz dizimi</h2> + +<pre class="syntaxbox">Array.from(arrayLike[, mapFn[, thisArg]]) +</pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt><code>arrayLike</code></dt> + <dd>Diziye çevrilecek olan dizi-benzeri ya da gezinilebilir nesnedir.</dd> + <dt><code>mapFn</code></dt> + <dd>İsteğe bağlı. Map fonksiyonu tüm dizi öğeleri için çağrılır.</dd> + <dt><code>thisArg</code></dt> + <dd>İsteğe bağlı. <code>mapFn fonksiyonu işletilirken kullanılacak olan this argüman değeridir.</code></dd> +</dl> + +<h3 id="Dönüş_değeri">Dönüş değeri</h3> + +<p>Yeni bir {{jsxref("Array")}} örneği.</p> + +<h2 id="Açıklama">Açıklama</h2> + +<p><code>Array.from(),</code> aşağıdaki yapılardan <code>Diziler</code> oluşturmanıza izin verir:</p> + +<ul> + <li>dizi-benzeri nesneler (sıralı öğeler ve bir uzunluk(<code>length</code>) özelliği olan nesneler) ya da</li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/iterable">gezinilebilir nesneler</a> (öğelerini alabildiğiniz nesneler, {{jsxref("Map")}} ve {{jsxref("Set")}} gibi).</li> +</ul> + +<p><code>Array.from()</code> has an optional parameter <code>mapFn</code>, which allows you to execute a {{jsxref("Array.prototype.map", "map")}} function on each element of the array (or subclass object) that is being created. More clearly,<code> Array.from(obj, mapFn, thisArg)</code> has the same result as <code>Array.from(obj).map(mapFn, thisArg)</code>, except that it does not create an intermediate array. This is especially important for certain array subclasses, like <a href="/en-US/docs/Web/JavaScript/Typed_arrays">typed arrays</a>, since the intermediate array would necessarily have values truncated to fit into the appropriate type.</p> + +<p>The <code>length</code> property of the <code>from()</code> method is 1.</p> + +<p>In ES2015, the class syntax allows for sub-classing of both built-in and user defined classes; as a result, static methods such as <code>Array.from</code> are "inherited" by subclasses of <code>Array</code> and create new instances of the subclass, not <code>Array</code>.</p> + +<h2 id="Örnekler">Örnekler</h2> + +<h3 id="Bir_metinden_Dizi_oluşturma">Bir metinden Dizi oluşturma</h3> + +<pre class="brush: js">Array.from("birşey"); +// ["b", "i", "r", "ş", "e", "y"]</pre> + +<h3 id="Bir_Set_nesnesinden_Dizi_oluşturma">Bir <code>Set nesnesinden Dizi oluşturma</code></h3> + +<pre class="brush: js">var s = new Set(["birşey", window]); +Array.from(s); +// ["birşey", window]</pre> + +<h3 id="Bir_Map_nesnesinden_Dizi_oluşturma">Bir <code>Map nesnesinden Dizi oluşturma</code></h3> + +<pre class="brush: js">var m = new Map([[1, 2], [2, 4], [4, 8]]); +Array.from(m); +// [[1, 2], [2, 4], [4, 8]]</pre> + +<h3 id="Bir_dizi-benzeri_nesneden_dizi_oluşturma_(argümanlar)">Bir dizi-benzeri nesneden dizi oluşturma (argümanlar)</h3> + +<pre class="brush: js">function f() { + return Array.from(arguments); +} + +f(1, 2, 3); + +// [1, 2, 3]</pre> + +<h3 id="Ok_işlevleri_ve_Array.from_kullanma">Ok işlevleri ve <code>Array.from kullanma</code></h3> + +<pre class="brush: js">// Bir işlevini, map işlevi olarak kullanıp +// öğeler üzerinde oynama yapmak +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> + +<h2 id="Polyfill">Polyfill</h2> + +<p><code>Array.from</code> was added to the ECMA-262 standard in the 6th edition (ES2015); as such it may not be present in other implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of <code>Array.from</code> in implementations that don't natively support it. This algorithm is exactly the one specified in ECMA-262, 6th edition, assuming <code>Object</code> and <code>TypeError</code> have their original values and that <code>callback.call</code> evaluates to the original value of {{jsxref("Function.prototype.call")}}. In addition, since true iterables can not be polyfilled, this implementation does not support generic iterables as defined in the 6th edition of ECMA-262.</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="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-array.from', 'Array.from')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.from', 'Array.from')}}</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>Edge</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("45")}}</td> + <td>{{CompatGeckoDesktop("32")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>9.0</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("32")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Array")}}</li> + <li>{{jsxref("Array.prototype.map()")}}</li> + <li>{{jsxref("TypedArray.from()")}}</li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/array/includes/index.html b/files/tr/web/javascript/reference/global_objects/array/includes/index.html new file mode 100644 index 0000000000..7ccb8cebc9 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/array/includes/index.html @@ -0,0 +1,176 @@ +--- +title: Array.prototype.includes() +slug: Web/JavaScript/Reference/Global_Objects/Array/includes +translation_of: Web/JavaScript/Reference/Global_Objects/Array/includes +--- +<div>{{JSRef}}</div> + +<p><code><strong>includes()</strong></code> metodu bir dizinin belirli bir elemanı içerip içermediğini belirler, içeriyorsa <code>true</code> içermiyorsa <code>false</code> değeri döndürür. Aranan öğenin bulunup bulunmadığını belirlemek için <code>sameValueZero</code> algoritmasını kullanır.</p> + +<pre class="brush: js">var a = [1, 2, 3]; +a.includes(2); // true +a.includes(4); // false +</pre> + +<p>{{EmbedInteractiveExample("pages/js/array-includes.html")}} </p> + +<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> +</div> + +<h2 id="Söz_Dizimi">Söz Dizimi</h2> + +<pre class="syntaxbox"><var>arr</var>.includes(<var>searchElement</var>) +<var>arr</var>.includes(<var>searchElement</var>, <var>fromIndex</var>) +</pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt><code>searchElement</code></dt> + <dd>Aranan eleman.</dd> + <dt><code>fromIndex</code> {{optional_inline}}</dt> + <dd>Dizide <code>searchElement</code> için aramanın başlatılacağı indis. Negatif bir değer, dizinin sonundan aramaya başlar. Varsayılan değer 0'dır.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>A {{jsxref("Boolean")}}.</p> + +<h2 id="Örnekler">Örnekler</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_dizi_uzunluğundan_büyük_veya_eşitse"><code>fromIndex</code> dizi uzunluğundan büyük veya eşitse</h3> + +<p>Eğer <code>fromIndex</code> dizinin uzunluğundan büyük veya eşitse, false döndürülür. Dizi aranmaz.</p> + +<pre class="brush: js">var arr = ['a', 'b', 'c']; + +arr.includes('c', 3); //false +arr.includes('c', 100); // false</pre> + +<h3 id="Hesaplanan_indis_0'dan_küçükse">Hesaplanan indis 0'dan küçükse</h3> + +<p>Eğer <code>fromIndex</code> negatifse, hesaplanan indis, <code>searchElement</code> için aramaya başlanacak konum olarak belirlenir. Hesaplanmış indis 0'dan küçükse, dizinin tamamı aranır.</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</pre> + +<h3 id="includes()_genel_bir_yöntem_olarak_kullanılması"><code>includes()</code> genel bir yöntem olarak kullanılması</h3> + +<p><code>includes()</code> yöntemi kasıtlı olarak geneldir. <code>this</code> değerinin bir Array nesnesi türünde olmasını gerektirmez, böylece diğer türlerdeki nesnelere (örn: dizi benzeri nesneler) uygulanabilir. Aşağıdaki örnek, fonksiyonun sahip olduğu <a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments">argümanlar</a> nesnesi için uygulanan <code>includes()</code> metodunu göstermektedir.</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="Polyfill">Polyfill</h2> + +<pre class="brush: js">// 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; + } + }); +} +</pre> + +<p><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty</a></code> desteklemeyen eski JavaScript motorlarını desteklemeniz gerekiyorsa, <code>Array.prototype</code> metodlarını non-enumerable yapamadığımız için polyfill uygulamamak daha iyidir.</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('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="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.includes")}}</p> +</div> + +<h2 id="See_also">See also</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/tr/web/javascript/reference/global_objects/array/index.html b/files/tr/web/javascript/reference/global_objects/array/index.html new file mode 100644 index 0000000000..7cebdbba0f --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/array/index.html @@ -0,0 +1,371 @@ +--- +title: Diziler +slug: Web/JavaScript/Reference/Global_Objects/Array +tags: + - Array + - JavaScript +translation_of: Web/JavaScript/Reference/Global_Objects/Array +--- +<div>{{JSRef}}</div> + +<p>JavaScript <strong><code>Array</code></strong> nesnesi, üst düzey, liste benzeri dizi yapıları için kullanılan genel bir nesnedir.</p> + +<p><strong>Bir dizi oluşturma</strong></p> + +<pre class="brush: js line-numbers language-js notranslate">var meyveler = ["Elma", "Muz"]; + +console.log(meyveler.length); +// 2</pre> + +<p><strong>Dizideki (indeks ile) elemana ulaşma</strong></p> + +<pre class="brush: js line-numbers language-js notranslate">var ilk = meyveler[0]; +// Elma + +var son = meyveler[meyveler.length - 1]; +/* Diziler sıfır-tabanlı olduğu için uzunluk-1'inci eleman son elemandır. +// Muz</pre> + +<p><strong>Bir dizi üzerinde döngü kurma</strong></p> + +<pre class="brush: js line-numbers language-js notranslate">meyveler.forEach(function (item, index, array) { + console.log(item, index); +}); +// Elma 0 +// Muz 1</pre> + +<p><strong>Dizinin sonuna eleman ekleme</strong></p> + +<pre class="brush: js line-numbers language-js notranslate">var yeniDizi = meyveler.push("Portakal"); +// ["Elma", "Muz", "Portakal"]</pre> + +<p><strong>Dizi sonundan eleman kaldırma</strong></p> + +<pre class="brush: js line-numbers language-js notranslate">var son = meyveler.pop(); // Portakal elemanını kaldır(sondan) +// ["Elma", "Muz"];</pre> + +<p><strong>Dizi başından eleman kaldırma</strong></p> + +<pre class="brush: js line-numbers language-js notranslate">var ilk = fruits.shift(); // Elma elemanını kaldır(baştan) +// ["Muz"];</pre> + +<p><strong>Dizi başına eleman ekleme</strong></p> + +<pre class="brush: js line-numbers language-js notranslate">var yeniDizi = fruits.unshift("Çilek") // Başa ekle +// ["Çilek", "Muz"];</pre> + +<p><strong>Dizideki elemanın kaçıncı sırada olduğunu bulma</strong></p> + +<pre class="brush: js line-numbers language-js notranslate">meyveler.push("Mango"); +// ["Çilek", "Muz", "Mango"] + +var pos = meyveler.indexOf("Muz"); +// 1</pre> + +<p><strong>Belirli bir sıradaki elemanı silme</strong></p> + +<pre class="brush: js line-numbers language-js notranslate">var silinenEleman = meyveler.splice(pos, 1); // bir elemanı kaldırma +// ["Çilek", "Mango"] +</pre> + +<p><strong>Dizi kopyalama</strong></p> + +<pre class="brush: js line-numbers language-js notranslate">var kopyalananDizi = meyveler.slice(); // +// ["Çilek", "Mango"]</pre> + +<h2 id="Söz_Dizimi">Söz Dizimi</h2> + +<pre class="syntaxbox notranslate">[<var>element0</var>, <var>element1</var>, ..., <var>elementN</var>] +new Array(<em>element0</em>, <em>element1</em>, ..., <em>elementN</em>) +new Array(<em>diziUzunlugu</em>) +</pre> + +<div class="note"> +<p><strong>Not: </strong>N + 1 = dizi uzunluğu</p> +</div> + +<dl> + <dt><code><var>element0</var>, <var>element1</var>, ..., <var>elementN</var> </code></dt> + <dd>Bir dizi <code>new Array() </code>nesnesine verilen argüman dışında(yukarıdaki diziUzunluğu argümanı gibi), verilen elemanlar ile oluşturulabilir.(Yukarıda görüldüğü üzere) Bu özel durum sadece <code>new Array()</code> nesnesiyle (<code>Array </code>Constructor) oluşturulan dizilere uygulanabilir, köşeli parantezler ( [ ve ] ) ile oluşturulan dizilere uygulanamaz.</dd> + <dt><code><var>arrayLength </var></code><var>(dizi uzunluğu)</var></dt> + <dd><code>array </code>nesnesinden sadece 0 ve 2<sup>32</sup>-1 (dahil) arasındaki tam sayılardan biri argüman olarak geçirilebilir.</dd> + <dd>If the only argument passed to the <code>Array</code> constructor is an integer between 0 and 2<sup>32</sup>-1 (inclusive), a new, empty JavaScript array and its length is set to that number. If the argument is any other number, a {{jsxref("Global_Objects/RangeError", "RangeError")}} exception is thrown.</dd> +</dl> + +<h2 id="Tanım">Tanım</h2> + +<p>Diziler liste benzeri nesnelerdir ve dönüştürme, tekrarlama gibi işlemlerini uygulamak için dahili methotlarla gelmektedir. JavaScript dizilerinin ne uzunlukları nede elemanları sabit değildir. Önceden tanımlamak gerekmez. Listenin uzunluğu her daim değişebilir ve dizi elemanları ayrık yerleştirilebilir. JavaScript dizilerin düzenli olmasını garanti etmez. Kullanımı tamamen geliştiricinin kullanım senaryosuna bağlıdır. Genel olarak bu yapı esnek ve kullanışlıdır fakat bu özelliklerin sizin belirli kullanım senaryonuzla uyuşup uyuşmadığını dikkate almalısınız.</p> + +<p>Note that <a class="external" href="http://www.andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/">you shouldn't use an array as an associative array</a>. You can use plain {{jsxref("Global_Objects/Object", "objects")}} instead, although doing so comes with its own caveats. See the post <a class="external" href="http://www.less-broken.com/blog/2010/12/lightweight-javascript-dictionaries.html" title="http://monogatari.doukut.su/2010/12/lightweight-javascript-dictionaries.html">Lightweight JavaScript dictionaries with arbitrary keys</a> as an example.</p> + +<h3 id="Dizi_nesnelerine_erişme">Dizi nesnelerine erişme</h3> + +<p>JS dizileri sıfır-tabanlı'dır. Yani ilk elemanın dizideki index'i 0'dır. Son elemanın index'i {{jsxref("Array.length", "length")}} değerinin bir eksiğine eşittir.</p> + +<pre class="brush: js notranslate">var arr = ["bu ilk eleman", "bu ikinci eleman"]; +console.log(arr[0]); // ilk elemanı yazdırır +console.log(arr[1]); // ikinci elemanı yazdırır +console.log(arr[arr.length - 1]); // son elemanı yazdırır +</pre> + +<p>Dizi öğeleri, {{jsxref("Array.toString", "toString")}} gibi sadece nesne özellikleridir. Geçersiz index numarası ile eleman çağırdığınız zaman <code>undefined</code> değerini alırsınız. Ancak, dizinin bir elemanına aşağıdaki gibi erişmeye çalışırsanız söz dizimi hatası alırsınız, çünkü özellik adı geçerli değildir.</p> + +<pre class="brush: js notranslate">console.log(arr.0); // bir söz dizimi hatasıdır +</pre> + +<p>Yukardaki kullanımın söz dizimi hatasına yol açmasında özel bir durum yoktur nokta ile gösterim sayı değeri ile başlayamaz tıpkı değişken tanımlamalarında olduğu gibi. Eğer '3d' isimli bir obje değerine ulaşmak istiyorsanız obj['3d'] çağırımını yapmalısınız.</p> + +<pre class="brush: js notranslate">var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010]; +console.log(years.0); // söz dizimi hatası +console.log(years[0]); // çalışır +</pre> + +<pre class="brush: js notranslate">renderer.3d.setTexture(model, "character.png"); // söz dizimi hatası +renderer["3d"].setTexture(model, "character.png"); // çalışır +</pre> + +<p>Note that in the <code>3d</code> example, "<code>3d</code>" had to be quoted. It's possible to quote the JavaScript array indexes as well (e.g., <code>years["2"]</code> instead of <code>years[2]</code>), although it's not necessary. The 2 in <code>years[2]</code> eventually gets coerced into a string by the JavaScript engine, anyway, through an implicit <code>toString</code> conversion. It is for this reason that "2" and "02" would refer to two different slots on the <code>years</code> object and the following example logs <code>true</code>:</p> + +<pre class="brush: js notranslate">console.log(years["2"] != years["02"]); +</pre> + +<p>Similarly, object properties which happen to be reserved words(!) can only be accessed as string literals in bracket notation:</p> + +<pre class="brush: js language-js notranslate">var promise = { + 'var' : 'text', + 'array': [1, 2, 3, 4] +}; + +console.log(promise['array']);</pre> + +<h3 id="Uzunluk_ve_sayısal_özellikler_arasındaki_ilişki">Uzunluk ve sayısal özellikler arasındaki ilişki</h3> + +<p>Bir JavaScript dizisinin {{jsxref("Array.length", "length")}} özelliği ve sayısal özellikleri bağlıdır. Bir takım ön tanımlı dizi metotları (örn., {{jsxref("Array.join", "join")}}, {{jsxref("Array.slice", "slice")}}, {{jsxref("Array.indexOf", "indexOf")}}, vb.) çağrıldıklarında, dizinin {{jsxref("Array.length", "length")}} özellik değerini hesaba katar. Diğer metotlar (örn., {{jsxref("Array.push", "push")}}, {{jsxref("Array.splice", "splice")}}, vb.) daha çok dizinin {{jsxref("Array.length", "length")}} özelliğinin güncellenmesine neden olur.</p> + +<pre class="brush: js notranslate">var meyveler = []; +meyveler.push("muz", "elma", "şeftali"); + +console.log(meyveler.length); // 3</pre> + +<p>Uygun bir index değeri ile beraber, bir dizi elemanı güncellenirse ve ilgili index sayısı dizi sınırları dışında ise; dizi boyutu, verilen index'e uyum sağlayacak biçimde büyüyecek ve Javascript motoru, dizinin {{jsxref("Array.length", "length")}} özelliğini uygun şekilde güncelleyecektir.</p> + +<pre class="brush: js notranslate">fruits[3] = "mango"; +console.log(fruits[3]); +console.log(fruits.length); // 4</pre> + +<p>Uzunluk özelliğini doğrudan ayarlamak, özel bir davranışa neden olur.</p> + +<pre class="brush: js notranslate">fruits.length = 10; +console.log(fruits); // Dizi, tanımsız olarak doldurulur +console.log(fruits.length); // 10 +</pre> + +<p>Bu özellik {{jsxref("Array.length")}} sayfasında daha ayrıntılı olarak anlatılmıştır.</p> + +<h3 id="Bir_diziyi_eşleşen_bir_sonuç_ile_oluşturmak">Bir diziyi eşleşen bir sonuç ile oluşturmak</h3> + +<p>Bir düzenli ifadeye yollanan metin sonucu bir JavaScript dizisi oluşturulabilir. Bu dizi, eşleşen sonuca ait özellikleri ve ifadeleri içerir. Böyle bir dizi {{jsxref("RegExp.exec")}}, {{jsxref("String.match")}}, ve {{jsxref("String.replace")}} tarafından döndürülür. Bu özellikler ve öğeleri açıklamaya yardımcı olabilmesi için aşağıdaki örneği ve altındaki tabloyu inceleyin.</p> + +<pre class="brush: js notranslate">// Match one d followed by one or more b's followed by one d +// Remember matched b's and the following d +// Ignore case + +var myRe = /d(b+)(d)/i; +var myArray = myRe.exec("cdbBdbsbz"); +</pre> + +<p>Eşleşen sonucun öğeleri ve özellikleri aşağıdaki gibidir:</p> + +<table class="fullwidth-table"> + <tbody> + <tr> + <td class="header">Özellik/Öğe</td> + <td class="header">Açıklama</td> + <td class="header">Örnek</td> + </tr> + <tr> + <td><code>input</code></td> + <td>Düzenli ifadeye yollanan metni işaret eden salt-okunur bir özelliktir.</td> + <td>cdbBdbsbz</td> + </tr> + <tr> + <td><code>index</code></td> + <td>Düzenli ifadeye yollanan metindeki eşleşmenin sıfır-tabanlı ve salt-okunur index özelliğidir.</td> + <td>1</td> + </tr> + <tr> + <td><code>[0]</code></td> + <td>Son eşleşen karakteri belirten salt-okunur bir özelliktir.</td> + <td>dbBd</td> + </tr> + <tr> + <td><code>[1], ...[n]</code></td> + <td>Read-only elements that specify the parenthesized substring matches, if included in the regular expression. The number of possible parenthesized substrings is unlimited.</td> + <td>[1]: bB<br> + [2]: d</td> + </tr> + </tbody> +</table> + +<h2 id="Özellikler">Özellikler</h2> + +<dl> + <dt>{{jsxref("Array.length")}}</dt> + <dd>The <code>Array</code> constructor's length property whose value is 1.</dd> + <dt>{{jsxref("Array.prototype")}}</dt> + <dd>Allows the addition of properties to all array objects.</dd> +</dl> + +<h2 id="Yöntemler">Yöntemler</h2> + +<dl> + <dt>{{jsxref("Array.from()")}} {{experimental_inline}}</dt> + <dd>Bir dizi benzeri veya bir yinelenebilir nesneden yeni bir Dizi örneği oluşturur.</dd> + <dt>{{jsxref("Array.isArray()")}}</dt> + <dd>Eğer bir dizi ise true, değilse false döndürür.</dd> + <dt>{{jsxref("Array.observe()")}} {{experimental_inline}}</dt> + <dd>Asynchronously observes changes to Arrays, similar to {{jsxref("Object.observe()")}} for objects. It provides a stream of changes in order of occurrence.</dd> + <dt>{{jsxref("Array.of()")}} {{experimental_inline}}</dt> + <dd>Creates a new <code>Array</code> instance with a variable number of arguments, regardless of number or type of the arguments.</dd> +</dl> + +<h2 id="Dizi_örnekleri"><code>Dizi</code> örnekleri</h2> + +<p>Tüm dizi örnekleri, {{jsxref("Array.prototype")}} 'dan türer. The prototype object of the <code>Array</code> constructor can be modified to affect all <code>Array</code> instances.</p> + +<h3 id="Özellikler_2">Özellikler</h3> + +<div>{{page('/tr/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Properties')}}</div> + +<h3 id="Metodlar">Metodlar</h3> + +<h4 id="Mutator_methods">Mutator methods</h4> + +<div>{{page('tr/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Mutator_methods')}}</div> + +<h4 id="Accessor_methods">Accessor methods</h4> + +<div>{{page('tr/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Accessor_methods')}}</div> + +<h4 id="Iteration_methods">Iteration methods</h4> + +<div>{{page('tr/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Iteration_methods')}}</div> + +<h2 id="Array_generic_methods"><code>Array</code> generic methods</h2> + +<p>Sometimes you would like to apply array methods to strings or other array-like objects (such as function {{jsxref("Functions/arguments", "arguments", "", 1)}}). By doing this, you treat a string as an array of characters (or otherwise treat a non-array as an array). For example, in order to check that every character in the variable <var>str</var> is a letter, you would write:</p> + +<pre class="brush: js notranslate">function isLetter(character) { + return (character >= "a" && character <= "z"); +} + +if (Array.prototype.every.call(str, isLetter)) + alert("The string '" + str + "' contains only letters!"); +</pre> + +<p>This notation is rather wasteful and JavaScript 1.6 introduced a generic shorthand:</p> + +<pre class="brush: js notranslate">if (Array.every(isLetter, str)) + alert("The string '" + str + "' contains only letters!"); +</pre> + +<p>{{jsxref("Global_Objects/String", "Generics", "#String_generic_methods", 1)}} are also available on {{jsxref("Global_Objects/String", "String")}}.</p> + +<p>These are currently not part of ECMAScript standards (though the ES6 {{jsxref("Array.from()")}} can be used to achieve this). The following is a shim to allow its use in all browsers:</p> + +<pre class="brush: js notranslate">// Assumes Array extras already present (one may use polyfills for these as well) +(function () { + 'use strict'; + + var i, + // We could also build the array of methods with the following, but the + // getOwnPropertyNames() method is non-shimable: + // Object.getOwnPropertyNames(Array).filter(function (methodName) {return typeof Array[methodName] === 'function'}); + methods = [ + 'join', 'reverse', 'sort', 'push', 'pop', 'shift', 'unshift', + 'splice', 'concat', 'slice', 'indexOf', 'lastIndexOf', + 'forEach', 'map', 'reduce', 'reduceRight', 'filter', + 'some', 'every', 'isArray' + ], + methodCount = methods.length, + assignArrayGeneric = function (methodName) { + var method = Array.prototype[methodName]; + Array[methodName] = function (arg1) { + return method.apply(arg1, Array.prototype.slice.call(arguments, 1)); + }; + }; + + for (i = 0; i < methodCount; i++) { + assignArrayGeneric(methods[i]); + } +}());</pre> + +<h2 id="Örnekler">Örnekler</h2> + +<h3 id="Bir_dizi_oluşturmak">Bir dizi oluşturmak</h3> + +<p>Aşağıdaki örnekte uzunluğu [0] olan bir dizi tanımlanıyor(<code>msgArray</code>), daha sonra <code>msgArray[0]</code> ve <code>msgArray[99]</code> indexlerine değer atanıyor ve böylece dizinin uzunluğu 100'e çıkıyor.</p> + +<pre class="brush: js notranslate">var msgArray = new Array(); +msgArray[0] = "Hello"; +msgArray[99] = "world"; + +if (msgArray.length == 100) + print("The length is 100."); +</pre> + +<h3 id="2_boyutlu_dizi_oluşturmak">2 boyutlu dizi oluşturmak</h3> + +<p>Aşağıdaki örnekte elemanları stringler olan 2 boyutlu bir diziden oluşturulmuş satranç tahtası bulunuyor. İlk hamle 'p' elemanının 6,4 indeksinden 4,4 indexine kopyalanarak yapılmış. Eski bulunduğu index olan 6,4 boş olarak işaretlenmiş.</p> + +<pre class="brush: js notranslate">var 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']]; +print(board.join('\n') + '\n\n'); + +// Move King's Pawn forward 2 +board[4][4] = board[6][4]; +board[6][4] = ' '; +print(board.join('\n')); +</pre> + +<p>Çıktı:</p> + +<pre class="eval notranslate">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> + +<h2 id="Tarayıcı_Uyumluluk_Tablosu">Tarayıcı Uyumluluk Tablosu</h2> + +<p>{{Compat("javascript.builtins.Array")}}</p> + +<h2 id="Daha_fazlası">Daha fazlası</h2> + +<ul> + <li><a href="https://github.com/plusdude/array-generics" title="https://github.com/plusdude/array-generics">Polyfill for JavaScript 1.8.5 Array Generics and ECMAScript 5 Array Extras</a></li> + <li><a href="/tr/docs/JavaScript/Guide/Working_with_Objects#Indexing_object_properties" title="JavaScript/Guide/Working_with_objects#Indexing_object_properties">"Indexing object properties" in JavaScript Guide: "Working with objects"</a></li> + <li><a href="/tr/docs/JavaScript/New_in_JavaScript/1.7#Array_comprehensions" title="New_in_JavaScript_1.7#Array_comprehensions">New in JavaScript 1.7: Array comprehensions</a></li> + <li><a href="/tr/docs/JavaScript/New_in_JavaScript/1.6#Array_extras" title="New_in_JavaScript_1.6#Array_extras">New in JavaScript 1.6: Array extras</a></li> + <li><a href="/tr/docs/JavaScript_typed_arrays" title="JavaScript_typed_arrays">Draft: Typed Arrays</a></li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/array/indexof/index.html b/files/tr/web/javascript/reference/global_objects/array/indexof/index.html new file mode 100644 index 0000000000..f53a9980d7 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/array/indexof/index.html @@ -0,0 +1,246 @@ +--- +title: Array.prototype.indexOf() +slug: Web/JavaScript/Reference/Global_Objects/Array/indexOf +translation_of: Web/JavaScript/Reference/Global_Objects/Array/indexOf +--- +<div>{{JSRef}}</div> + +<p><code><strong>indexOf()</strong></code> metodu, argüman olarak verilen elemanın array de ilk görüldüğü index'i verir. Eğer bu eleman array de bulunmuyorsa -1 değeri döner.</p> + +<pre class="brush: js">var a = [2, 9, 9]; +a.indexOf(2); // 0 +a.indexOf(7); // -1 + +if (a.indexOf(7) === -1) { + // eleman array de bulunmamaktadır. +} +</pre> + +<h2 id="Yazım">Yazım</h2> + +<pre class="syntaxbox"><var>arr</var>.indexOf(<var>aranacakEleman</var>) +<var>arr</var>.indexOf(<var>aranacakEleman</var>, <var>aramayaBaşlanacakİndex</var>) +</pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt><var>aranacakEleman</var></dt> + <dd>Array içerisinde aranacak elemanı karşılayacak metod parametresidir.</dd> + <dt><var>aramayaBaşlanacakİndex</var>{{optional_inline}}</dt> + <dd>Aramaya başlanacak index değerini karşılayacak metod parametresidir. Eğer index olarak gönderilmiş argümanın değeri array'in uzunluğuna eşit veya daha büyükse, metod -1 değerini döndürür, bu array'in hiç aranmayacağı anlamına gelmektedir. Eğer argümanın değeri negatif bir değerse bu durumda argüman değeri array'in sonundan offset olarak algılanacaktır. Not: eğer index argümanı negatif ise, array hala baştan sona aranacaktır. Bu durumda elemanın bulunduğu index negatif hesaplanırsa, bütün array baştan aranacaktır. Default: 0 (tüm array baştan aranacaktır).</dd> +</dl> + +<h3 id="Dönüş_değeri">Dönüş değeri</h3> + +<p>Elemanın array de ilk görüldüğü index; eğer eleman bulunamazsa <strong>-1 </strong>dir.</p> + +<h2 id="Açıklama">Açıklama</h2> + +<p><code>indexOf()</code> <var>aranacakEleman'ı </var><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Using_the_Equality_Operators">katı eşitlik</a> ilkesine göre dizi elemanları ile karşılaştırır (aynı yöntem <code>=== </code>veya üç eşittir operatörü tarafından da kullanılır<code>).</code></p> + +<h2 id="Örnekler">Örnekler</h2> + +<h3 id="indexOf()'u_kullanma"><code>indexOf()'u kullanma</code></h3> + +<p>Aşağıdaki örnekte <code>indexOf()</code> metodu kullanılarak, değerlerin bir dizideki konumları bulunuyor.</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="Bir_öğenin_tüm_konumlarını_bulma">Bir öğenin tüm konumlarını bulma</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="Bir_öğenin_dizide_olup_olmadığını_öğrenme_ve_diziyi_güncelleme">Bir öğenin dizide olup olmadığını öğrenme ve diziyi güncelleme</h3> + +<pre class="brush: js">function updateVegetablesCollection (veggies, veggie) { + if (veggies.indexOf(veggie) === -1) { + veggies.push(veggie); + console.log('New veggies collection is : ' + veggies); + } else if (veggies.indexOf(veggie) > -1) { + console.log(veggie + ' already exists in the veggies collection.'); + } +} + +var veggies = ['potato', 'tomato', 'chillies', 'green-pepper']; + +updateVegetablesCollection(veggies, 'spinach'); +// New veggies collection is : potato,tomato,chillies,green-papper,spinach +updateVegetablesCollection(veggies, 'spinach'); +// spinach already exists in the veggies collection. +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p><code>indexOf()</code> ECMA-262 standartlarına 5. sürümde eklendi; bu yüzden henüz tüm tarayıcılarda mevcut olmayabilir. Aşağıdaki kod parçasını kendi kodunuzun başına ekleyerek kullanabilirsiniz. Böylelikle <code>indexOf()</code> metodunu tarayıcı desteklemese bile kullanabilirsiniz. Aşağıdaki algoritma {{jsxref("Global_Objects/TypeError", "TypeError")}} ve {{jsxref("Math.abs()")}} öğelerinin orijinal değerlerine sahip olduğu varsayılarak ECMA-262, 5. sürümde belirtilenle eşleşir.</p> + +<pre class="brush: js">// Production steps of ECMA-262, Edition 5, 15.4.4.14 +// Reference: http://es5.github.io/#x15.4.4.14 +if (!Array.prototype.indexOf) { + Array.prototype.indexOf = function(searchElement, fromIndex) { + + var k; + + // 1. Let o be the result of calling ToObject passing + // the this value as the argument. + if (this == null) { + throw new TypeError('"this" is null or not defined'); + } + + 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 len is 0, return -1. + if (len === 0) { + return -1; + } + + // 5. If argument fromIndex was passed let n be + // ToInteger(fromIndex); else let n be 0. + var n = fromIndex | 0; + + // 6. If n >= len, return -1. + if (n >= len) { + return -1; + } + + // 7. If n >= 0, then Let k be n. + // 8. Else, n<0, Let k be len - abs(n). + // If k is less than 0, then let k be 0. + k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); + + // 9. Repeat, while k < len + while (k < len) { + // 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 + // i. Let elementK be the result of calling the Get + // internal method of o with the argument ToString(k). + // ii. Let same be the result of applying the + // Strict Equality Comparison Algorithm to + // searchElement and elementK. + // iii. If same is true, return k. + if (k in o && o[k] === searchElement) { + return k; + } + k++; + } + return -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('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="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>{{CompatGeckoDesktop("1.8")}}</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>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("1.8")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Compatibility_notes">Compatibility notes</h2> + +<ul> + <li>Starting with Firefox 47 {{geckoRelease(47)}}, this method will no longer return <code>-0</code>. For example, <code>[0].indexOf(0, -0)</code> will now always return <code>+0</code> ({{bug(1242043)}}).</li> +</ul> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Array.prototype.lastIndexOf()")}}</li> + <li>{{jsxref("TypedArray.prototype.indexOf()")}}</li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/array/isarray/index.html b/files/tr/web/javascript/reference/global_objects/array/isarray/index.html new file mode 100644 index 0000000000..aafa47718c --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/array/isarray/index.html @@ -0,0 +1,154 @@ +--- +title: Array.isArray() +slug: Web/JavaScript/Reference/Global_Objects/Array/isArray +tags: + - Dizi + - dizi kontrol +translation_of: Web/JavaScript/Reference/Global_Objects/Array/isArray +--- +<div>{{JSRef}}</div> + +<p><code><strong>Array.isArray()</strong></code> metodu değerin Array olup olmadığını kontrol eder. </p> + +<h2 id="Söz_dizimi">Söz dizimi</h2> + +<pre class="syntaxbox"><code>Array.isArray(<var>obj</var>)</code></pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>Kontrol edilecek nesne.</dd> +</dl> + +<h2 id="Açıklamalar">Açıklamalar</h2> + +<p>Nesne eğer {{jsxref("Array")}} ise <code>true</code> değilse <code>false </code>döndürür<code>.</code></p> + +<p>Daha fazla detay için makaleye göz atın: <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="Örnekler">Örnekler</h2> + +<pre class="brush: js">// Aşağıdaki tüm örnekler true döndürür +Array.isArray([]); +Array.isArray([1]); +Array.isArray(new Array()); +// Az bilinen gerçek: Array.prototype bir dizinin kendisidir: +Array.isArray(Array.prototype); + +// Aşağıdaki tüm örnekler false döndürür +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 }); +</pre> + +<h2 id="Kod_Parçası">Kod Parçası</h2> + +<p>Aşağıdaki kod, diğer kodlardan önce çalıştırılırsa; doğal olarak var olmaması durumunda Array.isArray() 'i oluşturacaktır.</p> + +<pre class="brush: js">if (!Array.isArray) { + Array.isArray = function(arg) { + return Object.prototype.toString.call(arg) === '[object Array]'; + }; +} +</pre> + +<h2 id="Tanımlamalar">Tanımlamalar</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Tanımlama</th> + <th scope="col">Durum</th> + <th scope="col">Açıklama</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.3.2', 'Array.isArray')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>İlk tanım. JavaScript 1.8.5 sürümünde uygulamaya koyuldu.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.isarray', 'Array.isArray')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.isarray', 'Array.isArray')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tarayıcı_uyumluluğu">Tarayıcı uyumluluğu</h2> + +<h2 id="CompatibilityTable"><span style="font-size: 14px; font-weight: normal; line-height: 1.5;">{{CompatibilityTable}}</span></h2> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Özellik</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Temel Destek</td> + <td>{{CompatChrome("5")}}</td> + <td>{{CompatGeckoDesktop("2.0")}}</td> + <td>{{CompatIE("9")}}</td> + <td>{{CompatOpera("10.5")}}</td> + <td>{{CompatSafari("5")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Özellik</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> + <table class="compat-table"> + <tbody> + <tr> + <td>Temel Destek</td> + <td> </td> + </tr> + </tbody> + </table> + </td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("2.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ayrıca_bakınız">Ayrıca bakınız</h2> + +<ul> + <li>{{jsxref("Array")}}</li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/array/join/index.html b/files/tr/web/javascript/reference/global_objects/array/join/index.html new file mode 100644 index 0000000000..37d876dc97 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/array/join/index.html @@ -0,0 +1,107 @@ +--- +title: Array.prototype.join() +slug: Web/JavaScript/Reference/Global_Objects/Array/join +translation_of: Web/JavaScript/Reference/Global_Objects/Array/join +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary"><code><strong>join()</strong></code> metodu bir array içerisinde yer alan bütün elemanları birleştirerek string bir ifade olarak geri döndürür. (veya <a href="/en-US/docs//en-US/docs/Web/JavaScript/Guide/Indexed_collections#Working_with_array-like_objects">array benzeri bir obje</a> olarak) Elemanlar varsayılan olarak virgül ile ayıracı ile ayrılır. İsteğe bağlı olarak elementleri birbirinden ayırmak için farklı ayıraçlar da kullanılabilir.</span></p> + +<div>{{EmbedInteractiveExample("pages/js/array-join.html")}}</div> + + + +<h2 id="Sözdizimi_(Syntax)">Sözdizimi (Syntax)</h2> + +<pre class="syntaxbox"><var>arr</var>.join([<var>separator</var>])</pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt><code>ayıraç</code> {{optional_inline}}</dt> + <dd>Bir diziye (array) ait elemanları birleştirerek string bir ifade haline getiir. Dizi içinde yer alan elamanları birbirine bağlarken istediğiniz ifadeyi ayıraç olarak kullanabilirsiniz. Eğer ayıraç kullanılmaz ise varsayılan ayıraç olarak virgül kullanılır. Eğer ayıraç olarak boş ifade ("") kullanılırsa, bütün dizinin bütün elemanları birbirine bitişik olacak şekilde dönüştürülür.</dd> +</dl> + +<p>String ifade oluşturulurken dizi (array) içerisinde yer alan bütün elemanlar kullanılır. Eğer array içerisinde eleman yok ise (array.length değeri sıfıra eşit ise) join metodu boş string ("") döndürür.</p> + +<h2 id="Açıklamalar">Açıklamalar</h2> + +<p>Dizi (array) içerisinde yer alan bütün elemanları tek bir ifade (string) haline getirir.</p> + +<p> </p> + +<div class="warning"> +<p>Eğer dizi içerisinde yer alan elemanlardan birinin değeri <code>undefined</code> veya <code>null</code> ise, o eleman boş ifadeye ("") dönüştürülür.</p> +</div> + +<h2 id="Örnekler">Örnekler</h2> + +<h3 id="Bir_arrayi_birleştirmenin_dört_farklı_yolu">Bir arrayi birleştirmenin dört farklı yolu</h3> + +<p>Aşağıda yer alan örnekte örnekte üç elemandan oluşan <strong>a</strong> dizisi oluşturup, farklı ayıraçlar kullanarak dört defa birleştirdik. İlk örnekte hiç bir ayıraç kullanmadık, ikinci örnekte virgül ve boşluk, üçüncü örnekte boşluk ve + işareti, son örnekte ise boş ifade (string) değeri kullandık</p> + +<pre class="brush: js">var a = ['Rüzgar', 'Yağmur', 'Ateş']; +a.join(); // 'Rüzgar,Yağmur,Ateş' +a.join(', '); // 'Rüzgar, Yağmur, Ateş' +a.join(' + '); // 'Rüzgar + Yağmur + Ateş' +a.join(''); // 'RüzgarYağmurAteş'</pre> + +<h3 id="Array_benzeri_obje_nasıl_birleştirlir">Array benzeri obje nasıl birleştirlir ?</h3> + +<p>Aşağıda yer alan örnekte array benzeri obje olarak bilinen (<code><a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments">a</a>rgümanlar</code>), yapıyı <code>Array.prototype.join</code> üzerinden call {{jsxref("Function.prototype.call")}} metodu kullanarak birleştireceğiz. </p> + +<pre class="brush: js">function f(a, b, c) { + var s = Array.prototype.join.call(arguments); + console.log(s); // '<span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body"><span class="objectBox objectBox-string">1,a,true'</span></span></span></span> +} +f(1, 'a', true); +//expected output: "1,a,true" +</pre> + +<h2 id="Özellikler">Özellikler</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.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> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.join', 'Array.prototype.join')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tarayıcı_Uyumluluğu">Tarayıcı Uyumluluğu</h2> + +<div class="hidden">Uyumluluk tablosu yapılandırılmış verilerden oluşmaktadır. Eğer bu verilere katkıda bulunmak isterseniz <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> linkinde yer alan repository'i açın ve bize pull request gönderin.</div> + +<p>{{Compat("javascript.builtins.Array.join")}}</p> + +<h2 id="See_also">See also</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/tr/web/javascript/reference/global_objects/array/length/index.html b/files/tr/web/javascript/reference/global_objects/array/length/index.html new file mode 100644 index 0000000000..b0ff9d264b --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/array/length/index.html @@ -0,0 +1,145 @@ +--- +title: Array.length +slug: Web/JavaScript/Reference/Global_Objects/Array/length +tags: + - Dizi + - dizi uzunluğu + - uzunluk +translation_of: Web/JavaScript/Reference/Global_Objects/Array/length +--- +<div>{{JSRef}}</div> + +<div>Dizinin <code><strong>length</strong></code> özelliği -yani uzunluğu-, bir dizideki öğe sayısını döndürür veya ayarlar. 32-bit işaretsiz bir tam sayı (integer) ile ifade edilir, sayısal değeri her zaman dizinin en yüksek değerli index'inden büyüktür.</div> + +<div> </div> + +<pre class="brush: js">var elemanlar = ["ayakkabılar", "gömlekler", "çoraplar", "kazaklar"]; +elemanlar.length; + +// 4 döndürür</pre> + +<h2 id="Açıklama">Açıklama</h2> + +<p>Uzunluk(length) özellik değeri, artı işaretli bir tam sayıdır ve değeri 2'nin 32. kuvvetinden küçüktür (2<sup>32</sup>).</p> + +<p><code>Uzunluk(length)</code> özellik değerini ayarlayarak bir diziyi istenen bir zamanda budayabilirsiniz. Bir diziyi <code>length</code> özelliğini ayarlayarak genişletirseniz, asıl öğe sayısı artmayacaktır; örneğin, uzunluğu 2 olan dizinin uzunluğunu 3 olarak ayarlarsanız, dizide hala 2 eleman olacaktır. Bu durumda, <code>length</code> özelliğinin her zaman dizideki tanımlı öğe sayısını göstermesi şart değildir. Ayrıca bkz. <a href="https://developer.mozilla.org/tr/docs/Web/JavaScript/Reference/Global_Objects/Array#Bir_diziyi_eşleşen_bir_sonuç_ile_oluşturmak" rel="internal">Bir diziyi eşleşen bir sonuç ile oluşturmak</a>.</p> + +<p>{{js_property_attributes(1, 0, 0)}}</p> + +<h2 id="Örnekler">Örnekler</h2> + +<h3 id="Bir_dizi_üzerinde_gezinim">Bir dizi üzerinde gezinim</h3> + +<p>Aşağıdaki örnekte, <code>numaralar</code> dizisinde, <code>length</code> özelliği kullanılarak gezinim yapılıyor. Her öğe değeri ikiye katlanıyor.</p> + +<pre class="brush: js">var numaralar = [1, 2, 3, 4, 5]; +var uzunluk = numaralar.length; +for (var i = 0; i < uzunluk; i++) { + numaralar[i] *= 2; +} +// numaralar şimdi [2, 4, 6, 8, 10] şeklindedir +</pre> + +<h3 id="Bir_diziyi_kısaltmak">Bir diziyi kısaltmak</h3> + +<p>Aşağıdaki örnekte <code>numaralar</code> dizi uzunluğu 3'ten büyükse, dizi kısaltılıyor.</p> + +<pre class="brush: js">var numaralar = [1, 2, 3, 4, 5]; + +if (numaralar.length > 3) { + numaralar.length = 3; +} + +console.log(numaralar); // [1, 2, 3] +console.log(numaralar.length); // 3 +</pre> + +<h2 id="Tanımlamalar">Tanımlamalar</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Tanımlama</th> + <th scope="col">Durum</th> + <th scope="col">Yorum</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>İlk tanım.</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="Tarayıcı_uyumluluğu">Tarayıcı uyumluluğu</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="Ayrıca_bakınız">Ayrıca bakınız</h2> + +<ul> + <li>{{jsxref("Array")}}</li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/array/map/index.html b/files/tr/web/javascript/reference/global_objects/array/map/index.html new file mode 100644 index 0000000000..0c8d66f4de --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/array/map/index.html @@ -0,0 +1,307 @@ +--- +title: Array.prototype.map() +slug: Web/JavaScript/Reference/Global_Objects/Array/map +translation_of: Web/JavaScript/Reference/Global_Objects/Array/map +--- +<div>{{JSRef}}</div> + +<p><code><strong>map()</strong></code> , dizinin her elemanı için, parametre olarak verilen fonksiyonu çağırır ve oluşan sonuçlarla da yeni bir dizi oluşturur.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-map.html")}}</div> + + + +<h2 id="Sözdizimi">Sözdizimi</h2> + +<pre class="syntaxbox"><var>var new_array = arr</var>.map(function <var>callback(currentValue[, index[, array]]) { + // Return element for new_array +}</var>[, <var>thisArg</var>])</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>Yeni oluşan dizinin elemanlarını döndürdüğü değerlerle oluşturur, üç parametre alır: + <dl> + <dt> </dt> + <dt><code>currentValue</code></dt> + <dd>Dizinin o anda işlem yapılan elemanı.</dd> + <dt><code>index</code>{{optional_inline}}</dt> + <dd>Dizinin o anda işlem yapılan elemanının indeksi.</dd> + <dt><code>array</code>{{optional_inline}}</dt> + <dd><code>map</code> tarafından çağırılan dizi.</dd> + </dl> + </dd> + <dt><code>thisArg</code>{{optional_inline}}</dt> + <dd><code>callback</code> fonsiyonu çalışırken kullanacağı <code>this</code> değeri.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>Elemanları, <code>callback</code> fonksiyonunun sonuçları olan yeni bir dizi.</p> + +<h2 id="Açıklama">Açıklama</h2> + +<p><code>map</code>, kendisine özel tahsis edilmiş geri çağırma (<code>callback</code>) fonksiyonunu çağırarak, sıraya uygun olarak <strong>döngüye </strong><strong>giren</strong><strong> her </strong><strong>eleman</strong> için sonuçtan yeni bir dizi(array) inşa eder. <code>callback</code> sadece değere tanımlanmış dizinin indeksleri için tetiklenir, <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined">undefined</a> de buna dahildir. Dizinin kayıp elemanları için çağrılmaz ( <strong>kayıp </strong><strong>elemanlar</strong>: silinmiş veya hiçbir değere eşitlenmemiş veya oluşmamış indeksleri ifade eder. )</p> + +<p><code>callback</code> şu üç argüman ile tetiklenir; Elemanın değeri, elemanın indeks numarası ve elemanları gezilecek olan dizi objesi...</p> + +<pre class="syntaxbox">dizi.map( (deger, index) => /* yapılacak işlem */ ) </pre> + +<p>If a <code>thisArg</code> parameter is provided to <code>map</code>, it will be used as callback's <code>this</code> value. Otherwise, the value {{jsxref("undefined")}} will be used as its <code>this</code> value. The <code>this</code> value ultimately observable by <code>callback</code> is determined according to <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">the usual rules for determining the <code>this</code> seen by a function</a>.</p> + +<p><code>map</code> does not mutate the array on which it is called (although <code>callback</code>, if invoked, may do so).</p> + +<p>The range of elements processed by <code>map</code> is set before the first invocation of <code>callback</code>. Elements which are appended to the array after the call to <code>map</code> begins will not be visited by <code>callback</code>. If existing elements of the array are changed, their value as passed to <code>callback</code> will be the value at the time <code>map</code> visits them. Elements that are deleted after the call to <code>map</code> begins and before being visited are not visited.<br> + <br> + Due to the algorithm defined in the specification if the array which map was called upon is sparse, resulting array will also be sparse keeping same indices blank.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Mapping_an_array_of_numbers_to_an_array_of_square_roots">Mapping an array of numbers to an array of square roots</h3> + +<p>The following code takes an array of numbers and creates a new array containing the square roots of the numbers in the first array.</p> + +<pre class="brush: js">var numbers = [1, 4, 9]; +var roots = numbers.map(Math.sqrt); +// roots is now [1, 2, 3] +// numbers is still [1, 4, 9] +</pre> + +<h3 id="Using_map_to_reformat_objects_in_an_array">Using map to reformat objects in an array</h3> + +<p>The following code takes an array of objects and creates a new array containing the newly reformatted objects.</p> + +<pre class="brush: js">var kvArray = [{key: 1, value: 10}, + {key: 2, value: 20}, + {key: 3, value: 30}]; + +var reformattedArray = kvArray.map(obj =>{ + var rObj = {}; + rObj[obj.key] = obj.value; + return rObj; +}) +// reformattedArray is now [{1: 10}, {2: 20}, {3: 30}], + +// kvArray is still: +// [{key: 1, value: 10}, +// {key: 2, value: 20}, +// {key: 3, value: 30}] +</pre> + +<h3 id="Mapping_an_array_of_numbers_using_a_function_containing_an_argument">Mapping an array of numbers using a function containing an argument</h3> + +<p>The following code shows how map works when a function requiring one argument is used with it. The argument will automatically be assigned from each element of the array as map loops through the original array.</p> + +<pre class="brush: js">var numbers = [1, 4, 9]; +var doubles = numbers.map(function(num) { + return num * 2; +}); + +// doubles is now [2, 8, 18] +// numbers is still [1, 4, 9] +</pre> + +<h3 id="Using_map_generically">Using <code>map</code> generically</h3> + +<p>This example shows how to use map on a {{jsxref("String")}} to get an array of bytes in the ASCII encoding representing the character values:</p> + +<pre class="brush: js">var map = Array.prototype.map; +var a = map.call('Hello World', function(x) { + return x.charCodeAt(0); +}); +// a now equals [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100] +</pre> + +<h3 id="Using_map_generically_querySelectorAll">Using <code>map</code> generically <code>querySelectorAll</code></h3> + +<p>This example shows how to iterate through a collection of objects collected by <code>querySelectorAll</code>. In this case we get all selected options on the screen and printed on the console:</p> + +<pre class="brush: js">var elems = document.querySelectorAll('select option:checked'); +var values = Array.prototype.map.call(elems, function(obj) { + return obj.value; +}); +</pre> + +<p>Easier way would be using {{jsxref("Array.from()")}} method.</p> + +<h3 id="Tricky_use_case">Tricky use case</h3> + +<p><a href="http://www.wirfs-brock.com/allen/posts/166">(inspired by this blog post)</a></p> + +<p>It is common to use the callback with one argument (the element being traversed). Certain functions are also commonly used with one argument, even though they take additional optional arguments. These habits may lead to confusing behaviors.</p> + +<pre class="brush: js">// Consider: +['1', '2', '3'].map(parseInt); +// While one could expect [1, 2, 3] +// The actual result is [1, NaN, NaN] + +// parseInt is often used with one argument, but takes two. +// The first is an expression and the second is the radix. +// To the callback function, Array.prototype.map passes 3 arguments: +// the element, the index, the array +// The third argument is ignored by parseInt, but not the second one, +// hence the possible confusion. See the blog post for more details + +function returnInt(element) { + return parseInt(element, 10); +} + +['1', '2', '3'].map(returnInt); // [1, 2, 3] +// Actual result is an array of numbers (as expected) + +// Same as above, but using the concise arrow function syntax +['1', '2', '3'].map( str => parseInt(str) ); + +// A simpler way to achieve the above, while avoiding the "gotcha": +['1', '2', '3'].map(Number); // [1, 2, 3] +// but unlike `parseInt` will also return a float or (resolved) exponential notation: +['1.1', '2.2e2', '3e300'].map(Number); // [1.1, 220, 3e+300] +</pre> + +<p>One alternative output of the map method being called with parseInt as a parameter runs as follows:</p> + +<pre class="brush: js">var xs = ['10', '10', '10']; + +xs = xs.map(parseInt); + +console.log(xs); +// Actual result of 10,NaN,2 may be unexpected based on the above description.</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p><code>map</code> was added to the ECMA-262 standard in the 5th edition; as such it may not be present in all implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of <code>map</code> in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming {{jsxref("Object")}}, {{jsxref("TypeError")}}, and {{jsxref("Array")}} have their original values and that <code>callback.call</code> evaluates to the original value of <code>{{jsxref("Function.prototype.call")}}</code>.</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 = arguments[1]; + } + + // 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">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>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.map")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Array.prototype.forEach()")}}</li> + <li>{{jsxref("Map")}} object</li> + <li>{{jsxref("Array.from()")}}</li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/array/of/index.html b/files/tr/web/javascript/reference/global_objects/array/of/index.html new file mode 100644 index 0000000000..07bd40a430 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/array/of/index.html @@ -0,0 +1,98 @@ +--- +title: Array.of() +slug: Web/JavaScript/Reference/Global_Objects/Array/of +tags: + - Dizi + - ECMAScript 2015 + - JavaScript + - metod + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/of +--- +<div>{{JSRef}}</div> + +<p><code><strong>Array.of()</strong></code> metodu, verilen argümanları içeren yeni bir dizi (<code>Array</code>) oluşturur. Argüman sayısı ve tipi konusunda herhangi bir kısıtı yoktur.</p> + +<p><code><strong>Array.of()</strong></code> ile <code><strong>Array</strong></code> yapıcı (constructor) arasındaki fark, sayısal argümanları kullanma biçimidir: <code><strong>Array.of(7)</strong></code> tek öğesi <code>7</code> olan bir dizi oluştururken, <code><strong>Array(7)</strong></code>, 7 öğe kapasiteli -<code>length</code> özelliği 7 olan- boş bir dizi oluşturur (<strong>Not:</strong> Bu ifade 7 boş yeri olan bir dizi oluştur, kapasitesi kadar tanımsız öğe içeren bir dizi değil).</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="Sözdizimi">Sözdizimi</h2> + +<pre class="syntaxbox">Array.of(<var>element0</var>[, <var>element1</var>[, ...[, <var>elementN</var>]]])</pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt><code>element<em>N</em></code></dt> + <dd>Diziyi oluşturacak öğeler.</dd> +</dl> + +<h3 id="Dönüş_değeri">Dönüş değeri</h3> + +<p>Yeni bir {{jsxref("Array")}} örneği.</p> + +<h2 id="Açıklama">Açıklama</h2> + +<p>Bu fonksiyon ECMAScript 2015 standardının bir parçasıdır. Daha fazla bilgi için <a href="https://gist.github.com/rwaldron/1074126"><code>Array.of</code> ve <code>Array.from</code> proposal</a> ve <a href="https://gist.github.com/rwaldron/3186576"><code>Array.of</code> polyfill</a> linklerine bakabilirsiniz.</p> + +<h2 id="Örnekler">Örnekler</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">Polyfill</h2> + +<p>Eğer <code>Array.of()</code> doğal olarak mevcut değilse, aşağıdaki kodu diğer kodlardan önce çalıştırarak oluşturabilirsiniz.</p> + +<pre class="brush: js">if (!Array.of) { + Array.of = function() { + return Array.prototype.slice.call(arguments); + }; +} +</pre> + +<h2 id="Şartnameler">Şartnameler</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Şartname</th> + <th scope="col">Durum</th> + <th scope="col">Yorum</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-array.of', 'Array.of')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>İlk tanım.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.of', 'Array.of')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tarayıcı_Uyumu">Tarayıcı Uyumu</h2> + +<div> +<div class="hidden">Bu sayfadaki uyumluluk tablosu, yapılandırılmış veriden oluşturulmuştur. Eğer katkıda bulunmak istiyorsanız, <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> adresini inceleyip bize çekme talebi gönderin.</div> + +<p>{{Compat("javascript.builtins.Array.of")}}</p> +</div> + +<h2 id="Ayrıca_bakınız">Ayrıca bakınız</h2> + +<ul> + <li>{{jsxref("Array")}}</li> + <li>{{jsxref("Array.from()")}}</li> + <li>{{jsxref("TypedArray.of()")}}</li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/array/pop/index.html b/files/tr/web/javascript/reference/global_objects/array/pop/index.html new file mode 100644 index 0000000000..649cb88921 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/array/pop/index.html @@ -0,0 +1,117 @@ +--- +title: Array.prototype.pop() +slug: Web/JavaScript/Reference/Global_Objects/Array/pop +translation_of: Web/JavaScript/Reference/Global_Objects/Array/pop +--- +<div>{{JSRef}}</div> + +<p><code><strong>pop()</strong></code> yöntemi, bir dizideki <strong>son</strong> öğeyi kaldırır ve o öğeyi döndürür. Bu yöntem dizinin uzunluğunu değiştirir.</p> + + + +<div>{{EmbedInteractiveExample("pages/js/array-pop.html")}}</div> + + + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><var>arr</var>.pop()</pre> + +<h3 id="Return_value">Return value</h3> + +<p>The removed element from the array; {{jsxref("undefined")}} if the array is empty.</p> + +<h2 id="Description">Description</h2> + +<p>The <code>pop</code> method removes the last element from an array and returns that value to the caller.</p> + +<p><code>pop</code> is intentionally generic; this method can be {{jsxref("Function.call", "called", "", 1)}} or {{jsxref("Function.apply", "applied", "", 1)}} to objects resembling arrays. 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.</p> + +<p>If you call <code>pop()</code> on an empty array, it returns {{jsxref("undefined")}}.</p> + +<p>{{jsxref("Array.prototype.shift()")}} has similar behavior to <code>pop</code>, but applied to the first element in an array.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Removing_the_last_element_of_an_array">Removing the last element of an array</h3> + +<p>The following code creates the <code>myFish</code> array containing four elements, then removes its last element.</p> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; + +var popped = myFish.pop(); + +console.log(myFish); // ['angel', 'clown', 'mandarin' ] + +console.log(popped); // 'sturgeon'</pre> + + + +<h3 id="Using_apply_or_call_on_array-like_objects">Using apply( ) or call ( ) on array-like objects</h3> + +<p>The following code creates the <code>myFish</code> array-like object containing four elements and a length parameter, then removes its last element and decrements the length parameter.</p> + +<pre class="brush: js">var myFish = {0:'angel', 1:'clown', 2:'mandarin', 3:'sturgeon', length: 4}; + +var popped = Array.prototype.pop.call(myFish); //same syntax for using apply( ) + +console.log(myFish); // {0:'angel', 1:'clown', 2:'mandarin', length: 3} + +console.log(popped); // 'sturgeon' +</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('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.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="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.pop")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Array.prototype.push()")}}</li> + <li>{{jsxref("Array.prototype.shift()")}}</li> + <li>{{jsxref("Array.prototype.unshift()")}}</li> + <li>{{jsxref("Array.prototype.concat()")}}</li> + <li>{{jsxref("Array.prototype.splice()")}}</li> +</ul> + +<div id="gtx-trans" style="position: absolute; left: 79px; top: 355px;"> +<div class="gtx-trans-icon"></div> +</div> diff --git a/files/tr/web/javascript/reference/global_objects/array/prototype/index.html b/files/tr/web/javascript/reference/global_objects/array/prototype/index.html new file mode 100644 index 0000000000..19ffe3c80f --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/array/prototype/index.html @@ -0,0 +1,205 @@ +--- +title: Array.prototype +slug: Web/JavaScript/Reference/Global_Objects/Array/prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Array/prototype +--- +<div>{{JSRef("Global_Objects", "Array")}}</div> + +<h2 id="Summary" name="Summary">Summary</h2> + +<p>The <strong><code>Array.prototype</code></strong> property represents the prototype for the {{jsxref("Global_Objects/Array", "Array")}} constructor.</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="Description" name="Description">Description</h2> + +<p>{{jsxref("Global_Objects/Array", "Array")}} instances inherit from <code>Array.prototype</code>. As with all constructors, you can change the constructor's prototype object to make changes to all {{jsxref("Global_Objects/Array", "Array")}} instances.</p> + +<p>Little known fact: <code>Array.prototype</code> itself is an {{jsxref("Global_Objects/Array", "Array")}}:</p> + +<pre class="brush: js">Array.isArray(Array.prototype); // true +</pre> + +<h2 id="Properties" name="Properties">Properties</h2> + +<dl> + <dt><code>Array.prototype.constructor</code></dt> + <dd>Specifies the function that creates an object's prototype.</dd> + <dt>{{jsxref("Array.prototype.length")}}</dt> + <dd>Reflects the number of elements in an array.</dd> +</dl> + +<h2 id="Methods" name="Methods">Methods</h2> + +<h3 id="Mutator_methods" name="Mutator_methods">Mutator methods</h3> + +<p>These methods modify the array:</p> + +<dl> + <dt>{{jsxref("Array.prototype.copyWithin()")}} {{experimental_inline}}</dt> + <dd>Copies a sequence of array elements within the array.</dd> + <dt>{{jsxref("Array.prototype.fill()")}} {{experimental_inline}}</dt> + <dd>Fills all the elements of an array from a start index to an end index with a static value.</dd> + <dt>{{jsxref("Array.prototype.pop()")}}</dt> + <dd>Removes the last element from an array and returns that element.</dd> + <dt>{{jsxref("Array.prototype.push()")}}</dt> + <dd>Adds one or more elements to the end of an array and returns the new length of the array.</dd> + <dt>{{jsxref("Array.prototype.reverse()")}}</dt> + <dd>Reverses the order of the elements of an array in place — the first becomes the last, and the last becomes the first.</dd> + <dt>{{jsxref("Array.prototype.shift()")}}</dt> + <dd>Removes the first element from an array and returns that element.</dd> + <dt>{{jsxref("Array.prototype.sort()")}}</dt> + <dd>Sorts the elements of an array in place and returns the array.</dd> + <dt>{{jsxref("Array.prototype.splice()")}}</dt> + <dd>Adds and/or removes elements from an array.</dd> + <dt>{{jsxref("Array.prototype.unshift()")}}</dt> + <dd>Adds one or more elements to the front of an array and returns the new length of the array.</dd> +</dl> + +<h3 id="Accessor_methods" name="Accessor_methods">Accessor methods</h3> + +<p>These methods do not modify the array and return some representation of the array.</p> + +<dl> + <dt>{{jsxref("Array.prototype.concat()")}}</dt> + <dd>Returns a new array comprised of this array joined with other array(s) and/or value(s).</dd> + <dt>{{jsxref("Array.prototype.includes()")}} {{experimental_inline}}</dt> + <dd>Determines whether an array contains a certain element, returning <code>true</code> or <code>false</code> as appropriate.</dd> + <dt>{{jsxref("Array.prototype.join()")}}</dt> + <dd>Joins all elements of an array into a string.</dd> + <dt>{{jsxref("Array.prototype.slice()")}}</dt> + <dd>Extracts a section of an array and returns a new array.</dd> + <dt>{{jsxref("Array.prototype.toSource()")}} {{non-standard_inline}}</dt> + <dd>Returns an array literal representing the specified array; you can use this value to create a new array. Overrides the {{jsxref("Object.prototype.toSource()")}} method.</dd> + <dt>{{jsxref("Array.prototype.toString()")}}</dt> + <dd>Returns a string representing the array and its elements. Overrides the {{jsxref("Object.prototype.toString()")}} method.</dd> + <dt>{{jsxref("Array.prototype.toLocaleString()")}}</dt> + <dd>Returns a localized string representing the array and its elements. Overrides the {{jsxref("Object.prototype.toLocaleString()")}} method.</dd> + <dt>{{jsxref("Array.prototype.indexOf()")}}</dt> + <dd>Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.</dd> + <dt>{{jsxref("Array.prototype.lastIndexOf()")}}</dt> + <dd>Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.</dd> +</dl> + +<h3 id="Iteration_methods" name="Iteration_methods">Iteration methods</h3> + +<p>Several methods take as arguments functions to be called back while processing the array. When these methods are called, the <code>length</code> of the array is sampled, and any element added beyond this length from within the callback is not visited. Other changes to the array (setting the value of or deleting an element) may affect the results of the operation if the method visits the changed element afterwards. While the specific behavior of these methods in such cases is well-defined, you should not rely upon it so as not to confuse others who might read your code. If you must mutate the array, copy into a new array instead.</p> + +<dl> + <dt>{{jsxref("Array.prototype.forEach()")}}</dt> + <dd>Calls a function for each element in the array.</dd> + <dt>{{jsxref("Array.prototype.entries()")}} {{experimental_inline}}</dt> + <dd>Returns a new <code>Array Iterator</code> object that contains the key/value pairs for each index in the array.</dd> + <dt>{{jsxref("Array.prototype.every()")}}</dt> + <dd>Returns true if every element in this array satisfies the provided testing function.</dd> + <dt>{{jsxref("Array.prototype.some()")}}</dt> + <dd>Returns true if at least one element in this array satisfies the provided testing function.</dd> + <dt>{{jsxref("Array.prototype.filter()")}}</dt> + <dd>Creates a new array with all of the elements of this array for which the provided filtering function returns true.</dd> + <dt>{{jsxref("Array.prototype.find()")}} {{experimental_inline}}</dt> + <dd>Returns the found value in the array, if an element in the array satisfies the provided testing function or <code>undefined</code> if not found.</dd> + <dt>{{jsxref("Array.prototype.findIndex()")}} {{experimental_inline}}</dt> + <dd>Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found.</dd> + <dt>{{jsxref("Array.prototype.keys()")}} {{experimental_inline}}</dt> + <dd>Returns a new <code>Array Iterator</code> that contains the keys for each index in the array.</dd> + <dt>{{jsxref("Array.prototype.map()")}}</dt> + <dd>Creates a new array with the results of calling a provided function on every element in this array.</dd> + <dt>{{jsxref("Array.prototype.reduce()")}}</dt> + <dd>Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value.</dd> + <dt>{{jsxref("Array.prototype.reduceRight()")}}</dt> + <dd>Apply a function against an accumulator and each value of the array (from right-to-left) as to reduce it to a single value.</dd> + <dt>{{jsxref("Array.prototype.values()")}} {{experimental_inline}}</dt> + <dd>Returns a new <code>Array Iterator</code> object that contains the values for each index in the array.</dd> + <dt>{{jsxref("Array.prototype.@@iterator()", "Array.prototype[@@iterator]()")}} {{experimental_inline}}</dt> + <dd>Returns a new <code>Array Iterator</code> object that contains the values for each index in the array.</dd> +</dl> + +<h3 id="Generic_methods" name="Generic_methods">Generic methods</h3> + +<p>Many methods on the JavaScript Array object are designed to be generally applied to all objects which “look like” Arrays. That is, they can be used on any object which has a <code>length</code> property, and which can usefully be accessed using numeric property names (as with <code>array[5]</code> indexing). <span class="comment">TODO: give examples with Array.prototype.forEach.call, and adding the method to an object like {{jsxref("Global_Objects/JavaArray", "JavaArray")}} or {{jsxref("Global_Objects/String", "String")}}.</span> Some methods, such as {{jsxref("Array.join", "join")}}, only read the <code>length</code> and numeric properties of the object they are called on. Others, like {{jsxref("Array.reverse", "reverse")}}, require that the object's numeric properties and <code>length</code> be mutable; these methods can therefore not be called on objects like {{jsxref("Global_Objects/String", "String")}}, which does not permit its <code>length</code> property or synthesized numeric properties to be set.</p> + +<h2 id="Specifications" name="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.4.3.1', 'Array.prototype')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype', 'Array.prototype')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="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/Array", "Array")}}</li> + <li>{{jsxref("Function.prototype")}}</li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/array/push/index.html b/files/tr/web/javascript/reference/global_objects/array/push/index.html new file mode 100644 index 0000000000..a5cd57980b --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/array/push/index.html @@ -0,0 +1,152 @@ +--- +title: Array.prototype.push() +slug: Web/JavaScript/Reference/Global_Objects/Array/push +tags: + - Dizi + - JavaScript + - Metot + - Prototype + - Referans +translation_of: Web/JavaScript/Reference/Global_Objects/Array/push +--- +<div>{{JSRef}}</div> + +<p><code><strong>push()</strong></code> metotu dizinin sonuna bir yada daha fazla element ekler ve dizinin yeni uzunluğunu geri döndürür.</p> + +<h2 id="Söz_dizimi">Söz dizimi</h2> + +<pre class="syntaxbox"><code><var>arr</var>.push(<var>element1</var>, ..., <var>elementN</var>)</code></pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt><code>element<em>N</em></code></dt> + <dd>Dizinin sonuna eklenecek elementler.</dd> +</dl> + +<h3 id="Geri_döndürür">Geri döndürür</h3> + +<p>Nesnenin yeni {{jsxref("Array.length", "length")}} özelliğini metotun çağrılması üzerine geri döndürür.</p> + +<h2 id="Tanım">Tanım</h2> + +<p><code>push</code> metotu değerleri bir diziye ekler.</p> + +<p><code>push</code> kasıtlı olarak genelleyicidir. Bu metot benzeyen nesnelerin dizilerinde {{jsxref("Function.call", "call()")}} veya {{jsxref("Function.apply", "apply()")}} ile kullanılabilir. <code>push</code> metotu verilen değerleri eklemeye nereden başlayacağını tespit etmek için <code>length</code> özelliğine dayanır. Eğer <code>length</code> özelliği bir sayıya dönüştürülemezse indeks 0 kabul edilir. Bu durum <code>length</code> özelliğinin bulunmama ihtimalini de kapsar, bu durumda <code>length</code> ayrıca oluşturulacaktır.</p> + +<p>Sadece yerel dizi benzeri nesneler {{jsxref("Global_Objects/String", "strings", "", 1)}} olduğu halde stringlerin değişmez olduğu gibi bu metotun uygulamalarına uygun değildirler.</p> + +<h2 id="Örnekler">Örnekler</h2> + +<h3 id="Bir_diziye_element_ekleme">Bir diziye element ekleme</h3> + +<p>Aşağıda bulunan kod iki elementi bulunan <code>sports</code> dizisini oluşturuyor, daha sonra iki diziye iki element daha ekliyor. <code>total</code> değişkeni dizinin yeni uzunluğunu tutuyor.</p> + +<pre class="brush: js">var sports = ['soccer', 'baseball']; +var total = sports.push('football', 'swimming'); + +console.log(sports); // ['soccer', 'baseball', 'football', 'swimming'] +console.log(total); // 4 +</pre> + +<h3 id="İki_diziyi_birleştirme">İki diziyi birleştirme</h3> + +<p>Bu örnek ikinci bir diziden bütün elemanları eklemek için {{jsxref("Function.apply", "apply()")}} kullanıyor.</p> + +<pre class="brush: js">var vegetables = ['parsnip', 'potato']; +var moreVegs = ['celery', 'beetroot']; + +// İkinci diziyi birinciyle birleştir +// Şuna eşdeğer, vegetables.push('celery', 'beetroot'); +Array.prototype.push.apply(vegetables, moreVegs); + +console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot'] +</pre> + +<h2 id="Şartnameler">Şartnameler</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Şartname</th> + <th scope="col">Durum</th> + <th scope="col">Yorum</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>İlk tanım. JavaScript 1.2'de uygulandı.</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> + </tbody> +</table> + +<h2 id="Tarayıcı_uyumu">Tarayıcı uyumu</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Özellik</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basit destek</td> + <td>{{CompatChrome("1.0")}}</td> + <td>{{CompatGeckoDesktop("1.7")}}</td> + <td>{{CompatIE("5.5")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Özellik</th> + <th>Android</th> + <th>Android için Chrome</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basit destek</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="Ayrıca_göz_at">Ayrıca göz at</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/tr/web/javascript/reference/global_objects/array/reverse/index.html b/files/tr/web/javascript/reference/global_objects/array/reverse/index.html new file mode 100644 index 0000000000..d9bdb98b76 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/array/reverse/index.html @@ -0,0 +1,107 @@ +--- +title: Array.prototype.reverse() +slug: Web/JavaScript/Reference/Global_Objects/Array/reverse +tags: + - JavaScript + - dizi ters çevirme + - fonksiyon +translation_of: Web/JavaScript/Reference/Global_Objects/Array/reverse +--- +<div>{{JSRef}}</div> + +<p><code><strong>reverse()</strong></code> metodu dizi elemanlarını tersten sıralar . Dizinin ilk elemanı son eleman olur, son elemanı ilk eleman olur.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-reverse.html")}}</div> + + + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><var>a</var>.reverse()</pre> + +<h3 id="Dönen_Değer">Dönen Değer</h3> + +<p>Ters dizi.</p> + +<h2 id="Açıklama">Açıklama</h2> + +<p><code>reverse</code> metodu dizinin olduğu halini kalıcı olarak değiştirir ve değiştirilmiş diziyi döndürür.</p> + +<p><code>reverse</code> bilinçli olarak generic metodtur; bu şekilde dizilere benzeyen nesneler <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call">çağrılabilir </a>veya <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply">uygulanabilir</a>. Bir dizi ardışık, sıfır tabanlı sayısal özellikte sonuncuyu yansıtan <code>length </code>özelliği içermeyen nesneler anlamlı bir şekilde davranmayabilir.</p> + +<h2 id="Örnekler">Örnekler</h2> + +<h3 id="Bir_dizideki_öğeleri_tersine_çevirme">Bir dizideki öğeleri tersine çevirme</h3> + +<p>Aşağıdaki örnek, üç öğe içeren bir <code>a </code>dizisi oluşturur, ardından diziyi tersine çevirir. <code>reverse()</code> çağrısı, ters çevrilmiş <code>a </code>dizisine bir referans döndürür.</p> + +<pre class="brush: js">const a = [1, 2, 3]; + +console.log(a); // [1, 2, 3] + +a.reverse(); + +console.log(a); // [3, 2, 1] + +</pre> + +<h3 id="Dizi_benzeri_bir_nesnedeki_öğeleri_tersine_çevirme">Dizi benzeri bir nesnedeki öğeleri tersine çevirme</h3> + +<p>Aşağıdaki örnek, üç öğe ve length özelliği içeren dizi benzeri bir nesne <code>a </code>oluşturur, sonra dizi benzeri nesneyi tersine çevirir. <code>reverse ()</code> çağrısı, ters dizi benzeri nesneye <code>a </code>bir referans döndürür.</p> + +<pre class="brush: js">const a = {0: 1, 1: 2, 2: 3, length: 3}; + +console.log(a); // {0: 1, 1: 2, 2: 3, length: 3} + +Array.prototype.reverse.call(a); //same syntax for using apply() + +console.log(a); // {0: 3, 1: 2, 2: 1, length: 3} +</pre> + +<h2 id="Özellikler">Özellikler</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Özellik</th> + <th scope="col">Durum</th> + <th scope="col">Yorum</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="Tarayıcı_Uyumluluğu">Tarayıcı Uyumluluğu</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.reverse")}}</p> +</div> + +<h2 id="See_also">See also</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/tr/web/javascript/reference/global_objects/array/shift/index.html b/files/tr/web/javascript/reference/global_objects/array/shift/index.html new file mode 100644 index 0000000000..3a85e72ca7 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/array/shift/index.html @@ -0,0 +1,112 @@ +--- +title: Array.prototype.shift() +slug: Web/JavaScript/Reference/Global_Objects/Array/shift +tags: + - Dizi + - JavaScript + - Prototype + - metod +translation_of: Web/JavaScript/Reference/Global_Objects/Array/shift +--- +<div>{{JSRef}}</div> + +<p><code><strong>shift()</strong></code> metodu bir dizinin <strong>ilk </strong>elementini diziden kaldırır ve kaldırılmış bu elementi geri döndürür. Bu metod dizinin boyunu değiştirir.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-shift.html")}}</div> + +<p class="hidden">Bu wtkileşimli örneğin kaynağı bir GitHub deposunda saklanmaktadır.Eğer bu etkileşimli örnekler projesine katkıda bulunmak isterseniz, lütfen <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> klonlayın ve bize bir "pull request" (çekme talebi) gönderin.</p> + +<h2 id="Dildizimi">Dildizimi</h2> + +<pre class="syntaxbox"><var>arr</var>.shift()</pre> + +<h3 id="Dönen_değer">Dönen değer</h3> + +<p>Diziden kaldırılan element; eğer dizi boş ise de {{jsxref("undefined")}} değerini döndürür.</p> + +<h2 id="Tanımlama">Tanımlama</h2> + +<p><code>shift</code> metodu sıfırıncı indeksteki elementi kaldırır ve ardışık indeksleri aşağı düşürür, daha sonra kaldırılan değeri geri döndürür. Eğer metod uygulandığında {{jsxref("Array.length", "length")}} değeri 0 ise, {{jsxref("undefined")}} geri döndürür.</p> + +<p><code>shift</code> özellikle geniş kapsamlıdır; bu metod {{jsxref("Function.call", "called", "", 1)}} veya {{jsxref("Function.apply", "applied", "", 1)}} dizilere benzeyen nesnelere de uygulanabilir. Ardışık bir serinin sonuncusu özelliği olan, sıfır-temelli, sayısal özellikleri olan ancak <code>length</code> özelliği bulundurmayan nesneler, anlamli bir davranış göstermeyebilirler.</p> + +<h2 id="Örnekler">Örnekler</h2> + +<h3 id="Bir_diziden_bir_elementi_kaldırmak">Bir diziden bir elementi kaldırmak</h3> + +<p>Aşağıdaki kod <code>myFish</code> dizisinin ilk elementini kaldırmadan önceki ve kaldırdıktan sonraki halini göstermektedir. Aynı zamanda kaldırılan elementi de gösterir:</p> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'mandarin', 'surgeon']; + +console.log('myFish öncesinde:', JSON.stringify(myFish)); +// myFish öncesinde: ['angel', 'clown', 'mandarin', 'surgeon'] + +var shifted = myFish.shift(); + +console.log('myFish sonrasında:', myFish); +// myFish sonrasında: ['clown', 'mandarin', 'surgeon'] + +console.log('Bu element kaldırıldı:', shifted); +// Bu element kaldırıldı: angel +</pre> + +<h3 id="shift()_metodunu_while_döngüsü_içerisinde_kullanmak">shift() metodunu while döngüsü içerisinde kullanmak</h3> + +<p>shift metodu sıklıkla while döngüsü içerisindeki şartlarda kullanılır . Takip eden örnekte her döngü dizi boşalana kadar bir sonraki elementi diziden kaldıracaktır:</p> + +<pre class="brush: js">var isimler = ["Andrew", "Edward", "Paul", "Chris" ,"John"]; + +while( (i = isimler.shift()) !== undefined ) { + console.log(i); +} +// Andrew, Edward, Paul, Chris, John +</pre> + +<h2 id="Özellikler">Özellikler</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Özellik</th> + <th scope="col">Durum</th> + <th scope="col">Açıklama</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>İlk tanımlama. JavaScript 1.2. de uygulandı.</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> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.shift', 'Array.prototype.shift')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tarayıcı_uyumluluğu">Tarayıcı uyumluluğu</h2> + +<div> +<div class="hidden">Bu sayfadaki uyumluluk tablosu yapılandırılmış verilerden üretilmiştir. Eğer verilere katkıda bulunmak isterseniz, lütfen <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> bakın ve bize bir "pull request" (çekme talebi) gönderin..</div> + +<p>{{Compat("javascript.builtins.Array.shift")}}</p> +</div> + +<h2 id="Ayrıca_bakınız">Ayrıca bakınız</h2> + +<ul> + <li>{{jsxref("Array.prototype.push()")}}</li> + <li>{{jsxref("Array.prototype.pop()")}}</li> + <li>{{jsxref("Array.prototype.unshift()")}}</li> + <li>{{jsxref("Array.prototype.concat()")}}</li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/array/sort/index.html b/files/tr/web/javascript/reference/global_objects/array/sort/index.html new file mode 100644 index 0000000000..783a3048f3 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/array/sort/index.html @@ -0,0 +1,251 @@ +--- +title: Array.prototype.sort() +slug: Web/JavaScript/Reference/Global_Objects/Array/sort +tags: + - Dizi + - Dizi methodu + - Sıralama + - metod +translation_of: Web/JavaScript/Reference/Global_Objects/Array/sort +--- +<div>{{JSRef}}</div> + +<p><code><strong>sort()</strong></code> metodu dizi ögelerini sıralayarak, ilgili dizini sıralanmış olarak geri döndürür. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.</p> + +<p>The time and space complexity of the sort cannot be guaranteed as it depends on the implementation.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-sort.html")}}</div> + + + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><var>arr</var>.sort(<var>[compareFunction]</var>) +</pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt><code>compareFunction</code> {{optional_inline}}</dt> + <dd>Specifies a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's <a href="/en-US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#Unicode">Unicode</a> code point value. + <dl> + <dt><code>firstEl</code></dt> + <dd>The first element for comparison.</dd> + <dt><code>secondEl</code></dt> + <dd>The second element for comparison.</dd> + </dl> + </dd> +</dl> + +<h3 id="Geri_dönen_değer">Geri dönen değer</h3> + +<p>The sorted array. Note that the array is sorted <em><a href="https://en.wikipedia.org/wiki/In-place_algorithm">in place</a></em>, and no copy is made.</p> + +<h2 id="Açıklama">Açıklama</h2> + +<p>If <code>compareFunction</code> is not supplied, all non-<code>undefined</code> array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order. For example, "banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in the Unicode order. All <code>undefined</code> elements are sorted to the end of the array.</p> + +<div class="blockIndicator note"> +<p><strong>Note :</strong> In UTF-16, Unicode characters above <code>\uFFFF</code> are encoded as two surrogate code units, of the range <code>\uD800</code>-<code>\uDFFF</code>. The value of each code unit is taken separately into account for the comparison. Thus the character formed by the surrogate pair <code>\uD655\uDE55</code> will be sorted before the character <code>\uFF3A</code>.</p> +</div> + +<p>If <code>compareFunction</code> is supplied, all non-<code>undefined</code> array elements are sorted according to the return value of the compare function (all <code>undefined</code> elements are sorted to the end of the array, with no call to <code>compareFunction</code>). If <code>a</code> and <code>b</code> are two elements being compared, then:</p> + +<ul> + <li>If <code>compareFunction(a, b)</code> returns less than 0, sort <code>a</code> to an index lower than <code>b</code> (i.e. <code>a</code> comes first).</li> + <li>If <code>compareFunction(a, b)</code> returns 0, leave <code>a</code> and <code>b</code> unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behavior, thus, not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.</li> + <li>If <code>compareFunction(a, b)</code> returns greater than 0, sort <code>b</code> to an index lower than <code>a</code> (i.e. <code>b</code> comes first).</li> + <li><code>compareFunction(a, b)</code> must always return the same value when given a specific pair of elements <code>a</code> and <code>b</code> as its two arguments. If inconsistent results are returned, then the sort order is undefined.</li> +</ul> + +<p>So, the compare function has the following form:</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>To compare numbers instead of strings, the compare function can simply subtract <code>b</code> from <code>a</code>. The following function will sort the array in ascending order (if it doesn't contain <code>Infinity</code> and <code>NaN</code>):</p> + +<pre class="brush: js">function compareNumbers(a, b) { + return a - b; +} +</pre> + +<p>The <code>sort</code> method can be conveniently used with {{jsxref("Operators/function", "function expressions", "", 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>ES2015 provides {{jsxref("Functions/Arrow_functions", "arrow function expressions", "", 1)}} with even shorter syntax.</p> + +<pre class="brush: js">let numbers = [4, 2, 5, 1, 3]; +numbers.sort((a, b) => a - b); +console.log(numbers); + +// [1, 2, 3, 4, 5]</pre> + +<p>Objects can be sorted, given the value of one of their properties.</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 } +]; + +// sort by value +items.sort(function (a, b) { + return a.value - b.value; +}); + +// sort by 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; + } + + // names must be equal + return 0; +});</pre> + +<h2 id="Örnekler">Örnekler</h2> + +<h3 id="Creating_displaying_and_sorting_an_array">Creating, displaying, and sorting an array</h3> + +<p>The following example creates four arrays and displays the original array, then the sorted arrays. The numeric arrays are sorted without a compare function, then sorted using one.</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>This example produces the following output. As the output shows, when a compare function is used, numbers sort correctly whether they are numbers or numeric strings.</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_olmayan_karakterleri_sıralama">ASCII olmayan karakterleri sıralama</h3> + +<p>For sorting strings with non-ASCII characters, i.e. strings with accented characters (e, é, è, a, ä, etc.), strings from languages other than English, use {{jsxref("String.localeCompare")}}. This function can compare those characters so they appear in the right order.</p> + +<pre class="brush: js">var items = ['réservé', 'premier', 'communiqué', 'café', 'adieu', 'éclair']; +items.sort(function (a, b) { + return a.localeCompare(b); +}); + +// items is ['adieu', 'café', 'communiqué', 'éclair', 'premier', 'réservé'] +</pre> + +<h3 id="Map_ile_sıralama">Map ile sıralama</h3> + +<p>The <code>compareFunction</code> can be invoked multiple times per element within the array. Depending on the <code>compareFunction</code>'s nature, this may yield a high overhead. The more work a <code>compareFunction</code> does and the more elements there are to sort, it may be more efficient to use <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a> for sorting. The idea is to traverse the array once to extract the actual values used for sorting into a temporary array, sort the temporary array, and then traverse the temporary array to achieve the right order.</p> + +<pre class="brush: js" dir="rtl">// the array to be sorted +var list = ['Delta', 'alpha', 'CHARLIE', 'bravo']; + +// temporary array holds objects with position and sort-value +var mapped = list.map(function(el, i) { + return { index: i, value: el.toLowerCase() }; +}) + +// sorting the mapped array containing the reduced values +mapped.sort(function(a, b) { + if (a.value > b.value) { + return 1; + } + if (a.value < b.value) { + return -1; + } + return 0; +}); + +// container for the resulting order +var result = mapped.map(function(el){ + return list[el.index]; +}); +</pre> + +<p>There is an open source library available called <a href="https://null.house/open-source/mapsort">mapsort</a> which applies this approach.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.sort', 'Array.prototype.sort')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Tarayıcı_uyumluluğu">Tarayıcı uyumluluğu</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.sort")}}</p> +</div> + +<h2 id="Bunlarada_göz_at">Bunlarada göz at</h2> + +<ul> + <li>{{jsxref("Array.prototype.reverse()")}}</li> + <li>{{jsxref("String.prototype.localeCompare()")}}</li> + <li><a href="https://v8.dev/blog/array-sort">About the stability of the algorithm used by V8 engine</a></li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/array/splice/index.html b/files/tr/web/javascript/reference/global_objects/array/splice/index.html new file mode 100644 index 0000000000..b853160481 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/array/splice/index.html @@ -0,0 +1,149 @@ +--- +title: Array.prototype.splice() +slug: Web/JavaScript/Reference/Global_Objects/Array/splice +tags: + - Dizi + - Referans + - metod + - prototip +translation_of: Web/JavaScript/Reference/Global_Objects/Array/splice +--- +<div>{{JSRef}}</div> + +<p><code><strong>splice()</strong></code> metodu; bir Dizi'nin içeriklerini, diziye ait öğeleri kaldırarak veya yeni öğeler ekleyerek ve/veya mevcut öğeleri silerek değiştirir.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-splice.html")}}</div> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><var>array</var>.splice(<var>başlangıç[</var>, <var>silinecekAdet[</var>, <var>item1[</var>, <var>item2[</var>, <em>...]]]]</em>) +</pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt><code>başlangıç</code></dt> + <dd>Dizi'yi değiştirmek için başlanılacak indeks (0 kökenli indeks). Dizi'nin uzunluğundan daha büyük ise, başlangıç indeksi Dizi'nin uzunluğuna ayarlanacak. Negatif ise, Dizi'nin sonundaki öğeler toplamından başlayacak (-1 kökenli indeks) ve eğer kesin değer Dizi'nin uzunluğundan büyük ise, başlangıç değeri 0 olacak.</dd> + <dt><code>silinecekAdet</code> {{optional_inline}}</dt> + <dd>Eski Dizi'nden silinecek öğelerin sayısını belirten bir tamsayı.</dd> + <dd><code>silinecekAdet</code> belirlenmemiş ise, veya değeri <code>dizi.uzunluk - başlangıç</code> 'tan büyük ise (daha sade bir tanımı, <code>başlangıç</code> başlayarak, Dizi'nde kalmış öğelerin toplam sayısından fazla ise), <code>start</code> sayısından Dizi'nin sonuna kadar yer alan bütün öğeler silinecek.</dd> + <dd><code>silinecekAdet</code> 0 veya negatif ise, hiçbir öğe silinmeyecek. Bu durumda, en az yeni bir öğe tanımlamalısın (aşağı bkz.).</dd> + <dt><code>item1, item2, <em>...</em></code> {{optional_inline}}</dt> + <dd>Dizi'ne eklenecek olan öğeler, <code>başlangıç</code> indeksinden başlayarak. hiçbir öğe tanımlamaz isen, <code>splice()</code> sadece Dizi'den öğeleri kaldıracak.</dd> +</dl> + +<h3 id="Geri_dönüş_değeri">Geri dönüş değeri</h3> + +<p>Silinen öğeleri barındıran bir Dizi. Sadece bir öğe silinmiş ise, tek öğeli bir Dizi geri dönülecek. Hiçbir öğe silinmemiş ise, boş bir Dizi dönecek.</p> + +<h2 id="Açıklama">Açıklama</h2> + +<p>Sileceğin öğe sayısından farklı bir sayıda öğe tanımlıyorsan, çağrının sonunda Dizi farklı bir uzunluğa sahip olacak.</p> + +<h2 id="Örnekler">Örnekler</h2> + +<h3 id="2_indeksinden_önce_0_öğe_sil_ve_drum_öğesini_ekle">2 indeksinden önce 0 öğe sil, ve "drum" öğesini ekle</h3> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; +var removed = myFish.splice(2, 0, 'drum'); + +// myFish dizi öğeleri ["angel", "clown", "drum", "mandarin", "sturgeon"] +// silinen [], hiçbir öğe silinmedi +</pre> + +<h3 id="3_indeksinden_1_öğe_sil">3 indeksinden 1 öğe sil</h3> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon']; +var removed = myFish.splice(3, 1); + +// silinen ["mandarin"] +// myFish Dizi'si ["angel", "clown", "drum", "sturgeon"] +</pre> + +<h3 id="2_indeksinden_1_öğe_sil_ve_trumpet_öğesini_ekle">2 indeksinden 1 öğe sil, ve "trumpet" öğesini ekle</h3> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'drum', 'sturgeon']; +var silinen = myFish.splice(2, 1, 'trumpet'); + +// myFish is ["angel", "clown", "trumpet", "sturgeon"] +// silinen ["drum"]</pre> + +<h3 id="0_indeksinden_başlayarak_2_öğe_sil_parrot_anemone_ve_blue_öğelerini_ekle">0 indeksinden başlayarak 2 öğe sil, "parrot", "anemone" ve "blue" öğelerini ekle</h3> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'trumpet', 'sturgeon']; +var silinen = myFish.splice(0, 2, 'parrot', 'anemone', 'blue'); + +// myFish is ["parrot", "anemone", "blue", "trumpet", "sturgeon"] +// silinen ["angel", "clown"]</pre> + +<h3 id="2_indeksinden_2_öğe_sil">2 indeksinden 2 öğe sil</h3> + +<pre class="brush: js">var myFish = ['parrot', 'anemone', 'blue', 'trumpet', 'sturgeon']; +var silinen = myFish.splice(myFish.length - 3, 2); + +// myFish is ["parrot", "anemone", "sturgeon"] +// silinen ["blue", "trumpet"]</pre> + +<h3 id="-2_indeksinden_1_öğe_sil">-2 indeksinden 1 öğe sil</h3> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; +var silinen = myFish.splice(-2, 1); + +// myFish ["angel", "clown", "sturgeon"] +// silinen ["mandarin"]</pre> + +<h3 id="2_indeksinden_sonra_bütün_öğeleri_sil_2_indeksi_de_dahil">2 indeksinden sonra bütün öğeleri sil (2 indeksi de dahil)</h3> + +<pre class="brush: js">var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; +var silinen = myFish.splice(2); + +// myFish ["angel", "clown"] +// silinen ["mandarin", "sturgeon"]</pre> + +<h2 id="Özellikler">Özellikler</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Özellik</th> + <th scope="col">Durum</th> + <th scope="col">Yorum</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> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.splice', 'Array.prototype.splice')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Tarayıcı_Uyumluluğu">Tarayıcı Uyumluluğu</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.splice")}}</p> +</div> + +<h2 id="Bkz.">Bkz.</h2> + +<ul> + <li>{{jsxref("Array.prototype.push()", "push()")}} / {{jsxref("Array.prototype.pop()", "pop()")}} — add/remove elements from the end of the array</li> + <li>{{jsxref("Array.prototype.unshift()", "unshift()")}} / {{jsxref("Array.prototype.shift()", "shift()")}} — add/remove elements from the beginning of the array</li> + <li>{{jsxref("Array.prototype.concat()", "concat()")}} — returns a new array comprised of this array joined with other array(s) and/or value(s)</li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/array/unshift/index.html b/files/tr/web/javascript/reference/global_objects/array/unshift/index.html new file mode 100644 index 0000000000..a34d4d8713 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/array/unshift/index.html @@ -0,0 +1,114 @@ +--- +title: Array.prototype.unshift() +slug: Web/JavaScript/Reference/Global_Objects/Array/unshift +translation_of: Web/JavaScript/Reference/Global_Objects/Array/unshift +--- +<div>{{JSRef}}</div> + +<p><code><strong>unshift()</strong></code> metodu dizinin başına bir veya daha fazla element ekler ve yeni dizinin uzunluğunu size geri döndürür.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-unshift.html")}}</div> + +<h2 id="Sözdizimi_Kuralları">Sözdizimi Kuralları</h2> + +<pre class="syntaxbox"><em>dizi</em>.unshift(<var>element1</var>[, ...[, <var>elementN</var>]])</pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt><code>element<em>N</em></code></dt> + <dd>Dizinin başına eklenecek değer.</dd> +</dl> + +<h3 id="Döndürülen_değer">Döndürülen değer</h3> + +<p>Üzerinde işlem yapılan dizinin yeni {{jsxref("Array.length", "length")}} değerini verir.</p> + +<h2 id="Açıklama">Açıklama</h2> + +<p><code>unshift</code><font><font>, girilen değerleri bir dizinin başına ekler.</font></font></p> + +<p><code>unshift</code><font><font>kasıtlı olarak geneldir; </font><font>bu yöntem, benzer nesnelere </font></font>{{jsxref("Function.call", "called", "", 1)}} veya<font><font> </font></font>{{jsxref("Function.apply", "applied", "", 1)}} <font><font>olabilir. diziler. </font><font>Birbirini </font></font><code>length</code> <font><font>ardışık, sıfıra dayalı sayısal özellikler dizisinde sonuncuyu yansıtan </font><font>bir </font><font>özellik </font><font>içermeyen nesneler </font><font>, anlamlı şekilde davranamazlar.</font></font></p> + +<p><font><font>Birden fazla eleman parametre olarak girildiğinde, elemanlar parametre sırasına göre dizinin başına yerleştirilmektedir. Parametreleri ayrı unshift metodlarıyla eklemek ve sadece bir unshift metodunda eklemek aynı sonucu vermez.</font></font></p> + +<pre class="syntaxbox">let dizi = [4, 5, 6]; +dizi.unshift(1, 2, 3); +console.log(dizi); +// [<strong>1, 2, 3</strong>, 4, 5, 6] + +dizi = [4, 5, 6]; // dizi sıfırlanır. + +dizi.unshift(1); +dizi.unshift(2); +dizi.unshift(3); + +console.log(dizi); +// [<strong>3, 2, 1</strong>, 4, 5, 6] +</pre> + +<h2 id="Örnekler">Örnekler</h2> + +<pre class="brush: js">let dizi = [1, 2]; + +dizi.unshift(0); // dizinin uzunluğu 3 olur. +// dizi: [0, 1, 2] + +dizi.unshift(-2, -1); // dizinin uzunluğu 5 olur. +// dizi: [-2, -1, 0, 1, 2] + +dizi.unshift([-4, -3]); // dizinin uzunluğu 6 olur. +// dizi: [[-4, -3], -2, -1, 0, 1, 2] + +dizi.unshift([-7, -6], [-5]); // dizinin uzunluğu 8 olur. +// dizi: [ [-7, -6], [-5], [-4, -3], -2, -1, 0, 1, 2 ] +</pre> + +<h2 id="Özellikler">Özellikler</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Özellik</th> + <th scope="col">Durum</th> + <th scope="col">Açıklama</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> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.unshift', 'Array.prototype.unshift')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Tarayıcı_desteği">Tarayıcı desteği</h2> + +<div> +<div class="hidden"><font>Bu sayfadaki uyumluluk tablosu yapılandırılmış verilerden üretilmiştir. </font><font>Verilere katkıda bulunmak istiyorsanız, lütfen</font><font><font> </font></font><a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> adresini ziyaret edin ve bize istek gönderin.</div> + +<p>{{Compat("javascript.builtins.Array.unshift")}}</p> +</div> + +<h2 id="Benzer_Makaleler">Benzer Makaleler</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/tr/web/javascript/reference/global_objects/array/values/index.html b/files/tr/web/javascript/reference/global_objects/array/values/index.html new file mode 100644 index 0000000000..1c949e93a5 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/array/values/index.html @@ -0,0 +1,86 @@ +--- +title: Array.prototype.values() +slug: Web/JavaScript/Reference/Global_Objects/Array/values +tags: + - Dizi yineleyici + - Iterator + - JavaScript + - metod + - prototip +translation_of: Web/JavaScript/Reference/Global_Objects/Array/values +--- +<div>{{JSRef}}</div> + +<div> </div> + +<p><strong><code>values()</code></strong> methodu dizideki tüm elemanları içeren yeni bir <strong><code>(Dizi yineleyici)</code></strong> nesnesi döner</p> + +<pre class="brush: js">var a = ['e', 'l', 'm', 'a']; +var yineleyici = a.values(); + +console.log(yineleyici.next().value); // e +console.log(yineleyici.next().value); // l +console.log(yineleyici.next().value); // m +console.log(yineleyici.next().value); // a + +</pre> + +<h2 id="Sintaks">Sintaks</h2> + +<pre class="syntaxbox"><var>arr</var>.values()</pre> + +<h3 id="Dönüş_değeri">Dönüş değeri</h3> + +<p>Yeni bir {{jsxref("Array")}} yineleyici nesne.</p> + +<h2 id="Örnekler">Örnekler</h2> + +<h3 id="for...of_loop_ile_yineleme"><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a></code> loop ile yineleme</h3> + +<pre class="brush: js">var arr = ['e', 'l', 'm', 'a']; +var yineleyici = arr.values(); + +for (let harf of yineleyici) { + console.log(harf); +} +</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-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="Web_tarayıcı_uyumluluğu">Web tarayıcı uyumluluğu</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.values")}}</p> +</div> + +<h2 id="See_also">See also</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/tr/web/javascript/reference/global_objects/arraybuffer/index.html b/files/tr/web/javascript/reference/global_objects/arraybuffer/index.html new file mode 100644 index 0000000000..8109b3f667 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/arraybuffer/index.html @@ -0,0 +1,222 @@ +--- +title: ArrayBuffer +slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer +tags: + - ArrayBuffer + - Constructor + - JavaScript + - Yazılı Diziler +translation_of: Web/JavaScript/Reference/Global_Objects/ArrayBuffer +--- +<div>{{JSRef}}</div> + +<p>Bir <strong><code>ArrayBuffer</code></strong> nesnesi, kapsamlı ve sabit uzunluktaki raw binary data buffer'ını temsil etmek için kullanılır. Bir ArrayBuffer'ın içeriklerini direkt olarak manipüle edemezsiniz; bunun yerine, <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray">yazılmış dizi nesnelerini</a> veya buffer'ı özel bir formatta temsil eden bir {{jsxref("DataView")}} nesnesini oluşturursunuz, buffer'a içerik yazmak veya buffer'dan içerik okumak için kullanırsınız.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">new ArrayBuffer(length) +</pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt><code>length</code></dt> + <dd>Byte cinsinden, oluşturulan array buffer'ın boyutudur.</dd> +</dl> + +<h3 id="Döndürülen_Değer">Döndürülen Değer</h3> + +<p>Belirlenen boyutta yeni bir ArrayBuffer nesnesi. İçeriği 0 atanmış durumdadır.</p> + +<h3 id="İstisnalar">İstisnalar</h3> + +<p>Eğer uzunluk {{jsxref("Number.MAX_SAFE_INTEGER")}} (>= 2 ** 53) ifadesinden büyük ya da negatif ise bir {{jsxref("RangeError")}} fırlatılır.</p> + +<h2 id="Tanım">Tanım</h2> + +<p><code>ArrayBuffer</code> constructor'ı, byte cinsinden verilen boyutta yeni bir ArrayBuffer oluşturur.</p> + +<h3 id="Var_olan_bir_data'dan_array_buffer_çekmek">Var olan bir data'dan array buffer çekmek</h3> + +<ul> + <li><a href="/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#Appendix.3A_Decode_a_Base64_string_to_Uint8Array_or_ArrayBuffer">Bir Base64 string'inden</a></li> + <li><a href="/en-US/docs/Web/API/FileReader#readAsArrayBuffer()">Yerel bir dosyadan</a></li> +</ul> + +<h2 id="Özellikler">Özellikler</h2> + +<dl> + <dt><code>ArrayBuffer.length</code></dt> + <dd>ArrayBuffer constructor'ının 1 değerine sahip uzunluk özelliği.</dd> + <dt>{{jsxref("ArrayBuffer.@@species", "get ArrayBuffer[@@species]")}}</dt> + <dd>Türetilmiş nesneleri oluşturmak için kullanılan constructor fonksiyonu.</dd> + <dt>{{jsxref("ArrayBuffer.prototype")}}</dt> + <dd>Bütün ArrayBuffer nesnelerine özellik eklemeye izin verir.</dd> +</dl> + +<h2 id="Metodlar">Metodlar</h2> + +<dl> + <dt>{{jsxref("ArrayBuffer.isView", "ArrayBuffer.isView(arg)")}}</dt> + <dd>Eğer <code>arg</code> bir ArrayBuffer view'i ise <code>true</code> döndürür, tıpkı <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray">yazılmış dizi nesneleri</a> veya bir {{jsxref("DataView")}}gibi. Aksi halde <code>false </code>döndürür.</dd> + <dt>{{jsxref("ArrayBuffer.transfer", "ArrayBuffer.transfer(oldBuffer [, newByteLength])")}} {{experimental_inline}}</dt> + <dd> + <div class="line" id="file-arraybuffer-transfer-LC6">oldBuffer'ın alınmış, ardından kesilmiş veya newByteLength tarafından sıfır-uzatılmış datasını içeren yeni bir ArrayBuffer döndürür.</div> + </dd> +</dl> + +<h2 id="ArrayBuffer_oluşumları"><code>ArrayBuffer</code> oluşumları</h2> + +<p>Bütün <code>ArrayBuffer</code> oluşumları {{jsxref("ArrayBuffer.prototype")}} tarafından miras alınır.</p> + +<h3 id="Özellikler_2">Özellikler</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/prototype','Properties')}}</p> + +<h3 id="Metodlar_2">Metodlar</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/prototype','Methods')}}</p> + +<dl> + <dt>{{jsxref("ArrayBuffer.slice()")}} {{non-standard_inline}}</dt> + <dd>{{jsxref("ArrayBuffer.prototype.slice()")}} ile aynı fonksiyonelliğe sahiptir.</dd> +</dl> + +<h2 id="Örnek">Örnek</h2> + +<p>Bu örnekte, {{jsxref("Global_Objects/Int32Array", "Int32Array")}} view'i aracılığıyla 8-byte'lık bir buffer oluştururuz.</p> + +<pre class="brush: js">var buffer = new ArrayBuffer(8); +var view = new Int32Array(buffer);</pre> + +<h2 id="Belirtmeler">Belirtmeler</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Belirtme</th> + <th scope="col">Durum</th> + <th scope="col">Yorumlar</th> + </tr> + <tr> + <td>{{SpecName('Typed Array')}}</td> + <td>{{Spec2('Typed Array')}}</td> + <td>ECMAScript 6 tarafından yenilenmiştir.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Bir ECMA standardı için başlangıç tanımı. <code>new</code>'in gerekli olduğu belirtilmiştir.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tarayıcı_Uyumluluğu">Tarayıcı Uyumluluğu</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Özellik</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Temel Destek</td> + <td>7.0</td> + <td>{{CompatGeckoDesktop("2")}}</td> + <td>10</td> + <td>11.6</td> + <td>5.1</td> + </tr> + <tr> + <td><code>ArrayBuffer()</code> <code>new</code> fırlatmadan</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("44")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>ArrayBuffer.slice()</code> {{non-standard_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}<br> + {{CompatNo}} {{CompatGeckoDesktop("53")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Özellik</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>Temel Destek</td> + <td>4.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("2")}}</td> + <td>10</td> + <td>11.6</td> + <td>4.2</td> + </tr> + <tr> + <td><code>ArrayBuffer()</code> <code>new</code> fırlatmadan</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("44")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>ArrayBuffer.slice()</code> {{non-standard_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}<br> + {{CompatNo}} {{CompatGeckoMobile("53")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Uyumluluk_Notları">Uyumluluk Notları</h2> + +<p> ECMAScript 2015'ten başlamak üzere, ArrayBuffer constructor'ları bir {{jsxref("Operators/new", "new")}} operatörü aracılığıyla inşa edilmeye ihtiyaç duymaktadır.<font face="Consolas, Liberation Mono, Courier, monospace"> Artık </font><code>new</code> fonksiyonu kullanmadan bir ArrayBuffer constructor'ı çağırmak, bir {{jsxref("TypeError")}} fırlatacaktır.</p> + +<pre class="brush: js example-bad">var dv = ArrayBuffer(10); +// TypeError:<code>new </code>komutu olmadan +// Gömülü bir ArrayBuffer constructor'u çağırmak </pre> + +<pre class="brush: js example-good">var dv = new ArrayBuffer(10);</pre> + +<h2 id="Ayrıca_Bakınız">Ayrıca Bakınız</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Typed_arrays">Yazılmış JavaScript Dizileri</a></li> + <li>{{jsxref("SharedArrayBuffer")}}</li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/boolean/index.html b/files/tr/web/javascript/reference/global_objects/boolean/index.html new file mode 100644 index 0000000000..532b7b02c9 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/boolean/index.html @@ -0,0 +1,159 @@ +--- +title: Boolean (Mantıksal Veri Tipi) +slug: Web/JavaScript/Reference/Global_Objects/Boolean +tags: + - Boolean + - JavaScript + - Veri + - kurucu + - mantıksal + - tipi +translation_of: Web/JavaScript/Reference/Global_Objects/Boolean +--- +<div>{{JSRef}}</div> + +<p><strong><code>Boolean</code></strong> nesnesi, bir boolean değeri için bir nesne sarmalayıcıdır.</p> + +<h2 id="Sözdizimi">Sözdizimi</h2> + +<pre class="syntaxbox">new Boolean([<em>değer</em>])</pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt><font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">değer</span></font></dt> + <dd>Opsiyonel. Boolean nesnesinin başlangıç değeri.</dd> +</dl> + +<h2 id="Açıklama">Açıklama</h2> + +<p>Eğer gerekli ise ilk parametre yerine geçen değer boolean değerine dönüştürülür.Eğer değer verilmediyse , 0 ,-0, {{jsxref("null")}}, false, {{jsxref("NaN")}}, {{jsxref("undefined")}}, ya da boş string ("") ise nesnenin ilk değeri false olur.DOM nesnesi {{domxref ("document.all")}} parametre olarak iletilirse, yeni boolean nesnesinin başlangıç değeri de false olur. Herhangi bir nesne veya "false" dizesi dahil olmak üzere diğer tüm değerler, başlangıç değeri true olan bir nesne oluşturur.</p> + +<p>İlkel Boolean değerlerini true ve false ile Boolean nesnesinin true ve false değerleriyle karıştırmayın.</p> + +<p>Değeri false olan bir Boolean nesnesi de dahil olmak üzere, {{jsxref ("undefined")}} veya {{jsxref ("null")}} olmayan herhangi bir nesne, şartlı ifadeye geçirildiğinde true olarak değerlendirilir. Örneğin, aşağıdaki {{jsxref ("İfadeler/if...else", "if")}} deyimindeki koşul true olarak değerlendirilir:</p> + +<pre class="brush: js">var x = new Boolean(false); +if (x) { + // bu kod gerçekleşti. +} +</pre> + +<p>Bu davranış, Boolean ilkelleri için geçerli değildir. Örneğin, aşağıdaki {{jsxref ("İfadeler / if ... else", "if")}} deyimindeki koşul false olarak değerlendirilir:</p> + +<pre class="brush: js">var x = false; +if (x) { + // bu kod gerçekleşmedi. +} +</pre> + +<p>Boolean olmayan bir değeri bir boolean değerine dönüştürmek için bir Boolean nesnesi kullanmayın. Bunun yerine, bu görevi yerine getirmek için bir işlev olarak Boolean'ı kullanın:</p> + +<pre class="brush: js">var x = Boolean(expression); // tercih edilen +var x = new Boolean(expression); // kullanma +</pre> + +<p>Bir Boolean nesnesi de dahil olmak üzere herhangi bir nesneyi bir Boolean nesnesinin başlangıç değerini false olarak belirterseniz, yeni Boolean nesnesinin değeri true olur.</p> + +<pre class="brush: js">var myFalse = new Boolean(false); // ilk değer false +var g = Boolean(myFalse); // ilk değer true +var myString = new String('Hello'); // string nesnesi +var s = Boolean(myString); // ilk değer true +</pre> + +<p>Boolean ilkelinin yerine bir Boolean nesnesi kullanmayın.</p> + +<h2 id="Özellikleri">Özellikleri</h2> + +<dl> + <dt><code>Boolean.length</code></dt> + <dd>Uzunluk özelliğinin değeri 1.</dd> + <dt>{{jsxref("Boolean.prototype")}}</dt> + <dd>Boolean yapıcısının prototipini temsil eder.</dd> +</dl> + +<h2 id="Metodlar">Metodlar</h2> + +<p>Genel Boolean nesnesi kendine özgü bir yöntem içermese de, prototip zinciri boyunca bazı yöntemleri devralır:</p> + +<h2 id="Boolean_örnekleri"><code>Boolean</code> örnekleri</h2> + +<p>Tüm Boolean örnekleri {{jsxref ("Boolean.prototype")}} 'den devralınır. Tüm yapıcılarda olduğu gibi, prototip nesne örneklerin kalıtsal özelliklerini ve yöntemlerini belirler.</p> + +<h3 id="Özellikleri_2">Özellikleri</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean/prototype', 'Properties')}}</div> + +<h3 id="Metodlar_2">Metodlar</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean/prototype', 'Methods')}}</div> + +<h2 id="Örnekler">Örnekler</h2> + +<h3 id="ilk_değeri_false_olan_Boolean_nesnesi_oluşturma">ilk değeri <code>false</code> olan <code>Boolean</code> nesnesi oluşturma </h3> + +<pre class="brush: js">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="ilk_değeri_true_olan_Boolean_nesnesi_oluşturma">ilk değeri <code>true</code> olan <code>Boolean</code> nesnesi oluşturma</h3> + +<pre class="brush: js">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="Özellikler">Özellikler</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Özellik</th> + <th scope="col">Durum</th> + <th scope="col">Yorum</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>İlk tanım. JavaScript 1.0'da uygulanmaktadır.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.6', 'Boolean')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-boolean-objects', 'Boolean')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-boolean-objects', 'Boolean')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tarayıcı_Uyumluluğu">Tarayıcı Uyumluluğu</h2> + +<div> +<div class="hidden">Bu sayfadaki uyumluluk tablosu yapılandırılmış verilerden oluşturulmuştur. Verilere katkıda bulunmak istiyorsanız, lütfen https://github.com/mdn/browser-compat-data adresini ziyaret edin ve bize pull request gönderin.</div> + +<p>{{Compat("javascript.builtins.Boolean")}} </p> +</div> + +<h2 id="Ayrıca_bakınız"><br> + Ayrıca bakınız</h2> + +<ul> + <li>{{jsxref("Boolean.prototype")}}</li> + <li>{{Glossary("Boolean")}}</li> + <li><a href="http://en.wikipedia.org/wiki/Boolean_data_type">Boolean veri tipi (Vikipedi)</a></li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/boolean/prototype/index.html b/files/tr/web/javascript/reference/global_objects/boolean/prototype/index.html new file mode 100644 index 0000000000..fa60081cc3 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/boolean/prototype/index.html @@ -0,0 +1,76 @@ +--- +title: Boolean.prototype +slug: Web/JavaScript/Reference/Global_Objects/Boolean/prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Boolean +--- +<div>{{JSRef}}</div> + +<p>Boolean.prototype özelliği {{jsxref ("Boolean")}} yapıcı methodunun prototipini temsil eder.</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<div>{{EmbedInteractiveExample("pages/js/boolean-constructor.html")}}</div> + +<p class="hidden">Bu etkileşimli örnek için kaynak bir GitHub deposunda saklanır. Etkileşimli örnek projeye katkıda bulunmak istiyorsanız lütfen https://github.com/mdn/interactive-examples'ları kopyalayıp bize pull request gönderin.</p> + +<h2 id="sect1"> </h2> + +<p>{{jsxref("Boolean")}} instances inherit from <code>Boolean.prototype</code>. You can use the constructor's prototype object to add properties or methods to all {{jsxref("Boolean")}} instances.</p> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt><code>Boolean.prototype.constructor</code></dt> + <dd>Bir örneğin prototipini oluşturan fonksiyonu döndürür. Bu varsayılan olarak {{jsxref ("Boolean")}} işlevidir.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{jsxref("Boolean.prototype.toSource()")}} {{non-standard_inline}}</dt> + <dd>{{Jsxref ("Boolean")}} nesnesinin kaynağını içeren bir dize döndürür; eşdeğer bir nesne oluşturmak için bu dizeyi kullanabilirsiniz. {{Jsxref ("Object.prototype.toSource ()")}} methodunu geçersiz kılar.</dd> + <dt>{{jsxref("Boolean.prototype.toString()")}}</dt> + <dd>Nesnenin değerine bağlı olarak <code>"true"</code> ya da <code>"false"</code> dizesini döndürür. {{Jsxref ("Object.prototype.toString ()")}} methodunu geçersiz kılar.</dd> + <dt>{{jsxref("Boolean.prototype.valueOf()")}}</dt> + <dd>{{Jsxref ("Boolean")}} nesnesinin temel değerini döndürür. {{Jsxref ("Object.prototype.valueOf ()")}} methodunu geçersiz kılar.</dd> +</dl> + +<h2 id="Özellikler">Özellikler</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Özellikler</th> + <th scope="col">Durum</th> + <th scope="col">Açıklama</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>İlk tanım. JavaScript 1.0'da uygulanmaktadır.</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="Tarayıcı_Uyumluluğu">Tarayıcı Uyumluluğu</h2> + +<div> +<div class="hidden">Bu sayfadaki uyumluluk tablosu yapılandırılmış verilerden oluşturulmuştur. Verilere katkıda bulunmak istiyorsanız, lütfen https://github.com/mdn/browser-compat-data adresini ziyaret edin ve bize pull request gönderin.</div> + +<p>{{Compat("javascript.builtins.Boolean.prototype")}}</p> +</div> diff --git a/files/tr/web/javascript/reference/global_objects/boolean/tosource/index.html b/files/tr/web/javascript/reference/global_objects/boolean/tosource/index.html new file mode 100644 index 0000000000..1d304fc29f --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/boolean/tosource/index.html @@ -0,0 +1,51 @@ +--- +title: Boolean.prototype.toSource() +slug: Web/JavaScript/Reference/Global_Objects/Boolean/toSource +translation_of: Web/JavaScript/Reference/Global_Objects/Boolean/toSource +--- +<div>{{JSRef}} {{non-standard_header}}</div> + +<p>ToSource () metodu, nesnenin kaynak kodunu temsil eden bir dize döndürür.</p> + +<h2 id="Sözdizimi">Sözdizimi</h2> + +<pre class="syntaxbox"><var>booleanObj</var>.toSource() +Boolean.toSource()</pre> + +<h3 id="Return_değeri">Return değeri</h3> + +<p>Nesnenin kaynak kodunu temsil eden bir dize.</p> + +<h2 id="Açıklama">Açıklama</h2> + +<p><code>toSource</code> metodu aşağıdaki değerleri döndürür:</p> + +<ul> + <li>Yerleşik(built-in) {{jsxref ("Boolean")}} nesne için toSource, kaynak kodun mevcut olmadığını belirten aşağıdaki dizeyi döndürür: + <pre class="brush: js">function Boolean() { + [native code] +} +</pre> + </li> + <li>{{Jsxref ("Boolean")}} örneği için toSource, kaynak kodunu temsil eden bir dize döndürür.</li> +</ul> + +<p>This method is usually called internally by JavaScript and not explicitly in code.</p> + +<h2 id="Özellikler">Özellikler</h2> + +<p>Herhangi bir standardın parçası değil. JavaScript 1.3'te uygulandı. 1.3.</p> + +<h2 id="Tarayıcı_Uyumluluğu">Tarayıcı Uyumluluğu</h2> + +<div> +<div class="hidden">Bu sayfadaki uyumluluk tablosu yapılandırılmış verilerden oluşturulmuştur. Verilere katkıda bulunmak istiyorsanız, lütfen https://github.com/mdn/browser-compat-data adresini ziyaret edin ve bize pull request gönderin.</div> + +<p>{{Compat("javascript.builtins.Boolean.toSource")}}</p> +</div> + +<h2 id="Ayrıca_Bakınız">Ayrıca Bakınız</h2> + +<ul> + <li>{{jsxref("Object.prototype.toSource()")}} {{non-standard_inline}}</li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/eval/index.html b/files/tr/web/javascript/reference/global_objects/eval/index.html new file mode 100644 index 0000000000..1b91b418ce --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/eval/index.html @@ -0,0 +1,318 @@ +--- +title: eval() +slug: Web/JavaScript/Reference/Global_Objects/eval +translation_of: Web/JavaScript/Reference/Global_Objects/eval +--- +<div>{{jsSidebar("Objects")}}</div> + +<p><code><strong>eval()</strong></code> fonksiyonu JavaScript kodunu bir String gibi değerlendirir.</p> + +<div>{{EmbedInteractiveExample("pages/js/globalprops-eval.html")}}</div> + + + +<h2 id="Sözdizimi">Sözdizimi</h2> + +<pre class="syntaxbox"><code>eval(<em>string</em>)</code></pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt><code>string</code></dt> + <dd>A string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects.</dd> +</dl> + +<h3 id="Return_değeri">Return değeri</h3> + +<p>The completion value of evaluating the given code. If the completion value is empty, {{jsxref("undefined")}} is returned.</p> + +<h2 id="Description">Description</h2> + +<p><code>eval()</code> is a function property of the global object.</p> + +<p>The argument of the <code>eval()</code> function is a string. If the string represents an expression, <code>eval()</code> evaluates the expression. If the argument represents one or more JavaScript statements, <code>eval()</code> evaluates the statements. Do not call <code>eval()</code> to evaluate an arithmetic expression; JavaScript evaluates arithmetic expressions automatically.</p> + +<p>If you construct an arithmetic expression as a string, you can use <code>eval()</code> to evaluate it at a later time. For example, suppose you have a variable <code>x</code>. You can postpone evaluation of an expression involving <code>x</code> by assigning the string value of the expression, say "<code>3 * x + 2</code>", to a variable, and then calling <code>eval()</code> at a later point in your script.</p> + +<p>If the argument of <code>eval()</code> is not a string, <code>eval()</code> returns the argument unchanged. In the following example, the <code>String</code> constructor is specified and <code>eval()</code> returns a <code>String</code> object rather than evaluating the string.</p> + +<pre class="brush:js">eval(new String('2 + 2')); // returns a String object containing "2 + 2" +eval('2 + 2'); // returns 4 +</pre> + +<p>You can work around this limitation in a generic fashion by using <code>toString()</code>.</p> + +<pre class="brush:js">var expression = new String('2 + 2'); +eval(expression.toString()); // returns 4 +</pre> + +<p>If you use the <code>eval</code> function <em>indirectly,</em> by invoking it via a reference other than <code>eval</code>, <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-10.4.2">as of ECMAScript 5</a> it works in the global scope rather than the local scope. This means, for instance, that function declarations create global functions, and that the code being evaluated doesn't have access to local variables within the scope where it's being called.</p> + +<pre class="brush:js">function test() { + var x = 2, y = 4; + console.log(eval('x + y')); // Direct call, uses local scope, result is 6 + var geval = eval; // equivalent to calling eval in the global scope + console.log(geval('x + y')); // Indirect call, uses global scope, throws ReferenceError because `x` is undefined + (0, eval)('x + y'); // another example of Indirect call +} +</pre> + +<h2 id="Do_not_ever_use_eval!">Do not ever use <code>eval</code>!</h2> + +<p><code>eval()</code> is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run <code>eval()</code> with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension. More importantly, a third-party code can see the scope in which <code>eval()</code> was invoked, which can lead to possible attacks in ways to which the similar {{jsxref("Global_Objects/Function", "Function")}} is not susceptible.</p> + +<p><code>eval()</code> is also slower than the alternatives, since it has to invoke the JS interpreter, while many other constructs are optimized by modern JS engines.</p> + +<p>Additionally, modern javascript interpreters convert javascript to machine code. This means that any concept of variable naming gets obliterated. Thus, any use of eval will force the browser to do long expensive variable name lookups to figure out where the variable exists in the machine code and set its value. Additonally, new things can be introduced to that variable through <code>eval()</code> such as changing the type of that variable, forcing the browser to reevaluate all of the generated machine code to compensate. However, there (thankfully) exists a very good alternative to eval: simply using <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function">window.Function</a>. As an example of how you convert code using evil <code>eval()</code> to using <code>Function</code><code>()</code>, see below.</p> + +<p>Bad code with eval:</p> + +<pre class="brush:js">function looseJsonParse(obj){ + return eval(obj); +} +console.log(looseJsonParse( + "{a:(4-1), b:function(){}, c:new Date()}" +)) +</pre> + +<p>Better code without eval:</p> + +<pre class="brush:js">function looseJsonParse(obj){ + return Function('"use strict";return (' + obj + ')')(); +} +console.log(looseJsonParse( + "{a:(4-1), b:function(){}, c:new Date()}" +)) +</pre> + +<p>Comparing the two code snippets above, the two code snippets might seem to work the same way, but think again: the eval one is a huge amount slower. Notice <code>c: new Date()</code> in the evaluated object. In the function without the eval, the object is being evaluated in the global scope, so it is safe for the browser to assume that <code>Date</code> refers to <code>window.Date</code> instead of a local variable called <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">Date</span></font>. But, in the code using <code>eval()</code>, the browser cannot assume this since what if your code looked like the following:</p> + +<pre class="brush:js">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>Thus, in the <code>eval()</code> version of the code, the browser is forced to make the expensive lookup call to check to see if there are any local variables called <code>Date()</code>. This is incredibly inefficient compared to <code>Function()</code>.</p> + +<p>In a related circumstance, what if you actually wanted your <code>Date</code> function to be able to be called from the code inside <code>Function()</code>. Should you just wimp out and fall back to <code>eval()</code>? Absolutely not, never ever. Instead try the approach below.</p> + +<pre class="brush:js">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>The code above may seem inefficiently slow because of the triple nested function, but let's analyse the benefits of the above efficient method:</p> + +<p>1. It allows the code in the string passed to <code>runCodeWithDateFunction</code> to be minified.</p> + +<p>2. Function call overhead is minimal, making the far smaller code size well worth the benefit</p> + +<p>3. <code>Function()</code> more easily allows your code to utilize the performance buttering <code>"use strict";</code></p> + +<p>4. The code does not use <code>eval()</code>, making it orders of magnitude faster than otherwise.</p> + +<p>Lastly, let's examine minification. With using <code>Function()</code> as shown above, you can minify the code string passed to <code>runCodeWithDateFunction</code> far more efficiently because the function arguments names can be minified too as seen in the minified code below.</p> + +<pre class="brush:js">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>There are also additional safer (and faster!) alternatives to <code>eval()</code> or <code>Function()</code> for common use-cases.</p> + +<h3 id="Accessing_member_properties">Accessing member properties</h3> + +<p>You should not use <code>eval()</code> to convert property names into properties. Consider the following example where the property of the object to be accessed is not known until the code is executed. This can be done with eval:</p> + +<pre class="brush:js">var obj = { a: 20, b: 30 }; +var propName = getPropName(); // returns "a" or "b" + +eval( 'var result = obj.' + propName ); +</pre> + +<p>However, <code>eval()</code> is not necessary here. In fact, its use here is discouraged. Instead, use the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors" title="JavaScript/Reference/Operators/Member_Operators">property accessors</a>, which are much faster and safer:</p> + +<pre class="brush:js">var obj = { a: 20, b: 30 }; +var propName = getPropName(); // returns "a" or "b" +var result = obj[ propName ]; // obj[ "a" ] is the same as obj.a</pre> + +<p>You can even use this method to access descendant properties. Using <code>eval()</code> this would look like:</p> + +<pre class="brush:js">var obj = {a: {b: {c: 0}}}; +var propPath = getPropPath(); // returns e.g. "a.b.c" + +eval( 'var result = obj.' + propPath ); +</pre> + +<p>Avoiding <code>eval()</code> here could be done by splitting the property path and looping through the different properties:</p> + +<pre class="brush:js">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(); // returns e.g. "a.b.c" +var result = getDescendantProp(obj, propPath);</pre> + +<p>Setting a property that way works similarly:</p> + +<pre class="brush:js">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(); // returns e.g. "a.b.c" +var result = setDescendantProp(obj, propPath, 1); // test.a.b.c will now be 1</pre> + +<h3 id="Use_functions_instead_of_evaluating_snippets_of_code">Use functions instead of evaluating snippets of code</h3> + +<p>JavaScript has <a class="external" href="http://en.wikipedia.org/wiki/First-class_function" title="http://en.wikipedia.org/wiki/First-class_function">first-class functions</a>, which means you can pass functions as arguments to other APIs, store them in variables and objects' properties, and so on. Many DOM APIs are designed with this in mind, so you can (and should) write:</p> + +<pre class="brush: js">// instead of setTimeout(" ... ", 1000) use: +setTimeout(function() { ... }, 1000); + +// instead of elt.setAttribute("onclick", "...") use: +elt.addEventListener('click', function() { ... } , false); </pre> + +<p><a href="/en-US/docs/Web/JavaScript/Closures" title="JavaScript/Guide/Closures">Closures</a> are also helpful as a way to create parameterized functions without concatenating strings.</p> + +<h3 id="Parsing_JSON_(converting_strings_to_JavaScript_objects)">Parsing JSON (converting strings to JavaScript objects)</h3> + +<p>If the string you're calling <code>eval()</code> on contains data (for example, an array: <code>"[1, 2, 3]"</code>), as opposed to code, you should consider switching to <a href="/en-US/docs/Glossary/JSON" title="JSON">JSON</a>, which allows the string to use a subset of JavaScript syntax to represent data. See also <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>Note that since JSON syntax is limited compared to JavaScript syntax, many valid JavaScript literals will not parse as JSON. For example, trailing commas are not allowed in JSON, and property names (keys) in object literals must be enclosed in quotes. Be sure to use a JSON serializer to generate strings that will be later parsed as JSON.</p> + +<h3 id="Pass_data_instead_of_code">Pass data instead of code</h3> + +<p>For example, an extension designed to scrape contents of web-pages could have the scraping rules defined in <a href="/en-US/docs/XPath" title="XPath">XPath</a> instead of JavaScript code.</p> + +<h3 id="Run_code_with_limited_privileges">Run code with limited privileges</h3> + +<p>If you must run the code, consider running it with reduced privileges. This advice applies mainly to extensions and XUL applications, which can use <a href="/en-US/docs/Components.utils.evalInSandbox" title="Components.utils.evalInSandbox">Components.utils.evalInSandbox</a> for this.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_eval">Using <code>eval</code></h3> + +<p>In the following code, both of the statements containing <code>eval()</code> return 42. The first evaluates the string "<code>x + y + 1</code>"; the second evaluates the string "<code>42</code>".</p> + +<pre class="brush:js">var x = 2; +var y = 39; +var z = '42'; +eval('x + y + 1'); // returns 42 +eval(z); // returns 42 +</pre> + +<h3 id="Using_eval_to_evaluate_a_string_of_JavaScript_statements">Using <code>eval</code> to evaluate a string of JavaScript statements</h3> + +<p>The following example uses <code>eval()</code> to evaluate the string <code>str</code>. This string consists of JavaScript statements that open an alert dialog box and assign <code>z</code> a value of 42 if <code>x</code> is five, and assigns 0 to <code>z</code> otherwise. When the second statement is executed, <code>eval()</code> will cause these statements to be performed, and it will also evaluate the set of statements and return the value that is assigned to <code>z</code>.</p> + +<pre class="brush:js">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>If you define multiple values then the last value is returned.</p> + +<pre class="brush:js">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 is 42 x is 420 +</pre> + + + +<h3 id="Last_expression_is_evaluated">Last expression is evaluated</h3> + +<p><code>eval()</code> returns the value of the last expression evaluated.</p> + +<pre class="brush:js">var str = 'if ( a ) { 1 + 1; } else { 1 + 2; }'; +var a = true; +var b = eval(str); // returns 2 + +console.log('b is : ' + b); + +a = false; +b = eval(str); // returns 3 + +console.log('b is : ' + b);</pre> + +<h3 id="eval_as_a_string_defining_function_requires_(_and_)_as_prefix_and_suffix"><code>eval</code> as a string defining function requires "(" and ")" as prefix and suffix</h3> + +<pre class="brush:js">var fctStr1 = 'function a() {}' +var fctStr2 = '(function a() {})' +var fct1 = eval(fctStr1) // return undefined +var fct2 = eval(fctStr2) // return a function +</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.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.1.2.1', 'eval')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-eval-x', 'eval')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-eval-x', 'eval')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.builtins.eval")}}</p> + +<h2 id="Firefox-specific_notes">Firefox-specific notes</h2> + +<ul> + <li>Historically <code>eval()</code> had an optional second argument, specifying an object in whose context the evaluation was to be performed. This argument was non-standard, and was definitely removed from Firefox 4. See {{bug(531675)}}.</li> +</ul> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Global_Objects/uneval", "uneval()")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors">Property accessors</a></li> + <li><a href="/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/tr/web/javascript/reference/global_objects/function/apply/index.html b/files/tr/web/javascript/reference/global_objects/function/apply/index.html new file mode 100644 index 0000000000..5a82d226a3 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/function/apply/index.html @@ -0,0 +1,262 @@ +--- +title: Function.prototype.apply() +slug: Web/JavaScript/Reference/Global_Objects/Function/apply +translation_of: Web/JavaScript/Reference/Global_Objects/Function/apply +--- +<div>{{JSRef}}</div> + +<p><code><strong>apply()</strong></code> methodu ile verilen bir "this" değeri ve diziyi(ya da dizi benzeri bir nesneyi) kullanarak bağımsız değişkenlerle bir işlevi(function) çağırır.</p> + +<div class="note"> +<p><strong>Not:</strong> <strong>call() , apply() </strong>syntaxları sizin de dikkat ettiğiniz gibi aynıdır. farkları şudur: <strong>call() </strong>: bir argüman listesini argüman olarak alırken, <strong>apply() </strong>argümanlardan oluşmuş bir array'ı argüman olarak kabul alır. </p> +</div> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><var>fun</var>.apply(<var>thisArg, </var>[<var>argsArray</var>])</pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt><code>thisArg</code></dt> + <dd>fun' ı çağırmak için atanan this in değeridir. Unutmayın, this,method tarafından görülen gerçek değer olmayabilir.: eğer method{{jsxref("Strict_mode", "non-strict mode", "", 1)}} içindeki bir kod ise{{jsxref("null")}}ve {{jsxref("undefined")}}global object ile yer değiştirecek, ve ilk değerleri saklanacak.</dd> + <dt><code>argsArray</code></dt> + <dd> + <p>Eğer fonkiyona hiç bir parametre verilmeyecekse dizi benzeri bir nesne (çağrılacak fun'ın argümanlarını belirler), veya {{jsxref("null")}} veya {{jsxref("undefined")}}. ECMAScript 5 ile, bu argümanlar dizi yerine eşdeğer dizi benzeri nesne olabilir. {{anch("Browser_compatibility", "browser compatibility")}} için aşağıya bakın.</p> + </dd> +</dl> + +<h3 id="Dönen_değer">Dönen değer</h3> + +<p><strong><code>this</code></strong> değeri ve argümanlar ile çağrılan fonksiyonun sonucu.</p> + +<h2 id="Açıklama">Açıklama</h2> + +<p>Varolan bir fonksiyonu çağırdığınızda farklı bir <strong>this</strong> objesi atayabilirsiniz. Burada <strong>this</strong> geçerli nesneyi (çağıran objeyi ) ifade eder. <strong>Apply</strong> ile bir kez yazılmış bir methodu başka bir objeden miras alarak aynı fonksiyonu tekrar yazmaktan kurtulmuş olursunuz. </p> + +<p><code>apply</code> is very similar to {{jsxref("Function.call", "call()")}}, except for the type of arguments it supports. You can use an arguments array instead of a named set of parameters. With <code>apply</code>, you can use an array literal, for example, <code><em>fun</em>.apply(this, ['eat', 'bananas'])</code>, or an {{jsxref("Array")}} object, for example, <code><em>fun</em>.apply(this, new Array('eat', 'bananas'))</code>.</p> + +<p>You can also use {{jsxref("Functions/arguments", "arguments")}} for the <code>argsArray</code> parameter. <code>arguments</code> is a local variable of a function. It can be used for all unspecified arguments of the called object. Thus, you do not have to know the arguments of the called object when you use the <code>apply</code> method. You can use <code>arguments</code> to pass all the arguments to the called object. The called object is then responsible for handling the arguments.</p> + +<p>Since ECMAScript 5th Edition you can also use any kind of object which is array-like, so in practice this means it's going to have a property <code>length</code> and integer properties in the range <code>(0...length-1)</code>. As an example you can now use a {{domxref("NodeList")}} or a custom object like <code>{ 'length': 2, '0': 'eat', '1': 'bananas' }</code>.</p> + +<div class="note"> +<p>Most browsers, including Chrome 14 and Internet Explorer 9, still do not accept array-like objects and will throw an exception.</p> +</div> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_apply_to_chain_constructors">Using <code>apply</code> to chain constructors</h3> + +<p>You can use <code>apply</code> to chain {{jsxref("Operators/new", "constructors", "", 1)}} for an object, similar to Java. In the following example we will create a global {{jsxref("Function")}} method called <code>construct</code>, which will enable you to use an array-like object with a constructor instead of an arguments list.</p> + +<pre class="brush: js">Function.prototype.construct = function (aArgs) { + var oNew = Object.create(this.prototype); + this.apply(oNew, aArgs); + return oNew; +}; +</pre> + +<div class="note"> +<p><strong>Note:</strong> The <code>Object.create()</code> method used above is relatively new. For an alternative method using closures, please consider the following alternative:</p> + +<pre class="brush: js">Function.prototype.construct = function(aArgs) { + var fConstructor = this, fNewConstr = function() { + fConstructor.apply(this, aArgs); + }; + fNewConstr.prototype = fConstructor.prototype; + return new fNewConstr(); +};</pre> +</div> + +<p>Example usage:</p> + +<pre class="brush: js">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' +</pre> + +<div class="note"> +<p><strong>Note:</strong> This non-native <code>Function.construct</code> method will not work with some native constructors (like {{jsxref("Date")}}, for example). In these cases you have to use the {{jsxref("Function.prototype.bind")}} method (for example, imagine having an array like the following, to be used with {{jsxref("Global_Objects/Date", "Date")}} constructor: <code>[2012, 11, 4]</code>; in this case you have to write something like: <code>new (Function.prototype.bind.apply(Date, [null].concat([2012, 11, 4])))()</code> — anyhow this is not the best way to do things and probably should not be used in any production environment).</p> +</div> + +<h3 id="Using_apply_and_built-in_functions">Using <code>apply</code> and built-in functions</h3> + +<p>Clever usage of <code>apply</code> allows you to use built-ins functions for some tasks that otherwise probably would have been written by looping over the array values. As an example here we are going to use <code>Math.max</code>/<code>Math.min</code> to find out the maximum/minimum value in an array.</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); +// This about equal to Math.max(numbers[0], ...) +// or 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>But beware: in using <code>apply</code> this way, you run the risk of exceeding the JavaScript engine's argument length limit. The consequences of applying a function with too many arguments (think more than tens of thousands of arguments) vary across engines (JavaScriptCore has hard-coded <a class="link-https" href="https://bugs.webkit.org/show_bug.cgi?id=80797">argument limit of 65536</a>), because the limit (indeed even the nature of any excessively-large-stack behavior) is unspecified. Some engines will throw an exception. More perniciously, others will arbitrarily limit the number of arguments actually passed to the applied function. (To illustrate this latter case: if such an engine had a limit of four arguments [actual limits are of course significantly higher], it would be as if the arguments <code>5, 6, 2, 3</code> had been passed to <code>apply</code> in the examples above, rather than the full array.) If your value array might grow into the tens of thousands, use a hybrid strategy: apply your function to chunks of the array at a time:</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="Using_apply_in_monkey-patching">Using apply in "monkey-patching"</h3> + +<p>Apply can be the best way to monkey-patch a built-in function of Firefox, or JS libraries. Given <code>someobject.foo</code> function, you can modify the function in a somewhat hacky way, like so:</p> + +<pre class="brush: js">var originalfoo = someobject.foo; +someobject.foo = function() { + // Do stuff before calling function + console.log(arguments); + // Call the function as it would have been called normally: + originalfoo.apply(this, arguments); + // Run stuff after, here. +} +</pre> + +<p>This method is especially handy where you want to debug events, or interface with something that has no API like the various <code>.on([event]...</code> events, such as those usable on the <a href="/en-US/docs/Tools/Page_Inspector#Developer_API">Devtools Inspector</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('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in 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="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>ES 5.1 generic array-like object as {{jsxref("Functions/arguments", "arguments")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("2.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>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> + <tr> + <td>ES 5.1 generic array-like object as {{jsxref("Functions/arguments", "arguments")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("2.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Functions/arguments", "arguments")}} object</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/tr/web/javascript/reference/global_objects/function/index.html b/files/tr/web/javascript/reference/global_objects/function/index.html new file mode 100644 index 0000000000..912f1acf1e --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/function/index.html @@ -0,0 +1,189 @@ +--- +title: Function +slug: Web/JavaScript/Reference/Global_Objects/Function +tags: + - fonksiyon + - yapıcı +translation_of: Web/JavaScript/Reference/Global_Objects/Function +--- +<div>{{JSRef}}</div> + +<p><strong><code>Fonksiyon</code> yapıcısı</strong> yeni bir <code>Fonksiyon </code>nesnesi yaratır. JavaScript'de her fonksiyon aslında bir <code>Fonksiyon</code> nesnesidir.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code>new Function ([<var>arg1</var>[, <var>arg2</var>[, ...<var>argN</var>]],] <var>functionBody</var>)</code></pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt><code>arg1, arg2, ... arg<em>N</em></code></dt> + <dd>Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier or a list of such strings separated with a comma; for example "<code>x</code>", "<code>theValue</code>", or "<code>a,b</code>".</dd> + <dt><code>functionBody</code></dt> + <dd>A string containing the JavaScript statements comprising the function definition.</dd> +</dl> + +<h2 id="Açıklama">Açıklama</h2> + +<p><code>Function</code> objects created with the <code>Function</code> constructor are parsed when the function is created. This is less efficient than declaring a function with a <a href="/en-US/docs/Web/JavaScript/Reference/Operators/function">function expression</a> or <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function">function statement</a> and calling it within your code, because such functions are parsed with the rest of the code.</p> + +<p>All arguments passed to the function are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed.</p> + +<p>Invoking the <code>Function</code> constructor as a function (without using the <code>new</code> operator) has the same effect as invoking it as a constructor.</p> + +<h2 id="Properties_and_Methods_of_Function">Properties and Methods of <code>Function</code></h2> + +<p>The global <code>Function</code> object has no methods or properties of its own, however, since it is a function itself it does inherit some methods and properties through the prototype chain from {{jsxref("Function.prototype")}}.</p> + +<h2 id="Function_prototype_object"><code>Function</code> prototype object</h2> + +<h3 id="Properties">Properties</h3> + +<div>{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Properties')}}</div> + +<h3 id="Methods">Methods</h3> + +<div>{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Methods')}}</div> + +<h2 id="Function_instances"><code>Function</code> instances</h2> + +<p><code>Function</code> instances inherit methods and properties from {{jsxref("Function.prototype")}}. As with all constructors, you can change the constructor's prototype object to make changes to all <code>Function</code> instances.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Specifying_arguments_with_the_Function_constructor">Specifying arguments with the <code>Function</code> constructor</h3> + +<p>The following code creates a <code>Function</code> object that takes two arguments.</p> + +<pre class="brush: js">// Example can be run directly in your JavaScript console + +// Create a function that takes two arguments and returns the sum of those arguments +var adder = new Function('a', 'b', 'return a + b'); + +// Call the function +adder(2, 6); +// > 8 +</pre> + +<p>The arguments "<code>a</code>" and "<code>b</code>" are formal argument names that are used in the function body, "<code>return a + b</code>".</p> + +<h3 id="Difference_between_Function_constructor_and_function_declaration">Difference between Function constructor and function declaration</h3> + +<p>Functions created with the <code>Function</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>Function</code> constructor was called. This is different from using {{jsxref("eval")}} with code for a function expression.</p> + +<pre class="brush: js">var x = 10; + +function createFunction1() { + var x = 20; + return new Function("return x;"); // this |x| refers global |x| +} + +function createFunction2() { + var x = 20; + function f() { + return x; // this |x| refers local |x| above + } + return f; +} + +var f1 = createFunction1(); +console.log(f1()); // 10 +var f2 = createFunction2(); +console.log(f2()); // 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.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.3', 'Function')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-function-objects', 'Function')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-function-objects', 'Function')}}</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("Functions", "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/tr/web/javascript/reference/global_objects/index.html b/files/tr/web/javascript/reference/global_objects/index.html new file mode 100644 index 0000000000..b03aa1f2d1 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/index.html @@ -0,0 +1,178 @@ +--- +title: Global Objeler +slug: Web/JavaScript/Reference/Global_Objects +tags: + - JavaScript + - Referensi +translation_of: Web/JavaScript/Reference/Global_Objects +--- +<div>{{jsSidebar("Objects")}}</div> + +<p>This chapter documents all of JavaScript's standard, built-in objects, including their methods and properties.</p> + +<div class="onlyinclude"> +<p>The term "global objects" (or standard built-in objects) here is not to be confused with the <strong>global object</strong>. Here, global objects refer to <strong>objects in the global scope</strong> (but only if ECMAScript 5 strict mode is not used; in that case it returns <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined">undefined</a>). The <strong>global object</strong> itself can be accessed using the {{jsxref("Operators/this", "this")}} operator in the global scope. In fact, the global scope <strong>consists of</strong> the properties of the global object, including inherited properties, if any.</p> + +<p>Other objects in the global scope are either <a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Creating_new_objects">created by the user script</a> or provided by the host application. The host objects available in browser contexts are documented in the <a href="/en-US/docs/Web/API/Reference">API reference</a>. For more information about the distinction between the <a href="/en-US/docs/DOM/DOM_Reference">DOM</a> and core <a href="/en-US/docs/Web/JavaScript">JavaScript</a>, see <a href="/en-US/docs/Web/JavaScript/JavaScript_technologies_overview">JavaScript technologies overview</a>.</p> + +<h2 id="Standard_objects_by_category">Standard objects (by category)</h2> + +<h3 id="Value_properties">Value properties</h3> + +<p>These global properties return a simple value; they have no properties or methods.</p> + +<ul> + <li>{{jsxref("Infinity")}}</li> + <li>{{jsxref("NaN")}}</li> + <li>{{jsxref("undefined")}}</li> + <li>{{jsxref("null")}} literal</li> +</ul> + +<h3 id="Function_properties">Function properties</h3> + +<p>These global functions—functions which are called globally rather than on an object—directly return their results to the caller.</p> + +<ul> + <li>{{jsxref("Global_Objects/eval", "eval()")}}</li> + <li>{{jsxref("Global_Objects/uneval", "uneval()")}} {{non-standard_inline}}</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/decodeURI", "decodeURI()")}}</li> + <li>{{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}</li> + <li>{{jsxref("Global_Objects/encodeURI", "encodeURI()")}}</li> + <li>{{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}</li> + <li>{{jsxref("Global_Objects/escape", "escape()")}} {{deprecated_inline}}</li> + <li>{{jsxref("Global_Objects/unescape", "unescape()")}} {{deprecated_inline}}</li> +</ul> + +<h3 id="Fundamental_objects">Fundamental objects</h3> + +<p>These are the fundamental, basic objects upon which all other objects are based. This includes objects that represent general objects, functions, and errors.</p> + +<ul> + <li>{{jsxref("Object")}}</li> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("Boolean")}}</li> + <li>{{jsxref("Symbol")}} {{experimental_inline}}</li> + <li>{{jsxref("Error")}}</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> + +<h3 id="Numbers_and_dates">Numbers and dates</h3> + +<p>These are the base objects representing numbers, dates, and mathematical calculations.</p> + +<ul> + <li>{{jsxref("Number")}}</li> + <li>{{jsxref("Math")}}</li> + <li>{{jsxref("Date")}}</li> +</ul> + +<h3 id="Text_processing">Text processing</h3> + +<p>These objects represent strings and support manipulating them.</p> + +<ul> + <li>{{jsxref("String")}}</li> + <li>{{jsxref("RegExp")}}</li> +</ul> + +<h3 id="Indexed_collections">Indexed collections</h3> + +<p>These objects represent collections of data which are ordered by an index value. This includes (typed) arrays and array-like constructs.</p> + +<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> +</ul> + +<h3 id="Keyed_collections">Keyed collections</h3> + +<p>These objects represent collections which use keys; these contain elements which are iterable in the order of insertion.</p> + +<ul> + <li>{{jsxref("Map")}} {{experimental_inline}}</li> + <li>{{jsxref("Set")}} {{experimental_inline}}</li> + <li>{{jsxref("WeakMap")}} {{experimental_inline}}</li> + <li>{{jsxref("WeakSet")}} {{experimental_inline}}</li> +</ul> + +<h3 id="Vector_collections">Vector collections</h3> + +<p>{{Glossary("SIMD")}} vector data types are objects where data is arranged into lanes.</p> + +<ul> + <li>{{jsxref("SIMD")}} {{experimental_inline}}</li> + <li>{{jsxref("float32x4", "SIMD.float32x4")}} {{experimental_inline}}</li> + <li>{{jsxref("float64x2", "SIMD.float64x2")}} {{experimental_inline}}</li> + <li>{{jsxref("int8x16", "SIMD.int8x16")}} {{experimental_inline}}</li> + <li>{{jsxref("int16x8", "SIMD.int16x8")}} {{experimental_inline}}</li> + <li>{{jsxref("int32x4", "SIMD.int32x4")}} {{experimental_inline}}</li> +</ul> + +<h3 id="Structured_data">Structured data</h3> + +<p>These objects represent and interact with structured data buffers and data coded using JavaScript Object Notation (JSON).</p> + +<ul> + <li>{{jsxref("ArrayBuffer")}}</li> + <li>{{jsxref("DataView")}}</li> + <li>{{jsxref("JSON")}}</li> +</ul> + +<h3 id="Control_abstraction_objects">Control abstraction objects</h3> + +<ul> + <li>{{jsxref("Promise")}} {{experimental_inline}}</li> + <li>{{jsxref("Generator")}} {{experimental_inline}}</li> + <li>{{jsxref("GeneratorFunction")}} {{experimental_inline}}</li> +</ul> + +<h3 id="Reflection">Reflection</h3> + +<ul> + <li>{{jsxref("Reflect")}} {{experimental_inline}}</li> + <li>{{jsxref("Proxy")}} {{experimental_inline}}</li> +</ul> + +<h3 id="Internationalization">Internationalization</h3> + +<p>Additions to the ECMAScript core for language-sensitive functionalities.</p> + +<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/NumberFormat", "Intl.NumberFormat")}}</li> +</ul> + +<h3 id="Non-standard_objects">Non-standard objects</h3> + +<ul> + <li>{{jsxref("Iterator")}} {{non-standard_inline}}</li> + <li>{{jsxref("ParallelArray")}} {{non-standard_inline}}</li> + <li>{{jsxref("StopIteration")}} {{non-standard_inline}}</li> +</ul> + +<h3 id="Other">Other</h3> + +<ul> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a></code></li> +</ul> +</div> diff --git a/files/tr/web/javascript/reference/global_objects/isfinite/index.html b/files/tr/web/javascript/reference/global_objects/isfinite/index.html new file mode 100644 index 0000000000..43268d42b7 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/isfinite/index.html @@ -0,0 +1,138 @@ +--- +title: isFinite() +slug: Web/JavaScript/Reference/Global_Objects/isFinite +tags: + - JavaScript + - Sonlu Sayı + - Sonsuz Sayı + - isFinite +translation_of: Web/JavaScript/Reference/Global_Objects/isFinite +--- +<div>{{jsSidebar("Objects")}}</div> + +<p>Global <code><strong>isFinite()</strong></code> fonksiyonu girilen değerin sonlu sayı olup olmadığını kararlaştırır. Gerekliyse, parametre ilk önce sayıya çevrilir.</p> + +<h2 id="Söz_Dizimi">Söz Dizimi</h2> + +<pre class="syntaxbox">isFinite(<em>testDegeri</em>)</pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt><code>testDegeri</code></dt> + <dd>Sonluluğu test edilecek sayı.</dd> +</dl> + +<h2 id="Açıklama">Açıklama</h2> + +<p><code>isFinite</code> en üst seviye fonksiyondur ve herhangi bir nesne ile ilişkilendirilemez.</p> + +<p>Bu fonksiyonu bir sayının sonlu olup olmadığını kararlaştırmak için kullanabilirsiniz. <code>isFinite</code> fonksiyonu argümanı olan sayıyı sorgular. Eğer argümanın değeri <code>NaN</code>, pozitif sonsuz veya negatif sonsuz ise, metod <strong>false</strong> döndürür; değilse, <strong>true</strong> döndürür.</p> + +<h2 id="Örnekler">Örnekler</h2> + +<pre class="brush: js">isFinite(SonsuzSayı); // false +isFinite(NaN); // false +isFinite(-SonsuzSayı); // false + +isFinite(0); // true +isFinite(2e64); // true +isFinite(null); // true + + +isFinite("0"); // true, daha güçlü bir ifade olan Number.isFinite("0") + // ile kullanılsaydı false olacaktı. +</pre> + +<h2 id="Tanımlamalar">Tanımlamalar</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Tanım</th> + <th scope="col">Durum</th> + <th scope="col">Açıklama</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.1.2.5', 'isFinite')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-isfinite-number', 'isFinite')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-isfinite-number', 'isFinite')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tarayıcı_Uyumluluğu">Tarayıcı Uyumluluğu</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Özellik</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Temel Destek</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>Özellik</th> + <th>Android</th> + <th>Android için Chrome</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Temel Destek</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="Ayrıca_Bakınız">Ayrıca Bakınız</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/tr/web/javascript/reference/global_objects/isnan/index.html b/files/tr/web/javascript/reference/global_objects/isnan/index.html new file mode 100644 index 0000000000..7a098629e6 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/isnan/index.html @@ -0,0 +1,170 @@ +--- +title: isNaN() +slug: Web/JavaScript/Reference/Global_Objects/isNaN +translation_of: Web/JavaScript/Reference/Global_Objects/isNaN +--- +<div>{{jsSidebar("Objects")}}</div> + +<p><code>isNaN()</code> bir değerin <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN">NaN </a>olup olmadığını belirler. Not: <code>isNaN</code> işlevi içindeki zorlamanın <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN#Description">ilginç</a> kuralları vardır; alternatif olarak ECMAScript 2015'te tanımlandığı gibi <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN">Number.isNaN()</a> yöntemini kullanmak isteyebilirsiniz.</p> + +<div>{{EmbedInteractiveExample("pages/js/globalprops-isnan.html")}}</div> + +<h2 id="Sözdizimi">Sözdizimi</h2> + +<pre class="syntaxbox"><code>isNaN(deger)</code></pre> + +<h3 id="Parametreler">Parametre(ler)</h3> + +<dl> + <dt><code>değer</code></dt> + <dd>Test edilecek değer.</dd> +</dl> + +<h3 id="Verilecek_değer">Verilecek değer</h3> + +<p>Verilen değer {{jsxref("NaN")}} ise<strong> <code>true</code></strong>; değilse <strong><code>false</code></strong>.</p> + +<h2 id="Açıklama">Açıklama</h2> + +<h3 id="isNaN_işlevi_gerekliliği"><code>isNaN</code> işlevi gerekliliği</h3> + +<p>JavaScript'teki diğer tüm olası değerlerden farklı olarak, bir değerin {{jsxref ("NaN")}} olup olmadığını belirlemek için eşitlik operatörlerine (== ve ===) güvenmek mümkün değildir, çünkü NaN == NaN ve NaN === NaN <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">false</span></font> olarak değerlendirilir. BU yüzden <code>isNaN</code> işlevi.</p> + +<h3 id="NaN_değerlerinin_kaynağı"><code>NaN</code> değerlerinin kaynağı</h3> + +<p>NaN değerleri, aritmetik işlemler <em>tanımsız (undefined)</em> veya <em>tekrarlanamayan</em> değerlerle sonuçlandığında üretilir. Bu tür değerler mutlaka taşma koşullarını temsil etmez. <code>NaN</code> ayrıca, ilkel sayısal değerin bulunmadığı sayısal olmayan değerlerin sayısal değerlerine zorlama girişiminden de kaynaklanır.</p> + +<p>Örneğin, sıfıra sıfıra bölmek bir <code>NaN</code> ile sonuçlanır - ancak diğer sayıları sıfıra bölmek olmaz.</p> + +<h3 id="Özel_durum_davranışlarını_karıştırmak">Özel durum davranışlarını karıştırmak</h3> + +<p><code>İsNaN</code> işlev belirtiminin en eski sürümleri olduğundan, sayısal olmayan bağımsız değişkenler için davranışı kafa karıştırıcı olur. İsNaN işlevinin bağımsız değişkeni <a href="http://es5.github.com/#x8.5">Number</a> türünde değilse, değer önce bir Number öğesine zorlanır. Dağa sonra elde edilen değer daha sonra {{jsxref ("NaN")}} olup olmadığını belirlemek için test edilir. Bu nedenle, sayısal tipe zorlandığında, geçerli bir <code>NaN</code> olmayan sayısal değerle sonuçlanan sayılar için (özellikle boş dize ve boolean ilkelleri, zorlandığında sayısal değerler sıfır veya bir verir), <code>"false"</code> döndürülen değer beklenmedik olabilir; örneğin, boş dize mutlaka "bir sayı değildir". Karışıklık, "sayı değil" teriminin IEEE-754 kayan nokta değerleri olarak gösterilen sayılar için özel bir anlamı olduğu gerçeğinden kaynaklanmaktadır. İşlev, "bu değer, sayısal değere zorlandığında IEEE-754 'Sayı Değil' değeri mi?" Sorusunu yanıtlıyor olarak yorumlanmalıdır.</p> + +<p>ECMAScript 2015, {{jsxref ("Number.isNaN ()")}} işlevini içerir. <code>Number.isNaN(x)</code>, x'in <code>NaN</code> olup olmadığını test etmenin güvenilir bir yoludur. Bununla birlikte, <code>Number.isNaN</code> ile bile, <code>NaN</code>'nin anlamı, basitçe "bir sayı değil", kesin sayısal anlam olarak kalır. Alternatif olarak, <code>Number.isNaN</code> yokluğunda, <code>(x != x)</code> ifadesi, <code>x</code> değişkeninin <code>NaN</code> olup olmadığını test etmenin daha güvenilir bir yoludur, çünkü sonuç <code>isNaN</code>'yi güvenilir olmayan sahte pozitiflere tabi değildir.</p> + +<p><code>isNaN</code> için bir çoklu dolgu (çoklu dolgu, <code>NaN</code>'nin kendine özgü asla eşit olmayan özelliğini kullanır):</p> + +<pre class="brush: js">var isNaN = function(deger) { + var n = Number(deger); + return n !== n; +};</pre> + +<h2 id="Examples">Examples</h2> + +<pre class="brush: js">isNaN(NaN); // true +isNaN(undefined); // true +isNaN({}); // true + +isNaN(true); // false +isNaN(null); // false +isNaN(37); // false + +// strings +isNaN('37'); // false: "37", NaN olmayan 37 sayısına dönüştürülür +isNaN('37.37'); // false: "37.37", NaN olmayan 37.37 sayısına dönüştürülür +isNaN("37,5"); // true +isNaN('123ABC'); // true: parseInt("123ABC") 123, ancak Number("123ABC") +isNaN(''); // false: boş dize, NaN olmayan 0'a dönüştürülür +isNaN(' '); // false: boşluklu bir dize, NaN olmayan 0'a dönüştürülür + +// tarihler +isNaN(new Date()); // false +isNaN(new Date().toString()); // true + +// Bu yanlış bir pozitiftir ve isNaN'ın tamamen güvenilir olmamasının nedenidir +isNaN('blabla'); // true: "blabla" bir sayıya dönüştürülür. + // Bunu bir sayı olarak ayrıştırma başarısız olur ve NaN döndürür</pre> + +<h3 id="Faydalı_özel_durum_davranışı">Faydalı özel durum davranışı</h3> + +<p><code>İsNaN()</code> yöntemini düşünmek için daha çok kullanıma yönelik bir yol vardır: <code>isNaN(x)</code> <code>false</code> değerini döndürürse, ifadeyi <code>NaN</code> döndürmeyen bir aritmetik ifadede <code>x</code> kullanabilirsiniz. <code>true</code> değerini döndürürse, <code>x</code> her aritmetik ifadeyi <code>NaN</code> döndürür. Bu, JavaScript'te,<code> isNaN(x) == true</code> değerinin, <code>NaN</code> döndüren <code>x - 0</code>'a eşdeğer olduğu anlamına gelir (JavaScript <code>x - 0 == NaN</code>'de her zaman <code>false</code> döndürür, bu nedenle test edemezsiniz). Aslında, <code>isNaN(x)</code>, <code>isNaN(x - 0)</code>, <code>isNaN(Number(x))</code>, <code>Number.isNaN(x - 0)</code> ve <code>Number.isNaN(Number(x))</code> her zaman aynı döndürür ve JavaScript <code>isNaN(x)</code> bu terimlerin her birini ifade etmek için mümkün olan en kısa biçimdir.</p> + +<p>Örneğin, bir işleve ait bir argümanın aritmetik olarak işlenebilir (bir sayı gibi "kullanılabilir") veya değilse ve varsayılan bir değer veya başka bir şey sağlamanız gerekip gerekmediğini test etmek için kullanabilirsiniz. Bu şekilde, içeriğe bağlı olarak değerleri dolaylı olarak dönüştürerek JavaScript'in sağladığı çok yönlülüğü kullanan bir işleve sahip olabilirsiniz.</p> + +<h2 id="Örnekler">Örnekler</h2> + +<pre class="brush: js">function artım(x) { + if (isNaN(x)) x = 0; + return x + 1; +} + +// Number.isNaN() ile aynı etki: +function artım(x) { + if (Number.isNaN(Number(x))) x = 0; + return x + 1; +} + +// Aşağıdaki durumlarda işlevin x argümanı için, +// isNaN(x) her zaman yanlıştır, ancak x gerçekten bir +// ancak aritmetik olarak kullanılabilir +// ifadeler +increment(''); // 1: "", 0'a dönüştürülür +increment(new String()); // 1: Boş bir dizeyi temsil eden dize nesnesi 0'a dönüştürülür +increment([]); // 1: [], 0'a dönüştürülür +increment(new Array()); // 1: Boş bir diziyi temsil eden dizi nesnesi 0'a dönüştürülür +increment('0'); // 1: "0", 0'a dönüştürülür +increment('1'); // 2: "1", 1'e dönüştürülür +increment('0.1'); // 1.1: "0.1", 0.1'a dönüştürülür. +increment('Infinity'); // Infinity: "Infinity", Infinity dönüştürülür +increment(null); // 1: null değeri 0'a dönüştürülür +increment(false); // 1: false değeri 0'a dönüştürülür +increment(true); // 2: true değeri 1'e dönüştürülür +increment(new Date()); // milisaniye cinsinden geçerli tarih/saati döndürür artı 1 + +// Aşağıdaki durumlarda işlevin x argümanı için, +// isNaN (x) her zaman falsetır ve x gerçekten bir sayıdır. +increment(-1); // 0 +increment(-0.1); // 0.9 +increment(0); // 1 +increment(1); // 2 +increment(2); // 3 +// ...ve bunun gibi... +increment(Infinity); // Infinity + +// Aşağıdaki durumlarda işlevin x argümanı için, +// isNaN(x) her zaman doğrudur ve x gerçekten bir sayı değildir, +// böylece fonksiyon 0 ile değiştirilir ve 1 döndürür +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) her zaman isNaN(Number(x)) ile aynıdır, +// ama x'in varlığı burada zorunludur! +isNaN(x) == isNaN(Number(x)); // x == undefined dahil, x'in her değeri için true, + // çünkü isNaN(undefined) == true ve Number(undefined) NaN değerini döndürür, + // ama... +isNaN() == isNaN(Number()); // false, çünküisNaN() == true ve Number() == 0 +</pre> + +<h2 id="Özellikler">Özellikler</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Şartname</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-isnan-number', 'isNaN')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Tarayıcı_Uyumluluğu">Tarayıcı Uyumluluğu</h2> + + + +<p>{{Compat("javascript.builtins.isNaN")}}</p> + +<h2 id="Ayrıca_bakınız">Ayrıca bakınız</h2> + +<ul> + <li>{{jsxref("NaN")}}</li> + <li>{{jsxref("Number.isNaN()")}}</li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/json/index.html b/files/tr/web/javascript/reference/global_objects/json/index.html new file mode 100644 index 0000000000..f458b5390e --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/json/index.html @@ -0,0 +1,205 @@ +--- +title: JSON +slug: Web/JavaScript/Reference/Global_Objects/JSON +tags: + - JSON + - JavaScript Nesneler + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/JSON +--- +<div>{{JSRef}}</div> + +<p>JSON nesnesi, <a href="http://json.org/">JavaScript Object Notasyonunu</a> çözümlemek ve değerleri JSON'a çevirmek için kullanılan metodları içinde barındırır. Çağırılamaz veya inşa edilemez, ve iki özelliği haricinde kendisine ait başka ilginç bir kullanılabilirliği de yoktur.</p> + +<h2 id="Açıklama">Açıklama</h2> + +<h3 id="JavaScript_Obje_Notasyonu">JavaScript Obje Notasyonu</h3> + +<p>JSON; nesneleri, dizileri, sayıları, dizeleri, boolean değerleri ve {{jsxref("null")}} değerini seri haline getirmek için kullanılan bir sözdizimidir. JavaScript sözdizimine bağlıdır ama farklılıkları da vardır: Her JavaScript, JSON olmadığı gibi her JSON da JavaScript olmayabilir. Buna da göz atın: <a href="http://timelessrepo.com/json-isnt-a-javascript-subset">JSON: The JavaScript subset that isn't</a>.</p> + +<table> + <caption>JavaScript ve JSON farklılıkları</caption> + <thead> + <tr> + <th scope="col">JavaScript tipi</th> + <th scope="col">JSON farklılıkları</th> + </tr> + </thead> + <tbody> + <tr> + <td>Nesneler ve Diziler</td> + <td>Property isimleri çift tırnaklı dizeler olmalıdır; sona konulan virgüller yasaktır.</td> + </tr> + <tr> + <td>Sayılar</td> + <td>Öne gelecek sıfırlar yasaktır( JSON.stringify'da sıfırlar göz ardı edilirler, ama JSON.parse'da SyntaxError döndürürler); bir ondalik noktanın devamında en az bir sayı gelmelidir.</td> + </tr> + <tr> + <td>Dizeler</td> + <td> + <p>Sadece sınırlı sayıda karakterin kaçmasına izin verilebilir; belli kontrol karakterleri yasaklanmıştır; Unicode satır ayırıcı (<a href="http://unicode-table.com/en/2028/">U+2028</a>) ve paragraf ayırıcı (<a href="http://unicode-table.com/en/2029/">U+2029</a>) karakterlerine izin verilir; dizeler çift tırnaklı olmalıdır. Aşağıdaki örneğe göz atarsanız; {{jsxref("JSON.parse()")}}'ın düzgün çalıştığını ve JavaScript olarak değerlendiği zaman bir {{jsxref("SyntaxError")}} döndürüldüğünü görebilirsiniz:</p> + + <pre class="brush: js"> +var code = '"\u2028\u2029"'; +JSON.parse(code); // düzgün çalışıyor. +eval(code); // hata veriyor. +</pre> + </td> + </tr> + </tbody> +</table> + +<p>Tüm JSON söz dizimi aşağıdaki gibidir:</p> + +<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>Önemsiz boşluklar; <code><var>JSONNumber ve JSONString</var></code> dışında herhangi bir yerde kullanılabilirler (sayılar boşluk içeremezler) veya (Dizeler için, dizede karşılık gelen karakter olarak yorumlanır, veye hataya sebep verir). Tab karakteri (<a href="http://unicode-table.com/en/0009/">U+0009</a>), satırbaşı (<a href="http://unicode-table.com/en/000D/">U+000D</a>), line feed (<a href="http://unicode-table.com/en/000A/">U+000A</a>), ve boşluk (<a href="http://unicode-table.com/en/0020/">U+0020</a>) karakterleri tek kabul edilen boşluk karakterleridir.</p> + +<h2 id="Metotlar">Metotlar</h2> + +<dl> + <dt>{{jsxref("JSON.parse()")}}</dt> + <dd>Bir dizeyi; JSON olarak çözümler, opsiyonel olarak üretilen değer ve değerin özelliklerini de dönüştürebilir. Sonrasında değeri döndürür.</dd> + <dt>{{jsxref("JSON.stringify()")}}</dt> + <dd>Belirtilen değerle ilişkili JSON dizesini döndürür, opsiyonel olarak sadece belirlenen özellikleri ekler veya özellik değerlerini kullanıcı tanımlı biçimde değiştirir.</dd> +</dl> + +<h2 id="Polyfill">Polyfill</h2> + +<p><code>JSON</code> nesnesi eski tarayıcılar tarafından desteklenmemektedir. Bunun üstesinden geçici bir şekilde gelmek için scriptinizin başına aşağıdaki kodu ekleyebilirsiniz, bu şekilde aslen destenlenmediğinde <code>JSON</code> nesnesinin kullanımına izin verilmiş olur (Internet Explorer 6 gibi).</p> + +<p>Aşağıdaki algoritma asıl <code>JSON</code> nesnesinin bir taklididir.</p> + +<pre class="brush: js">if (!window.JSON) { + window.JSON = { + parse: function(sJSON) { return eval('(' + sJSON + ')'); }, + stringify: (function () { + var toString = Object.prototype.toString; + var hasOwnProperty = Object.prototype.hasOwnProperty; + var isArray = Array.isArray || function (a) { return toString.call(a) === '[object Array]'; }; + var escMap = {'"': '\\"', '\\': '\\\\', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t'}; + var escFunc = function (m) { return escMap[m] || '\\u' + (m.charCodeAt(0) + 0x10000).toString(16).substr(1); }; + var escRE = /[\\"\u0000-\u001F\u2028\u2029]/g; + return function stringify(value) { + if (value == null) { + return 'null'; + } else if (typeof value === 'number') { + return isFinite(value) ? value.toString() : 'null'; + } else if (typeof value === 'boolean') { + return value.toString(); + } else if (typeof value === 'object') { + if (typeof value.toJSON === 'function') { + return stringify(value.toJSON()); + } else if (isArray(value)) { + var res = '['; + for (var i = 0; i < value.length; i++) + res += (i ? ', ' : '') + stringify(value[i]); + return res + ']'; + } else if (toString.call(value) === '[object Object]') { + var tmp = []; + for (var k in value) { + // in case "hasOwnProperty" has been shadowed + if (hasOwnProperty.call(value, k)) + tmp.push(stringify(k) + ': ' + stringify(value[k])); + } + return '{' + tmp.join(', ') + '}'; + } + } + return '"' + value.toString().replace(escRE, escFunc) + '"'; + }; + })() + }; +} +</pre> + +<p><code>JSON</code> nesnesi için daha karmaşık ve bilindik <a class="external" href="http://remysharp.com/2010/10/08/what-is-a-polyfill/">polyfill</a>ler ise: <a class="link-https" href="https://github.com/douglascrockford/JSON-js">JSON2</a> ve <a class="external" href="http://bestiejs.github.com/json3">JSON3</a>'tür.</p> + +<h2 id="Özellikler">Özellikler</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', 'JSON')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>İlk tanım.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-json-object', 'JSON')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-json-object', 'JSON')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tarayıcı_uyumluluğu">Tarayıcı uyumluluğu</h2> + +<div> +<div> +<div class="hidden">Bu sayfadaki uyumluluk tablosu yapılandırılmış verilerle oluşturulmuştur. Eğer bu verilere katkıda bulunmak isterseniz, lütfen <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> linkine göz atın ve bize pull request gönderin.</div> + +<p>{{Compat("javascript.builtins.JSON")}}</p> +</div> +</div> + +<h2 id="Ayrıca_Bakınız">Ayrıca Bakınız</h2> + +<ul> + <li>{{jsxref("Date.prototype.toJSON()")}}</li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/json/stringify/index.html b/files/tr/web/javascript/reference/global_objects/json/stringify/index.html new file mode 100644 index 0000000000..541e87d523 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/json/stringify/index.html @@ -0,0 +1,313 @@ +--- +title: JSON.stringify() +slug: Web/JavaScript/Reference/Global_Objects/JSON/stringify +translation_of: Web/JavaScript/Reference/Global_Objects/JSON/stringify +--- +<div>{{JSRef}}</div> + +<p><strong><code>JSON.stringify()</code></strong> metodu(fonksyionu) Javascript objesinin değerlerini JSON string'ine çevirir. Bu javascript nesnesi üzerinde değişiklik yapabilecek bir fonksiyon tanımlı ise nesne üzerinde çevirme işlemi yanında bunlar da yapılabilir.</p> + +<div>{{EmbedInteractiveExample("pages/js/json-stringify.html")}}</div> + + + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code>JSON.stringify(<var>value</var>[, <var>replacer</var>[, <var>space</var>]])</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>value</code></dt> + <dd>The value to convert to a JSON string.</dd> + <dt><code>replacer</code> {{optional_inline}}</dt> + <dd>A function that alters the behavior of the stringification process, or an array of {{jsxref("String")}} and {{jsxref("Number")}} objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string.</dd> + <dt><code>space</code> {{optional_inline}}</dt> + <dd>A {{jsxref("String")}} or {{jsxref("Number")}} object that's used to insert white space into the output JSON string for readability purposes. If this is a <code>Number</code>, it indicates the number of space characters to use as white space; this number is capped at 10 (if it is greater, the value is just 10). Values less than 1 indicate that no space should be used. If this is a <code>String</code>, the string (or the first 10 characters of the string, if it's longer than that) is used as white space. If this parameter is not provided (or is null), no white space is used.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>A JSON string representing the given value.</p> + +<h3 id="Exceptions">Exceptions</h3> + +<p>Throws a {{jsxref("TypeError")}} ("cyclic object value") exception when a circular reference is found.</p> + +<h2 id="Description">Description</h2> + +<p><code>JSON.stringify()</code> converts a value to JSON notation representing it:</p> + +<ul> + <li>If the value has a <a href="#toJSON()_behavior">toJSON()</a> method, it's responsible to define what data will be serialized.</li> + <li>{{jsxref("Boolean")}}, {{jsxref("Number")}}, and {{jsxref("String")}} objects are converted to the corresponding primitive values during stringification, in accord with the traditional conversion semantics.</li> + <li>If {{jsxref("undefined")}}, a {{jsxref("Function")}}, or a {{jsxref("Symbol")}} is encountered during conversion it is either omitted (when it is found in an object) or censored to {{jsxref("null")}} (when it is found in an array). <code>JSON.stringify()</code> can also just return <code>undefined</code> when passing in "pure" values like <code>JSON.stringify(function(){})</code> or <code>JSON.stringify(undefined)</code>.</li> + <li>All {{jsxref("Symbol")}}-keyed properties will be completely ignored, even when using the <code>replacer</code> function.</li> + <li>The instances of {{jsxref("Date")}} implement the <code>toJSON()</code> function by returning a string (the same as <code>date.toISOString()</code>), thus they are treated as strings.</li> + <li>The numbers {{jsxref("Infinity")}} and {{jsxref("NaN")}} as well as the object {{jsxref("null")}} are all considered as <code>null</code>.</li> + <li>For all the other {{jsxref("Object")}} instances (including {{jsxref("Map")}}, {{jsxref("Set")}}, {{jsxref("WeakMap")}} and {{jsxref("WeakSet")}}), only their enumerable properties will be serialized.</li> +</ul> + +<pre class="brush: js">JSON.stringify({}); // '{}' +JSON.stringify(true); // 'true' +JSON.stringify('foo'); // '"foo"' +JSON.stringify([1, 'false', false]); // '[1,"false",false]' +JSON.stringify([NaN, null, Infinity]); // '[null,null,null]' +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}' +JSON.stringify([new Number(3), new String('false'), new Boolean(false)]); +// '[3,"false",false]' + +// String-keyed array elements are not enumerable and make no sense in JSON +let a = ['foo', 'bar']; +a['baz'] = 'quux'; // a: [ 0: 'foo', 1: 'bar', baz: 'quux' ] +JSON.stringify(a); +// '["foo","bar"]' + +JSON.stringify({ x: [10, undefined, function(){}, Symbol('')] }); +// '{"x":[10,null,null,null]}' + +// Standard data structures +JSON.stringify([new Set([1]), new Map([[1, 2]]), new WeakSet([{a: 1}]), new WeakMap([[{a: 1}, 2]])]); +// '[{},{},{},{}]' + +// TypedArray +JSON.stringify([new Int8Array([1]), new Int16Array([1]), new Int32Array([1])]); +// '[{"0":1},{"0":1},{"0":1}]' +JSON.stringify([new Uint8Array([1]), new Uint8ClampedArray([1]), new Uint16Array([1]), new Uint32Array([1])]); +// '[{"0":1},{"0":1},{"0":1},{"0":1}]' +JSON.stringify([new Float32Array([1]), new Float64Array([1])]); +// '[{"0":1},{"0":1}]' + +// toJSON() +JSON.stringify({ x: 5, y: 6, toJSON(){ return this.x + this.y; } }); +// '11' + +// 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'; + } +}); +// undefined + +// Non-enumerable properties: +JSON.stringify( Object.create(null, { x: { value: 'x', enumerable: false }, y: { value: 'y', enumerable: true } }) ); +// '{"y":"y"}' +</pre> + +<h3 id="The_replacer_parameter"><a id="The replacer parameter" name="The replacer parameter"></a>The <code>replacer</code> parameter</h3> + +<p>The <code>replacer</code> parameter can be either a function or an array. As a function, it takes two parameters, the key and the value being stringified. The object in which the key was found is provided as the replacer's <code>this</code> parameter. Initially it gets called with an empty string as key representing the object being stringified, and it then gets called for each property on the object or array being stringified. It should return the value that should be added to the JSON string, as follows:</p> + +<ul> + <li>If you return a {{jsxref("Number")}}, the string corresponding to that number is used as the value for the property when added to the JSON string.</li> + <li>If you return a {{jsxref("String")}}, that string is used as the property's value when adding it to the JSON string.</li> + <li>If you return a {{jsxref("Boolean")}}, "true" or "false" is used as the property's value, as appropriate, when adding it to the JSON string.</li> + <li>If you return <code>null</code>, <code>null</code> will be added to the JSON string.</li> + <li>If you return any other object, the object is recursively stringified into the JSON string, calling the <code>replacer</code> function on each property, unless the object is a function, in which case nothing is added to the JSON string.</li> + <li>If you return <code>undefined</code>, the property is not included (i.e., filtered out) in the output JSON string.</li> +</ul> + +<div class="note"><strong>Note:</strong> You cannot use the <code>replacer</code> function to remove values from an array. If you return <code>undefined</code> or a function then <code>null</code> is used instead.</div> + +<div class="note"><strong>Note:</strong> If you wish the replacer to distinguish an initial object from a key with an empty string property (since both would give the empty string as key and potentially an object as value), you will have to keep track of the iteration count (if it is beyond the first iteration, it is a genuine empty string key).</div> + +<h4 id="Example_with_a_function">Example with a function</h4> + +<pre class="brush: js">function replacer(key, value) { + // Filtering out properties + if (typeof value === 'string') { + return undefined; + } + return value; +} + +var foo = {foundation: 'Mozilla', model: 'box', week: 45, transport: 'car', month: 7}; +JSON.stringify(foo, replacer); +// '{"week":45,"month":7}' +</pre> + +<h4 id="Example_with_an_array">Example with an array</h4> + +<p>If <code>replacer</code> is an array, the array's values indicate the names of the properties in the object that should be included in the resulting JSON string.</p> + +<pre class="brush: js">JSON.stringify(foo, ['week', 'month']); +// '{"week":45,"month":7}', only keep "week" and "month" properties +</pre> + +<h3 id="The_space_argument"><a id="The space argument" name="The space argument"></a>The <code>space</code> argument</h3> + +<p>The <code>space</code> argument may be used to control spacing in the final string. If it is a number, successive levels in the stringification will each be indented by this many space characters (up to 10). If it is a string, successive levels will be indented by this string (or the first ten characters of it).</p> + +<pre class="brush: js">JSON.stringify({ a: 2 }, null, ' '); +// '{ +// "a": 2 +// }' +</pre> + +<p>Using a tab character mimics standard pretty-print appearance:</p> + +<pre class="brush: js">JSON.stringify({ uno: 1, dos: 2 }, null, '\t'); +// returns the string: +// '{ +// "uno": 1, +// "dos": 2 +// }' +</pre> + +<h3 id="toJSON()_behavior"><code>toJSON()</code> behavior</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. <code>JSON.stringify()</code> calls <code>toJSON</code> with one parameter:</p> + +<ul> + <li>if this object is a property value, the property name</li> + <li>if it is in an array, the index in the array, as a string</li> + <li>an empty string if <code>JSON.stringify()</code> was directly called on this object</li> +</ul> + +<p>For example:</p> + +<pre class="brush: js">var obj = { + data: 'data', + + toJSON(key){ + if(key) + return `Now I am a nested object under key '${key}'`; + + else + return this; + } +}; + +JSON.stringify(obj); +// '{"data":"data"}' + +JSON.stringify({ obj }) +// '{"obj":"Now I am a nested object under key 'obj'"}' + +JSON.stringify([ obj ]) +// '["Now I am a nested object under key '0'"]' +</pre> + +<h3 id="Issue_with_JSON.stringify()_when_serializing_circular_references">Issue with <code>JSON.stringify()</code> when serializing circular references</h3> + +<p>Note that since the <a href="https://www.json.org/">JSON format</a> doesn't support object references (although an <a href="http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03">IETF draft exists</a>), a {{jsxref("TypeError")}} will be thrown if one attempts to encode an object with circular references.</p> + +<pre class="brush: js example-bad">const circularReference = {}; +circularReference.myself = circularReference; + +// Serializing circular references throws "TypeError: cyclic object value" +JSON.stringify(circularReference); +</pre> + +<p>To serialize circular references you can use a library that supports them (e.g. <a href="https://github.com/douglascrockford/JSON-js/blob/master/cycle.js">cycle.js</a> by Douglas Crockford) or implement a solution by yourself, which will require finding and replacing (or removing) the cyclic references by serializable values.</p> + +<h3 id="Issue_with_plain_JSON.stringify_for_use_as_JavaScript">Issue with plain <code>JSON.stringify</code> for use as JavaScript</h3> + +<p>Note that JSON is <a href="http://timelessrepo.com/json-isnt-a-javascript-subset">not a completely strict subset of JavaScript</a>, with two line terminators (Line separator and Paragraph separator) not needing to be escaped in JSON but needing to be escaped in JavaScript. Therefore, if the JSON is meant to be evaluated or directly utilized within <a href="https://en.wikipedia.org/wiki/JSONP">JSONP</a>, the following utility can be used:</p> + +<pre class="brush: js">function jsFriendlyJSONStringify (s) { + return JSON.stringify(s). + replace(/\u2028/g, '\\u2028'). + replace(/\u2029/g, '\\u2029'); +} + +var s = { + a: String.fromCharCode(0x2028), + b: String.fromCharCode(0x2029) +}; +try { + eval('(' + JSON.stringify(s) + ')'); +} catch (e) { + console.log(e); // "SyntaxError: unterminated string literal" +} + +// No need for a catch +eval('(' + jsFriendlyJSONStringify(s) + ')'); + +// console.log in Firefox unescapes the Unicode if +// logged to console, so we use alert +alert(jsFriendlyJSONStringify(s)); // {"a":"\u2028","b":"\u2029"}</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> + +<pre class="brush: js">// 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="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.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="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.JSON.stringify")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("JSON.parse()")}}</li> + <li><a href="https://github.com/douglascrockford/JSON-js/blob/master/cycle.js">cycle.js</a> – Introduces two functions, <code>JSON.decycle</code> and <code>JSON.retrocycle</code>, which makes it possible to encode and decode cyclical structures and dags into an extended and retrocompatible JSON format.</li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/map/index.html b/files/tr/web/javascript/reference/global_objects/map/index.html new file mode 100644 index 0000000000..67f46594f6 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/map/index.html @@ -0,0 +1,207 @@ +--- +title: Map +slug: Web/JavaScript/Reference/Global_Objects/Map +tags: + - ECMAScript 2015 + - JavaScript + - Map + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Map +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary">The <strong><code>Map</code></strong> object holds key-value pairs.</span> Any value (both objects and {{Glossary("Primitive", "primitive values")}}) may be used as either a key or a value.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">new Map([<em>iterable</em>])</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>iterable</code></dt> + <dd>An {{jsxref("Array")}} or other <a href="/en-US/docs/Web/JavaScript/Guide/iterable">iterable</a> object whose elements are key-value pairs (arrays with two elements, e.g. <code>[[ 1, 'one' ],[ 2, 'two' ]]</code>). Each key-value pair is added to the new <code>Map</code>; <code>null</code> values are treated as <code>undefined</code>.</dd> +</dl> + +<h2 id="Description">Description</h2> + +<p>A <code>Map</code> object iterates its elements in insertion order — a {{jsxref("Statements/for...of", "for...of")}} loop returns an array of <code>[key, value]</code> for each iteration.<br> + <br> + It should be noted that a <code>Map</code> which is a map of an object, especially a dictionary of dictionaries, will only map to the object's insertion order—which is random and not ordered.</p> + +<h3 id="Key_equality">Key equality</h3> + +<p>Key equality is based on the "SameValueZero" algorithm: <code>NaN</code> is considered the same as <code>NaN</code> (even though <code>NaN !== NaN</code>) and all other values are considered equal according to the semantics of the <code>===</code> operator. In the current ECMAScript specification <code>-0</code> and <code>+0</code> are considered equal, although this was not so in earlier drafts. See "Value equality for -0 and 0" in the <a href="#Browser_compatibility">browser compatibility</a> table for details.</p> + +<h3 id="Objects_and_maps_compared">Objects and maps compared</h3> + +<p>{{jsxref("Object", "Objects")}} are similar to <code>Maps</code> in that both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. Because of this (and because there were no built-in alternatives), <code>Object</code>s have been used as <code>Maps</code> historically; however, there are important differences that make using a <code>Map</code> preferable in certain cases:</p> + +<ul> + <li>The keys of an <code>Object</code> are {{jsxref("String", "Strings")}} and {{jsxref("Symbol", "Symbols")}}, whereas they can be any value for a <code>Map</code>, including functions, objects, and any primitive.</li> + <li>You can get the size of a <code>Map</code> easily with the <code>size</code> property, while the number of properties in an <code>Object</code> must be determined manually.</li> + <li>A <code>Map</code> is an <a href="/en-US/docs/Web/JavaScript/Guide/iterable">iterable</a> and can thus be directly iterated, whereas iterating over an <code>Object</code> requires obtaining its keys in some fashion and iterating over them.</li> + <li>An <code>Object</code> has a prototype, so there are default keys in the map that could collide with your keys if you're not careful. As of ES5 this can be bypassed by using <code>map = Object.create(null)</code>, but this is seldom done.</li> + <li>A <code>Map</code> may perform better in scenarios involving frequent addition and removal of key pairs.</li> +</ul> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt><code>Map.length</code></dt> + <dd>The value of the <code>length</code> property is 0.</dd> + <dt>{{jsxref("Map.@@species", "get Map[@@species]")}}</dt> + <dd>The constructor function that is used to create derived objects.</dd> + <dt>{{jsxref("Map.prototype")}}</dt> + <dd>Represents the prototype for the <code>Map</code> constructor. Allows the addition of properties to all <code>Map</code> objects.</dd> +</dl> + +<h2 id="Map_instances"><code>Map</code> instances</h2> + +<p>All <code>Map</code> instances inherit from {{jsxref("Map.prototype")}}.</p> + +<h3 id="Properties_2">Properties</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Map/prototype','Properties')}}</p> + +<h3 id="Methods">Methods</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Map/prototype','Methods')}}</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_the_Map_object">Using the <code>Map</code> object</h3> + +<pre class="brush: js">var myMap = new Map(); + +var keyString = 'a string', + keyObj = {}, + keyFunc = function() {}; + +// setting the values +myMap.set(keyString, "value associated with 'a string'"); +myMap.set(keyObj, 'value associated with keyObj'); +myMap.set(keyFunc, 'value associated with keyFunc'); + +myMap.size; // 3 + +// getting the values +myMap.get(keyString); // "value associated with 'a string'" +myMap.get(keyObj); // "value associated with keyObj" +myMap.get(keyFunc); // "value associated with keyFunc" + +myMap.get('a string'); // "value associated with 'a string'" + // because keyString === 'a string' +myMap.get({}); // undefined, because keyObj !== {} +myMap.get(function() {}) // undefined, because keyFunc !== function () {} +</pre> + +<h3 id="Using_NaN_as_Map_keys">Using <code>NaN</code> as <code>Map</code> keys</h3> + +<p><code>NaN</code> can also be used as a key. Even though every <code>NaN</code> is not equal to itself (<code>NaN !== NaN</code> is true), the following example works because <code>NaN</code>s are indistinguishable from each other:</p> + +<pre class="brush: js">var myMap = new Map(); +myMap.set(NaN, 'not a number'); + +myMap.get(NaN); // "not a number" + +var otherNaN = Number('foo'); +myMap.get(otherNaN); // "not a number" +</pre> + +<h3 id="Iterating_Maps_with_for..of">Iterating <code>Maps</code> with <code>for..of</code></h3> + +<p>Maps can be iterated using a <code>for..of</code> loop:</p> + +<pre class="brush: js">var myMap = new Map(); +myMap.set(0, 'zero'); +myMap.set(1, 'one'); +for (var [key, value] of myMap) { + console.log(key + ' = ' + value); +} +// 0 = zero +// 1 = one + +for (var key of myMap.keys()) { + console.log(key); +} +// 0 +// 1 + +for (var value of myMap.values()) { + console.log(value); +} +// zero +// one + +for (var [key, value] of myMap.entries()) { + console.log(key + ' = ' + value); +} +// 0 = zero +// 1 = one +</pre> + +<h3 id="Iterating_Maps_with_forEach()">Iterating <code>Maps</code> with <code>forEach()</code></h3> + +<p>Maps can be iterated using the <code>forEach()</code> method:</p> + +<pre class="brush: js">myMap.forEach(function(value, key) { + console.log(key + ' = ' + value); +}); +// Will show 2 logs; first with "0 = zero" and second with "1 = one" +</pre> + +<h3 id="Relation_with_Array_objects">Relation with <code>Array</code> objects</h3> + +<pre class="brush: js">var kvArray = [['key1', 'value1'], ['key2', 'value2']]; + +// Use the regular Map constructor to transform a 2D key-value Array into a map +var myMap = new Map(kvArray); + +myMap.get('key1'); // returns "value1" + +// Use the Array.from function to transform a map into a 2D key-value Array +console.log(Array.from(myMap)); // Will show you exactly the same Array as kvArray + +// Or use the keys or values iterators and convert them to an array +console.log(Array.from(myMap.keys())); // Will show ["key1", "key2"] +</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-objects', 'Map')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-map-objects', 'Map')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.builtins.Map")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a class="link-https" href="https://bugzilla.mozilla.org/show_bug.cgi?id=697479">Map and Set bug at Mozilla</a></li> + <li><a class="external" href="http://wiki.ecmascript.org/doku.php?id=harmony:simple_maps_and_sets">ECMAScript Harmony proposal</a></li> + <li>{{jsxref("Set")}}</li> + <li>{{jsxref("WeakMap")}}</li> + <li>{{jsxref("WeakSet")}}</li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/map/prototype/index.html b/files/tr/web/javascript/reference/global_objects/map/prototype/index.html new file mode 100644 index 0000000000..5bad06ed4a --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/map/prototype/index.html @@ -0,0 +1,84 @@ +--- +title: Map.prototype +slug: Web/JavaScript/Reference/Global_Objects/Map/prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Map +--- +<div>{{JSRef}}</div> + +<p><code><strong>Map</strong></code><strong><code>.prototype</code></strong> özelliği {{jsxref("Map")}} kurucusunun prototipini temsil eder.</p> + +<div>{{js_property_attributes(0,0,0)}}</div> + +<h2 id="Tanım">Tanım</h2> + +<p>{{jsxref("Map")}} örnekleri {{jsxref("Map.prototype")}}'den miras alınır. Tüm <code>Map</code> örneklerine özellikler veya yöntemler eklemek için yapıcının prototip nesnesini kullanabilirsiniz.</p> + +<h2 id="Özellikleri">Özellikleri</h2> + +<dl> + <dt><code>Map.prototype.constructor</code></dt> + <dd>Bir örneğin prototipini oluşturan işlevi döndürür. Bu, varsayılan olarak {{jsxref("Map")}} işlevidir.</dd> + <dt>{{jsxref("Map.prototype.size")}}</dt> + <dd><code>Map</code> nesnesindeki anahtar / değer çiftlerinin sayısını döndürür.</dd> +</dl> + +<h2 id="Yöntemler">Yöntemler</h2> + +<dl> + <dt>{{jsxref("Map.prototype.clear()")}}</dt> + <dd>Tüm anahtar / değer çiftlerini <code>Map</code> objesinden siler.</dd> + <dt>{{jsxref("Map.delete", "Map.prototype.delete(key)")}}</dt> + <dd><code>Map</code> nesnesindeki bir öge varsa ve kaldırılmışsa <code>true</code> öge yoksa <code>false</code> döndürür. <code>Map.prototype.has(key)</code> daha sonra <code>false</code> döndürür.</dd> + <dt>{{jsxref("Map.prototype.entries()")}}</dt> + <dd>Ekleme sırasındaki <code>Map</code> nesnesindeki her öge için <strong><code>[anahtar, değer] </code></strong>dizisini içeren yeni bir <code>Iterator</code> nesnesini döndürür.</dd> + <dt>{{jsxref("Map.forEach", "Map.prototype.forEach(callbackFn[, thisArg])")}}</dt> + <dd><code>Map</code> nesnesindeki her anahtar - değer çifti için ekleme sırasına göre callbackFn ögesini bir kez çağırır. thisArg parametresi forEach için sağlanmışsa, her geri çağırma için bu değer olarak kullanılacaktır.</dd> + <dt>{{jsxref("Map.get", "Map.prototype.get(key)")}}</dt> + <dd><code>key</code> ile ilişkilendirilmiş değeri veya hiçbir şey yoksa <code>undefined</code> değerini döndürür.</dd> + <dt>{{jsxref("Map.has", "Map.prototype.has(key)")}}</dt> + <dd><code>Map</code> nesnesindeki bir değerin <code>key</code> ile ilişkili olup olmadığını belirten bir boolean döndürür.</dd> + <dt>{{jsxref("Map.prototype.keys()")}}</dt> + <dd><code>Map</code> nesnesindeki her bir ögenin<strong> anahtarlarını</strong> ekleme sırasına göre içeren yeni bir <code>Iterator</code> nesnesi döndürür.</dd> + <dt>{{jsxref("Map.set", "Map.prototype.set(key, value)")}}</dt> + <dd><code>Map</code>nesnesindeki <code>key</code> değerini ayarlar. <code>Map</code> nesnesini döndürür.</dd> + <dt>{{jsxref("Map.prototype.values()")}}</dt> + <dd><code>Map</code> nesnesindeki her bir ögenin <strong>değerlerini </strong>ekleme sırasına göre içeren yeni bir <code>Iterator</code> nesnesi döndürür.</dd> + <dt>{{jsxref("Map.@@iterator", "Map.prototype[@@iterator]()")}}</dt> + <dd>Ekleme sırasındaki <code>Map</code> nesnesindeki her bir öge için<strong><code>[anahtar, değer]</code></strong> dizisini içeren yeni bir <code>Iterator</code> nesnesini döndürür.</dd> +</dl> + +<h2 id="Şartlar">Şartlar</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Şart</th> + <th scope="col">Durum</th> + <th scope="col">Açıklama</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-map.prototype', 'Map.prototype')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td> + <p>İlk tanım</p> + </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-map.prototype', 'Map.prototype')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tarayıcı_Uyumluluğu">Tarayıcı Uyumluluğu</h2> + +<div class="hidden">Bu sayfadaki uyumluluk tablosu yapılandırılmış verilerden oluşturulmuştur. Verilere katkıda bulunmak istiyorsanız, lütfen <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> adresini ziyaret etin ve bize bir istek gönderin.</div> + +<p>{{Compat("javascript.builtins.Map.prototype")}}</p> + +<h2 id="Ayrıca_Bakınız">Ayrıca Bakınız</h2> + +<ul> + <li>{{jsxref("Set.prototype")}}</li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/math/index.html b/files/tr/web/javascript/reference/global_objects/math/index.html new file mode 100644 index 0000000000..774ed159f2 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/math/index.html @@ -0,0 +1,191 @@ +--- +title: Math +slug: Web/JavaScript/Reference/Global_Objects/Math +tags: + - JavaScript + - Math + - Namespace + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Math +--- +<div></div> + +<div>{{JSRef}}</div> + +<p><strong><code>Math</code></strong> is a built-in object that has properties and methods for mathematical constants and functions. It’s not a function object.</p> + +<p><code>Math</code> works with the {{jsxref("Number")}} type. It doesn't work with {{jsxref("BigInt")}}.</p> + +<h2 id="Description">Description</h2> + +<p>Unlike many other global objects, <code>Math</code> is not a constructor. All properties and methods of <code>Math</code> are static. You refer to the constant pi as <code>Math.PI</code> and you call the sine function as <code>Math.sin(<var>x</var>)</code>, where <code><var>x</var></code> is the method’s argument. Constants are defined with the full precision of real numbers in JavaScript.</p> + +<div class="note"> +<p><strong>Note:</strong> Many <code>Math</code> functions have a precision that’s <em>implementation-dependent.</em></p> + +<p>This means that different browsers can give a different result. Even the same JavaScript engine on a different OS or architecture can give different results!</p> +</div> + +<h2 id="Static_properties">Static properties</h2> + +<dl> + <dt>{{jsxref("Math.E")}}</dt> + <dd>Euler's constant and the base of natural logarithms; approximately <code>2.718</code>.</dd> + <dt>{{jsxref("Math.LN2")}}<code>lllllđđlđ</code></dt> + <dd>lllllđđ v<img alt="" src="https://mdn.mozillademos.org/files/14829/trigonometry.png" style="height: 166px; width: 200px;">ili ga ti tu of <code>2</code>; approximately <code>0.693</code>.</dd> + <dt>{{jsxref("Math.LN10")}}</dt> + <dd>Natural logarithm of <code>10</code>; approximately <code>2.303</code>.</dd> + <dt>{{jsxref("Math.LOG2E")}}</dt> + <dd>Base-2 logarithm of <code>E</code>; approximately <code>1.443</code>.</dd> + <dt>{{jsxref("Math.LOG10E")}}</dt> + <dd>Base-10 logarithm of <code>E</code>; approximately <code>0.434</code>.</dd> + <dt>{{jsxref("Math.PI")}}</dt> + <dd>Ratio of the a circle's circumference to its diameter; approximately <code>3.14159</code>.</dd> + <dt>{{jsxref("Math.SQRT1_2")}}</dt> + <dd>Square root of ½ (or equivalently, <sup>1</sup>/<sub>√2</sub>); approximately <code>0.707</code>.</dd> + <dt>{{jsxref("Math.SQRT2")}}</dt> + <dd>Square root of <code>2</code>; approximately <code>1.414</code>.</dd> +</dl> + +<h2 id="Static_methods">Static methods</h2> + +<dl> + <dt>{{jsxref("Global_Objects/Math/abs", "Math.abs(<var>x</var>)")}}</dt> + <dd>Returns the absolute value of <code><var>x</var></code>.</dd> + <dt>{{jsxref("Global_Objects/Math/acos", "Math.acos(<var>x</var>)")}}</dt> + <dd>Returns the arccosine of <code><var>x</var></code>.</dd> + <dt>{{jsxref("Global_Objects/Math/acosh", "Math.acosh(<var>x</var>)")}}</dt> + <dd>Returns the hyperbolic arccosine of <code><var>x</var></code>.</dd> + <dt>{{jsxref("Global_Objects/Math/asin", "Math.asin(<var>x</var>)")}}</dt> + <dd>Returns the arcsine of <code><var>x</var></code>.</dd> + <dt>{{jsxref("Global_Objects/Math/asinh", "Math.asinh(<var>x</var>)")}}</dt> + <dd>Returns the hyperbolic arcsine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/atan", "Math.atan(<var>x</var>)")}}</dt> + <dd>Returns the arctangent of <code><var>x</var></code>.</dd> + <dt>{{jsxref("Global_Objects/Math/atanh", "Math.atanh(<var>x</var>)")}}</dt> + <dd>Returns the hyperbolic arctangent of <code><var>x</var></code>.</dd> + <dt>{{jsxref("Global_Objects/Math/atan2", "Math.atan2(<var>y</var>, <var>x</var>)")}}</dt> + <dd>Returns the arctangent of the quotient of its arguments.</dd> + <dt>{{jsxref("Global_Objects/Math/cbrt", "Math.cbrt(<var>x</var>)")}}</dt> + <dd>Returns the cube root of <code><var>x</var></code>.</dd> + <dt>{{jsxref("Global_Objects/Math/ceil", "Math.ceil(<var>x</var>)")}}</dt> + <dd>Returns the smallest integer greater than or equal to <code><var>x</var></code>.</dd> + <dt>{{jsxref("Global_Objects/Math/clz32", "Math.clz32(<var>x</var>)")}}</dt> + <dd>Returns the number of leading zeroes of the 32-bit integer <code><var>x</var></code>.</dd> + <dt>{{jsxref("Global_Objects/Math/cos", "Math.cos(<var>x</var>)")}}</dt> + <dd>Returns the cosine of <code><var>x</var></code>.</dd> + <dt>{{jsxref("Global_Objects/Math/cosh", "Math.cosh(<var>x</var>)")}}</dt> + <dd>Returns the hyperbolic cosine of <code><var>x</var></code>.</dd> + <dt>{{jsxref("Global_Objects/Math/exp", "Math.exp(<var>x</var>)")}}</dt> + <dd>Returns <code>E<var><sup>x</sup></var></code>, where <code><var>x</var></code> is the argument, and <code>E</code> is Euler's constant (<code>2.718</code>…, the base of the natural logarithm).</dd> + <dt>{{jsxref("Global_Objects/Math/expm1", "Math.expm1(<var>x</var>)")}}</dt> + <dd>Returns subtracting <code>1</code> from <code>exp(<var>x</var>)</code>.</dd> + <dt>{{jsxref("Global_Objects/Math/floor", "Math.floor(<var>x</var>)")}}</dt> + <dd>Returns the largest integer less than or equal to <code><var>x</var></code>.</dd> + <dt>{{jsxref("Global_Objects/Math/fround", "Math.fround(<var>x</var>)")}}</dt> + <dd>Returns the nearest <a href="https://en.wikipedia.org/wiki/Single-precision_floating-point_format" title="link to the wikipedia page on single precision">single precision</a> float representation of <code><var>x</var></code>.</dd> + <dt>{{jsxref("Global_Objects/Math/hypot", "Math.hypot([<var>x</var>[, <var>y</var>[, …]]])")}}</dt> + <dd>Returns the square root of the sum of squares of its arguments.</dd> + <dt>{{jsxref("Global_Objects/Math/imul", "Math.imul(<var>x</var>, <var>y</var>)")}}</dt> + <dd>Returns the result of the 32-bit integer multiplication of <code><var>x</var></code> and <code><var>y</var></code>.</dd> + <dt>{{jsxref("Global_Objects/Math/log", "Math.log(<var>x</var>)")}}</dt> + <dd>Returns the natural logarithm (㏒<sub>e</sub>; also, ㏑) of <code><var>x</var></code>.</dd> + <dt>{{jsxref("Global_Objects/Math/log1p", "Math.log1p(<var>x</var>)")}}</dt> + <dd>Returns the natural logarithm (㏒<sub>e</sub>; also ㏑) of <code>1 + <var>x</var></code> for the number <code><var>x</var></code>.</dd> + <dt>{{jsxref("Global_Objects/Math/log10", "Math.log10(<var>x</var>)")}}</dt> + <dd>Returns the base-10 logarithm of <code><var>x</var></code>.</dd> + <dt>{{jsxref("Global_Objects/Math/log2", "Math.log2(<var>x</var>)")}}</dt> + <dd>Returns the base-2 logarithm of <code><var>x</var></code>.</dd> + <dt>{{jsxref("Global_Objects/Math/max", "Math.max([<var>x</var>[, <var>y</var>[, …]]])")}}</dt> + <dd>Returns the largest of zero or more numbers.</dd> + <dt>{{jsxref("Global_Objects/Math/min", "Math.min([<var>x</var>[, <var>y</var>[, …]]])")}}</dt> + <dd>Returns the smallest of zero or more numbers.</dd> + <dt>{{jsxref("Global_Objects/Math/pow", "Math.pow(<var>x</var>, <var>y</var>)")}}</dt> + <dd>Returns base <code><var>x</var></code> to the exponent power <code><var>y</var></code> (that is, <code><var>x</var><var><sup>y</sup></var></code>).</dd> + <dt>{{jsxref("Global_Objects/Math/random", "Math.random()")}}</dt> + <dd>Returns a pseudo-random number between <code>0</code> and <code>1</code>.</dd> + <dt>{{jsxref("Global_Objects/Math/round", "Math.round(<var>x</var>)")}}</dt> + <dd>Returns the value of the number <code><var>x</var></code> rounded to the nearest integer.</dd> + <dt>{{jsxref("Global_Objects/Math/sign", "Math.sign(<var>x</var>)")}}</dt> + <dd>Returns the sign of the <code><var>x</var></code>, indicating whether <code><var>x</var></code> is positive, negative, or zero.</dd> + <dt>{{jsxref("Global_Objects/Math/sin", "Math.sin(<var>x</var>)")}}</dt> + <dd>Returns the sine of <code><var>x</var></code>.</dd> + <dt>{{jsxref("Global_Objects/Math/sinh", "Math.sinh(<var>x</var>)")}}</dt> + <dd>Returns the hyperbolic sine of <code><var>x</var></code>.</dd> + <dt>{{jsxref("Global_Objects/Math/sqrt", "Math.sqrt(<var>x</var>)")}}</dt> + <dd>Returns the positive square root of <code><var>x</var></code>.</dd> + <dt>{{jsxref("Global_Objects/Math/tan", "Math.tan(<var>x</var>)")}}</dt> + <dd>Returns the tangent of <code><var>x</var></code>.</dd> + <dt>{{jsxref("Global_Objects/Math/tanh", "Math.tanh(<var>x</var>)")}}</dt> + <dd>Returns the hyperbolic tangent of <code><var>x</var></code>.</dd> + <dt>{{jsxref("Global_Objects/Math/trunc", "Math.trunc(<var>x</var>)")}}</dt> + <dd>Returns the integer portion of <code><var>x</var></code>, removing any fractional digits.</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<h3 id="Converting_between_degrees_and_radians">Converting between degrees and radians</h3> + +<p>The trigonometric functions <code>sin()</code>, <code>cos()</code>, <code>tan()</code>, <code>asin()</code>, <code>acos()</code>, <code>atan()</code>, and <code>atan2()</code> expect (and return) angles in <em>radians</em>.</p> + +<p>Since humans tend to think in degrees, and some functions (such as CSS transforms) can accept degrees, it is a good idea to keep functions handy that convert between the two:</p> + +<pre class="brush: js"><code class="language-js"><span class="keyword token">function</span> <span class="function token">degToRad</span><span class="punctuation token">(</span><span class="parameter token">degrees</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">return</span> degrees <span class="operator token">*</span> (Math<span class="punctuation token">.</span><span class="constant token">PI</span> <span class="operator token">/</span> <span class="number token">180</span><span class="punctuation token">);</span> +<span class="punctuation token">}</span><span class="punctuation token">;</span></code> + +function radToDeg(rad) { + return rad / (Math.PI / 180); +};</pre> + +<h3 id="Calculating_the_height_of_an_equalateral_triangle">Calculating the height of an equalateral triangle</h3> + +<p>If we want to calculate the height of an equalateral triangle, and we know its side length is 100, we can use the formulae <em>length of the adjacent multiplied by the tangent of the angle is equal to the opposite.</em></p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/14829/trigonometry.png" style="display: block; margin: 0 auto;"></p> + +<p>In JavaScript, we can do this with the following:</p> + +<pre class="brush: js">50 * Math.tan(degToRad(60)).</pre> + +<p>We use our <code>degToRad()</code> function to convert 60 degrees to radians, as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/tan"><code>Math.tan()</code></a> expects an input value in radians.</p> + +<h3 id="Returning_a_random_integer_between_two_bounds">Returning a random integer between two bounds</h3> + +<p>This can be achieved with a combination of <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random">Math.random()</a></code> and <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor">Math.floor()</a></code>:</p> + +<pre class="brush: js">function random(min, max) { + const num = Math.floor(Math.random() * (max - min + 1)) + min; + return num; +} + +random(1, 10);</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-math-object', 'Math')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.builtins.Math")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Number")}}</li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/math/sign/index.html b/files/tr/web/javascript/reference/global_objects/math/sign/index.html new file mode 100644 index 0000000000..cbed44a438 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/math/sign/index.html @@ -0,0 +1,110 @@ +--- +title: Math.sign() +slug: Web/JavaScript/Reference/Global_Objects/Math/sign +translation_of: Web/JavaScript/Reference/Global_Objects/Math/sign +--- +<div>{{JSRef}}</div> + +<div><code><strong>Math.sign()</strong></code> fonksiyonu, parametre olarak aldığı sayının negatif (-1) veya pozitif (1) olduğu bilgisini döndürür. Parametre olarak 0 gönderilirse, +/- 0 döndürür. Sayı pozitifse ayrıca + işareti döndürülmez.</div> + +<div></div> + +<div>{{EmbedInteractiveExample("pages/js/math-sign.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="Syntax">Syntax</h2> + +<pre class="syntaxbox">Math.sign(<var>x</var>)</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code><var>x</var></code></dt> + <dd>A number. If this argument is not a <code>number</code>, it is implicitly converted to one.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>A number representing the sign of the given argument:</p> + +<ul> + <li>If the argument is positive, returns <code>1</code>.</li> + <li>If the argument is negative, returns <code>-1</code>.</li> + <li>If the argument is positive zero, returns <code>0</code>.</li> + <li>If the argument is negative zero, returns <code>-0</code>.</li> + <li>Otherwise, {{jsxref("NaN")}} is returned.</li> +</ul> + +<h2 id="Description">Description</h2> + +<p>Because <code>sign()</code> is a static method of <code>Math</code>, you always use it as <code>Math.sign()</code>, rather than as a method of a <code>Math</code> object you created (<code>Math</code> is not a constructor).</p> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js">if (!Math.sign) { + Math.sign = function(x) { + // If x is NaN, the result is NaN. + // If x is -0, the result is -0. + // If x is +0, the result is +0. + // If x is negative and not -0, the result is -1. + // If x is positive and not +0, the result is +1. + return ((x > 0) - (x < 0)) || +x; + // A more aesthetic pseudo-representation: + // + // ( (x > 0) ? 1 : 0 ) // if x is positive, then positive one + // + // else (because you can't be both - and +) + // ( (x < 0) ? -1 : 0 ) // if x is negative, then negative 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>In the above polyfill, no extra type-coercing is needed to make <code>(x > 0)</code> or <code>(x < 0)</code> numbers because subtracting them from each other forces a type conversion from booleans to numbers.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_Math.sign">Using <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="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.sign', 'Math.sign')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</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 class="external" 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.Math.sign")}}</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.trunc()")}}</li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/object/assign/index.html b/files/tr/web/javascript/reference/global_objects/object/assign/index.html new file mode 100644 index 0000000000..9490bcec2d --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/object/assign/index.html @@ -0,0 +1,311 @@ +--- +title: Object.assign() +slug: Web/JavaScript/Reference/Global_Objects/Object/assign +translation_of: Web/JavaScript/Reference/Global_Objects/Object/assign +--- +<div>{{JSRef}}</div> + +<p><strong><code>Object.assign() </code></strong><code>metodu</code><strong><code> </code></strong><code>bir</code><strong><code> </code></strong><code>ya da daha fazla kaynaktaki sayılabilir özellikteki nesnelerin tüm değerlerini hedef kaynaktaki nesneye kopyalamak için kullanılır. Hedef nesnesini geri döndürür.</code></p> + +<h2 id="Yazım_Şekli">Yazım Şekli</h2> + +<pre class="syntaxbox">Object.assign(<var>hedef_nesne</var>, ...<em>kaynak_nesneler</em>)</pre> + +<h3 id="Değişkenler">Değişkenler</h3> + +<dl> + <dt><code>hedef_nesne</code></dt> + <dd>Kaydedilecek olan hedef nesne.</dd> + <dt><code>kaynak_nesneler</code></dt> + <dd>Kaynak nesne(ler).</dd> +</dl> + +<h3 id="Dönüş_Değeri">Dönüş Değeri</h3> + +<p>Hedef nesne.</p> + +<h2 id="Açıklama">Açıklama</h2> + +<p>Hedef nesnedeki değişkenlerin özellikleri kaynak nesnedeklerle aynı anahtar değerlerine sahipse üzerine yazılır. Daha sonra kaynaklardaki değerler benzer şekilde bir öncekiler gibi üzerine yazılır.</p> + +<p><code>Object.assign() metodu</code> bir kaynak nesnesinden bir hedef nesnesine <code>sadece</code><em> sayılabilir </em>ve sahip olduğu<em> özellikleri</em> kopyalar. Kaynak nesne için <code>[[Get]] ve hedef nesne için [[Set]]'i kullanır, böylelikle <em>getter</em> ve <em>setter</em></code> metodlarını çağırır. Bu nedenle yeni özellikleri sadece kopyalama ya da tanımlamaya karşı hedef nesneye atama yapar. Birleştirme kaynakları <em>getter</em> içeriyorsa, yeni özelliklerin bir prototip halinde birleştirilmesi uygun olmayabilir. Sayılabilir özellikler de dahil olmak üzere özellik tanımlamalarını kopyalamak için, prototiplerdeki {{jsxref("Object.getOwnPropertyDescriptor()")}} yerine {{jsxref("Object.defineProperty()")}} kullanılmalıdır.</p> + +<p>{{jsxref("String")}} ve {{jsxref("Symbol")}} özelliklerin her ikisi de kopyalanır.</p> + +<p>Hata durumunda,örneğin bir özelliklik yazılamaz durumda ise, bir {{jsxref("TypeError")}} durumu oluşacaktır ve hedef nesne değişmeden kalacaktır.</p> + +<p><code>Object.assign() metodu kaynak nesnelerdeki</code> {{jsxref("null")}} ya da {{jsxref("undefined")}} durumlarını fırlatmayacağını not ediniz.</p> + +<h2 id="Örnekler">Örnekler</h2> + +<h3 id="Nesne_klonlama">Nesne klonlama</h3> + +<pre class="brush: js">var obj = { a: 1 }; +var copy = Object.assign({}, obj); +console.log(copy); // { a: 1 } +</pre> + +<h3 id="Deep_Clone" name="Deep_Clone">Derin Klonlamada Bir Uyarı</h3> + +<p>Derin klonlama(kopyalama) için, diğer alternatiflere ihtiyacımız vardır. Çünkü <code>Object.assign() özellikleri kopyalar. Eğer kaynak değeri bir nesnenin referansı ise sadece referans değerini kopyalar.</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; + console.log(JSON.stringify(obj1)); // { a: 1, b: { c: 3}} + console.log(JSON.stringify(obj2)); // { a: 2, b: { c: 3}} + + // Deep Clone + 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="Nesneleri_Birleştirme">Nesneleri Birleştirme</h3> + +<pre class="brush: js">var o1 = { a: 1 }; +var o2 = { b: 2 }; +var o3 = { c: 3 }; + +var obj = Object.assign(o1, o2, o3); +console.log(obj); // { a: 1, b: 2, c: 3 } +console.log(o1); // { a: 1, b: 2, c: 3 } // hedef nesnenin kendisi değişti.</pre> + +<h3 id="Nesneleri_Aynı_Özelliklerde_Birleştirme">Nesneleri Aynı Özelliklerde Birleştirme</h3> + +<pre class="brush: js">var o1 = { a: 1, b: 1, c: 1 }; +var o2 = { b: 2, c: 2 }; +var o3 = { c: 3 }; + +var obj = Object.assign({}, o1, o2, o3); +console.log(obj); // { a: 1, b: 2, c: 3 } +</pre> + +<p>Özellikler diğer nesneler tarafından parametreler içindeki sonra gelen aynı özelliklerdeki nesnelerin özellikleri olarak üzerine yazıldı.</p> + +<h3 id="Sembol-Tipdeki_Özellikleri_Kopyalama">Sembol-Tipdeki Özellikleri Kopyalama </h3> + +<pre class="brush: js">var o1 = { a: 1 }; +var o2 = { [Symbol('foo')]: 2 }; + +var 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="Prototipteki_Zincirleme_Özellikler_ve_Sayılamayan_Özellikler_Kopyalanamaz">Prototipteki Zincirleme Özellikler ve Sayılamayan Özellikler Kopyalanamaz</h3> + +<pre class="brush: js">var obj = Object.create({ foo: 1 }, { // foo is on obj's prototype chain. + bar: { + value: 2 // bar sayılamayan özellik + }, + baz: { + value: 3, + enumerable: true // baz sayılabilen özellik + } +}); + +var copy = Object.assign({}, obj); +console.log(copy); // { baz: 3 } + +</pre> + +<h3 id="Değişken_Tipleri_Objelere_Sarmalanır">Değişken Tipleri Objelere Sarmalanır</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); +// Değişken tipleri sarmalanır, null ve undefined görmezden gelinir. +// Sadece string tipteki değişkenler sayılabilir özelliktedir. +console.log(obj); // { "0": "a", "1": "b", "2": "c" } + +</pre> + +<h3 id="Hatalar_Devam_Eden_Kopyalama_İşlemlerini_Kesintiye_Uğratır">Hatalar Devam Eden Kopyalama İşlemlerini Kesintiye Uğratır</h3> + +<pre class="brush: js">var target = Object.defineProperty({}, 'foo', { + value: 1, + writable: false +}); // target.foo sadece-okunabilir özellik + +Object.assign(target, { bar: 2 }, { foo2: 3, foo: 3, foo3: 3 }, { baz: 4 }); +// TypeError: "foo" sadece-okunabilir özellik +// foo hedefe aktarma sırasında hata fırlatır + +console.log(target.bar); // 2: ilk kaynak başarıyla kopyalandı. +console.log(target.foo2); // 3: ikinci kaynağın ilk özelliği başarıyla kopyalandı. +console.log(target.foo); // 1: burada hata oluşur. +console.log(target.foo3); // undefined: atama metodu bitti, foo3 kopyalanmayacak. +console.log(target.baz); // undefined: üçüncü kaynak da kopyalanmayacak. +</pre> + +<h3 id="Erişimcileri_Kopyalama">Erişimcileri Kopyalama</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 }, the value of copy.bar is obj.bar's getter's return value. + +// This is an assign function that copies full descriptors +function completeAssign(target, ...sources) { + sources.forEach(source => { + let descriptors = Object.keys(source).reduce((descriptors, key) => { + descriptors[key] = Object.getOwnPropertyDescriptor(source, key); + return descriptors; + }, {}); + // by default, Object.assign copies enumerable Symbols too + 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="Polyfill">Polyfill</h2> + +<p> ES5 sembol özelliğine sahip olmadığından {{Glossary("Polyfill","polyfill")}} sembol özelliği desteklenmez:</p> + +<pre class="brush: js">if (typeof Object.assign != 'function') { + Object.assign = function(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; + }; +} +</pre> + +<h2 id="Belirtimler">Belirtimler</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Belirtim</th> + <th scope="col">Durumlar</th> + <th scope="col">Açıklama</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-object.assign', 'Object.assign')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.assign', 'Object.assign')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Tarayıcı_Destekleme_Durumu">Tarayıcı Destekleme Durumu</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>Edge</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("45")}}</td> + <td>{{CompatGeckoDesktop("34")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatOpera("32")}}</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("45")}}</td> + <td>{{CompatGeckoMobile("34")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Daha_Fazlası_İçin">Daha Fazlası İçin</h2> + +<ul> + <li>{{jsxref("Object.defineProperties()")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties">Enumerability and ownership of properties</a></li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/object/defineproperty/index.html b/files/tr/web/javascript/reference/global_objects/object/defineproperty/index.html new file mode 100644 index 0000000000..ae72df74e5 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/object/defineproperty/index.html @@ -0,0 +1,391 @@ +--- +title: Object.defineProperty() +slug: Web/JavaScript/Reference/Global_Objects/Object/defineProperty +translation_of: Web/JavaScript/Reference/Global_Objects/Object/defineProperty +--- +<div>{{JSRef}}</div> + +<p>The <code><strong>Object.defineProperty()</strong></code> method defines a new property directly on an object, or modifies an existing property on an object, and returns the object.</p> + +<p id="Syntax">Syntax</p> + +<pre class="syntaxbox"><code>Object.defineProperty(<var>obj</var>, <var>prop</var>, <var>descriptor</var>)</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>The object on which to define the property.</dd> + <dt><code>prop</code></dt> + <dd>The name of the property to be defined or modified.</dd> + <dt><code>descriptor</code></dt> + <dd>The descriptor for the property being defined or modified.</dd> +</dl> + +<h2 id="Description">Description</h2> + +<p>This method allows precise addition to or modification of a property on an object. Normal property addition through assignment creates properties which show up during property enumeration ({{jsxref("Statements/for...in", "for...in")}} loop or {{jsxref("Object.keys")}} method), whose values may be changed, and which may be {{jsxref("Operators/delete", "deleted", "", 1)}}. This method allows these extra details to be changed from their defaults. By default, values added using <code>Object.defineProperty()</code> are immutable.</p> + +<p>Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A <em><dfn>data descriptor</dfn></em> is a property that has a value, which may or may not be writable. An <dfn>accessor descriptor</dfn> is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both.</p> + +<p>Both data and accessor descriptors are objects. They share the following required keys:</p> + +<dl> + <dt><code>configurable</code></dt> + <dd><code>true</code> if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.<br> + <strong>Defaults to <code>false</code>.</strong></dd> + <dt><code>enumerable</code></dt> + <dd><code>true</code> if and only if this property shows up during enumeration of the properties on the corresponding object.<br> + <strong>Defaults to <code>false</code>.</strong></dd> +</dl> + +<p>A data descriptor also has the following optional keys:</p> + +<dl> + <dt><code>value</code></dt> + <dd>The value associated with the property. Can be any valid JavaScript value (number, object, function, etc).<br> + <strong>Defaults to {{jsxref("undefined")}}.</strong></dd> + <dt><code>writable</code></dt> + <dd><code>true</code> if and only if the value associated with the property may be changed with an {{jsxref("Operators/Assignment_Operators", "assignment operator", "", 1)}}.<br> + <strong>Defaults to <code>false</code>.</strong></dd> +</dl> + +<p>An accessor descriptor also has the following optional keys:</p> + +<dl> + <dt><code>get</code></dt> + <dd>A function which serves as a getter for the property, or {{jsxref("undefined")}} if there is no getter. The function return will be used as the value of property.<br> + <strong>Defaults to {{jsxref("undefined")}}.</strong></dd> + <dt><code>set</code></dt> + <dd>A function which serves as a setter for the property, or {{jsxref("undefined")}} if there is no setter. The function will receive as only argument the new value being assigned to the property.<br> + <strong>Defaults to {{jsxref("undefined")}}.</strong></dd> +</dl> + +<p>Bear in mind that these options are not necessarily own properties so, if inherited, will be considered too. In order to ensure these defaults are preserved you might freeze the {{jsxref("Object.prototype")}} upfront, specify all options explicitly, or point to {{jsxref("null")}} as {{jsxref("Object.prototype.__proto__", "__proto__")}} property.</p> + +<pre class="brush: js">// using __proto__ +var obj = {}; +Object.defineProperty(obj, 'key', { + __proto__: null, // no inherited properties + value: 'static' // not enumerable + // not configurable + // not writable + // as defaults +}); + +// being explicit +Object.defineProperty(obj, 'key', { + enumerable: false, + configurable: false, + writable: false, + value: 'static' +}); + +// recycling same object +function withValue(value) { + var d = withValue.d || ( + withValue.d = { + enumerable: false, + writable: false, + configurable: false, + value: null + } + ); + d.value = value; + return d; +} +// ... and ... +Object.defineProperty(obj, 'key', withValue('static')); + +// if freeze is available, prevents adding or +// removing the object prototype properties +// (value, get, set, enumerable, writable, configurable) +(Object.freeze || Object)(Object.prototype); +</pre> + +<h2 id="Examples">Examples</h2> + +<p>If you want to see how to use the <code>Object.defineProperty</code> method with a <em>binary-flags-like</em> syntax, see <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty/Additional_examples">additional examples</a>.</p> + +<h3 id="Creating_a_property">Creating a property</h3> + +<p>When the property specified doesn't exist in the object, <code>Object.defineProperty()</code> creates a new property as described. Fields may be omitted from the descriptor, and default values for those fields are imputed. All of the Boolean-valued fields default to <code>false</code>. The <code>value</code>, <code>get</code>, and <code>set</code> fields default to {{jsxref("undefined")}}. A property which is defined without <code>get</code>/<code>set</code>/<code>value</code>/<code>writable</code> is called “generic” and is “typed” as a data descriptor.</p> + +<pre class="brush: js">var o = {}; // Creates a new object + +// Example of an object property added with defineProperty with a data property descriptor +Object.defineProperty(o, 'a', { + value: 37, + writable: true, + enumerable: true, + configurable: true +}); +// 'a' property exists in the o object and its value is 37 + +// Example of an object property added with defineProperty with an accessor property descriptor +var bValue = 38; +Object.defineProperty(o, 'b', { + get: function() { return bValue; }, + set: function(newValue) { bValue = newValue; }, + enumerable: true, + configurable: true +}); +o.b; // 38 +// 'b' property exists in the o object and its value is 38 +// The value of o.b is now always identical to bValue, unless o.b is redefined + +// You cannot try to mix both: +Object.defineProperty(o, 'conflict', { + value: 0x9f91102, + get: function() { return 0xdeadbeef; } +}); +// throws a TypeError: value appears only in data descriptors, get appears only in accessor descriptors +</pre> + +<h3 id="Modifying_a_property">Modifying a property</h3> + +<p>When the property already exists, <code>Object.defineProperty()</code> attempts to modify the property according to the values in the descriptor and the object's current configuration. If the old descriptor had its <code>configurable</code> attribute set to <code>false</code> (the property is said to be “non-configurable”), then no attribute besides <code>writable</code> can be changed. In that case, it is also not possible to switch back and forth between the data and accessor property types.</p> + +<p>If a property is non-configurable, its <code>writable</code> attribute can only be changed to <code>false</code>.</p> + +<p>A {{jsxref("TypeError")}} is thrown when attempts are made to change non-configurable property attributes (besides the <code>writable</code> attribute) unless the current and new values are the same.</p> + +<h4 id="Writable_attribute">Writable attribute</h4> + +<p>When the <code>writable</code> property attribute is set to <code>false</code>, the property is said to be “non-writable”. It cannot be reassigned.</p> + +<pre class="brush: js">var o = {}; // Creates a new object + +Object.defineProperty(o, 'a', { + value: 37, + writable: false +}); + +console.log(o.a); // logs 37 +o.a = 25; // No error thrown (it would throw in strict mode, even if the value had been the same) +console.log(o.a); // logs 37. The assignment didn't work. +</pre> + +<p>As seen in the example, trying to write into the non-writable property doesn't change it but doesn't throw an error either.</p> + +<h4 id="Enumerable_attribute">Enumerable attribute</h4> + +<p>The <code>enumerable</code> property attribute defines whether the property shows up in a {{jsxref("Statements/for...in", "for...in")}} loop and {{jsxref("Object.keys()")}} or not.</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 + +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 +</pre> + +<h4 id="Configurable_attribute">Configurable attribute</h4> + +<p>The <code>configurable</code> attribute controls at the same time whether the property can be deleted from the object and whether its attributes (other than <code>writable</code>) can be changed.</p> + +<pre class="brush: js">var o = {}; +Object.defineProperty(o, 'a', { + get: function() { 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: function() {} }); // throws a TypeError (set was undefined previously) +Object.defineProperty(o, 'a', { get: function() { 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>If the <code>configurable</code> attribute of <code>o.a</code> had been <code>true</code>, none of the errors would be thrown and the property would be deleted at the end.</p> + +<h3 id="Adding_properties_and_default_values">Adding properties and default values</h3> + +<p>It's important to consider the way default values of attributes are applied. There is often a difference between simply using dot notation to assign a value and using <code>Object.defineProperty()</code>, as shown in the example below.</p> + +<pre class="brush: js">var o = {}; + +o.a = 1; +// is equivalent to: +Object.defineProperty(o, 'a', { + value: 1, + writable: true, + configurable: true, + enumerable: true +}); + + +// On the other hand, +Object.defineProperty(o, 'a', { value: 1 }); +// is equivalent to: +Object.defineProperty(o, 'a', { + value: 1, + writable: false, + configurable: false, + enumerable: false +}); +</pre> + +<h3 id="Custom_Setters_and_Getters">Custom Setters and Getters</h3> + +<p>Example below shows how to implement a self-archiving object. When <code>temperature</code> property is set, the <code>archive</code> array gets a log entry.</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="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.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="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Firefox (Gecko)</th> + <th>Chrome</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatGeckoDesktop("2")}}</td> + <td>{{CompatChrome("5")}}</td> + <td>{{CompatIE("9")}} [1]</td> + <td>{{CompatOpera("11.60")}}</td> + <td>{{CompatSafari("5.1")}} [2]</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Firefox Mobile (Gecko)</th> + <th>Android</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatGeckoMobile("2")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatIE("9")}}</td> + <td>{{CompatOperaMobile("11.5")}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] In Internet Explorer 8 only on DOM objects and with some non-standard behaviors.</p> + +<p>[2] Also supported in Safari 5, but not on DOM objects.</p> + +<h2 id="Compatibility_notes">Compatibility notes</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("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="https://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="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/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="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty/Additional_examples">Additional <code>Object.defineProperty</code> examples</a></li> + <li>{{jsxref("Reflect.defineProperty()")}}</li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/object/entries/index.html b/files/tr/web/javascript/reference/global_objects/object/entries/index.html new file mode 100644 index 0000000000..456bfd6afa --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/object/entries/index.html @@ -0,0 +1,141 @@ +--- +title: Object.entries() +slug: Web/JavaScript/Reference/Global_Objects/Object/entries +tags: + - JavaScript + - Metot + - Referans + - nesne +translation_of: Web/JavaScript/Reference/Global_Objects/Object/entries +--- +<div>{{JSRef}}</div> + +<p>The <code><strong>Object.entries()</strong></code> metodu, verilen bir nesnenin sıralanabilir <code>[anahtar, değer]</code> çiftlerini {{jsxref("Statements/for...in", "for...in")}} döngüsünün sunacağı sırayla (for-in döngüsü, farklı olarak nesnenin prototip zincirindeki özelliklerini de sıralar) dizi olarak döner.</p> + +<div>{{EmbedInteractiveExample("pages/js/object-entries.html")}}</div> + + + +<h2 id="Sözdizimi">Sözdizimi</h2> + +<pre class="syntaxbox">Object.entries(<var>obj</var>)</pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>Sıralanabilir özellik çiftleri <code>[key, value]</code> dönülecek olan nesne.</dd> +</dl> + +<h3 id="Dönüş_değeri">Dönüş değeri</h3> + +<p>Verilen nesnenin sıralanabilir özellik çiftlerini <code>[key, value]</code> içeren dizi</p> + +<h2 id="Tanım">Tanım</h2> + +<p><code>Object.entries()</code> elemanları <code>object</code> nesnesinin sıralanabilir özellik çiftlerine <code>[key, value]</code> karşılık gelen diziler olan bir dizi döner. Özelliklerin sırası, özellikler üzerinde döngü ile dönülmesi durumunda oluşacak sırayla aynıdır.</p> + +<h2 id="Örnekler">Örnekler</h2> + +<pre class="brush: js">const obj = { foo: 'bar', baz: 42 }; +console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ] + +// dizi benzeri nesne +const obj = { 0: 'a', 1: 'b', 2: 'c' }; +console.log(Object.entries(obj)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ] + +// anahtarları rastgele sıralı olan dizi benzeri nesne +const anObj = { 100: 'a', 2: 'b', 7: 'c' }; +console.log(Object.entries(anObj)); // [ ['2', 'b'], ['7', 'c'], ['100', 'a'] ] + +// getFoo, sıralanabilir bir özellik değildir +const myObj = Object.create({}, { getFoo: { value() { return this.foo; } } }); +myObj.foo = 'bar'; +console.log(Object.entries(myObj)); // [ ['foo', 'bar'] ] + +// nesne olmayan parametre nesneye dönüştürülür +console.log(Object.entries('foo')); // [ ['0', 'f'], ['1', 'o'], ['2', 'o'] ] + +// ilkel tiplerin kendi özellikleri olmadığı için, boş dizi döner +console.log(Object.entries(100)); // [ ] + +// anahtar-değer çiftlerinin üzerinden for-of döngüsü ile geçelim +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" +} + +// Veya, Array ekstra metotlarını kullanarak geçelim +Object.entries(obj).forEach(([key, value]) => { +console.log(`${key} ${value}`); // "a 5", "b 7", "c 9" +}); +</pre> + +<h3 id="Bir_Object'in_bir_Map'e_dönüştürülmesi">Bir <code>Object</code>'in bir <code>Map</code>'e dönüştürülmesi</h3> + +<p>{{jsxref("Map", "new Map()")}} yapıcısı, <code>entries</code> üzerinde ilerlenebilir nesnesini ister. <code>Object.entries</code> ile, {{jsxref("Object")}}'ten {{jsxref("Map")}}'e kolayca dönüşüm yapabilirsiniz:</p> + +<pre class="brush: js">const obj = { foo: 'bar', baz: 42 }; +const map = new Map(Object.entries(obj)); +console.log(map); // Map { foo: "bar", baz: 42 } +</pre> + +<h3 id="Bir_Object'in_üzerinde_ilerlemek">Bir <code>Object</code>'in üzerinde ilerlemek</h3> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Array_destructuring">Array Destructuring</a> kullanarak, nesnelerin üzerinde kolayca ilerleyebilirsiniz.</p> + +<pre class="brush: js">const obj = { foo: 'bar', baz: 42 }; +Object.entries(obj).forEach(([key, value]) => console.log(`${key}: ${value}`)); // "foo: bar", "baz: 42" +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>Doğal olarak desteklemeyen eski ortamlara <code>Object.entries</code> desteği eklemek için, Object.entries'in gösterme amaçlı gerçeklemesini <a href="https://github.com/tc39/proposal-object-values-entries">tc39/proposal-object-values-entries</a>'de (IE desteğine ihtiyacınız yoksa), <a href="https://github.com/es-shims/Object.entries">es-shims/Object.entries</a> repertuarındaki polyfill ile, veya aşağıdaki gibi kullanıma hazır basit polyfill kullanabilirsiniz.</p> + +<p>if (!Object.entries) Object.entries = function( obj ){ var ownProps = Object.keys( obj ), i = ownProps.length, resArray = new Array(i); // diziyi önden ayıralım while (i--) resArray[i] = [ownProps[i], obj[ownProps[i]]]; return resArray; };</p> + +<p>Yukardaki polyfill kod parçası için IE < 9 desteğine ihtiyacınız varsa, aynı zamanda Object.keys polyfill desteğine de ihtiyaç duyacaksınız ({{jsxref("Object.keys")}} sayfasındaki gibi)</p> + +<h2 id="Şartnameler">Şartnameler</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.entries', 'Object.entries')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>İlk tanım.</td> + </tr> + <tr> + <td>{{SpecName('ES8', '#sec-object.entries', 'Object.entries')}}</td> + <td>{{Spec2('ES8')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Gezgin_uyumluluğu">Gezgin uyumluluğu</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Object.entries")}}</p> +</div> + +<h2 id="Ayrıca_bakınız">Ayrıca bakınız</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.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/tr/web/javascript/reference/global_objects/object/freeze/index.html b/files/tr/web/javascript/reference/global_objects/object/freeze/index.html new file mode 100644 index 0000000000..058f34011b --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/object/freeze/index.html @@ -0,0 +1,234 @@ +--- +title: Object.freeze() +slug: Web/JavaScript/Reference/Global_Objects/Object/freeze +translation_of: Web/JavaScript/Reference/Global_Objects/Object/freeze +--- +<div>{{JSRef}}</div> + +<p><code><strong>Object.freeze()</strong></code> metodu bir objeyi <strong>dondurmak</strong> amaçlı kullanılır. Bir obje dondurulduktan sonra artık değiştirilemez, yeni bir property eklenemez, çıkarılamaz veya değiştirilemez. Objenin propertyleri üzerinde herhangi bir düzenleme veya konfigurasyon yapılamaz. Bir obje dondurulduktan sonra sadece property'lerini değil bu objeye bağlı olan prototype da değiştir. <code>freeze()</code> metodu kendisine verilen objeyi dondurulmuş olarak geri döndürür ancak gelen değişkenin yeniden atanması zorunlu değildir. <code>freeze()</code> metoduna gönderdiğiniz obje referans yoluyla geçeceği için tekrardan bir atama işlemi yapmak zorunda değilsiniz. Redux dahil bir çok state yönetim sistemleri bu metodu kullanarak state objesini immutable - değiştirilemez - yapmakta ve bu işleme bağlı olarak store üzerinden gerçekleştirilen işlemleri yenilemektedir. </p> + +<div>{{EmbedInteractiveExample("pages/js/object-freeze.html")}}</div> + + + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox notranslate"><code>Object.freeze(<var>obje</var>)</code></pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt><code>obje</code></dt> + <dd>Dondurmak istediğiniz obje.</dd> +</dl> + +<h3 id="Dönüt">Dönüt</h3> + +<p>Metoda gönderilen obje dondurularak geri döndürülür</p> + +<h2 id="Description">Description</h2> + +<p>Dondurulmuş obje üzerinde hiç bir düzenleme, ekleme ve çıkarma işlemi yapılamaz. Bu amaçla yapılan herhangi bir değişim {{jsxref("TypeError")}} hatası verir (Farklı çevrelerde daha alt seviye hatalar vermesine karşın, {{jsxref("Strict_mode", "strict mode", "", 1)}} etkinleştirildiği durumlarda {{jsxref("TypeError")}} hatası kesin olarak alınır).</p> + +<p>Dondurulmuş bir objeye ait değer değiştirilemez, <code>writeable</code> ve <code>configurable</code> özellikleri <code>false</code> olarka atanır. Accessor properties (getter and setter) work the same (and still give the illusion that you are changing the value). Note that values that are objects can still be modified, unless they are also frozen. As an object, an array can be frozen; after doing so, its elements cannot be altered and no elements can be added to or removed from the array.</p> + +<p><code>freeze()</code> returns the same object that was passed into the function. It <em>does not</em> create a frozen copy.</p> + +<p>In ES5, if the argument to this method is not an object (a primitive), then it will cause a {{jsxref("TypeError")}}. In ES2015, a non-object argument will be treated as if it were a frozen ordinary object, and be simply returned.</p> + +<pre class="brush: js notranslate">> Object.freeze(1) +TypeError: 1 is not an object // ES5 code + +> Object.freeze(1) +1 // ES2015 code +</pre> + +<p>An <a href="/en-US/docs/Web/API/ArrayBufferView" title="ArrayBufferView is a helper type representing any of the following JavaScript TypedArray types:"><code>ArrayBufferView</code></a> with elements will cause a {{jsxref("TypeError")}}, as they are views over memory and will definitely cause other possible issues:</p> + +<pre class="brush: js notranslate">> Object.freeze(new Uint8Array(0)) // No elements +Uint8Array [] + +> Object.freeze(new Uint8Array(1)) // Has elements +TypeError: Cannot freeze array buffer views with elements + +> Object.freeze(new DataView(new ArrayBuffer(32))) // No elements +DataView {} + +> Object.freeze(new Float64Array(new ArrayBuffer(64), 63, 0)) // No elements +Float64Array [] + +> Object.freeze(new Float64Array(new ArrayBuffer(64), 32, 2)) // Has elements +TypeError: Cannot freeze array buffer views with elements +</pre> + +<p>Note that; as the standard three properties (<code>buf.byteLength</code>, <code>buf.byteOffset</code> and <code>buf.buffer</code>) are read-only (as are those of an {{jsxref("ArrayBuffer")}} or {{jsxref("SharedArrayBuffer")}}), there is no reason for attempting to freeze these properties.</p> + +<h3 id="Comparison_to_Object.seal">Comparison to <code>Object.seal()</code></h3> + +<p>Objects sealed with {{jsxref("Object.seal()")}} can have their existing properties changed. Existing properties in objects frozen with <code>Object.freeze()</code> are made immutable.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Freezing_objects">Freezing objects</h3> + +<pre class="brush: js notranslate">var obj = { + prop: function() {}, + foo: 'bar' +}; + +// Before freezing: new properties may be added, +// and existing properties may be changed or removed +obj.foo = 'baz'; +obj.lumpy = 'woof'; +delete obj.prop; + +// Freeze. +var o = Object.freeze(obj); + +// The return value is just the same object we passed in. +o === obj; // true + +// The object has become frozen. +Object.isFrozen(obj); // === true + +// Now any changes will fail +obj.foo = 'quux'; // silently does nothing +// silently doesn't add the property +obj.quaxxor = 'the friendly duck'; + +// In strict mode such attempts will throw TypeErrors +function fail(){ + 'use strict'; + obj.foo = 'sparky'; // throws a TypeError + delete obj.foo; // throws a TypeError + delete obj.quaxxor; // returns true since attribute 'quaxxor' was never added + obj.sparky = 'arf'; // throws a TypeError +} + +fail(); + +// Attempted changes through Object.defineProperty; +// both statements below throw a TypeError. +Object.defineProperty(obj, 'ohai', { value: 17 }); +Object.defineProperty(obj, 'foo', { value: 'eit' }); + +// It's also impossible to change the prototype +// both statements below will throw a TypeError. +Object.setPrototypeOf(obj, { x: 20 }) +obj.__proto__ = { x: 20 } +</pre> + +<h3 id="Freezing_arrays">Freezing arrays</h3> + +<pre class="brush: js notranslate">let a = [0]; +Object.freeze(a); // The array cannot be modified now. + +a[0] = 1; // fails silently + +// In strict mode such attempt will throw a TypeError +function fail() { + "use strict" + a[0] = 1; +} + +fail(); + +// Attempted to push +a.push(2); // throws a TypeError</pre> + +<p>The object being frozen is <em>immutable</em>. However, it is not necessarily <em>constant</em>. The following example shows that a frozen object is not constant (freeze is shallow).</p> + +<pre class="brush: js notranslate">obj1 = { + internal: {} +}; + +Object.freeze(obj1); +obj1.internal.a = 'aValue'; + +obj1.internal.a // 'aValue'</pre> + +<p>To be a constant object, the entire reference graph (direct and indirect references to other objects) must reference only immutable frozen objects. The object being frozen is said to be immutable because the entire object <em>state</em> (values and references to other objects) within the whole object is fixed. Note that strings, numbers, and booleans are always immutable and that Functions and Arrays are objects.</p> + +<h4 id="What_is_shallow_freeze">What is "shallow freeze"?</h4> + +<p>The result of calling <code>Object.freeze(<var>object</var>)</code> only applies to the immediate properties of <code>object</code> itself and will prevent future property addition, removal or value re-assignment operations <em>only</em> on <code>object</code>. If the value of those properties are objects themselves, those objects are not frozen and may be the target of property addition, removal or value re-assignment operations.</p> + +<pre class="brush: js notranslate">var employee = { + name: "Mayank", + designation: "Developer", + address: { + street: "Rohini", + city: "Delhi" + } +}; + +Object.freeze(employee); + +employee.name = "Dummy"; // fails silently in non-strict mode +employee.address.city = "Noida"; // attributes of child object can be modified + +console.log(employee.address.city) // Output: "Noida" +</pre> + +<p>To make an object immutable, recursively freeze each property which is of type object (deep freeze). Use the pattern on a case-by-case basis based on your design when you know the object contains no <a href="https://en.wikipedia.org/wiki/Cycle_(graph_theory)" title="cycles">cycles</a> in the reference graph, otherwise an endless loop will be triggered. An enhancement to <code>deepFreeze()</code> would be to have an internal function that receives a path (e.g. an Array) argument so you can suppress calling <code>deepFreeze()</code> recursively when an object is in the process of being made immutable. You still run a risk of freezing an object that shouldn't be frozen, such as [window].</p> + +<pre class="brush: js notranslate">function deepFreeze(object) { + + // Retrieve the property names defined on object + var propNames = Object.getOwnPropertyNames(object); + + // Freeze properties before freezing self + + for (let name of propNames) { + let value = object[name]; + + if(value && typeof value === "object") { + deepFreeze(value); + } + } + + return Object.freeze(object); +} + +var obj2 = { + internal: { + a: null + } +}; + +deepFreeze(obj2); + +obj2.internal.a = 'anotherValue'; // fails silently in non-strict mode +obj2.internal.a; // null +</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-object.freeze', 'Object.freeze')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.builtins.Object.freeze")}}</p> + +<h2 id="See_also">See also</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/tr/web/javascript/reference/global_objects/object/getprototypeof/index.html b/files/tr/web/javascript/reference/global_objects/object/getprototypeof/index.html new file mode 100644 index 0000000000..c6bf7acbbf --- /dev/null +++ b/files/tr/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 + - nesne + - prototip +translation_of: Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf +--- +<div>{{JSRef}}</div> + +<p><code><strong>Object.getPrototypeOf()</strong></code> metodu, belirtilen nesnenin prototipini döndürür.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code>Object.getPrototypeOf(<em>nesne</em>)</code></pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt><font face="Consolas, Liberation Mono, Courier, monospace">nesne</font></dt> + <dd>Prototipi döndürülecek olan nesne.</dd> +</dl> + +<h2 id="Örnekler">Örnekler</h2> + +<pre class="brush: js">var proto = {}; +var nesne = Object.create(proto); +Object.getPrototypeOf(nesne) === proto; // true +</pre> + +<h2 id="Notlar">Notlar</h2> + +<p>ES5'te, <code>nesne</code> parametresi bir nesne değilse sistem bir {{jsxref("TypeError")}} fırlatır. ES6'da ise, parametre bir nesne olmaya zorlanır.</p> + +<pre class="brush: js">Object.getPrototypeOf("foo"); +// TypeError: "foo" bir nesne değil (ES5 kodu) +Object.getPrototypeOf("foo"); +// String.prototype (ES6 kodu) +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Durum</th> + <th scope="col">Yorum</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.2', 'Object.getPrototypeOf')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>İlk tanımlama.</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="Tarayıcı_Uyumluluğu">Tarayıcı Uyumluluğu</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Özellik</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Temel destek</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>Özellik</th> + <th>Android</th> + <th>Android için Chrome</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Temel destek</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'ya_özel_notlar">Opera'ya özel notlar</h2> + +<p>Eski Opera versiyonları <code>Object.getPrototypeOf()</code> fonksiyonunu desteklemiyor olsa da, Opera, 10.50 sürümünden beri standartlarda yer almayan {{jsxref("Object.proto", "__proto__")}} özelliğini desteklemektedir.</p> + +<h2 id="Bunlara_da_göz_atın">Bunlara da göz atın</h2> + +<ul> + <li>{{jsxref("Object.prototype.isPrototypeOf()")}}</li> + <li>{{jsxref("Object.setPrototypeOf()")}}</li> + <li>{{jsxref("Object.prototype.__proto__")}}</li> + <li>John Resig'in <a class="external" href="http://ejohn.org/blog/objectgetprototypeof/">getPrototypeOf</a> üzerine olan blog yazısı</li> + <li>{{jsxref("Reflect.getPrototypeOf()")}}</li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/object/index.html b/files/tr/web/javascript/reference/global_objects/object/index.html new file mode 100644 index 0000000000..7e5dfd4c7b --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/object/index.html @@ -0,0 +1,213 @@ +--- +title: Object +slug: Web/JavaScript/Reference/Global_Objects/Object +tags: + - Constructor + - JavaScript + - NeedsTranslation + - Object + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Object +--- +<div>{{JSRef}}</div> + +<p>The <code><strong>Object</strong></code> constructor creates an object wrapper.</p> + +<h2 id="Syntax" name="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code>// Object initialiser or literal +{ [ <var>nameValuePair1</var>[, <var>nameValuePair2</var>[, ...<var>nameValuePairN</var>] ] ] } + +// Called as a constructor +new Object([<var>value</var>])</code></pre> + +<h3 id="Parameters" name="Parameters">Parameters</h3> + +<dl> + <dt><code>nameValuePair1, nameValuePair2, ... nameValuePair<em>N</em></code></dt> + <dd>Pairs of names (strings) and values (any value) where the name is separated from the value by a colon.</dd> + <dt><code>value</code></dt> + <dd>Any value.</dd> +</dl> + +<h2 id="Description" name="Description">Description</h2> + +<p>The <code>Object</code> constructor creates an object wrapper for the given value. If the value is {{jsxref("Global_Objects/null", "null")}} or {{jsxref("Global_Objects/undefined", "undefined")}}, it will create and return an empty object, otherwise, it will return an object of a Type that corresponds to the given value. If the value is an object already, it will return the value.</p> + +<p>When called in a non-constructor context, <code>Object</code> behaves identically to <code>new Object()</code>.</p> + +<p>See also the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer">object initializer / literal syntax</a>.</p> + +<h2 id="Properties" name="Properties">Properties of the <code>Object</code> constructor</h2> + +<dl> + <dt><code>Object.length</code></dt> + <dd>Has a value of 1.</dd> + <dt>{{jsxref("Object.prototype")}}</dt> + <dd>Allows the addition of properties to all objects of type Object.</dd> +</dl> + +<h2 id="Methods" name="Methods">Methods of the <code>Object</code> constructor</h2> + +<dl> + <dt>{{jsxref("Object.assign()")}} {{experimental_inline}}</dt> + <dd>Creates a new object by copying the values of all enumerable own properties from one or more source objects to a target object.</dd> + <dt>{{jsxref("Object.create()")}}</dt> + <dd>Creates a new object with the specified prototype object and properties.</dd> + <dt>{{jsxref("Object.defineProperty()")}}</dt> + <dd>Adds the named property described by a given descriptor to an object.</dd> + <dt>{{jsxref("Object.defineProperties()")}}</dt> + <dd>Adds the named properties described by the given descriptors to an object.</dd> + <dt>{{jsxref("Object.freeze()")}}</dt> + <dd>Freezes an object: other code can't delete or change any properties.</dd> + <dt>{{jsxref("Object.getOwnPropertyDescriptor()")}}</dt> + <dd>Returns a property descriptor for a named property on an object.</dd> + <dt>{{jsxref("Object.getOwnPropertyNames()")}}</dt> + <dd>Returns an array containing the names of all of the given object's <strong>own</strong> enumerable and non-enumerable properties.</dd> + <dt>{{jsxref("Object.getOwnPropertySymbols()")}} {{ experimental_inline() }}</dt> + <dd>Returns an array of all symbol properties found directly upon a given object.</dd> + <dt>{{jsxref("Object.getPrototypeOf()")}}</dt> + <dd>Returns the prototype of the specified object.</dd> + <dt>{{jsxref("Object.is()")}} {{ experimental_inline() }}</dt> + <dd>Compares if two values are distinguishable (ie. the same)</dd> + <dt>{{jsxref("Object.isExtensible()")}}</dt> + <dd>Determines if extending of an object is allowed.</dd> + <dt>{{jsxref("Object.isFrozen()")}}</dt> + <dd>Determines if an object was frozen.</dd> + <dt>{{jsxref("Object.isSealed()")}}</dt> + <dd>Determines if an object is sealed.</dd> + <dt>{{jsxref("Object.keys()")}}</dt> + <dd>Returns an array containing the names of all of the given object's <strong>own</strong> enumerable properties.</dd> + <dt>{{jsxref("Object.observe()")}} {{experimental_inline}}</dt> + <dd>Asynchronously observes changes to an object.</dd> + <dt>{{jsxref("Object.preventExtensions()")}}</dt> + <dd>Prevents any extensions of an object.</dd> + <dt>{{jsxref("Object.seal()")}}</dt> + <dd>Prevents other code from deleting properties of an object.</dd> + <dt>{{jsxref("Object.setPrototypeOf()")}} {{experimental_inline}}</dt> + <dd>Sets the prototype (i.e., the internal <code>[[Prototype]]</code> property)</dd> +</dl> + +<h2 id="Object_instances" name="Object_instances"><code>Object</code> instances and <code>Object</code> prototype object</h2> + +<p>All objects in JavaScript are descended from <code>Object</code>; all objects inherit methods and properties from {{jsxref("Object.prototype")}}, although they may be overridden. For example, other constructors' prototypes override the <code>constructor</code> property and provide their own <code>toString()</code> methods. Changes to the <code>Object</code> prototype object are propagated to all objects unless the properties and methods subject to those changes are overridden further along the prototype chain.</p> + +<h3 id="Properties_of_Object_instances" name="Properties_of_Object_instances">Properties</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Properties') }}</div> + +<h3 id="Methods_of_Object_instances" name="Methods_of_Object_instances">Methods</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Methods') }}</div> + +<h2 id="Examples" name="Examples">Examples</h2> + +<h3 id="Example.3A_Using_Object_given_undefined_and_null_types" name="Example.3A_Using_Object_given_undefined_and_null_types">Example: Using <code>Object</code> given <code>undefined</code> and <code>null</code> types</h3> + +<p>The following examples store an empty <code>Object</code> object in <code>o</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="Example_Using_Object_to_create_Boolean_objects">Example: Using <code>Object</code> to create <code>Boolean</code> objects</h3> + +<p>The following examples store {{jsxref("Global_Objects/Boolean", "Boolean")}} objects in <code>o</code>:</p> + +<pre class="brush: js">// equivalent to o = new Boolean(true); +var o = new Object(true); +</pre> + +<pre class="brush: js">// equivalent to o = new Boolean(false); +var o = new Object(Boolean()); +</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>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> </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><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer">Object initializer</a></li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/object/observe/index.html b/files/tr/web/javascript/reference/global_objects/object/observe/index.html new file mode 100644 index 0000000000..bf46ed0504 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/object/observe/index.html @@ -0,0 +1,194 @@ +--- +title: Object.observe() +slug: Web/JavaScript/Reference/Global_Objects/Object/observe +tags: + - Değişim İzle + - Obje + - Obje Gözlem + - Obje İzle +translation_of: Archive/Web/JavaScript/Object.observe +--- +<div>{{JSRef("Global_Objects", "Object")}}</div> + +<h2 id="Özet">Özet</h2> + +<p><strong><code>Object.observe()</code></strong> methodu bir objedeki değişimleri izlemenizi sağlar. Geri dönüş için belirlediğiniz fonksiyona, obje üzerinde gerçeklenen değişikleri, oluşma sırasına göre gönderir.</p> + +<h2 id="Söz_Dizimi">Söz Dizimi</h2> + +<pre><code>Object.observe(<var>obj</var>, <var>callback</var>[, <var>acceptList</var>])</code></pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt><code>obj</code></dt> + <dd>İzlenecek Obje.</dd> + <dt>callback</dt> + <dd>Değişiklikler her gerçekleştiğinde çağırılacak fonksiyon. Aşağıdaki argümanlar ile çağırılır, + <dl> + <dt><code>changes</code></dt> + <dd>Her bir değişikliği temsilen bir objenin bulunduğu bir dizi döner. Objenin elemanları; + <ul> + <li><strong><code>name</code></strong>: Değişen elemanın adı.</li> + <li><strong><code>object</code></strong>: Objenin yeni hali.</li> + <li><strong><code>type</code></strong>: Metin türünde değişim. Bu metin <code>"add"</code>, <code>"update"</code>, ve <code>"delete" </code>olabilir<code>.</code></li> + <li><strong><code>oldValue</code></strong>: Eğer değiştirme ve ya silme işlemi gerçekleşti ise değişimden önceki değeri içerir.</li> + </ul> + </dd> + </dl> + </dd> + <dt><code>acceptList</code></dt> + <dd>The list of types of changes to be observed on the given object for the given callback. If omitted, the array <code>["add", "update", "delete", "reconfigure", "setPrototype", "preventExtensions"]</code> will be used.</dd> +</dl> + +<h2 id="Açıklama">Açıklama</h2> + +<p><code>callback</code> fonksiyonu objede gerçekleşen her değişimde çağırılır. Bir dizi içerisinde değişiklikleri içeren objeler bulunur.</p> + +<h2 id="Örnekler">Örnekler</h2> + +<h3 id="Örnelk_6_farklı_tipi_kayıt_altına_alma">Örnelk: 6 farklı tipi kayıt altına alma</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="Örnek_Veri_bağlama">Örnek: Veri bağlama</h3> + +<pre class="brush: js">// bir kullanıcı sınıfı +var user = { + id: 0, + name: 'Brendan Eich', + title: 'Mr.' +}; + +// Kullanıcı için bir selemlama oluştur. +function updateGreeting() { + user.greeting = 'Merhaba, ' + user.title + ' ' + user.name + '!'; +} +updateGreeting(); + +Object.observe(user, function(changes) { + changes.forEach(function(change) { + // isim yada soyisim her değiştiğinde oluşturulan selamlayı düzenle. + if (change.name === 'name' || change.name === 'title') { + updateGreeting(); + } + }); +}); +</pre> + +<h3 id="Örnek_Özel_değişim_türü">Örnek: Özel değişim türü</h3> + +<pre class="brush: js">// 2 boyutlu düzlemde bir nokta +var point = {x: 0, y: 0, distance: 0}; + +function setPosition(pt, x, y) { + // özel bir değişim gerçekleştir. + 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); +// Mesafe değişimi: 5 +</pre> + +<h2 id="Specifications" name="Specifications">Özellikler</h2> + +<p><a href="https://github.com/arv/ecmascript-object-observe">Strawman proposal for ECMAScript 7</a>.</p> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Tarayıcılar Arası Uyumluluk</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Özellik</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Temel Destek</td> + <td>{{CompatChrome("36")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatOpera("23")}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Özellik</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>Temel Destek</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome("36")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatOpera("23")}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also" name="See_also">Ayrıca bakınız</h2> + +<ul> + <li>{{jsxref("Object.unobserve()")}} {{experimental_inline}}</li> + <li>{{jsxref("Array.observe()")}} {{experimental_inline}}</li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/object/tostring/index.html b/files/tr/web/javascript/reference/global_objects/object/tostring/index.html new file mode 100644 index 0000000000..23593555e1 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/object/tostring/index.html @@ -0,0 +1,161 @@ +--- +title: Object.prototype.toString() +slug: Web/JavaScript/Reference/Global_Objects/Object/toString +translation_of: Web/JavaScript/Reference/Global_Objects/Object/toString +--- +<div>{{JSRef}}</div> + +<p><code><strong>toString() </strong>methodu verilen nesneyi String'e dönüştürür.</code></p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>obj</var>.toString()</code></pre> + +<h2 id="Açıklama">Açıklama</h2> + +<p>Every object has a <code>toString()</code> method that is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected. By default, the <code>toString()</code> method is inherited by every object descended from <code>Object</code>. If this method is not overridden in a custom object, <code>toString()</code> returns "[object <em>type</em>]", where <code><em>type</em></code> is the object type. The following code illustrates this:</p> + +<pre class="brush: js">var o = new Object(); +o.toString(); // returns [object Object] +</pre> + +<div class="note"> +<p><strong>Note:</strong> Starting in JavaScript 1.8.5 <code>toString()</code> called on {{jsxref("null")}} returns <code>[object <em>Null</em>]</code>, and {{jsxref("undefined")}} returns <code>[object <em>Undefined</em>]</code>, as defined in the 5th Edition of ECMAScript and a subsequent Errata. See {{anch("Using_toString_to_detect_object_type", "Using toString to detect object type")}}.</p> +</div> + +<h2 id="Examples">Examples</h2> + +<h3 id="Overriding_the_default_toString_method">Overriding the default <code>toString</code> method</h3> + +<p>You can create a function to be called in place of the default <code>toString()</code> method. The <code>toString()</code> method takes no arguments and should return a string. The <code>toString()</code> method you create can be any value you want, but it will be most useful if it carries information about the object.</p> + +<p>The following code defines the <code>Dog</code> object type and creates <code>theDog</code>, an object of type <code>Dog</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>If you call the <code>toString()</code> method on this custom object, it returns the default value inherited from {{jsxref("Object")}}:</p> + +<pre class="brush: js">theDog.toString(); // returns [object Object] +</pre> + +<p>The following code creates and assigns <code>dogToString()</code> to override the default <code>toString()</code> method. This function generates a string containing the name, breed, color, and sex of the object, in the form "<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>With the preceding code in place, any time <code>theDog</code> is used in a string context, JavaScript automatically calls the <code>dogToString()</code> function, which returns the following string:</p> + +<pre class="brush: js">"Dog Gabby is a female chocolate Lab" +</pre> + +<h3 id="Using_toString()_to_detect_object_class">Using <code>toString()</code> to detect object class</h3> + +<p><code>toString()</code> can be used with every object and allows you to get its class. To use the <code>Object.prototype.toString()</code> with every object, you need to call {{jsxref("Function.prototype.call()")}} or {{jsxref("Function.prototype.apply()")}} on it, passing the object you want to inspect as the first parameter called <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("Global_Objects/null", "null")}} returns <code>[object <em>Null</em>]</code>, and {{jsxref("Global_Objects/undefined", "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> + </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("Object.prototype.toSource()")}}</li> + <li>{{jsxref("Object.prototype.valueOf()")}}</li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/object/values/index.html b/files/tr/web/javascript/reference/global_objects/object/values/index.html new file mode 100644 index 0000000000..82ee284be2 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/object/values/index.html @@ -0,0 +1,96 @@ +--- +title: Object.values() +slug: Web/JavaScript/Reference/Global_Objects/Object/values +tags: + - Javascripts Metot Nesneler +translation_of: Web/JavaScript/Reference/Global_Objects/Object/values +--- +<div>{{JSRef}}</div> + +<p><code><strong>Object.values()</strong></code> yöntemi belirli bir nesnenin kendi numaralandırılabilir özellik değerlerinin {{jsxref("Statements/for...in", "for...in")}} döngüsü tarafından sağlanan sırayla dizileri döndürür (fark şu ki; bir for-in döngüsü prototip zincirindeki özelliklerle numaralandırılır).</p> + +<h2 id="Sözdizimi">Sözdizimi</h2> + +<pre class="syntaxbox">Object.values(<var>obj</var>)</pre> + +<h3 id="Parametre">Parametre</h3> + +<dl> + <dd>Nesne, sayısız numaralandırılabilir kendi özellikleri döndürülendir.</dd> +</dl> + +<h3 id="Return_değeri">Return değeri</h3> + +<p>Diziler verilen nesnenin kendi numaralandırılabilir özellik değerlerini içerir.</p> + +<h2 id="Tanım">Tanım</h2> + +<p><code>Object.values()</code> Nesne, nesne üzerinde bulunan özellik değerleri numaralandırılabilir elemanları olan dizileri döndürür. Özelliklerin sıralaması nesnenin özellik değerleri üzerinde manul olarak döndürülenle aynıdır.</p> + +<p>Örnekler</p> + +<pre class="brush: js">var obj = { foo: 'bar', baz: 42 }; +console.log(Object.values(obj)); // ['bar', 42] + +// nesne gibi olan diziler +var obj = { 0: 'a', 1: 'b', 2: 'c' }; +console.log(Object.values(obj)); // ['a', 'b', 'c'] + +// nesneler gibi rast gele anahtar sıralamalı diziler +// numerik anahtarları kullandığımızda değerler, anahtarlara göre numerik sırayla döndürülür. +var an_obj = { 100: 'a', 2: 'b', 7: 'c' }; +console.log(Object.values(an_obj)); // ['b', 'c', 'a'] + +// getFoo bir sayılamayan özelliktir. +var my_obj = Object.create({}, { getFoo: { value: function() { return this.foo; } } }); +my_obj.foo = 'bar'; +console.log(Object.values(my_obj)); // ['bar'] + +// nesne olmayan değişken nesne olmaya zorlanır. +console.log(Object.values('foo')); // ['f', 'o', 'o'] +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>Uyumlu <code>Object.values</code> eklemek için doğal olarak desteklenmeyen daha eski ortamları destekler. Siz şu adreste " <a href="https://github.com/tc39/proposal-object-values-entries">tc39/proposal-object-values-entries</a> " veya "<a href="https://github.com/es-shims/Object.values">es-shims/Object.values</a> "repositorilerde bir polyfill bulabilirsiniz.</p> + +<h2 id="Specificatsupport_in_older_environments_that_do_not_natively_support_it_you_can_find_a_Polyfill_in_the_ions">Specificatsupport in older environments that do not natively support it, you can find a Polyfill in the ions</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Tanım</th> + <th scope="col">Konum</th> + <th scope="col">Yorum</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.values', 'Object.values')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Ilk tanım.</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/tr/web/javascript/reference/global_objects/promise/all/index.html b/files/tr/web/javascript/reference/global_objects/promise/all/index.html new file mode 100644 index 0000000000..cc57749d77 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/promise/all/index.html @@ -0,0 +1,234 @@ +--- +title: Promise.all() +slug: Web/JavaScript/Reference/Global_Objects/Promise/all +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/all +--- +<div>{{JSRef}}</div> + +<p>The <strong><code>Promise.all()</code></strong> method returns a single {{jsxref("Promise")}} that resolves when all of the promises passed as an iterable have resolved or when the iterable contains no promises. It rejects with the reason of the first promise that rejects.</p> + +<div>{{EmbedInteractiveExample("pages/js/promise-all.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="Söz_dizimi">Söz dizimi</h2> + +<pre class="syntaxbox">Promise.all(<var>iterable</var>);</pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt><code>iterable</code></dt> + <dd>{{jsxref("Array")}} yada {{jsxref("String")}} gibi <a href="/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol">iterable</a> nesnesi.</dd> +</dl> + +<h3 id="Dönen_değer">Dönen değer</h3> + +<ul> + <li>An <strong>already resolved</strong> {{jsxref("Promise")}} if the <var>iterable</var> passed is empty.</li> + <li>An <strong>asynchronously resolved</strong> {{jsxref("Promise")}} if the <var>iterable</var> passed contains no promises. Note, Google Chrome 58 returns an <strong>already resolved</strong> promise in this case.</li> + <li>A <strong>pending</strong> {{jsxref("Promise")}} in all other cases. This returned promise is then resolved/rejected <strong>asynchronously</strong> (as soon as the stack is empty) when all the promises in the given <var>iterable</var> have resolved, or if any of the promises reject. See the example about "Asynchronicity or synchronicity of Promise.all" below. Returned values will be in order of the Promises passed, regardless of completion order.</li> +</ul> + +<h2 id="Açıklama">Açıklama</h2> + +<p>This method can be useful for aggregating the results of multiple promises.</p> + +<h3 id="Fulfillment">Fulfillment</h3> + +<p>The returned promise is fulfilled with an array containing <strong>all </strong>the values of the <var>iterable</var> passed as argument (also non-promise values).</p> + +<ul> + <li>If an empty <var>iterable</var> is passed, then this method returns (synchronously) an already resolved promise.</li> + <li>If all of the passed-in promises fulfill, or are not promises, the promise returned by <code>Promise.all</code> is fulfilled asynchronously.</li> +</ul> + +<h3 id="Rejection">Rejection</h3> + +<p>If any of the passed-in promises reject, <code>Promise.all</code> asynchronously rejects with the value of the promise that rejected, whether or not the other promises have resolved.</p> + +<h2 id="Örnekler">Örnekler</h2> + +<h3 id="Promise.all_Kullanımı"><code>Promise.all</code> Kullanımı</h3> + +<p><code>Promise.all</code> tüm işlemler yerine getirilene kadar bekler (yada ilk reddedilmeye kadar).</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>If the <var>iterable</var> contains non-promise values, they will be ignored, but still counted in the returned promise array value (if the promise is fulfilled):</p> + +<pre class="brush: js">// this will be counted as if the iterable passed is empty, so it gets fulfilled +var p = Promise.all([1,2,3]); +// this will be counted as if the iterable passed contains only the resolved promise with value "444", so it gets fulfilled +var p2 = Promise.all([1,2,3, Promise.resolve(444)]); +// this will be counted as if the iterable passed contains only the rejected promise with value "555", so it gets rejected +var p3 = Promise.all([1,2,3, Promise.reject(555)]); + +// using setTimeout we can execute code after the stack is empty +setTimeout(function() { + console.log(p); + console.log(p2); + console.log(p3); +}); + +// logs +// Promise { <state>: "fulfilled", <value>: Array[3] } +// Promise { <state>: "fulfilled", <value>: Array[4] } +// Promise { <state>: "rejected", <reason>: 555 }</pre> + +<h3 id="Asynchronicity_or_synchronicity_of_Promise.all">Asynchronicity or synchronicity of <code>Promise.all</code></h3> + +<p>This following example demonstrates the asynchronicity (or synchronicity, if the <var>iterable</var> passed is empty) of <code>Promise.all</code>:</p> + +<pre class="brush: js">// we are passing as argument an array of promises that are already resolved, +// to trigger Promise.all as soon as possible +var resolvedPromisesArray = [Promise.resolve(33), Promise.resolve(44)]; + +var p = Promise.all(resolvedPromisesArray); +// immediately logging the value of p +console.log(p); + +// using setTimeout we can execute code after the stack is empty +setTimeout(function() { + console.log('the stack is now empty'); + console.log(p); +}); + +// logs, in order: +// Promise { <state>: "pending" } +// the stack is now empty +// Promise { <state>: "fulfilled", <value>: Array[2] } +</pre> + +<p>The same thing happens if <code>Promise.all</code> rejects:</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); +}); + +// logs +// Promise { <state>: "pending" } +// the stack is now empty +// Promise { <state>: "rejected", <reason>: 44 } +</pre> + +<p>But, <code>Promise.all</code> resolves synchronously <strong>if and only if</strong> the <var>iterable</var> passed is empty:</p> + +<pre class="brush: js">var p = Promise.all([]); // will be immediately resolved +var p2 = Promise.all([1337, "hi"]); // non-promise values will be ignored, but the evaluation will be done asynchronously +console.log(p); +console.log(p2) +setTimeout(function() { + console.log('the stack is now empty'); + console.log(p2); +}); + +// logs +// 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_fail-fast_behaviour"><code>Promise.all</code> fail-fast behaviour</h3> + +<p><code>Promise.all</code> is rejected if any of the elements are rejected. For example, if you pass in four promises that resolve after a timeout and one promise that rejects immediately, then <code>Promise.all</code> will reject immediately.</p> + +<pre class="brush: js">var p1 = new Promise((resolve, reject) => { + setTimeout(() => resolve('one'), 1000); +}); +var p2 = new Promise((resolve, reject) => { + setTimeout(() => resolve('two'), 2000); +}); +var p3 = new Promise((resolve, reject) => { + setTimeout(() => resolve('three'), 3000); +}); +var p4 = new Promise((resolve, reject) => { + setTimeout(() => resolve('four'), 4000); +}); +var p5 = new Promise((resolve, reject) => { + reject(new Error('reject')); +}); + + +// Using .catch: +Promise.all([p1, p2, p3, p4, p5]) +.then(values => { + console.log(values); +}) +.catch(error => { + console.log(error.message) +}); + +//From console: +//"reject" + +</pre> + +<p>It is possible to change this behaviour by handling possible rejections:</p> + +<pre class="brush: js">var p1 = new Promise((resolve, reject) => { + setTimeout(() => resolve('p1_delayed_resolvement'), 1000); +}); + +var p2 = new Promise((resolve, reject) => { + reject(new Error('p2_immediate_rejection')); +}); + +Promise.all([ + p1.catch(error => { return error }), + p2.catch(error => { return error }), +]).then(values => { + console.log(values[0]) // "p1_delayed_resolvement" + console.log(values[1]) // "Error: p2_immediate_rejection" +}) +</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-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="Browser_compatibility">Browser compatibility</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.all")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Promise")}}</li> + <li>{{jsxref("Promise.race()")}}</li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/promise/catch/index.html b/files/tr/web/javascript/reference/global_objects/promise/catch/index.html new file mode 100644 index 0000000000..3360f87fbb --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/promise/catch/index.html @@ -0,0 +1,201 @@ +--- +title: Promise.prototype.catch() +slug: Web/JavaScript/Reference/Global_Objects/Promise/catch +tags: + - JavaScript + - Promise + - Prototype + - fonksiyon + - metod +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/catch +--- +<div>{{JSRef}}</div> + +<p>The <strong>catch()</strong> method returns a <code>Promise</code> and deals with rejected cases only. It behaves the same as calling {{jsxref("Promise.then", "Promise.prototype.then(undefined, onRejected)")}} (in fact, calling <code>obj.catch(onRejected)</code> internally calls <code>obj.then(undefined, onRejected)</code>). This means, that you have to provide <code>onRejected</code> function even if you want to fallback to <code>undefined</code> result value - for example <code>obj.catch(() => {})</code>.</p> + +<div>{{EmbedInteractiveExample("pages/js/promise-catch.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.</p> + +<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="Sözdizimi">Sözdizimi</h2> + +<pre class="syntaxbox"><var>p.catch(onRejected)</var>; + +p.catch(function(reason) { + // rejection +}); +</pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt>onRejected</dt> + <dd>A {{jsxref("Function")}} called when the <code>Promise</code> is rejected. This function has one argument: + <dl> + <dt><code>reason</code></dt> + <dd>The rejection reason.</dd> + </dl> + The Promise returned by <code>catch()</code> is rejected if <code>onRejected</code> throws an error or returns a Promise which is itself rejected; otherwise, it is resolved.</dd> +</dl> + +<h3 id="Dönen_değer">Dönen değer</h3> + +<p>Internally calls <code>Promise.prototype.then</code> on the object upon which is called, passing the parameters <code>undefined</code> and the <code>onRejected</code> handler received; then returns the value of that call (which is a {{jsxref("Promise")}}).</p> + +<div class="warning"> +<p>Note the examples below are throwing instances of <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error">Error</a>. This is considered good practice in contrast to throwing Strings: Otherwise the part doing the catching would have to make checks to see if the argument was a string or an error, and you might lose valuable information like stack traces.</p> +</div> + +<p><strong>Demonstration of the internal call:</strong></p> + +<pre class="brush: js">// overriding original Promise.prototype.then/catch just to add some logs +(function(Promise){ + var originalThen = Promise.prototype.then; + var originalCatch = Promise.prototype.catch; + + Promise.prototype.then = function(){ + console.log('> > > > > > called .then on %o with arguments: %o', this, arguments); + return originalThen.apply(this, arguments); + }; + Promise.prototype.catch = function(){ + console.log('> > > > > > called .catch on %o with arguments: %o', this, arguments); + return originalCatch.apply(this, arguments); + }; + +})(this.Promise); + + + +// calling catch on an already resolved promise +Promise.resolve().catch(function XXX(){}); + +// logs: +// > > > > > > called .catch on Promise{} with arguments: Arguments{1} [0: function XXX()] +// > > > > > > called .then on Promise{} with arguments: Arguments{2} [0: undefined, 1: function XXX()] +</pre> + +<h2 id="Açıklama">Açıklama</h2> + +<p>The <code>catch</code> method can be useful for error handling in your promise composition.</p> + +<h2 id="Örnekler">Örnekler</h2> + +<h3 id="Using_and_chaining_the_catch_method">Using and chaining the <code>catch</code> method</h3> + +<pre class="brush: js">var p1 = new Promise(function(resolve, reject) { + resolve('Success'); +}); + +p1.then(function(value) { + console.log(value); // "Success!" + throw new Error('oh, no!'); +}).catch(function(e) { + console.log(e.message); // "oh, no!" +}).then(function(){ + console.log('after a catch the chain is restored'); +}, function () { + console.log('Not fired due to the catch'); +}); + +// The following behaves the same as above +p1.then(function(value) { + console.log(value); // "Success!" + return Promise.reject('oh, no!'); +}).catch(function(e) { + console.log(e); // "oh, no!" +}).then(function(){ + console.log('after a catch the chain is restored'); +}, function () { + console.log('Not fired due to the catch'); +}); +</pre> + +<h3 id="Gotchas_when_throwing_errors">Gotchas when throwing errors</h3> + +<pre class="brush: js">// Throwing an error will call the catch method most of the time +var p1 = new Promise(function(resolve, reject) { + throw new Error('Uh-oh!'); +}); + +p1.catch(function(e) { + console.log(e); // "Uh-oh!" +}); + +// Errors thrown inside asynchronous functions will act like uncaught errors +var p2 = new Promise(function(resolve, reject) { + setTimeout(function() { + throw new Error('Uncaught Exception!'); + }, 1000); +}); + +p2.catch(function(e) { + console.log(e); // This is never called +}); + +// Errors thrown after resolve is called will be silenced +var p3 = new Promise(function(resolve, reject) { + resolve(); + throw new Error('Silenced Exception!'); +}); + +p3.catch(function(e) { + console.log(e); // This is never called +});</pre> + +<h3 id="If_it_is_resolved">If it is resolved</h3> + +<pre class="brush: js">//Create a promise which would not call onReject +var p1 = Promise.resolve("calling next"); + +var p2 = p1.catch(function (reason) { + //This is never called + console.log("catch p1!"); + console.log(reason); +}); + +p2.then(function (value) { + console.log("next promise's onFulfilled"); /* next promise's onFulfilled */ + console.log(value); /* calling next */ +}, function (reason) { + console.log("next promise's onRejected"); + console.log(reason); +});</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-promise.prototype.catch', 'Promise.prototype.catch')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition in an ECMA standard.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tarayıcı_uyumluluğu">Tarayıcı uyumluluğu</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.catch")}}</p> + +<h2 id="Ayrıca_bakınız">Ayrıca bakınız</h2> + +<ul> + <li>{{jsxref("Promise")}}</li> + <li>{{jsxref("Promise.prototype.then()")}}</li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/promise/index.html b/files/tr/web/javascript/reference/global_objects/promise/index.html new file mode 100644 index 0000000000..90f9dcabc0 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/promise/index.html @@ -0,0 +1,317 @@ +--- +title: Promise +slug: Web/JavaScript/Reference/Global_Objects/Promise +tags: + - JavaScript + - Promise + - Referans +translation_of: Web/JavaScript/Reference/Global_Objects/Promise +--- +<div>{{JSRef}}</div> + +<div><code><strong>Promise</strong></code> nesnesi eşzamansız olan ve ertelenen işlemlerde kullanılır. Bir <code><strong>Promise</strong></code> nesnesi henüz işlemin tamamlamadığını ama sonradan tamamlanabileceğini gösterir.</div> + +<div></div> + +<h2 id="Sözdizimi">Sözdizimi</h2> + +<pre class="syntaxbox">new Promise(function(resolve, reject) { ... });</pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt>executor</dt> + <dd><code>resolve </code>ve <code>reject </code>içeren iki parametreli bir fonksiyon nesnesidir. İlk parametre promise nesnesi tamamlandığında, ikinci parametre ise reddettiğinde çağrılır. Bu fonksiyonları işlemimiz bittiğinde (başarılı yada başarısız) çağırırız.</dd> +</dl> + +<h2 id="Açıklama">Açıklama</h2> + +<p>Oluşturulan bir <code>promise </code>başka bir <code>promise </code>için proxy görevi görür.<br> + Başarılı yada başarısız bir şekilde sonuç üreten asenkron işlemlerin ilişkilendirilmesine olanak tanır.Bu asenkron methodların senkron methodlar gibi sonuç döndürmesi'ni sağlar.Asenkron method hemen sonuçlanmaz.Bunun yerine işlemin tamamlandığı noktayı temsil eden bir <code>promise </code>döndürür.</p> + +<p>Bir <code>Promise</code> şu durumları içerir:</p> + +<ul> + <li><em>pending</em>: ne işlem görmüş ne de red edilmiş başlangıç durumu.</li> + <li><em>fulfilled</em>: operasyon ' un başarılı bir şekilde tamamlandığı durum.</li> + <li><em>rejected</em>: operasyon ' un başarısızlıkla tamamlandığı durum.</li> +</ul> + +<p>Bekleyen bir Promise, bir sonuç döndürerek tamamlanabilir veya bir nedenle reddedilebilir(hata).Bunlardan herhanbiri gerçekleştiğinde (resolve/reject) sıraya konulmuş ilişkili methodlar sıra ile çağrılır.(Promise tamamlandığında yada red edildiğinde sırada bağlanmış bir method var ise o method çalıştırılır.Böylece asenkron işlemler arasında bir rekabet/mücadele olmaz.Sırası gelen çalışır.)</p> + +<p>As the <code>{{jsxref("Promise.then", "Promise.prototype.then()")}}</code> and <code>{{jsxref("Promise.catch", "Promise.prototype.catch()")}}</code> methods return promises, bunlar zincirlenebilirler—an operation called <em>composition</em>.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/8633/promises.png"></p> + +<div class="note"> +<p><strong>Note</strong>: A promise is said to be <em>settled </em>if it is either fulfilled or rejected, but not pending. You will also hear the term <em>resolved</em> used with promises — this means that the promise is settled, or it is locked into a promise chain. Domenic Denicola's <a href="https://github.com/domenic/promises-unwrapping/blob/master/docs/states-and-fates.md">States and fates</a> contains more details about promise terminology.</p> +</div> + +<h2 id="Özellikler">Özellikler</h2> + +<dl> + <dt><code>Promise.length</code></dt> + <dd>Değeri 1 olan Length özelliği (constructor argümanları sayısı).</dd> + <dt>{{jsxref("Promise.prototype")}}</dt> + <dd>Represents the prototype for the <code>Promise</code> constructor.</dd> +</dl> + +<h2 id="Metodlar">Metodlar</h2> + +<dl> + <dt>{{jsxref("Promise.all", "Promise.all(iterable)")}}</dt> + <dd>Returns a promise that either resolves when all of the promises in the iterable argument have resolved or rejects as soon as one of the promises in the iterable argument rejects. If the returned promise resolves, it is resolved with an array of the values from the resolved promises in the iterable. If the returned promise rejects, it is rejected with the reason from the promise in the iterable that rejected. This method can be useful for aggregating results of multiple promises together.</dd> + <dt>{{jsxref("Promise.race", "Promise.race(iterable)")}}</dt> + <dd>Returns a promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects, with the value or reason from that promise.</dd> +</dl> + +<dl> + <dt>{{jsxref("Promise.reject", "Promise.reject(reason)")}}</dt> + <dd>Belirtilen bir nedenden dolayı reddedilen <code>Promise</code> nesnesini döndürür.</dd> +</dl> + +<dl> + <dt>{{jsxref("Promise.resolve", "Promise.resolve(value)")}}</dt> + <dd>Returns a <code>Promise</code> object that is resolved with the given value. If the value is a thenable (i.e. has a <code>then</code> method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value. Generally, if you want to know if a value is a promise or not - {{jsxref("Promise.resolve", "Promise.resolve(value)")}} it instead and work with the return value as a promise.</dd> +</dl> + +<h2 id="Promise_prototype"><code>Promise</code> prototype</h2> + +<h3 id="Özellikler_2">Özellikler</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Properties')}}</p> + +<h3 id="Metodlar_2">Metodlar</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Methods')}}</p> + +<h2 id="Örnekler">Örnekler</h2> + +<h3 id="Promise_Oluşturma">Promise Oluşturma</h3> + +<pre class="brush: html hidden"><button id="btn">Promise yap!</button> +<div id="log"></div> +</pre> + +<p>Bu küçük örnek <code>Promise</code> mekanizmasını gösterir. {{HTMLElement("button")}} her tıklandığında <code>testPromise()</code> metodu çağrılır . It creates a promise that will resolve, using {{domxref("window.setTimeout()")}}, to the string "result" every 1-3 seconds, at random. The <code>Promise()</code> constructor is used to create the promise.</p> + +<p>The fulfillment of the promise is simply logged, via a fulfill callback set using {{jsxref("Promise.prototype.then()","p1.then()")}}. A few logs shows how the synchronous part of the method is decoupled of the asynchronous completion of the promise.</p> + +<pre class="brush: js">'use strict'; +var promiseCount = 0; + +function testPromise() { + var thisPromiseCount = ++promiseCount; + + var log = document.getElementById('log'); + log.insertAdjacentHTML('beforeend', thisPromiseCount + + ') Started (<small>Sync code started</small>)<br/>'); + + // We make a new promise: we promise the string 'result' (after waiting 3s) + var p1 = new Promise( + // The resolver function is called with the ability to resolve or + // reject the promise + function(resolve, reject) { + log.insertAdjacentHTML('beforeend', thisPromiseCount + + ') Promise started (<small>Async code started</small>)<br/>'); + // This is only an example to create asynchronism + window.setTimeout( + function() { + // We fulfill the promise ! + resolve(thisPromiseCount); + }, Math.random() * 2000 + 1000); + }); + + // We define what to do when the promise is resolved/fulfilled with the then() call, + // and the catch() method defines what to do if the promise is rejected. + p1.then( + // Log the fulfillment value + function(val) { + log.insertAdjacentHTML('beforeend', val + + ') Promise fulfilled (<small>Async code terminated</small>)<br/>'); + }) + .catch( + // Log the rejection reason + function(reason) { + console.log('Handle rejected promise ('+reason+') here.'); + }); + + log.insertAdjacentHTML('beforeend', thisPromiseCount + + ') Promise made (<small>Sync code terminated</small>)<br/>'); +}</pre> + +<pre class="brush:js hidden">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> + +<p>Bu örnek buton'a tıkladığınızda çalışır. <code>Promise</code> destekleyen bir tarayıcıya ihtiyacınız var. Buton'a birden fazla tıklamanız durumunda farklı promise nesnelerinin kısa sürede tamamlandığını göreceksiniz.</p> + +<p>{{EmbedLiveSample("Creating_a_Promise", "500", "200")}}</p> + +<h2 id="new_XMLHttpRequest_Kullanım_Örneği">new XMLHttpRequest() Kullanım Örneği</h2> + +<h3 id="Promise_Oluşturma_2">Promise Oluşturma</h3> + +<p>Bu örnekte {{domxref("XMLHttpRequest")}} nesnesinin başarılı yada başarısız durumunu <code>Promise</code> kullanarak nasıl raporlanabildiğini göstermektedir.</p> + +<pre class="brush: js">'use strict'; + +// A-> $http function is implemented in order to follow the standard Adapter pattern +function $http(url){ + + // A small example of object + var core = { + + // Method that performs the ajax request + ajax : function (method, url, args) { + + // Creating a promise + var promise = new Promise( function (resolve, reject) { + + // Instantiates the XMLHttpRequest + var client = new XMLHttpRequest(); + var uri = url; + + if (args && (method === 'POST' || method === 'PUT')) { + uri += '?'; + var argcount = 0; + for (var key in args) { + if (args.hasOwnProperty(key)) { + if (argcount++) { + uri += '&'; + } + uri += encodeURIComponent(key) + '=' + encodeURIComponent(args[key]); + } + } + } + + client.open(method, uri); + client.send(); + + client.onload = function () { + if (this.status >= 200 && this.status < 300) { + // Performs the function "resolve" when this.status is equal to 2xx + resolve(this.response); + } else { + // Performs the function "reject" when this.status is different than 2xx + reject(this.statusText); + } + }; + client.onerror = function () { + reject(this.statusText); + }; + }); + + // Return the promise + return promise; + } + }; + + // Adapter pattern + return { + 'get' : function(args) { + return core.ajax('GET', url, args); + }, + 'post' : function(args) { + return core.ajax('POST', url, args); + }, + 'put' : function(args) { + return core.ajax('PUT', url, args); + }, + 'delete' : function(args) { + return core.ajax('DELETE', url, args); + } + }; +}; +// End A + +// B-> Here you define its functions and its payload +var mdnAPI = 'https://developer.mozilla.org/en-US/search.json'; +var payload = { + 'topic' : 'js', + 'q' : 'Promise' +}; + +var callback = { + success : function(data){ + console.log(1, 'success', JSON.parse(data)); + }, + error : function(data){ + console.log(2, 'error', JSON.parse(data)); + } +}; +// End B + +// Executes the method call +$http(mdnAPI) + .get(payload) + .then(callback.success) + .catch(callback.error); + +// Executes the method call but an alternative way (1) to handle Promise Reject case +$http(mdnAPI) + .get(payload) + .then(callback.success, callback.error); + +// Executes the method call but an alternative way (2) to handle Promise Reject case +$http(mdnAPI) + .get(payload) + .then(callback.success) + .then(undefined, callback.error); +</pre> + +<h3 id="XHR_ile_görsel_yükleme">XHR ile görsel yükleme</h3> + +<p>Another simple example using <code>Promise</code> and <code><a href="/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequest</a></code> to load an image is available at the MDN GitHub<a href="https://github.com/mdn/promises-test/blob/gh-pages/index.html"> promise-test</a> repository. You can also <a href="http://mdn.github.io/promises-test/">see it in action</a>. Each step is commented and allows you to follow the Promise and XHR architecture closely.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Durum</th> + <th scope="col">Yorum</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-promise-objects', 'Promise')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition in an ECMA standard.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-promise-objects', 'Promise')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Tarayıcı_uyumluluğu">Tarayıcı uyumluluğu</h2> + + + +<div> + + +<p>{{Compat("javascript.builtins.Promise")}}</p> +</div> + + + +<h2 id="Ayrıca_bakınız">Ayrıca bakınız</h2> + +<ul> + <li><a href="http://promisesaplus.com/">Promises/A+ specification</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="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> + <li><a href="https://github.com/jakearchibald/es6-promise/">Promise polyfill</a></li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/regexp/index.html b/files/tr/web/javascript/reference/global_objects/regexp/index.html new file mode 100644 index 0000000000..f60e06d0df --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/regexp/index.html @@ -0,0 +1,606 @@ +--- +title: RegExp +slug: Web/JavaScript/Reference/Global_Objects/RegExp +translation_of: Web/JavaScript/Reference/Global_Objects/RegExp +--- +<div>{{JSRef}}</div> + +<p>The <strong><code>RegExp</code></strong> constructor creates a regular expression object for matching text with a pattern.</p> + +<p>For an introduction to regular expressions, read the <a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions">Regular Expressions chapter</a> in the <a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions">JavaScript Guide</a>.</p> + +<h2 id="Syntax">Syntax</h2> + +<p>Literal, constructor, and factory notations are possible:</p> + +<pre class="syntaxbox">/<var>pattern</var>/<var>flags</var> +new RegExp(<var>pattern</var>[, <var>flags</var>]) +RegExp(<var>pattern</var>[, <var>flags</var>]) +</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>pattern</code></dt> + <dd>Duzenli ifadenin metni.</dd> + <dt><code>flags</code></dt> + <dd> + <p>If specified, flags can have any combination of the following values:</p> + + <dl> + <dt><code>g</code></dt> + <dd>global match; find all matches rather than stopping after the first match</dd> + <dt><code>i</code></dt> + <dd>ignore case</dd> + <dt><code>m</code></dt> + <dd>multiline; treat beginning and end characters (^ and $) as working over multiple lines (i.e., match the beginning or end of <em>each</em> line (delimited by \n or \r), not only the very beginning or end of the whole input string)</dd> + <dt><code>u</code></dt> + <dd>unicode; treat pattern as a sequence of unicode code points</dd> + <dt><code>y</code></dt> + <dd>sticky; matches only from the index indicated by the <code>lastIndex</code> property of this regular expression in the target string (and does not attempt to match from any later indexes).</dd> + </dl> + </dd> +</dl> + +<h2 id="Description">Description</h2> + +<p>There are 2 ways to create a <code>RegExp</code> object: a literal notation and a constructor. To indicate strings, the parameters to the literal notation do not use quotation marks while the parameters to the constructor function do use quotation marks. So the following expressions create the same regular expression:</p> + +<pre class="brush: js">/ab+c/i; +new RegExp('ab+c', 'i'); +new RegExp(/ab+c/, 'i'); +</pre> + +<p>The literal notation provides compilation of the regular expression when the expression is evaluated. Use literal notation when the regular expression will remain constant. For example, if you use literal notation to construct a regular expression used in a loop, the regular expression won't be recompiled on each iteration.</p> + +<p>The constructor of the regular expression object, for example, <code>new RegExp('ab+c')</code>, provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.</p> + +<p>Starting with ECMAScript 6, <code>new RegExp(/ab+c/, 'i')</code> no longer throws a {{jsxref("TypeError")}} ("can't supply flags when constructing one RegExp from another") when the first argument is a <code>RegExp</code> and the second <code>flags</code> argument is present. A new <code>RegExp</code> from the arguments is created instead.</p> + +<p>When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary. For example, the following are equivalent:</p> + +<pre class="brush: js">var re = /\w+/; +var re = new RegExp('\\w+'); +</pre> + +<h2 id="Düzenli_İfadelerde_(Regular_Expressions)_Özel_Karakterlerin_Anlamları">Düzenli İfadelerde (Regular Expressions) Özel Karakterlerin Anlamları</h2> + +<ul> + <li><a href="/en-US/docs/">Karakter Sınıfları</a></li> + <li><a href="#character-sets">Karakter Kümele</a>ri</li> + <li>Kısıtlar</li> + <li><a href="#alternation">D</a>eğişim</li> + <li>Gruplama ve Referansa Geri Dönme</li> + <li><a href="#quantifiers">N</a>iceleyiciler</li> + <li><a href="#assertions">O</a>naylamalar</li> +</ul> + +<table class="fullwidth-table"> + <tbody> + <tr id="character-classes"> + <th colspan="2">Karakter Sınıfları</th> + </tr> + <tr> + <th>Karakter</th> + <th>Anlamı</th> + </tr> + <tr> + <td><code>.</code></td> + <td> + <p>(The dot, the decimal point) matches any single character <em>except</em> line terminators: <code>\n</code>, <code>\r</code>, <code>\u2028</code> or <code>\u2029</code>.</p> + + <p>Inside a character set, the dot loses its special meaning and matches a literal dot.</p> + + <p>Note that the <code>m</code> multiline flag doesn't change the dot behavior. So to match a pattern across multiple lines, the character set <code>[^]</code> can be used (if you don't mean an old version of IE, of course), it will match any character including newlines.</p> + + <p>For example, <code>/.y/</code> matches "my" and "ay", but not "yes", in "yes make my day".</p> + </td> + </tr> + <tr> + <td><code>\d</code></td> + <td> + <p>Matches any digit (Arabic numeral). Equivalent to <code>[0-9]</code>.</p> + + <p>For example, <code>/\d/</code> or <code>/[0-9]/</code> matches "2" in "B2 is the suite number".</p> + </td> + </tr> + <tr> + <td><code>\D</code></td> + <td> + <p>Matches any character that is not a digit (Arabic numeral). Equivalent to <code>[^0-9]</code>.</p> + + <p>For example, <code>/\D/</code> or <code>/[^0-9]/</code> matches "B" in "B2 is the suite number".</p> + </td> + </tr> + <tr> + <td><code>\w</code></td> + <td> + <p>Matches any alphanumeric character from the basic Latin alphabet, including the underscore. Equivalent to <code>[A-Za-z0-9_]</code>.</p> + + <p>For example, <code>/\w/</code> matches "a" in "apple", "5" in "$5.28", and "3" in "3D".</p> + </td> + </tr> + <tr> + <td><code>\W</code></td> + <td> + <p>Matches any character that is not a word character from the basic Latin alphabet. Equivalent to <code>[^A-Za-z0-9_]</code>.</p> + + <p>For example, <code>/\W/</code> or <code>/[^A-Za-z0-9_]/</code> matches "%" in "50%".</p> + </td> + </tr> + <tr> + <td><code>\s</code></td> + <td> + <p>Matches a single white space character, including space, tab, form feed, line feed and other Unicode spaces. Equivalent to <code>[ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]</code>.</p> + + <p>For example, <code>/\s\w*/</code> matches " bar" in "foo bar".</p> + </td> + </tr> + <tr> + <td><code>\S</code></td> + <td> + <p>Matches a single character other than white space. Equivalent to <code>[^ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]</code>.</p> + + <p>For example, <code>/\S\w*/</code> matches "foo" in "foo bar".</p> + </td> + </tr> + <tr> + <td><code>\t</code></td> + <td>Matches a horizontal tab.</td> + </tr> + <tr> + <td><code>\r</code></td> + <td>Matches a carriage return.</td> + </tr> + <tr> + <td><code>\n</code></td> + <td>Matches a linefeed.</td> + </tr> + <tr> + <td><code>\v</code></td> + <td>Matches a vertical tab.</td> + </tr> + <tr> + <td><code>\f</code></td> + <td>Matches a form-feed.</td> + </tr> + <tr> + <td><code>[\b]</code></td> + <td>Matches a backspace. (Not to be confused with <code>\b</code>)</td> + </tr> + <tr> + <td><code>\0</code></td> + <td>Matches a NUL character. Do not follow this with another digit.</td> + </tr> + <tr> + <td><code>\c<em>X</em></code></td> + <td> + <p>Where <code><em>X</em></code> is a letter from A - Z. Matches a control character in a string.</p> + + <p>For example, <code>/\cM/</code> matches control-M in a string.</p> + </td> + </tr> + <tr> + <td><code>\x<em>hh</em></code></td> + <td>Matches the character with the code <code><em>hh</em></code> (two hexadecimal digits).</td> + </tr> + <tr> + <td><code>\u<em>hhhh</em></code></td> + <td>Matches a UTF-16 code-unit with the value <code><em>hhhh</em></code> (four hexadecimal digits).</td> + </tr> + <tr> + <td><code>\u<em>{hhhh} </em>or <em>\u{hhhhh}</em></code></td> + <td>(only when u flag is set) Matches the character with the Unicode value U+<code><em>hhhh</em> or </code>U+<code><em>hhhhh</em></code> (hexadecimal digits).</td> + </tr> + <tr> + <td><code>\</code></td> + <td> + <p>For characters that are usually treated literally, indicates that the next character is special and not to be interpreted literally.</p> + + <p>For example, <code>/b/</code> matches the character "b". By placing a backslash in front of "b", that is by using <code>/\b/</code>, the character becomes special to mean match a word boundary.</p> + + <p><em>or</em></p> + + <p>For characters that are usually treated specially, indicates that the next character is not special and should be interpreted literally.</p> + + <p>For example, "*" is a special character that means 0 or more occurrences of the preceding character should be matched; for example, <code>/a*/</code> means match 0 or more "a"s. To match <code>*</code> literally, precede it with a backslash; for example, <code>/a\*/</code> matches "a*".</p> + </td> + </tr> + </tbody> + <tbody> + <tr id="character-sets"> + <th colspan="2">Karakter Kümeleri</th> + </tr> + <tr> + <th>Karakter</th> + <th>Anlamı</th> + </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.</p> + + <p>For example, <code>[^abc]</code> is the same as <code>[^a-c]</code>. They initially match "o" in "bacon" and "h" in "chop".</p> + </td> + </tr> + </tbody> + <tbody> + <tr id="alternation"> + <th colspan="2">Değişim</th> + </tr> + <tr> + <th>Karakter</th> + <th>Anlamı</th> + </tr> + <tr> + <td><code><em>x</em>|<em>y</em></code></td> + <td> + <p>Matches either <code><em>x</em></code> or <code><em>y</em></code>.</p> + + <p>For example, <code>/green|red/</code> matches "green" in "green apple" and "red" in "red apple".</p> + </td> + </tr> + </tbody> + <tbody> + <tr id="boundaries"> + <th colspan="2">Kısıtlar</th> + </tr> + <tr> + <th>Karakter</th> + <th>Anlamı</th> + </tr> + <tr> + <td><code>^</code></td> + <td> + <p>Matches beginning of input. If the multiline flag is set to true, also matches immediately after a line break character.</p> + + <p>For example, <code>/^A/</code> does not match the "A" in "an A", but does match the first "A" in "An A".</p> + </td> + </tr> + <tr> + <td><code>$</code></td> + <td> + <p>Matches end of input. If the multiline flag is set to true, also matches immediately before a line break character.</p> + + <p>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:<br> + <code>/\bm/</code> matches the 'm' in "moon" ;<br> + <code>/oo\b/</code> does not match the 'oo' in "moon", because 'oo' is followed by 'n' which is a word character;<br> + <code>/oon\b/</code> matches the 'oon' in "moon", because 'oon' is the end of the string, thus not followed by a word character;<br> + <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.</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. Such as 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 bondary is also not included in the match.</p> + + <p>For example, <code>/\Bon/</code> matches "on" in "at noon", and <code>/ye\B/</code> matches "ye" in "possibly yesterday".</p> + </td> + </tr> + </tbody> + <tbody> + <tr id="grouping-back-references"> + <th colspan="2">Gruplama ve Referansa Geri Dönme</th> + </tr> + <tr> + <th>Karakter</th> + <th>Anlamı</th> + </tr> + <tr> + <td><code>(<em>x</em>)</code></td> + <td> + <p>Matches <code><em>x</em></code> and remembers the match. These are called capturing groups.</p> + + <p>For example, <code>/(foo)/</code> matches and remembers "foo" in "foo bar". </p> + + <p>The capturing groups are numbered according to the order of left parentheses of capturing groups, starting from 1. The matched substring can 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>.</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> + </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).</p> + + <p>For example, <code>/apple(,)\sorange\1/</code> matches "apple, orange," in "apple, orange, cherry, peach". A more complete example follows this table.</p> + </td> + </tr> + <tr> + <td><code>(?:<em>x</em>)</code></td> + <td>Matches <code><em>x</em></code> but does not remember the match. These are called non-capturing groups. The matched substring can not 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> + <tbody> + <tr id="quantifiers"> + <th colspan="2">Niceleyiciler</th> + </tr> + <tr> + <th>Karakter</th> + <th>Anlamı</th> + </tr> + <tr> + <td><code><em>x</em>*</code></td> + <td> + <p>Matches the preceding item <em>x</em> 0 or more times.</p> + + <p>For example, <code>/bo*/</code> matches "boooo" in "A ghost booooed" and "b" in "A bird warbled", but nothing in "A goat grunted".</p> + </td> + </tr> + <tr> + <td><code><em>x</em>+</code></td> + <td> + <p>Matches the preceding item <em>x</em> 1 or more times. Equivalent to <code>{1,}</code>.</p> + + <p>For example, <code>/a+/</code> matches the "a" in "candy" and all the "a"'s in "caaaaaaandy".</p> + </td> + </tr> + <tr> + <td><code><em>x</em>?</code></td> + <td> + <p>Matches the preceding item <em>x</em> 0 or 1 time.</p> + + <p>For example, <code>/e?le?/</code> matches the "el" in "angel" and the "le" in "angle."</p> + + <p>If used immediately after any of the quantifiers <code>*</code>, <code>+</code>, <code>?</code>, or <code>{}</code>, makes the quantifier non-greedy (matching the minimum number of times), as opposed to the default, which is greedy (matching the maximum number of times).</p> + </td> + </tr> + <tr> + <td><code><em>x</em>{<em>n</em>}</code></td> + <td> + <p>Where <code><em>n</em></code> is a positive integer. Matches exactly <code><em>n</em></code> occurrences of the preceding item <em>x</em>.</p> + + <p>For example, <code>/a{2}/</code> doesn't match the "a" in "candy", but it matches all of the "a"'s in "caandy", and the first two "a"'s in "caaandy".</p> + </td> + </tr> + <tr> + <td><code><em>x</em>{<em>n</em>,}</code></td> + <td> + <p>Where <code><em>n</em></code> is a positive integer. Matches at least <code><em>n</em></code> occurrences of the preceding item <em>x</em>.</p> + + <p>For example, <code>/a{2,}/</code> doesn't match the "a" in "candy", but matches all of the a's in "caandy" and in "caaaaaaandy".</p> + </td> + </tr> + <tr> + <td><code><em>x</em>{<em>n</em>,<em>m</em>}</code></td> + <td> + <p>Where <code><em>n</em></code> and <code><em>m</em></code> are positive integers. Matches at least <code><em>n</em></code> and at most <code><em>m</em></code> occurrences of the preceding item <em>x</em>.</p> + + <p>For example, <code>/a{1,3}/</code> matches nothing in "cndy", the "a" in "candy", the two "a"'s in "caandy", and the first three "a"'s in "caaaaaaandy". Notice that when matching "caaaaaaandy", the match is "aaa", even though the original string had more "a"'s in it.</p> + </td> + </tr> + <tr> + <td> + <p><code><em>x</em>*?</code><br> + <code><em>x</em>+?</code><br> + <code><em>x</em>??</code><br> + <code><em>x</em>{n}?</code><br> + <code><em>x</em>{n,}?</code><br> + <code><em>x</em>{n,m}?</code></p> + </td> + <td> + <p>Matches the preceding item <em>x</em> like <code>*</code>, <code>+</code>, <code>?</code>, and <code>{...}</code> from above, however the match is the smallest possible match.</p> + + <p>For example, <code>/<.*?>/</code> matches "<foo>" in "<foo> <bar>", whereas <code>/<.*>/</code> matches "<foo> <bar>".</p> + + <p>Quantifiers without <code>?</code> are said to be greedy. Those with <code>?</code> are called "non-greedy".</p> + </td> + </tr> + </tbody> + <tbody> + <tr id="assertions"> + <th colspan="2">Onaylamalar</th> + </tr> + <tr> + <th>Karakter</th> + <th>Anlamı</th> + </tr> + <tr> + <td><code><em>x</em>(?=<em>y</em>)</code></td> + <td> + <p>Matches <code><em>x</em></code> only if <code><em>x</em></code> is followed by <code><em>y</em></code>.</p> + + <p>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><em>x</em>(?!<em>y</em>)</code></td> + <td> + <p>Matches <code><em>x</em></code> only if <code><em>x</em></code> is not followed by <code><em>y</em></code>.</p> + + <p>For example, <code>/\d+(?!\.)/</code> matches a number only if it is not followed by a decimal point.<br> + <code>/\d+(?!\.)/.exec('3.141')</code> matches "141" but not "3.141".</p> + </td> + </tr> + </tbody> +</table> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt>{{jsxref("RegExp.prototype")}}</dt> + <dd>Allows the addition of properties to all objects.</dd> + <dt><code>RegExp.length</code></dt> + <dd>The value of <code>RegExp.length</code> is 2.</dd> + <dt>{{jsxref("RegExp.@@species", "get RegExp[@@species]")}}</dt> + <dd>The constructor function that is used to create derived objects.</dd> + <dt>{{jsxref("RegExp.lastIndex")}}</dt> + <dd>The index at which to start the next match.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p>The global <code>RegExp</code> object has no methods of its own, however, it does inherit some methods through the prototype chain.</p> + +<h2 id="RegExp_prototype_objects_and_instances"><code>RegExp</code> prototype objects and instances</h2> + +<h3 id="Properties_2">Properties</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/prototype', 'Properties')}}</div> + +<h3 id="Methods_2">Methods</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/prototype', 'Methods')}}</div> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_a_regular_expression_to_change_data_format">Using a regular expression to change data format</h3> + +<p>The following script uses the {{jsxref("String.prototype.replace()", "replace()")}} method of the {{jsxref("Global_Objects/String", "String")}} instance to match a name in the format <em>first last</em> and output it in the format <em>last, first</em>. In the replacement text, the script uses <code>$1</code> and <code>$2</code> to indicate the results of the corresponding matching parentheses in the regular expression pattern.</p> + +<pre class="brush: js">var re = /(\w+)\s(\w+)/; +var str = 'John Smith'; +var newstr = str.replace(re, '$2, $1'); +console.log(newstr); +</pre> + +<p>This displays "Smith, John".</p> + +<h3 id="Using_regular_expression_to_split_lines_with_different_line_endingsends_of_lineline_breaks">Using regular expression to split lines with different <strong>line endings/ends of line/line breaks</strong></h3> + +<p>The default line ending varies depending on the platform (Unix, Windows, etc.). The line splitting provided in this example works on all platforms.</p> + +<pre class="brush: js">var text = 'Some text\nAnd some more\r\nAnd yet\rThis is the end'; +var lines = text.split(/\r\n|\r|\n/); +console.log(lines); // logs [ 'Some text', 'And some more', 'And yet', 'This is the end' ] +</pre> + +<p>Note that the order of the patterns in the regular expression matters.</p> + +<h3 id="Using_regular_expression_on_multiple_lines">Using regular expression on multiple lines</h3> + +<pre class="brush: js">var s = 'Please yes\nmake my day!'; +s.match(/yes.*day/); +// Returns null +s.match(/yes[^]*day/); +// Returns ["yes\nmake my day"] +</pre> + +<h3 id="Using_a_regular_expression_with_the_sticky_flag">Using a regular expression with the sticky flag</h3> + +<p>The <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky">sticky flag</a> indicates that the regular expression performs sticky matching in the target string by attempting to match starting at {{jsxref("RegExp.prototype.lastIndex")}}.</p> + +<pre class="brush: js">var str = '#foo#'; +var 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="Regular_expression_and_Unicode_characters">Regular expression and Unicode characters</h3> + +<p>As mentioned above, <code>\w</code> or <code>\W</code> only matches ASCII based characters; for example, "a" to "z", "A" to "Z", "0" to "9" and "_". To match characters from other languages such as Cyrillic or Hebrew, use <code>\uhhhh</code>, where "hhhh" is the character's Unicode value in hexadecimal. This example demonstrates how one can separate out Unicode characters from a word.</p> + +<pre class="brush: js">var text = 'Образец text на русском языке'; +var regex = /[\u0400-\u04FF]+/g; + +var match = regex.exec(text); +console.log(match[0]); // logs 'Образец' +console.log(regex.lastIndex); // logs '7' + +var match2 = regex.exec(text); +console.log(match2[0]); // logs 'на' [did not log 'text'] +console.log(regex.lastIndex); // logs '15' + +// and so on +</pre> + +<p>Here's an external resource for getting the complete Unicode block range for different scripts: <a href="http://kourge.net/projects/regexp-unicode-block">Regexp-unicode-block</a>.</p> + +<h3 id="Extracting_sub-domain_name_from_URL">Extracting sub-domain name from URL</h3> + +<pre class="brush: js">var url = 'http://xxx.domain.com'; +console.log(/[^.]+/.exec(url)[0].substr(7)); // logs 'xxx' +</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('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.10', 'RegExp')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-regexp-regular-expression-objects', 'RegExp')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>The <code>RegExp</code> constructor no longer throws when the first argument is a <code>RegExp</code> and the second argument is present. Introduces Unicode and sticky flags.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-regexp-regular-expression-objects', 'RegExp')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.RegExp")}}</p> +</div> + +<h3 id="Firefox-specific_notes">Firefox-specific notes</h3> + +<p>Starting with Firefox 34, in the case of a capturing group with quantifiers preventing its exercise, the matched text for a capturing group is now <code>undefined</code> instead of an empty string:</p> + +<pre class="brush: js">// Firefox 33 or older +'x'.replace(/x(.)?/g, function(m, group) { + console.log("'group:" + group + "'"); +}); // 'group:' + +// Firefox 34 or newer +'x'.replace(/x(.)?/g, function(m, group) { + console.log("'group:" + group + "'"); +}); // 'group:undefined' +</pre> + +<p>Note that due to web compatibility, <code>RegExp.$N</code> will still return an empty string instead of <code>undefined</code> ({{bug(1053944)}}).</p> + +<h2 id="See_also">See also</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("String.prototype.match()")}}</li> + <li>{{jsxref("String.prototype.replace()")}}</li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/string/index.html b/files/tr/web/javascript/reference/global_objects/string/index.html new file mode 100644 index 0000000000..bbf4377f32 --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/string/index.html @@ -0,0 +1,316 @@ +--- +title: String +slug: Web/JavaScript/Reference/Global_Objects/String +tags: + - ECMAScript 2015 + - JavaScript + - NeedsTranslation + - Reference + - String + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/String +--- +<div>{{JSRef}}</div> + +<p>Genel bir nesne olan <strong><code>String</code></strong>, dizgi veya karakter dizilerinin yapıcısıdır.</p> + +<p> </p> + +<h2 id="Sözdizimi">Sözdizimi</h2> + +<p>String literals take the forms:</p> + +<pre class="syntaxbox">'string text' +"string text" +"中文 español deutsch Türkçe हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ 한국어 தமிழ் עברית"</pre> + +<p>Strings can also be created using the <code>String</code> global object directly:</p> + +<pre class="syntaxbox">String(thing)</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>thing</code></dt> + <dd>Anything to be converted to a string.</dd> +</dl> + +<h3 id="Template_literals">Template literals</h3> + +<p>Starting with ECMAScript 2015, string literals can also be so-called <a href="/en-US/docs/Web/JavaScript/Reference/Template_literals">Template literals</a>:</p> + +<pre class="syntaxbox">`hello world` +`hello! + world!` +`hello ${who}` +escape `<a>${who}</a>`</pre> + +<dl> +</dl> + +<h3 id="Escape_notation">Escape notation</h3> + +<p>Beside regular, printable characters, special characters can be encoded using escape notation:</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Code</th> + <th scope="col">Output</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>\0</code></td> + <td>the NULL character</td> + </tr> + <tr> + <td><code>\'</code></td> + <td>single quote</td> + </tr> + <tr> + <td><code>\"</code></td> + <td>double quote</td> + </tr> + <tr> + <td><code>\\</code></td> + <td>backslash</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>\v</code></td> + <td>vertical tab</td> + </tr> + <tr> + <td><code>\t</code></td> + <td>tab</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>\uXXXX</code></td> + <td>unicode codepoint</td> + </tr> + <tr> + <td><code>\u{X}</code> ... <code>\u{XXXXXX}</code></td> + <td>unicode codepoint {{experimental_inline}}</td> + </tr> + <tr> + <td><code>\xXX</code></td> + <td>the Latin-1 character</td> + </tr> + </tbody> +</table> + +<div class="note"> +<p>Unlike some other languages, JavaScript makes no distinction between single-quoted strings and double-quoted strings; therefore, the escape sequences above work in strings created with either single or double quotes.</p> +</div> + +<dl> +</dl> + +<h3 id="Long_literal_strings">Long literal strings</h3> + +<p>Sometimes, your code will include strings which are very long. Rather than having lines that go on endlessly, or wrap at the whim of your editor, you may wish to specifically break the string into multiple lines in the source code without affecting the actual string contents. There are two ways you can do this.</p> + +<p>You can use the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Addition_()">+</a> operator to append multiple strings together, like this:</p> + +<pre class="brush: js">let longString = "This is a very long string which needs " + + "to wrap across multiple lines because " + + "otherwise my code is unreadable."; +</pre> + +<p>Or you can use the backslash character ("\") at the end of each line to indicate that the string will continue on the next line. Make sure there is no space or any other character after the backslash (except for a line break), or as an indent; otherwise it will not work. That form looks like this:</p> + +<pre class="brush: js">let longString = "This is a very long string which needs \ +to wrap across multiple lines because \ +otherwise my code is unreadable."; +</pre> + +<p>Both of these result in identical strings being created.</p> + +<h2 id="Description">Description</h2> + +<p>Strings are useful for holding data that can be represented in text form. Some of the most-used operations on strings are to check their {{jsxref("String.length", "length")}}, to build and concatenate them using the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/String_Operators">+ and += string operators</a>, checking for the existence or location of substrings with the {{jsxref("String.prototype.indexOf()", "indexOf()")}} method, or extracting substrings with the {{jsxref("String.prototype.substring()", "substring()")}} method.</p> + +<h3 id="Character_access">Character access</h3> + +<p>There are two ways to access an individual character in a string. The first is the {{jsxref("String.prototype.charAt()", "charAt()")}} method:</p> + +<pre class="brush: js">return 'cat'.charAt(1); // returns "a" +</pre> + +<p>The other way (introduced in ECMAScript 5) is to treat the string as an array-like object, where individual characters correspond to a numerical index:</p> + +<pre class="brush: js">return 'cat'[1]; // returns "a" +</pre> + +<p>For character access using bracket notation, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable. (See {{jsxref("Object.defineProperty()")}} for more information.)</p> + +<h3 id="Comparing_strings">Comparing strings</h3> + +<p>C developers have the <code>strcmp()</code> function for comparing strings. In JavaScript, you just use the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">less-than and greater-than operators</a>:</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>A similar result can be achieved using the {{jsxref("String.prototype.localeCompare()", "localeCompare()")}} method inherited by <code>String</code> instances.</p> + +<h3 id="Distinction_between_string_primitives_and_String_objects">Distinction between string primitives and <code>String</code> objects</h3> + +<p>Note that JavaScript distinguishes between <code>String</code> objects and primitive string values. (The same is true of {{jsxref("Boolean")}} and {{jsxref("Global_Objects/Number", "Numbers")}}.)</p> + +<p>String literals (denoted by double or single quotes) and strings returned from <code>String</code> calls in a non-constructor context (i.e., without using the {{jsxref("Operators/new", "new")}} keyword) are primitive strings. JavaScript automatically converts primitives to <code>String</code> objects, so that it's possible to use <code>String</code> object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.</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>String primitives and <code>String</code> objects also give different results when using {{jsxref("Global_Objects/eval", "eval()")}}. Primitives passed to <code>eval</code> are treated as source code; <code>String</code> objects are treated as all other objects are, by returning the object. For example:</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>For these reasons, code may break when it encounters <code>String</code> objects when it expects a primitive string instead, although generally authors need not worry about the distinction.</p> + +<p>A <code>String</code> object can always be converted to its primitive counterpart with the {{jsxref("String.prototype.valueOf()", "valueOf()")}} method.</p> + +<pre class="brush: js">console.log(eval(s2.valueOf())); // returns the number 4 +</pre> + +<div class="note"><strong>Note:</strong> For another possible approach to strings in JavaScript, please read the article about <a href="/en-US/Add-ons/Code_snippets/StringView"><code>StringView</code> — a C-like representation of strings based on typed arrays</a>.</div> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt>{{jsxref("String.prototype")}}</dt> + <dd>Allows the addition of properties to a <code>String</code> object.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{jsxref("String.fromCharCode()")}}</dt> + <dd>Returns a string created by using the specified sequence of Unicode values.</dd> + <dt>{{jsxref("String.fromCodePoint()")}} {{experimental_inline}}</dt> + <dd>Returns a string created by using the specified sequence of code points.</dd> + <dt>{{jsxref("String.raw()")}} {{experimental_inline}}</dt> + <dd>Returns a string created from a raw template string.</dd> +</dl> + +<h2 id="String_generic_methods"><code>String</code> generic methods</h2> + +<div class="warning"> +<p><strong>String generics are non-standard, deprecated and will get removed near future</strong>.</p> +</div> + +<p>The <code>String</code> instance methods are also available in Firefox as of JavaScript 1.6 (<strong>not</strong> part of the ECMAScript standard) on the <code>String</code> object for applying <code>String</code> methods to any object:</p> + +<pre class="brush: js">var num = 15; +console.log(String.replace(num, /5/, '2')); +</pre> + +<p>For migrating away from String generics, see also <a href="/en-US/docs/Web/JavaScript/Reference/Errors/Deprecated_string_generics">Warning: String.x is deprecated; use String.prototype.x instead</a>.</p> + +<p>{{jsxref("Global_Objects/Array", "Generics", "#Array_generic_methods", 1)}} are also available on {{jsxref("Array")}} methods.</p> + +<h2 id="String_instances"><code>String</code> instances</h2> + +<h3 id="Properties_2">Properties</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Properties')}}</div> + +<h3 id="Methods_2">Methods</h3> + +<h4 id="Methods_unrelated_to_HTML">Methods unrelated to HTML</h4> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Methods_unrelated_to_HTML')}}</div> + +<h4 id="HTML_wrapper_methods">HTML wrapper methods</h4> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'HTML_wrapper_methods')}}</div> + +<h2 id="Examples">Examples</h2> + +<h3 id="String_conversion">String conversion</h3> + +<p>It's possible to use <code>String</code> as a "safer" {{jsxref("String.prototype.toString()", "toString()")}} alternative, although it still normally calls the underlying <code>toString()</code>. It also works for {{jsxref("null")}}, {{jsxref("undefined")}}, and for {{jsxref("Symbol", "symbols")}}. For example:</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="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.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5', 'String')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-string-objects', 'String')}}</td> + <td>{{Spec2('ES2015')}}</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">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.String")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{domxref("DOMString")}}</li> + <li><a href="/en-US/Add-ons/Code_snippets/StringView"><code>StringView</code> — a C-like representation of strings based on typed arrays</a></li> + <li><a href="/en-US/docs/Web/API/DOMString/Binary">Binary strings</a></li> +</ul> diff --git a/files/tr/web/javascript/reference/global_objects/string/substring/index.html b/files/tr/web/javascript/reference/global_objects/string/substring/index.html new file mode 100644 index 0000000000..d3a177406c --- /dev/null +++ b/files/tr/web/javascript/reference/global_objects/string/substring/index.html @@ -0,0 +1,149 @@ +--- +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>The <strong><code>substring()</code></strong> method returns a subset of a <code>string</code> between one index and another, or through the end of the string.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>str</var>.substring(<var>indexStart</var>[, <var>indexEnd</var>])</code></pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt><code><var>indexStart</var></code></dt> + <dd>An integer between <code>0</code> and the length of the string, specifying the offset into the string of the first character to include in the returned substring.</dd> + <dt><code>indexEnd</code></dt> + <dd>Optional. An integer between <code>0</code> and the length of the string, which specifies the offset into the string of the first character <strong>not</strong> to include in the returned substring.</dd> +</dl> + +<h3 id="Dönen_değer">Dönen değer</h3> + +<p>A new string containing the extracted section of the given string.</p> + +<h2 id="Açıklama">Açıklama</h2> + +<p><code>substring()</code> extracts characters from <code>indexStart</code> up to <em>but not including</em> <code>indexEnd</code>. In particular:</p> + +<ul> + <li>If <code><var>indexStart </var></code>equals <code><var>indexEnd</var></code>, <code>substring()</code> returns an empty string.</li> + <li>If <code>indexEnd</code> is omitted, <code>substring()</code> extracts characters to the end of the string.</li> + <li>If either argument is less than 0 or is {{jsxref("NaN")}}, it is treated as if it were 0.</li> + <li>If either argument is greater than <code>stringName.length</code>, it is treated as if it were <code>stringName.length</code>.</li> +</ul> + +<p>If <code>indexStart</code> is greater than <code>indexEnd</code>, then the effect of <code>substring()</code> is as if the two arguments were swapped; for example, <code><em>str</em>.substring(1, 0) == <em>str</em>.substring(0, 1)</code>.</p> + +<h2 id="Örnekler">Örnekler</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 'Moz' +console.log(anyString.substring(0, 3)); +console.log(anyString.substring(3, 0)); + +// Displays 'lla' +console.log(anyString.substring(4, 7)); +console.log(anyString.substring(4)); +console.log(anyString.substring(7, 4)); + +// Displays 'Mozill' +console.log(anyString.substring(0, 6)); + +// 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="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> into <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"> + <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>Implemented in JavaScript 1.0.</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('ES6', '#sec-string.prototype.substring', 'String.prototype.substring')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.substring', 'String.prototype.substring')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tarayıcı_uyumluluğu">Tarayıcı uyumluluğu</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="Ayrıca_bakınız">Ayrıca bakınız</h2> + +<ul> + <li>{{jsxref("String.prototype.substr()")}}</li> + <li>{{jsxref("String.prototype.slice()")}}</li> +</ul> diff --git a/files/tr/web/javascript/reference/index.html b/files/tr/web/javascript/reference/index.html new file mode 100644 index 0000000000..b54be98c56 --- /dev/null +++ b/files/tr/web/javascript/reference/index.html @@ -0,0 +1,48 @@ +--- +title: JavaScript Referansı +slug: Web/JavaScript/Reference +tags: + - JavaScript +translation_of: Web/JavaScript/Reference +--- +<div>{{JsSidebar}}</div> + +<p>This part of the JavaScript section on MDN serves as a repository of facts about the JavaScript language. Read more <a href="/en-US/docs/Web/JavaScript/Reference/About">about this reference</a>.</p> + +<h2 id="Global_Objects">Global Objects</h2> + +<p>This chapter documents all the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects">JavaScript standard built-in objects</a>, along with their methods and properties.</p> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects', 'Standard objects (by category)')}}</div> + +<h2 id="Statements">Statements</h2> + +<p>This chapter documents all the <a href="/en-US/docs/Web/JavaScript/Reference/Statements">JavaScript statements and declarations</a>.</p> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Statements', 'Statements_and_declarations_by_category')}}</div> + +<h2 id="Expressions_and_operators">Expressions and operators</h2> + +<p>This chapter documents all the <a href="/en-US/docs/Web/JavaScript/Reference/Operators">JavaScript expressions and operators</a>.</p> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Operators', 'Expressions_and_operators_by_category')}}</div> + +<h2 id="Functions">Functions</h2> + +<p>This chapter documents how to work with <a href="/en-US/docs/Web/JavaScript/Reference/Functions">JavaScript functions</a> to develop your applications.</p> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments"><code>arguments</code></a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">Arrow functions</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters">Default parameters</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">Rest parameters</a></li> +</ul> + +<h2 id="Additional_reference_pages">Additional reference pages</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar">Lexical grammar</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Data_structures">Data types and data structures</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">Strict mode</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features">Deprecated features</a></li> +</ul> diff --git a/files/tr/web/javascript/reference/lexical_grammar/index.html b/files/tr/web/javascript/reference/lexical_grammar/index.html new file mode 100644 index 0000000000..6ea10234bc --- /dev/null +++ b/files/tr/web/javascript/reference/lexical_grammar/index.html @@ -0,0 +1,379 @@ +--- +title: Lexical grammar +slug: Web/JavaScript/Reference/Lexical_grammar +translation_of: Web/JavaScript/Reference/Lexical_grammar +--- +<p>{{JsSidebar ("Daha çox")}}</p> + +<p>Bu səhifə JavaScript-in leksik qrammatikasını təsvir edir. ECMAScript skriptlərinin mənbə mətni soldan sağa taranır və ayələr, nəzarət simvolları, xətt terminatorları, şərhlər və ya ağ boşluq olan giriş elementlərinin ardıcıllığına çevrilir. ECMAScript, həmçinin müəyyən açar sözlər və hərfləri müəyyənləşdirir və ifadələri sona çatdırmaq üçün nöqtəli vergüllərə avtomatik qoşulma qaydalarına malikdir.</p> + +<p>Nəzarət simvolları<br> + İdarəetmə simvollarının vizual nümayəndəliyi yoxdur, ancaq mətnin şərhini idarə etmək üçün istifadə olunur.</p> + +<p>Unicode formatına nəzarət simvolları<br> + Kod nöqtəsi Adı Qısaldılması Təsviri<br> + U + 200C Sıfır eni qoşulmayan <ZWNJ> Müəyyən dillərdə ligaturlara qoşulmamaq üçün simvolların arasına yerləşdirilib (Wikipedia).<br> + U + 200D Sıfır eniştiricisi <ZWJ> İşarələrin müəyyən dillərdə (Wikipedia) əlaqəli formasından istifadə olunmasına səbəb olmaq üçün ümumiyyətlə bağlanmayacaq simvollar arasında yerləşdirilmişdir.<br> + U + FEFF Bayt sifariş nişanı <BOM> Skriptin əvvəlində onu Unicode və mətnin bayt sifarişi (Wikipedia) kimi qeyd etmək üçün istifadə olunur.<br> + Ağ boşluq<br> + Ağ boşluq simvolları mənbə mətninin oxunuşunu yaxşılaşdırır və ayələrini bir-birindən ayırır. Bu işarələr ümumiyyətlə kodun işləməsi üçün lazımsızdır. Transfer edilməsi lazım olan məlumatların miqdarını azaltmaq üçün tez-tez boşluq silmək üçün minifikasiya vasitələri istifadə olunur.</p> + +<p>Ağ boşluq simvolları<br> + Kod nöqtəsi Adı Qısaldılması Təsvir Escape ardıcıllığı<br> + U + 0009 Xarakter cədvəli <HT> Üfüqi cədvəl \ t<br> + U + 000B Xətt cədvəli <VT> Şaquli cədvəl \ v<br> + U + 000C Forma yemi <FF> Səhifəni pozan idarəetmə xarakteri (Wikipedia). \ f<br> + U + 0020 Məkan <SP> Normal yer<br> + U + 00A0 Arası olmayan yer <NBSP> Normal yer, lakin xəttin qırıla biləcəyi nöqtə yoxdur<br> + Digərləri Digər Unicode kosmik simvolları <USP> Wikipedia'dakı Unicode'dakı boşluqlar<br> + Xətt terminatorları<br> + Ağ boşluq simvollarına əlavə olaraq, mənbə mətninin oxunuşunu yaxşılaşdırmaq üçün xətt terminatoru simvolları istifadə olunur. Bununla birlikdə, bəzi hallarda, xətt terminatorları JavaScript kodunun icrasına təsir göstərə bilər, çünki qadağan edilmiş bir neçə yer var. Xətt terminatorları avtomatik nöqtəli vergül daxil edilməsi prosesinə də təsir göstərir. Sətir terminatorları müntəzəm ifadələrdə siniflər tərəfindən uyğunlaşdırılır.</p> + +<p>Yalnız aşağıdakı Unicode kod nöqtələrinə ECMAScript-də xətt terminatoru kimi baxılır, digər xətt kəsici simvollara ağ boşluq kimi baxılır (məsələn, Next Line, NEL, U + 0085 ağ boşluq sayılır).</p> + +<p>Xətt terminatoru simvolları<br> + Kod nöqtəsi Adı Qısaldılması Təsvir Escape ardıcıllığı<br> + U + 000A Line Feed <LF> UNIX sistemlərində yeni xətt xarakteri. \ n<br> + U + 000D Daşımanın qaytarılması <CR> Commodore və erkən Mac sistemlərində yeni xətt xarakteri. \ r<br> + U + 2028 Xət ayırıcı <LS> Vikipediya<br> + U + 2029 Paraqraf ayırıcı <PS> Wikipedia<br> + Şərhlər<br> + Şərhlər JavaScript koduna işarə, qeyd, təklif və ya xəbərdarlıq əlavə etmək üçün istifadə olunur. Bu oxumağı və başa düşməyi asanlaşdıra bilər. Kodun icra edilməməsi üçün deaktiv edilmək üçün istifadə edilə bilər; bu dəyərli ayıklama vasitəsi ola bilər.</p> + +<p>JavaScript'də şərhə əlavə etmək üçün uzun müddətdir davam edən iki yol var.</p> + +<p>Birinci yol // şərh; bu eyni sətirdə onu izləyən bütün mətnləri bir şərh halına gətirir. Misal üçün:</p> + +<p>funksiya comment () {<br> + // Bu bir xəttli JavaScript şərhidir<br> + console.log ('Salam dünya!');<br> + }<br> + Şərh();<br> + İkinci yol daha çevik olan / * * / üslubdur.</p> + +<p>Məsələn, bir xəttdə istifadə edə bilərsiniz:</p> + +<p>funksiya comment () {<br> + / * Bu bir xəttli JavaScript şərhidir * /<br> + console.log ('Salam dünya!');<br> + }<br> + Şərh();<br> + Bununla yanaşı, çox sətirli şərhlər edə bilərsiniz:</p> + +<p>funksiya comment () {<br> + / * Bu şərh çox sətri əhatə edir. Xəbərdarlıq<br> + başa çatana qədər şərhə son qoymaq lazım deyil. * /<br> + console.log ('Salam dünya!');<br> + }<br> + Şərh();<br> + İstəsəniz, bir xəttin ortasında da istifadə edə bilərsiniz, baxmayaraq ki bu kodunuzu oxumağı çətinləşdirə bilər, buna görə ehtiyatla istifadə olunmalıdır:</p> + +<p>funksiya şərhi (x) {<br> + console.log ('Salam' + x / * x * / + '!' dəyərini daxil edin);<br> + }<br> + şərh ('dünya');<br> + Bundan əlavə, kodu bir şərhə bağlayaraq işə salmamaq üçün kodu deaktiv etmək üçün istifadə edə bilərsiniz:</p> + +<p>funksiya comment () {<br> + / * console.log ('Salam dünya!'); * /<br> + }<br> + Şərh();<br> + Bu vəziyyətdə, konsol.log () çağırışı heç bir şərh daxilində olmadığı üçün verilmir. İstənilən sayda kod xətti bu şəkildə əlil ola bilər.</p> + +<p>Hashbang şərhləri<br> + Xüsusi üçüncü bir şərh sintaksisi, hashbang comment, ECMAScript-də standartlaşdırılma mərhələsindədir (Hashbang Qrammatikası təklifinə baxın).</p> + +<p>Bir hashbang şərhini yalnız bir xətt (yalnız) şərh kimi edir. Bunun əvəzinə # ilə başlayır! və yalnız bir yazı və ya modulun mütləq başlanğıcında etibarlıdır. Nəzərə alın ki, hər hansı bir boşluq # # -dan əvvəl icazə verilmir. Şərh # sonrakı bütün simvollardan ibarətdir! birinci sətrin sonuna qədər; yalnız bir belə şərhə icazə verilir.</p> + +<p>Hashbang şərh, skriptin icrası üçün istifadə etmək istədiyiniz xüsusi JavaScript tərcüməçisinə gedən yolu göstərir. Nümunə aşağıdakı kimidir:</p> + +<p>#! / usr / bin / env node</p> + +<p>console.log ("Salam dünya");<br> + Qeyd: JavaScript-dəki Hashbang şərhləri Unix-də təqlid olunan shebangs-ləri faylları düzgün tərcüməçi ilə işlədirdi.</p> + +<p>Hashbang şərhindən əvvəl BOM bir brauzerdə işləsə də, BOM-u hasbang yazılmış bir skriptdə istifadə etmək tövsiyə edilmir. Unix / Linux-da skript işə saldığınız zaman BOM işləməyəcək. Skriptləri birbaşa işlətmək istəyirsinizsə UTF-8-ni BOM olmadan istifadə edin</p> + +<p>qabıqdan.</p> + +<p>Yalnız # istifadə etməlisiniz! JavaScript tərcüməçisini təyin etmək üçün şərh tərzi. Digər bütün hallarda sadəcə bir // şərh (və ya mulitiline comment) istifadə edin.</p> + +<p>Açar sözlər<br> + ECMAScript 2015 kimi qorunan açar sözlər<br> + {{jsxref ("Bəyanatlar / break", "break")}}<br> + {{jsxref ("Bəyanatlar / keçid", "dava")}}<br> + {{jsxref ("Bəyanatlar / çalışın ... tutun", "tutun")}}<br> + {{jsxref ("Bəyanatlar / sinif", "sinif")}}<br> + {{jsxref ("Bəyanatlar / const", "const")}}<br> + {{jsxref ("Bəyanatlar / davam et", "davam et")}}<br> + {{jsxref ("Bəyanatlar / debugger", "debugger")}}<br> + {{jsxref ("Bəyanatlar / default", "default")}}<br> + {{jsxref ("Operatorlar / silmək", "Sil")}}<br> + {{jsxref ("Bəyanatlar / etmək ... edərkən", "etmək")}}<br> + {{jsxref ("Bəyanatlar / əgər ... başqa", "başqa")}}<br> + {{jsxref ("Bəyanatlar / ixrac", "ixrac")}}<br> + {{jsxref ("Bəyanatlar / sinif", "uzanır")}}<br> + {{jsxref ("Bəyanatlar / cəhd edin ... tutun", "nəhayət")}}<br> + {{jsxref ("Bəyanatlar / üçün", "üçün")}}<br> + {{jsxref ("Bildirişlər / funksiya", "funksiya")}}<br> + {{jsxref ("Bəyanatlar / əgər ... başqa", "əgər")}}<br> + {{jsxref ("Bəyanatlar / idxal", "idxal")}}<br> + {{jsxref ("Operatorlar / ilə", "in")}}<br> + {{jsxref ("Əməliyyatçılar / instanceof", "instanceof")}}<br> + {{jsxref ("Operatorlar / yeni", "yeni")}}<br> + {{jsxref ("Bəyanatlar / qayıt", "qayıt")}}<br> + {{jsxref ("Əməliyyatçılar / super", "super")}}<br> + {{jsxref ("Bəyanatlar / keçid", "keçid")}}<br> + {{jsxref ("Əməliyyatçılar / bu", "bu")}}<br> + {{jsxref ("Bəyanatlar / atmaq", "atmaq")}}<br> + {{jsxref ("Bəyanatlar / cəhd edin ... tutun", "cəhd edin")}}<br> + {{jsxref ("Operatorlar / typeof", "typeof")}}<br> + {{jsxref ("Bəyanatlar / var", "var")}}<br> + {{jsxref ("Operatorlar / etibarsız", "etibarsız")}}<br> + {{jsxref ("Bəyanatlar / edərkən", "isə")}}<br> + {{jsxref ("Bəyanatlar / ilə", "ilə")}}<br> + {{jsxref ("Əməliyyatçılar / məhsuldarlıq", "gəlir")}}<br> + Gələcək qorunan açar sözlər<br> + Aşağıdakılar ECMAScript spesifikasiyası ilə gələcək açar sözlər kimi qorunur. Hal-hazırda onların heç bir xüsusi funksionallığı yoxdur, lakin gələcəkdə də ola bilər, buna görə identifikator kimi istifadə edilə bilməzlər.</p> + +<p>Bunlar həmişə qorunur:</p> + +<p>enum<br> + Aşağıdakılar yalnız ciddi rejim kodlarında tapıldıqda qorunur:</p> + +<p>tətbiq edir<br> + interfeysi<br> + {{jsxref ("Bəyanatlar / qoy", "qoy")}}<br> + paket<br> + özəl<br> + qorunur<br> + ictimai<br> + statik<br> + Aşağıdakılar yalnız modul kodu tapdıqda qorunur:</p> + +<p>gözləmək<br> + Gələcəkdə köhnə standartlarda qorunan açar sözlər<br> + Aşağıdakılar köhnə ECMAScript xüsusiyyətlərinə görə gələcək açar sözlər olaraq qorunur (ECMAScript 1-dən 3-ə qədər).</p> + +<p>mücərrəd<br> + boolean<br> + bayt<br> + char<br> + ikiqat<br> + final<br> + sal<br> + getmək<br> + int<br> + uzun<br> + doğma<br> + qısa<br> + sinxronizasiya olunur<br> + atır<br> + keçici<br> + uçucu<br> + Bundan əlavə, null, əsl və yalnış hərflər ECMAScript-də identifikator kimi istifadə edilə bilməz.</p> + +<p>Ehtiyat söz istifadəsi<br> + Qorunan sözlər əslində yalnız identifikatorlara aiddir (identifikator adları). Es5.github.com/#A.1-də təsvir olunduğu kimi, bunlar hamısı ReserveWords-ı istisna etməyən identifikator adlarıdır.</p> + +<p>a.import<br> + a ['idxal']<br> + a = {idxal: 'test'}.<br> + Digər tərəfdən aşağıdakılar qanunsuzdur, çünki qorunan sözlər olmadan bir identifikator adıdır. Eyniləşdiricilər FunctionDeclaration, FunctionExpression, Dəyişən Deklarasiya və s. Üçün istifadə olunur. Identifikator adları MemberExpression, CallExpression və s. Üçün istifadə olunur.</p> + +<p>funksiya import () {} // qeyri-qanuni.<br> + Xüsusi mənaları olan identifikatorlar<br> + Bəzi identifikatorların heç bir növ açar sözlər olmadan bəzi məzmunlarda xüsusi bir mənası var. Bunlara daxildir:</p> + +<p>bu sintaksis ECMAScript 2015-də yenidir, brauzer uyğunluğu cədvəlinə baxın. 0o-dan sonrakı rəqəmlər (01234567) aralığın xaricindədirsə, aşağıdakı {{jsxref ("SyntaxError")}} atılır: "0o-dan sonra itmiş səkkizbucaqlı rəqəmlər".</p> + +<p>var n = 0O755; // 493<br> + var m = 0o644; // 420</p> + +<p>// Yalnız bir aparıcı sıfır ilə mümkündür (yuxarıdakı onluğa dair qeydə baxın)<br> + 0755<br> + 0644<br> + Altıbucaqlıdır<br> + Hexadecimal nömrə sintaksisində kiçik və ya böyük hərfli Latın "X" (0x və ya 0X) hərfinin ardınca aparıcı sıfır istifadə olunur. 0x-dən sonra rəqəmlər aralığın xaricindədirsə (0123456789ABCDEF), aşağıdakı {{jsxref ("SyntaxError")}} atılır: "Identifikator rəqəmli hərfdən dərhal sonra başlayır".</p> + +<p>0xFFFFFFFFFFFFFFFFF // 295147905179352830000<br> + 0x123456789ABCDEF // 81985529216486900<br> + 0XA // 10<br> + BigInt hərfi<br> + {{Jsxref ("BigInt")}} növü JavaScript-də ixtiyari dəqiqliklə tam ədədləri təmsil edə bilən ədədi ibtidai. BigInt hərfləri tam ədədin sonuna n əlavə etməklə yaradılır.</p> + +<p>123456789123456789n // 123456789123456789<br> + 0o777777777777n // 68719476735<br> + 0x123456789ABCDEFn // 81985529216486895<br> + 0b11101001010101010101n // 955733<br> + Qeyd edək ki, yalnız bir lider sıfır olan köhnə səkkizbucaqlı rəqəmlər BigInt üçün işləməyəcək:</p> + +<p>// 0755n<br> + // SyntaxError: etibarsız BigInt sintaksisi<br> + Səkkizbucaqlı BigInt nömrələri üçün hər zaman sıfırdan sonra "o" hərfi ilə (böyük və ya kiçik hərf) istifadə edin:</p> + +<p>0o755n<br> + BigInt haqqında daha çox məlumat üçün JavaScript məlumat strukturlarına da baxın.</p> + +<p>Sayısal ayırıcılar<br> + Rəqəmsal hərflərin oxunuşunu yaxşılaşdırmaq üçün alt nöqtələrdən (_, U + 005F) ayırıcı kimi istifadə edilə bilər</p> + +<p>// onluq sayda ayırıcılar<br> + 1_000_000_000_000<br> + 1_050.95</p> + +<p>// ikili nömrələrdə ayırıcılar<br> + 0b1010_0001_1000_0101</p> + +<p>// səkkizbucaqlı ədədlərdə ayrıcılar<br> + 0o2_2_5_6</p> + +<p>// hex ədədlərindəki ayırıcılar<br> + 0xA0_B0_C0</p> + +<p>// BigInts-də ayırıcılar<br> + 1_000_000_000_000_000_000_000n<br> + Bu məhdudiyyətlərə diqqət yetirin:</p> + +<p>// Bir dəfədən çox alt qeyd etməyə icazə verilmir<br> + 100__000; // Söz düzümü səhvi</p> + +<p>// Rəqəmsal hərflərin sonunda icazə verilmir<br> + 100_; // Söz düzümü səhvi</p> + +<p>// 0-dan sonra istifadə edilə bilməz<br> + 0_1; // Söz düzümü səhvi<br> + Obyekt hərfləri<br> + Əlavə məlumat üçün {{jsxref ("Obyekt")}} və Obyekt başlatıcısına da baxın.</p> + +<p>var o = {a: 'foo', b: 'bar', c: 42};</p> + +<p>// stenoqram notation. ES2015-də yenidir<br> + var a = 'foo', b = 'bar', c = 42;<br> + var o = {a, b, c};</p> + +<p>// əvəzinə<br> + var o = {a: a, b: b, c: c};<br> + Sıra hərfləri<br> + Əlavə məlumat üçün {{jsxref ("Array")}} da baxın.</p> + +<p>[1954, 1974, 1990, 2014]<br> + Simli hərflər<br> + Sətir hərfi sıfır və ya daha çox və ya ikiqat tirnoqla əlavə olunmuş Unicode kod nöqtələridir. Unicode kod nöqtələri də bir qaçış ardıcıllığı ilə təmsil oluna bilər. Bütün bağ nöqtələri sözün həqiqi kod nöqtələri istisna olmaqla hərfi mənada bir simli olaraq görünə bilər:</p> + +<p>U + 005C \ (arxa cığır),<br> + U + 000D <CR>,<br> + və U + 000A <LF>.<br> + Bütün JSON mətnini etibarlı ECMA-262, U + 2028 <LS> və U + 2029 <PS> etiketli etmək təklifindən əvvəl də simli hərflərdə görünməməsi qadağan edildi.</p> + +<p>Hər hansı bir kod nöqtəsi qaçış ardıcıllığı şəklində görünə bilər. String hərfləri ECMAScript String dəyərlərini qiymətləndirir. Bu Sətir dəyərlərini yaradan zaman Unicode kod nöqtələri UTF-16 kodlanır.</p> + +<p>'foo'<br> + "bar"<br> + Hexadecimal escape ardıcıllığı<br> + Hexadecimal escape ardıcıllığı, 0x0000 ilə 0x00FF aralığında bir kod vahidi və ya kod nöqtəsini təmsil edən iki iki altıbucaqlı rəqəmin ardınca \ x ibarətdir.</p> + +<p>'\ xA9' // "©"<br> + Unicode qaçış ardıcıllığı<br> + Unicode qaçış ardıcıllığı tam olaraq dörd altıbucaqlı rəqəmlərdən ibarətdir \ u. UTF-16 kodlaşdırmada bir kod vahidini təmsil edir. U + 0000 ilə U + FFFF kod nöqtələri üçün kod vahidi kod nöqtəsinə bərabərdir. U + 10000 ilə U + 10FFFF kod nöqtələri, xarakteri kodlamaq üçün istifadə olunan iki kod vahidini (bir surroqat cütü) təmsil edən iki qaçış ardıcıllığını tələb edir; surroqat cütlüyü kod nöqtəsindən fərqlidir.</p> + +<p>Buna da baxın: {{jsxref ("String.fromCharCode ()")}} və {{jsxref ("String.prototype.charCodeAt ()")}}.</p> + +<p>'\ u00A9' // "©" (U + A9)<br> + Unicode kod nöqtəsi qaçır<br> + Unicode kod nöqtəsindən qaçış \ u {, ardından altıbucaqlı bazada kod nöqtəsi, ardınca} daxil edilir. Altıbucaqlı rəqəmlərin dəyəri 0 ilə 0x10FFFF arasında olmalıdır. U + 10000 ilə U + 10FFFF arasındakı kod nöqtələrinin surroqat cütü kimi göstərilməsinə ehtiyac yoxdur. Kod nöqtələrinin qaçışları ECMAScript 2015 (ES6) -də JavaScript-ə əlavə edildi.</p> + +<p>Buna da baxın: {{jsxref ("String.fromCodePoint ()")}} və {{jsxref ("String.prototype.codePointAt ()")}}.</p> + +<p>'\ u {2F804}' // CJK uyğunluğu İDEOĞRAF-2F804 (U + 2F804)</p> + +<p>// eyni xarakterli bir surroqat cütü olaraq təmsil olunur<br> + '\ uD87E \ uDC04'<br> + Daimi ifadə hərfi<br> + Əlavə məlumat üçün {{jsxref ("RegExp")}} də baxın.</p> + +<p>/ ab + c / g</p> + +<p>// Bir "boş" müntəzəm ifadə<br> + // Boş tutmayan qrup lazımdır<br> + // tək sətirli şərhlərlə qeyri-müəyyənliyə yol verməmək.<br> + / (?:) /<br> + Şablon hərfləri<br> + Daha çox məlumat üçün şablon iplərinə baxın.</p> + +<p>`simli mətn`</p> + +<p>`simli mətn xətti 1<br> + simli mətn xətti 2`</p> + +<p>`string mətni $ {ifadə} simli mətn '</p> + +<p>etiketli "string mətni $ {ifadə} string mətni"<br> + Avtomatik nöqtəli vergül<br> + Bəzi JavaScript ifadələri nöqtəli vergul ilə dayandırılmalı və buna görə də</p> + +<p>avtomatik nöqtəli vergül daxil edilməsindən təsirləndi (ASI):</p> + +<p>Boş bəyanat<br> + qoy, const, dəyişən bir ifadə<br> + idxal, ixrac, modul bəyannaməsi<br> + İfadə ifadəsi<br> + debugger<br> + davam etmək, qırmaq, atmaq<br> + qayıtmaq<br> + ECMAScript spesifikasiyası nöqtəli vergül daxil edilməsinin üç qaydasını xatırladır.</p> + +<p>1. Bir xətt terminatoru və ya "}" ilə qarşılaşdıqda, qrammatika tərəfindən icazə verilməyən nöqtələrə vergül qoyulur.</p> + +<p>{1 2} 3</p> + +<p>// ASI tərəfindən çevrilir</p> + +<p>{1 2;} 3;<br> + 2. Ayələr giriş axınının sonu aşkar edildikdə və analizator bir giriş axını tam bir proqram olaraq təhlil edə bilmədikdə son nöqtəyə nöqtə qoyulur.</p> + +<p>Burada ++ dəyişən b tətbiq olunan bir postfiks operatoru kimi qəbul edilmir, çünki b və ++ arasında bir xətt terminatoru meydana gəlir.</p> + +<p>a = b<br> + ++ c</p> + +<p>// ASI tərəfindən dəyişdirilir</p> + +<p>a = b;<br> + ++ c;<br> + 3. Sonunda nöqtə vergül qoyulur, qrammatikada məhdud məhsullar olan bir söz bir xətt terminatoru izlədikdə. "Burada LineTerminator yoxdur" qaydaları olan bu ifadələr:</p> + +<p>Postfiks İfadə (++ və -)<br> + davam edin<br> + fasilə<br> + qayıtmaq<br> + gəlir, gəlir *<br> + modul<br> + qayıtmaq<br> + a + b</p> + +<p>// ASI tərəfindən çevrilir</p> + +<p>qayıtmaq;<br> + a + b;<br> + Texniki şərtlər<br> + Xüsusiyyət<br> + {{SpecName ('ESDraft', '# sec-ecmascript-language-leksik-qrammatika', 'Leksik qrammatika')}}<br> + Brauzer uyğunluğu<br> + Bu səhifədəki uyğunluq cədvəli strukturlaşdırılmış məlumatlardan hazırlanmışdır. Verilənlərə töhfə vermək istəyirsinizsə, lütfən https://github.com/mdn/browser-compat-data-ya baxın və bizə bir sorğu göndərin.<br> + {{Compat ("javascript.grammar")}}</p> + +<p>İcra Tərəqqi<br> + Aşağıdakı cədvəl bu xüsusiyyət üçün gündəlik tətbiq statusunu təmin edir, çünki bu xüsusiyyət hələ brauzer sabitliyinə çatmamışdır. Verilənlər, Gecə qurulması və ya hər brauzerin JavaScript mühərrikinin son buraxılışı olan Test262, JavaScript standart test paketi ilə əlaqəli xüsusiyyət testlərini aparmaqla yaradılır.</p> + +<p>{{EmbedTest262ReportResultsTable ("hashbang")}}<br> + Həmçinin bax<br> + Jeff Walden: İkili və səkkizbucaqlı ədədlər<br> + Mathias Bynens: JavaScript xarakter qaçış ardıcıllığı<br> + {{jsxref ("Boolean")}}<br> + {{jsxref ("Sayı")}}<br> + {{jsxref ("RegExp")}}<br> + {{jsxref ("Sətir")}}</p> + +<ul> +</ul> diff --git a/files/tr/web/javascript/reference/operatörler/arithmetic_operators/index.html b/files/tr/web/javascript/reference/operatörler/arithmetic_operators/index.html new file mode 100644 index 0000000000..e78a71c2d9 --- /dev/null +++ b/files/tr/web/javascript/reference/operatörler/arithmetic_operators/index.html @@ -0,0 +1,293 @@ +--- +title: Arithmetic operators +slug: Web/JavaScript/Reference/Operatörler/Arithmetic_Operators +tags: + - Aritmetik Operatörler + - JavaScript +translation_of: Web/JavaScript/Reference/Operators +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>Aritmetik operatörler</strong> sayısal değerleri (değişmez değerler veya değişkenler) kendi değişkeni olarak alır ve tek bir sayısal değer döndürür. Standart aritmetik operatörler toplama (+), çıkarma (-), çıkarma (*), ve bölme (/).</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-arithmetic.html")}}</div> + + + +<h2 id="Addition" name="Addition">Toplama (+)</h2> + +<p>Toplama işleci, sayısal değişkenlerin veya dize birleşiminin toplamını üretir.</p> + +<h3 id="Syntax">Syntax</h3> + +<pre class="syntaxbox"><strong>Operator:</strong> x + y +</pre> + +<h3 id="Examples">Examples</h3> + +<pre class="brush: js">// Number + Number -> Toplama +1 + 2 // 3 + +// Boolean + Number -> Toplama +true + 1 // 2 + +// Boolean + Boolean -> Toplama +false + false // 0 + +// Number + String -> Birleşim +5 + 'foo' // "5foo" + +// String + Boolean -> Birleşim +'foo' + false // "foofalse" + +// String + String -> Birleşim +'foo' + 'bar' // "foobar" +</pre> + +<h2 id="Subtraction" name="Subtraction">Çıkarma (-)</h2> + +<p>Çıkarma işleci (operator), iki değişkeni çıkarır ve farklarını üretir.</p> + +<h3 id="Söz_Dizimi">Söz Dizimi</h3> + +<pre class="syntaxbox"><strong>Operator:</strong> x - y +</pre> + +<h3 id="Örnekler">Örnekler</h3> + +<pre class="brush: js">5 - 3 // 2 +3 - 5 // -2 +'foo' - 3 // NaN(Sayı Değil)</pre> + +<h2 id="Division" name="Division">Bölme (/)</h2> + +<p>Bölme operatörü, sol değişkenin bölüm olduğu ve sağ değişkenin bölen olduğu işlenenlerin bölümünü üretir.</p> + +<h3 id="Söz_Dizimi_2">Söz Dizimi</h3> + +<pre class="syntaxbox"><strong>Operator:</strong> x / y +</pre> + +<h3 id="Örnekler_2">Örnekler</h3> + +<pre class="brush: js">1 / 2 // 0.5 döndürür +1 / 2 // Java''da 0 döndürür +// (her iki sayı da açıkça kayan nokta sayısıdır) + +1.0 / 2.0 // JavaScript ve Java 0.5 döndürür + +2.0 / 0 // JavaScript sonsuz döndürür +2.0 / 0.0 // Sonsuzu da döndürür +2.0 / -0.0 // JavaScript eksi sonsuz da döndürür</pre> + +<h2 id="Multiplication" name="Multiplication">Çarpma (*)</h2> + +<p>Çarpma operatörü değişkenlerin ürününü üretir.</p> + +<h3 id="Söz_Dizimi_3">Söz Dizimi</h3> + +<pre class="syntaxbox"><strong>Operator:</strong> x * y +</pre> + +<h3 id="Örnekler_3">Örnekler</h3> + +<pre class="brush: js">2 * 2 // 4 +-2 * 2 // -4 +Infinity * 0 // NaN(Sayı Değil1) +Infinity * Infinity // Sonsuz +'foo' * 2 // NaN +</pre> + +<h2 id="Remainder" name="Remainder">Kalan (%)</h2> + +<p>Kalan operatörü, bir değişken ikinci bir değişken tarafından bölündüğünde kalan döndürür. Her zaman bölüm işareti alır.</p> + +<h3 id="Söz_Dizimi_4">Söz Dizimi</h3> + +<pre class="syntaxbox"><strong>Operator:</strong> var1 % var2 +</pre> + +<h3 id="Örnekler_4">Örnekler</h3> + +<pre class="brush: js">12 % 5 // 2 +-1 % 2 // -1 +1 % -2 // 1 +NaN % 2 // NaN +1 % 2 // 1 +2 % 3 // 2 +-4 % 2 // -0 +5.5 % 2 // 1.5 +</pre> + +<h2 id="Exponentiation" name="Exponentiation">Üs (**)</h2> + +<p>The exponentiation operator returns the result of raising first operand to the power second operand. That is, <code>var1</code><sup><code>var2</code></sup>, in the preceding statement, where <code>var1</code> and <code>var2</code> are variables. Exponentiation operator is right associative. <code>a ** b ** c</code> is equal to <code>a ** (b ** c)</code>.</p> + +<h3 id="Syntax_2">Syntax</h3> + +<pre class="syntaxbox"><strong>Operator:</strong> var1 ** var2 +</pre> + +<h3 id="Notes">Notes</h3> + +<p>In most languages like PHP and Python and others that have an exponentiation operator (**), the exponentiation operator is defined to have a higher precedence than unary operators such as unary + and unary -, but there are a few exceptions. For example, in Bash the ** operator is defined to have a lower precedence than unary operators. In JavaScript, it is impossible to write an ambiguous exponentiation expression, i.e. you cannot put a unary operator (<code>+/-/~/!/delete/void/typeof</code>) immediately before the base number.</p> + +<pre class="brush: js">-2 ** 2; +// 4 in Bash, -4 in other languages. +// This is invalid in JavaScript, as the operation is ambiguous. + + +-(2 ** 2); +// -4 in JavaScript and the author's intention is unambiguous. +</pre> + +<h3 id="Examples_2">Examples</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>To invert the sign of the result of an exponentiation expression:</p> + +<pre class="brush: js">-(2 ** 2) // -4 +</pre> + +<p>To force the base of an exponentiation expression to be a negative number:</p> + +<pre class="brush: js">(-2) ** 2 // 4 +</pre> + +<div class="note"> +<p><strong>Note:</strong> JavaScript also has <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_XOR">a bitwise operator ^ (logical XOR)</a>. <code>**</code> and <code>^</code> are different (for example : <code>2 ** 3 === 8</code> when <code>2 ^ 3 === 1</code>.)</p> +</div> + +<h2 id="Increment" name="Increment">Artırma (++)</h2> + +<p>Artış operatörü işlenenini artırır (bir ekler) ve bir değer döndürür.</p> + +<ul> + <li>İlk önce değişken adı kullanılırsa, değişkenden sonra operatörle (örneğin, x++) kullanılırsa artmadan önce değeri artırır ve döndürür.</li> + <li>Ön ek kullanılırsa, değişkenden önce operatörle (örneğin, ++x), daha sonra artırıldıktan sonra değeri artıtrır ve döndürür.</li> +</ul> + +<h3 id="Söz_Dizimi_5">Söz Dizimi</h3> + +<pre class="syntaxbox"><strong>Operator:</strong> x++ yada ++x +</pre> + +<h3 id="Örnekler_5">Örnekler</h3> + +<pre class="brush: js">// Postfix +var x = 3; +y = x++; // y = 3, x = 4 + +// Prefix +var a = 2; +b = ++a; // a = 3, b = 3 +</pre> + +<h2 id="Decrement" name="Decrement">Azaltma (--)</h2> + +<p>The decrement operator decrements (subtracts one from) its operand and returns a value.</p> + +<ul> + <li>If used postfix, with operator after operand (for example, x--), then it decrements and returns the value before decrementing.</li> + <li>If used prefix, with operator before operand (for example, --x), then it decrements and returns the value after decrementing.</li> +</ul> + +<h3 id="Syntax_3">Syntax</h3> + +<pre class="syntaxbox"><strong>Operator:</strong> x-- or --x +</pre> + +<h3 id="Examples_3">Examples</h3> + +<pre class="brush: js">// Postfix +var x = 3; +y = x--; // y = 3, x = 2 + +// Prefix +var a = 2; +b = --a; // a = 1, b = 1 +</pre> + +<h2 id="Unary_negation" name="Unary_negation">Unary negation (-)</h2> + +<p>The unary negation operator precedes its operand and negates it.</p> + +<h3 id="Syntax_4">Syntax</h3> + +<pre class="syntaxbox"><strong>Operator:</strong> -x +</pre> + +<h3 id="Examples_4">Examples</h3> + +<pre class="brush: js">var x = 3; +y = -x; // y = -3, x = 3 + +// Unary negation operator can convert non-numbers into a number +var x = "4"; +y = -x; // y = -4 +</pre> + +<h2 id="Unary_plus_2"><a name="Unary_plus">Unary plus</a> (+)</h2> + +<p>The unary plus operator precedes its operand and evaluates to its operand but attempts to convert it into a number, if it isn't already. Although unary negation (-) also can convert non-numbers, unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number. It can convert string representations of integers and floats, as well as the non-string values <code>true</code>, <code>false</code>, and <code>null</code>. Integers in both decimal and hexadecimal ("0x"-prefixed) formats are supported. Negative numbers are supported (though not for hex). If it cannot parse a particular value, it will evaluate to {{jsxref("NaN")}}.</p> + +<h3 id="Syntax_5">Syntax</h3> + +<pre class="syntaxbox"><strong>Operator:</strong> +x +</pre> + +<h3 id="Examples_5">Examples</h3> + +<pre class="brush: js">+3 // 3 ++'3' // 3 ++true // 1 ++false // 0 ++null // 0 ++function(val){ return val } // NaN +</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-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="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.operators.arithmetic")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators">Assignment operators</a></li> +</ul> diff --git a/files/tr/web/javascript/reference/operatörler/bitwise_operators/index.html b/files/tr/web/javascript/reference/operatörler/bitwise_operators/index.html new file mode 100644 index 0000000000..d2ad12abff --- /dev/null +++ b/files/tr/web/javascript/reference/operatörler/bitwise_operators/index.html @@ -0,0 +1,564 @@ +--- +title: Bitwise operators +slug: Web/JavaScript/Reference/Operatörler/Bitwise_Operators +translation_of: Web/JavaScript/Reference/Operators +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>Bitsel işleçler</strong> işlediği elemanlara ondalık, onaltılık veya <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number" title="/en-US/docs/JavaScript/Reference/Global_Objects/Number">sayılar</a></code> yerine 32 bit diziler(sıfır ve birler) olarak davranır. Örneğin, onluk bir sayı olan 9, ikilik sistemde 1001 ile gösterilir. Bitsel işleçler, işlemin iki tarafınada ikili değerleriyle işlem yapar ancak JavaScript standartı olan sayısal değerleri döner.</p> + +<p>Aşağıdaki tablo JavaScript'in bitsel işleçlerini özetler:</p> + +<table class="standard-table"> + <tbody> + <tr> + <th>Operator</th> + <th>Usage</th> + <th>Description</th> + </tr> + <tr> + <td><a href="#Bitwise_AND">Bitwise AND</a></td> + <td><code>a & b</code></td> + <td>Bitsel işleçin iki tarafının karşılık gelen bitleri 1 ise, en az bir tanesi 0 ise 0 döndürür.</td> + </tr> + <tr> + <td><a href="#Bitwise_OR">Bitwise OR</a></td> + <td><code>a | b</code></td> + <td>Bitsel işleçin iki tarafının karşılık gelen bitlerinden en az biri 1 ise 1 döndürür.</td> + </tr> + <tr> + <td><a href="#Bitwise_XOR">Bitwise XOR</a></td> + <td><code>a ^ b</code></td> + <td>Bitsel işleçin iki tarafının karşılık gelen bitlerinden ancak bir tanesi 1 ise, 1 döndürür.</td> + </tr> + <tr> + <td><a href="#Bitwise_NOT">Bitwise NOT</a></td> + <td><code>~ a</code></td> + <td>İşlenenin bitlerini ters çevirir.</td> + </tr> + <tr> + <td><a href="#Left_shift">Left shift</a></td> + <td><code>a << b</code></td> + <td><code>a</code> sayısının ikili haline, sağına <code>b</code> (< 32) adet bit 0 ekleyerek sola doğru kaydırır.</td> + </tr> + <tr> + <td><a href="#Right_shift">Sign-propagating right shift</a></td> + <td><code>a >> b</code></td> + <td><code>a</code> sayısının ikili halini <code>b</code> (< 32) adet bit sağa kaydırır. Pozitif sayılar için b adet 0, negatif sayılar için 1 ekleyerek kaydırır.</td> + </tr> + <tr> + <td><a href="#Unsigned_right_shift">Zero-fill right shift</a></td> + <td><code>a >>> b</code></td> + <td><code>a</code> sayısının ikili gösterimine <code>b</code> (< 32) bit sağa kaydırır, <code>a</code> sayısının pozitif negatif olmasına bakmadan sayının soluna <code>b</code> adet 0 ekler.</td> + </tr> + </tbody> +</table> + +<h2 id="İşaretli_32-bit_integer_sayılar">İşaretli 32-bit integer sayılar</h2> + +<p>The operands of all bitwise operators are converted to signed 32-bit integers in two's complement format. Two's complement format means that a number's negative counterpart (e.g. 5 vs. -5) is all the number's bits inverted (bitwise NOT of the number, a.k.a. ones' complement of the number) plus one. For example, the following encodes the integer 314:</p> + +<pre>00000000000000000000000100111010 +</pre> + +<p>The following encodes <code>~314</code>, i.e. the ones' 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 through a 32bit signed number.</p> + +<h2 id="Bitwise_logical_operators">Bitwise logical operators</h2> + +<p>Conceptually, the bitwise logical operators work as follows:</p> + +<ul> + <li>The operands are converted to 32-bit integers and expressed by a series of bits (zeroes and ones). Numbers with more than 32 bits get their most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32 bit integer: + <pre>Before: 11100110111110100000000000000110000000000001 +After: 10100000000000000110000000000001</pre> + </li> + <li>Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.</li> + <li>The operator is applied to each pair of bits, and the result is constructed bitwise.</li> +</ul> + +<h3 id="(Bitwise_AND)"><a name="Bitwise_AND">& (Bitwise AND)</a></h3> + +<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 x with 0 yields 0. Bitwise ANDing any number x with -1 yields x.</p> + +<h3 id="(Bitwise_OR)"><a name="Bitwise_OR">| (Bitwise 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. Bitwise ORing any number x with -1 yields -1.</p> + +<h3 id="(Bitwise_XOR)"><a name="Bitwise_XOR">^ (Bitwise 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. Bitwise XORing any number x with -1 yields ~x.</p> + +<h3 id="(Bitwise_NOT)"><a name="Bitwise_NOT">~ (Bitwise 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 4.</p> + +<p>Example with indexOf:</p> + +<pre class="brush: js">var str = 'rawr'; +var searchFor = 'a'; + +// this is alternative way of typing if (-1*str.indexOf('a') <= 0) +if (~str.indexOf(searchFor)) { + // searchFor is in the string +} else { + // searchFor is not in the string +} + +// here are the values returned by (~str.indexOf(searchFor)) +// r == -1 +// a == -2 +// w == -3 +</pre> + +<h2 id="Bitwise_shift_operators">Bitwise shift operators</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 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 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 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="Examples">Examples</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 zeroes (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 +// (0101 & 0010) || (0101 & 0100) => 0000 || 0100 => true +if ((flags & FLAG_B) || (flags & FLAG_C)) { + // 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/Web/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/Web/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/Web/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/Web/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>You can create multiple masks from a set of <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean" title="/en-US/docs/JavaScript/Reference/Global_Objects/Boolean">Boolean</a></code> values, like this:</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/Web/JavaScript/Reference/Global_Objects/Array" title="/en-US/docs/JavaScript/Reference/Global_Objects/Array">Array</a></code> of <code><a href="/en-US/docs/Web/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/Web/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/Web/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/Web/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/Web/JavaScript/Reference/Global_Objects/Array" title="/en-US/docs/JavaScript/Reference/Global_Objects/Array">Array</a></code> of <code><a href="/en-US/docs/Web/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="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.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11.7')}}</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.8">Bitwise NOT operator</a>, <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-11.7">Bitwise shift operators</a>, <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-11.10">Binary bitwise operators</a></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-bitwise-shift-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-bitwise-not-operator">Bitwise NOT operator</a>, <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-bitwise-shift-operators">Bitwise shift operators</a>, <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-binary-bitwise-operators">Binary bitwise operators</a></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-bitwise-shift-operators')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Defined in several sections of the specification: <a href="http://tc39.github.io/ecma262/#sec-bitwise-not-operator">Bitwise NOT operator</a>, <a href="http://tc39.github.io/ecma262/#sec-bitwise-shift-operators">Bitwise shift operators</a>, <a href="http://tc39.github.io/ecma262/#sec-binary-bitwise-operators">Binary bitwise operators</a></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.operators.bitwise")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators">Logical operators</a></li> +</ul> diff --git a/files/tr/web/javascript/reference/operatörler/function_star_/index.html b/files/tr/web/javascript/reference/operatörler/function_star_/index.html new file mode 100644 index 0000000000..193e00f205 --- /dev/null +++ b/files/tr/web/javascript/reference/operatörler/function_star_/index.html @@ -0,0 +1,84 @@ +--- +title: function* expression +slug: Web/JavaScript/Reference/Operatörler/function* +translation_of: Web/JavaScript/Reference/Operators/function* +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>The <strong><code>function*</code></strong> keyword can be used to define a generator function inside an expression.</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="Parametreler">Parametreler</h3> + +<dl> + <dt><code>name</code></dt> + <dd>The function name. Can be omitted, in which case the function is <em>anonymous</em>. The name is only local to the function body.</dd> + <dt><code>paramN</code></dt> + <dd>Argüman adıdır, bir fonksiyon maxiumum 255 argüman alır.</dd> + <dt><code>statements</code></dt> + <dd>Fonksiyon kodları.</dd> +</dl> + +<h2 id="Açıklama">Açıklama</h2> + +<p>A <code>function*</code> expression is very similar to and has almost the same syntax as a {{jsxref('Statements/function*', 'function* statement')}}. The main difference between a <code>function*</code> expression and a <code>function*</code> statement is the <em>function name,</em> which can be omitted in <code>function*</code> expressions to create <em>anonymous</em> generator functions. See also the chapter about <a href="/en-US/docs/Web/JavaScript/Reference/Functions">functions</a> for more information.</p> + +<h2 id="Örnekler">Örnekler</h2> + +<p>Aşağıdaki adlandırılmamış fonksiyondur ve gelen değer karesini verir.</p> + +<pre class="brush: js">var x = function*(y) { + yield y * y; +}; +</pre> + +<h2 id="Özellikler">Özellikler</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="Tarayıcı_uyumluluğu">Tarayıcı uyumluluğu</h2> + + + +<p>{{Compat("javascript.operators.function_star")}}</p> + +<h2 id="Bakabilirsiniz">Bakabilirsiniz</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/tr/web/javascript/reference/operatörler/index.html b/files/tr/web/javascript/reference/operatörler/index.html new file mode 100644 index 0000000000..f42305b092 --- /dev/null +++ b/files/tr/web/javascript/reference/operatörler/index.html @@ -0,0 +1,277 @@ +--- +title: İfadeler ve operatörler +slug: Web/JavaScript/Reference/Operatörler +translation_of: Web/JavaScript/Reference/Operators +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>Bu döküman bütün JavaScript ifadelerini,operatörlerini ve anahtar kelimeleri içerir.</p> + +<h2 id="Expressions_and_operators_by_category">Expressions and operators by category</h2> + +<p>For an alphabetical listing see the sidebar on the left.</p> + +<h3 id="Birincil_İfadeler">Birincil İfadeler</h3> + +<p>Genel İfadeler ve basit anahtar kelimeler.</p> + +<dl> + <dt>{{jsxref("Operators/this", "this")}}</dt> + <dd>The <code>this</code> keyword refers to the function's execution context.</dd> + <dt>{{jsxref("Operators/function", "function")}}</dt> + <dd>The <code>function</code> keyword defines a function expression.</dd> + <dt>{{experimental_inline}} {{jsxref("Operators/class", "class")}}</dt> + <dd>The <code>class</code> keyword defines a class expression.</dd> + <dt>{{experimental_inline}} {{jsxref("Operators/function*", "function*")}}</dt> + <dd>The <code>function*</code> keyword defines a generator function expression.</dd> + <dt>{{experimental_inline}} {{jsxref("Operators/yield", "yield")}}</dt> + <dd>Pause and resume a generator function</dd> + <dt>{{experimental_inline}} {{jsxref("Operators/yield*", "yield*")}}</dt> + <dd>Delegate to another generator function or iterable object.</dd> + <dt>{{jsxref("Global_Objects/Array", "[]")}}</dt> + <dd>Array initializer/literal syntax.</dd> + <dt>{{jsxref("Operators/Object_initializer", "{}")}}</dt> + <dd>Object initializer/literal syntax.</dd> + <dt>{{jsxref("Global_Objects/RegExp", "/ab+c/i")}}</dt> + <dd>Regular expression literal syntax.</dd> + <dt>{{experimental_inline}} {{jsxref("Operators/Array_comprehensions", "[for (x of y) x]")}}</dt> + <dd>Array comprehensions.</dd> + <dt>{{experimental_inline}} {{jsxref("Operators/Generator_comprehensions", "(for (x of y) y)")}}</dt> + <dd>Generator comprehensions.</dd> + <dt>{{jsxref("Operators/Grouping", "( )")}}</dt> + <dd>Grouping operator.</dd> +</dl> + +<h3 id="Left-hand-side_expressions">Left-hand-side expressions</h3> + +<p>Left values are the destination of an assignment.</p> + +<dl> + <dt>{{jsxref("Operators/Property_accessors", "Property accessors", "", 1)}}</dt> + <dd>Member operators provide access to a property or method of an object<br> + (<code>object.property</code> and <code>object["property"]</code>).</dd> + <dt>{{jsxref("Operators/new", "new")}}</dt> + <dd>The <code>new</code> operator creates an instance of a constructor.</dd> + <dt>{{experimental_inline}} {{jsxref("Operators/super", "super")}}</dt> + <dd>The <code>super</code> keyword calls the parent constructor.</dd> + <dt>{{experimental_inline}} {{jsxref("Operators/Spread_operator", "...obj")}}</dt> + <dd>The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.</dd> +</dl> + +<h3 id="Increment_and_decrement">Increment and decrement</h3> + +<p>Postfix/prefix increment and postfix/prefix decrement operators.</p> + +<dl> + <dt>{{jsxref("Operators/Arithmetic_Operators", "A++", "#Increment")}}</dt> + <dd>Postfix increment operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "A--", "#Decrement")}}</dt> + <dd>Postfix decrement operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "++A", "#Increment")}}</dt> + <dd>Prefix increment operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "--A", "#Decrement")}}</dt> + <dd>Prefix decrement operator.</dd> +</dl> + +<h3 id="Unary_operators">Unary operators</h3> + +<p>A unary operation is operation with only one operand.</p> + +<dl> + <dt>{{jsxref("Operators/delete", "delete")}}</dt> + <dd>The <code>delete</code> operator deletes a property from an object.</dd> + <dt>{{jsxref("Operators/void", "void")}}</dt> + <dd>The <code>void</code> operator discards an expression's return value.</dd> + <dt>{{jsxref("Operators/typeof", "typeof")}}</dt> + <dd>The <code>typeof</code> operator determines the type of a given object.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "+", "#Unary_plus")}}</dt> + <dd>The unary plus operator converts its operand to Number type.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "-", "#Unary_negation")}}</dt> + <dd>The unary negation operator converts its operand to Number type and then negates it.</dd> + <dt>{{jsxref("Operators/Bitwise_Operators", "~", "#Bitwise_NOT")}}</dt> + <dd>Bitwise NOT operator.</dd> + <dt>{{jsxref("Operators/Logical_Operators", "!", "#Logical_NOT")}}</dt> + <dd>Logical NOT operator.</dd> +</dl> + +<h3 id="Arithmetic_operators">Arithmetic operators</h3> + +<p>Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.</p> + +<dl> + <dt>{{jsxref("Operators/Arithmetic_Operators", "+", "#Addition")}}</dt> + <dd>Addition operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "-", "#Subtraction")}}</dt> + <dd>Subtraction operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "/", "#Division")}}</dt> + <dd>Division operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "*", "#Multiplication")}}</dt> + <dd>Multiplication operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "%", "#Remainder")}}</dt> + <dd>Remainder operator.</dd> +</dl> + +<h3 id="Relational_operators">Relational operators</h3> + +<p>A comparison operator compares its operands and returns a <code>Boolean</code> value based on whether the comparison is true.</p> + +<dl> + <dt>{{jsxref("Operators/in", "in")}}</dt> + <dd>The <code>in</code> operator determines whether an object has a given property.</dd> + <dt>{{jsxref("Operators/instanceof", "instanceof")}}</dt> + <dd>The <code>instanceof</code> operator determines whether an object is an instance of another object.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", "<", "#Less_than_operator")}}</dt> + <dd>Less than operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", ">", "#Greater_than_operator")}}</dt> + <dd>Greater than operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", "<=", "#Less_than_or_equal_operator")}}</dt> + <dd>Less than or equal operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", ">=", "#Greater_than_or_equal_operator")}}</dt> + <dd>Greater than or equal operator.</dd> +</dl> + +<h3 id="Equality_operators">Equality operators</h3> + +<p>The result of evaluating an equality operator is always of type <code>Boolean</code> based on whether the comparison is true.</p> + +<dl> + <dt>{{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}</dt> + <dd>Equality operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", "!=", "#Inequality")}}</dt> + <dd>Inequality operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}</dt> + <dd>Identity operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", "!==", "#Nonidentity")}}</dt> + <dd>Nonidentity operator.</dd> +</dl> + +<h3 id="Bitwise_shift_operators">Bitwise shift operators</h3> + +<p>Operations to shift all bits of the operand.</p> + +<dl> + <dt>{{jsxref("Operators/Bitwise_Operators", "<<", "#Left_shift")}}</dt> + <dd>Bitwise left shift operator.</dd> + <dt>{{jsxref("Operators/Bitwise_Operators", ">>", "#Right_shift")}}</dt> + <dd>Bitwise right shift operator.</dd> + <dt>{{jsxref("Operators/Bitwise_Operators", ">>>", "#Unsigned_right_shift")}}</dt> + <dd>Bitwise unsigned right shift operator.</dd> +</dl> + +<h3 id="Binary_bitwise_operators">Binary bitwise operators</h3> + +<p>Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.</p> + +<dl> + <dt>{{jsxref("Operators/Bitwise_Operators", "&", "#Bitwise_AND")}}</dt> + <dd>Bitwise AND.</dd> + <dt>{{jsxref("Operators/Bitwise_Operators", "|", "#Bitwise_OR")}}</dt> + <dd>Bitwise OR.</dd> + <dt>{{jsxref("Operators/Bitwise_Operators", "^", "#Bitwise_XOR")}}</dt> + <dd>Bitwise XOR.</dd> +</dl> + +<h3 id="Binary_logical_operators">Binary logical operators</h3> + +<p>Logical operators are typically used with boolean (logical) values, and when they are, they return a boolean value.</p> + +<dl> + <dt>{{jsxref("Operators/Logical_Operators", "&&", "#Logical_AND")}}</dt> + <dd>Logical AND.</dd> + <dt>{{jsxref("Operators/Logical_Operators", "||", "#Logical_OR")}}</dt> + <dd>Logical OR.</dd> +</dl> + +<h3 id="Conditional_(ternary)_operator">Conditional (ternary) operator</h3> + +<dl> + <dt>{{jsxref("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}</dt> + <dd> + <p>The conditional operator returns one of two values based on the logical value of the condition.</p> + </dd> +</dl> + +<h3 id="Assignment_operators">Assignment operators</h3> + +<p>An assignment operator assigns a value to its left operand based on the value of its right operand.</p> + +<dl> + <dt>{{jsxref("Operators/Assignment_Operators", "=", "#Assignment")}}</dt> + <dd>Assignment operator.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "*=", "#Multiplication_assignment")}}</dt> + <dd>Multiplication assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "/=", "#Division_assignment")}}</dt> + <dd>Division assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "%=", "#Remainder_assignment")}}</dt> + <dd>Remainder assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "+=", "#Addition_assignment")}}</dt> + <dd>Addition assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "-=", "#Subtraction_assignment")}}</dt> + <dd>Subtraction assignment</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "<<=", "#Left_shift_assignment")}}</dt> + <dd>Left shift assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", ">>=", "#Right_shift_assignment")}}</dt> + <dd>Right shift assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", ">>>=", "#Unsigned_right_shift_assignment")}}</dt> + <dd>Unsigned right shift assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "&=", "#Bitwise_AND_assignment")}}</dt> + <dd>Bitwise AND assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "^=", "#Bitwise_XOR_assignment")}}</dt> + <dd>Bitwise XOR assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "|=", "#Bitwise_OR_assignment")}}</dt> + <dd>Bitwise OR assignment.</dd> + <dt>{{experimental_inline}} {{jsxref("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}<br> + {{experimental_inline}} {{jsxref("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}</dt> + <dd> + <p>Destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals.</p> + </dd> +</dl> + +<h3 id="Comma_operator">Comma operator</h3> + +<dl> + <dt>{{jsxref("Operators/Comma_Operator", ",")}}</dt> + <dd>The comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression.</dd> +</dl> + +<h3 id="Non-standard_features">Non-standard features</h3> + +<dl> + <dt>{{non-standard_inline}} {{jsxref("Operators/Legacy_generator_function", "Legacy generator function", "", 1)}}</dt> + <dd>The <code>function</code> keyword can be used to define a legacy generator function inside an expression. To make the function a legacy generator, the function body should contains at least one {{jsxref("Operators/yield", "yield")}} expression.</dd> + <dt>{{non-standard_inline}} {{jsxref("Operators/Expression_closures", "Expression closures", "", 1)}}</dt> + <dd>The expression closure syntax is a shorthand for writing simple function.</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-11', 'Expressions')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>New: Spread operator, destructuring assignment, <code>super</code> keyword, Array comprehensions, Generator comprehensions</td> + </tr> + </tbody> +</table> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">Operator precedence</a></li> +</ul> diff --git a/files/tr/web/javascript/reference/operatörler/instanceof/index.html b/files/tr/web/javascript/reference/operatörler/instanceof/index.html new file mode 100644 index 0000000000..3434ea34b9 --- /dev/null +++ b/files/tr/web/javascript/reference/operatörler/instanceof/index.html @@ -0,0 +1,207 @@ +--- +title: instanceof +slug: Web/JavaScript/Reference/Operatörler/instanceof +translation_of: Web/JavaScript/Reference/Operators/instanceof +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><code><strong>I</strong></code><strong><code>nstanceof</code> operatorü</strong> bir nesne'nin prototip (prototype) zincirinin, <code>belirli bir prototipin kurucu(constructor) metodu olup olmadığını testeder.</code></p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><em>object</em> instanceof <em>constructor</em></pre> + +<h3 id="Parametreler">Parametreler</h3> + +<dl> + <dt><code>object</code></dt> + <dd>Test edilecek nesne</dd> +</dl> + +<dl> + <dt><code>constructor</code></dt> + <dd>Test edilecek karşı kurucu fonksiyon</dd> +</dl> + +<h2 id="Açıklama">Açıklama</h2> + +<p><code><strong>I</strong>nstanceof</code> operatorü <span id="result_box" lang="tr"><span>nesnenin prototip zincirinde 'constructor.prototype' varlığını testeder.</span></span></p> + +<pre class="brush: js">// defining constructors +function C() {} +function D() {} + +var o = new C(); + +// true, because: Object.getPrototypeOf(o) === C.prototype +o instanceof C; + +// false, because D.prototype is nowhere in o's prototype chain +o instanceof D; + +o instanceof Object; // true, because: +C.prototype instanceof Object // true + +C.prototype = {}; +var o2 = new C(); + +o2 instanceof C; // true + +// false, because C.prototype is nowhere in +// o's prototype chain anymore +o instanceof C; + +D.prototype = new C(); // add C to [[Prototype]] linkage of D +var o3 = new D(); +o3 instanceof D; // true +o3 instanceof C; // true since C.prototype is now in o3's prototype chain +</pre> + +<p>Bir instanceof testinin değerinin yapıcıların prototip özelliklerinde yapılan değişikliklere göre değişebileceğini ve Object.setPrototypeOf kullanılarak bir nesne prototipini değiştirerek de değişebileceğini unutmayın. Standart olmayan __proto__ sözde-özelliği(pseudo-property) kullanarak da mümkündür.</p> + +<h3 id="instanceof_ve_çoklu_bağlam_(multiple_context)_(e.g._frames_or_windows)"><code>instanceof</code> ve çoklu bağlam (multiple context) (e.g. frames or windows)</h3> + +<p>Farklı kapsamların (Scopes) farklı yürütme (execution) ortamları vardır. Bu, farklı yerleşik yapılara sahip oldukları anlamına gelir (farklı global nesne, farklı yapıcılar, vb.). Bu, beklenmedik sonuçlara neden olabilir. Örneğin, [] instanceof window.frames [0] .Array false döndürür, çünkü Array.prototype! == window.frames [0] .Array ve diziler belli bir dizgeden (former) miras alırlar. Bu başlangıçta mantıklı gelmeyebilir, ancak betiğinizde (script) birden çok cerceve (frame) veya pencereyi (window) ele almaya başladığınızda ve nesneleri fonsiyonlarla bir bağlamdan diğerine geçirirken, bu geçerli ve güçlü bir sayı olacaktır. Örneğin, belirli bir nesnenin aslında Array.isArray (myObj) kullanarak bir Array olup olmadığını güvenli bir şekilde kontrol edebilirsiniz.</p> + +<div class="note"><strong>Mozilla geliştiricleri için not:</strong> + +<p>Kodda XPCOM kullanımının özel bir etkisi vardır: obj instanceof xpcomInterface (ör. Components.interfaces.nsIFile), obj.QueryInterface (xpcomInterface) çağırır ve QueryInterface başarılı olursa true değerini döndürür. Bu tür bir aramanın bir yan etkisi, başarılı bir örnekleme sonucunda obj'de xpcomInterface özelliklerini kullanabilmenizdir. Standart JavaScript globals'ın aksine, test obj instance of xpcomInterface, obj farklı bir kapsamdan olsa bile beklendiği gibi çalışır.</p> +</div> + +<h2 id="Examples">Examples</h2> + +<h3 id="Demonstrating_that_String_and_Date_are_of_type_Object_and_exceptional_cases">Demonstrating that <code>String</code> and <code>Date</code> are of type <code>Object</code> and exceptional cases</h3> + +<p>The following code uses <code>instanceof</code> to demonstrate that <code>String</code> and <code>Date</code> objects are also of type <code>Object</code> (they are derived from <code>Object</code>).</p> + +<p>However, objects created with the object literal notation are an exception here: Although the prototype is undefined, <code>instanceof Object</code> returns <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, checks the prototype chain, finds undefined +myString instanceof String; // returns true +newStr instanceof String; // returns true +myString instanceof Object; // returns true + +myObj instanceof Object; // returns true, despite an undefined prototype +({}) instanceof Object; // returns true, same case as above + +myString instanceof Date; // returns false + +myDate instanceof Date; // returns true +myDate instanceof Object; // returns true +myDate instanceof String; // returns false +</pre> + +<h3 id="Demonstrating_that_mycar_is_of_type_Car_and_type_Object">Demonstrating that <code>mycar</code> is of type <code>Car</code> and type <code>Object</code></h3> + +<p>The following code creates an object type <code>Car</code> and an instance of that object type, <code>mycar</code>. The <code>instanceof</code> operator demonstrates that the <code>mycar</code> object is of type <code>Car</code> and of type <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="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-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>Initial definition. Implemented in JavaScript 1.4.</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>{{CompatVersionUnknown}}</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>Edge</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> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/typeof" title="/en-US/docs/JavaScript/Reference/Operators/typeof">typeof</a></code></li> + <li>{{jsxref("Symbol.hasInstance")}}</li> +</ul> diff --git a/files/tr/web/javascript/reference/operatörler/mantiksal_operatorler/index.html b/files/tr/web/javascript/reference/operatörler/mantiksal_operatorler/index.html new file mode 100644 index 0000000000..b283f9e06c --- /dev/null +++ b/files/tr/web/javascript/reference/operatörler/mantiksal_operatorler/index.html @@ -0,0 +1,311 @@ +--- +title: Mantıksal Operatörler +slug: Web/JavaScript/Reference/Operatörler/Mantiksal_Operatorler +tags: + - Değil + - JavaScript + - Mantıksal Operatörler + - Operator + - Referans + - ve + - ya da +translation_of: Web/JavaScript/Reference/Operators +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>Mantıksal operatörler genellikle {{jsxref("Boolean")}} (mantıksal) değerleri ile kullanılır. Kullanıldıklarında, bir boolean değer döndürürler. Ancak, <code>&&</code> ve <code>||</code> operatörleri aslında belirtilmiş olan operandlardan birinin değerini döndürür, bu sebeple eğer bu operatörler Boolean olmayan değerler ile kullanılırsa, Boolean olmayan değerler üretebilirler.</p> + +<h2 id="Açıklama">Açıklama</h2> + +<p>Mantıksal operatörler aşağıdaki tabloda açıklanıyor:</p> + +<table class="fullwidth-table"> + <tbody> + <tr> + <th>Operatör</th> + <th>Kullanım</th> + <th>Açıklama</th> + </tr> + <tr> + <td>Mantıksal VE (<code>&&</code>)</td> + <td><code><em>expr1</em> && <em>expr2</em></code></td> + <td>Eğer <code>expr1</code> false değerine dönüştürülebilirse, <code>expr1</code> döndürülür. Aksi halde, <code>expr2</code> döndürülür. Böylece, Boolean değerleri ile kullanıldıklarında, <code>&&</code> her iki operand <code>true</code> ise <code>true</code> ; aksi halde, <code>false</code> döndürür.</td> + </tr> + <tr> + <td>Mantıksal YA DA (<code>||</code>)</td> + <td><code><em>expr1</em> || <em>expr2</em></code></td> + <td>Eğer <code>expr1</code> true değerine dönüştürülebilirse, expr1 döndürülür, aksi halde, <code>expr2</code> döndürülür. Böylece, Boolean değerleri ile kullanıldıklarında, <code>||</code> her iki operanddan herhangi biri <code>true</code> ise <code>true</code> döndürür.</td> + </tr> + <tr> + <td>Mantıksal DEĞİL (<code>!</code>)</td> + <td><code>!<em>expr</em></code></td> + <td>Eğer operandın değeri <code>true</code> is false döndürür, aksi alde <code>true</code> döndürür.</td> + </tr> + </tbody> +</table> + +<p>Eğer bir değer <code>true</code> değerine dönüştürülebiliyorsa, ona {{Glossary("truthy")}} ismi verilir. Eğer bir değer <code>false</code> değerine dönüştürülebiliyorsa, ona {{Glossary("falsy")}} denir.</p> + +<p><code><a href="https://developer.mozilla.org/en-US/docs/Glossary/Falsy">False</a></code> değerine dönüştürülebilen ifadelere örnekler:</p> + +<ul> + <li><code>null</code>;</li> + <li><code>NaN;</code></li> + <li><code>0</code>;</li> + <li>boş string (<code>""</code>); </li> + <li><code>undefined</code>.</li> +</ul> + +<p>&& ve || operatörleri <code>Boolean</code> olmayan değerler ile kullanılabiliyor olmasına rağmen, döndürdükleri değerler her zaman <code>Boolean</code> değerlerine çevirilebildiğinden, halen <code>Boolean</code> operatörleri olarak düşünülebilirler.</p> + +<h3 id="Kısa-devre_değerlendirmeleri">Kısa-devre değerlendirmeleri</h3> + +<p>Mantıksal operatörler soldan sağa çalıştırıldıkları gibi, mümkünse aşağıdaki kurallar kullanılarak "kısa devre" testine tabi tutulurlar:</p> + +<ul> + <li><code>false && (<em>herhangi)</em></code> bir kısa devre, false değerine çevrilir.</li> + <li><code>true || (<em>herhangi)</em></code> bir kısa devre, true değerine çevrilir.</li> +</ul> + +<p>Mantık kuralları bu değerlendirmelerin doğruluğunu garantiler. Yukarıdaki ifadelerin tümünün çalıştırılmayacağına, bu sebeple hepsinin yan etkisinin olmayacağına dikkat edin. Ayrıca yukarıdaki ifadenin <code>(herhangi)</code> kısmının tamamıyla bir mantıksal ifadeye eşit olduğuna dikkat edin. (parantezler ile gösterildiği gibi).</p> + +<p>Örneğin, aşağıdaki iki fonksiyon birbirinin aynısıdır.</p> + +<pre class="brush: js">function shortCircuitEvaluation() { + doSomething() || doSomethingElse() +} + +function equivalentEvaluation() { + var flag = doSomething(); + if (!flag) { + doSomethingElse(); + } +} +</pre> + +<p>Ancak, aşağıdaki ifadeler operatör önceliğine göre eşit değildir ve sağ el operatörünün tek bir ifade olmasının önemini vurgular (gerekirse parantezler ile gruplanır).</p> + +<pre class="brush: js">false && true || true // returns true +false && (true || true) // returns false</pre> + +<h3 id="Mantıksal_VE_()"><a name="Logical_AND">Mantıksal VE (<code>&&</code>)</a></h3> + +<p>Aşağıdaki kod && (mantıksal VE) operatörüyle ilgili örnekleri gösterir.</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 // returns "" +a9 = false && || // returns false +</pre> + +<h3 id="Mantıksal_YA_DA_()"><a name="Logical_OR">Mantıksal YA DA (<code>||</code>)</a></h3> + +<p>Aşağıdaki kod || (mantıksal YA DA) operatörüyle ilgili örnekleri gösterir.</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 // returns false +o9 = false || "" // returns "" +</pre> + +<h3 id="Mantıksal_DEĞİL_(!)"><a name="Logical_NOT">Mantıksal DEĞİL (<code>!</code>)</a></h3> + +<p>Aşağıdaki kod ! (mantıksal DEĞİL) operatörüyle ilgili örnekleri gösterir.</p> + +<pre class="brush: js">n1 = !true // !t returns false +n2 = !false // !f returns true +n3 = !"Cat" // !t returns false +</pre> + +<h3 id="Dönüşüm_kuralları">Dönüşüm kuralları</h3> + +<h4 id="VE_operatörünü_YA_DA_operatörüne_dönüştürmek">VE operatörünü YA DA operatörüne dönüştürmek</h4> + +<p>Booleanları içeren aşağıdaki ifade:</p> + +<pre class="brush: js">bCondition1 && bCondition2</pre> + +<p>her zaman şuna eşittir:</p> + +<pre class="brush: js">!(!bCondition1 || !bCondition2)</pre> + +<h4 id="YA_DA_operatörünü_VE_operatörüne_çevirmek">YA DA operatörünü VE operatörüne çevirmek</h4> + +<p>Booleanları içeren aşağıdaki ifade:</p> + +<pre class="brush: js">bCondition1 || bCondition2</pre> + +<p>her zaman şuna eşittir:</p> + +<pre class="brush: js">!(!bCondition1 && !bCondition2)</pre> + +<h4 id="DEĞİL_operatörleri_arasında_dönüşüm_yapmak">DEĞİL operatörleri arasında dönüşüm yapmak</h4> + +<p>Booleanları içeren aşağıdaki ifade:</p> + +<pre class="brush: js">!!bCondition</pre> + +<p>her zaman şuna eşittir: </p> + +<pre class="brush: js">bCondition</pre> + +<h3 id="İç_içe_geçmiş_parantezleri_kaldırmak">İç içe geçmiş parantezleri kaldırmak</h3> + +<p>Mantıksal operatörlerin soldan sağa değerlendirilmesi durumunda, kompleks bir ifadeden parantezleri bazı kuralları takip ederek kaldırmak mümkündür.</p> + +<h4 id="İç_içe_geçmiş_VE_operatörünü_kaldırmak">İç içe geçmiş VE operatörünü kaldırmak</h4> + +<p>Aşağıda, Boolean içeren bu bileşik işlem:</p> + +<pre class="brush: js">bCondition1 || (bCondition2 && bCondition3)</pre> + +<p>her zaman şuna eşittir:</p> + +<pre class="brush: js">bCondition1 || bCondition2 && bCondition3</pre> + +<h4 id="İç_içe_geçmiş_YA_DA_operatörünü_kaldırmak">İç içe geçmiş YA DA operatörünü kaldırmak</h4> + +<p>Aşağıda, Boolean içeren bu bileşik ifade:</p> + +<pre class="brush: js">bCondition1 && (bCondition2 || bCondition3)</pre> + +<p>her zaman şuna eşittir:</p> + +<pre class="brush: js">!(!bCondition1 || !bCondition2 && !bCondition3)</pre> + +<h2 id="Özellikler">Özellikler</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Özellik</th> + <th scope="col">Durum</th> + <th scope="col">Açıklama</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>İlk tanım.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11.11')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Tarifnamenin birkaç bölümünde tanımlandı: <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>Tarifnamenin birkaç bölümünde tanımlandı: <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>Tarifnamenin birkaç bölümünde tanımlandı: <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="Tarayıcı_Uyumluluğu">Tarayıcı Uyumluluğu</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>Mantıksal VE (<code>&&</code>)</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td> + <p>Mantıksal YA DA (<code>||</code>)</p> + </td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Mantıksal DEĞİL (<code>!</code>)</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>Özellik</th> + <th>Android</th> + <th>Android üzerinde Chrome</th> + <th>Firefox Mobil (Gecko)</th> + <th>IE Mobil</th> + <th>Opera Mobil</th> + <th>Safari Mobil</th> + </tr> + <tr> + <td>Logical AND (<code>&&</code>)</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Logical OR (<code>||</code>)</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Logical NOT (<code>!</code>)</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="Ayrıca_bakın">Ayrıca bakın</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators">Bitwise operators</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean">Boolean</a></li> +</ul> diff --git a/files/tr/web/javascript/reference/operatörler/super/index.html b/files/tr/web/javascript/reference/operatörler/super/index.html new file mode 100644 index 0000000000..3dd3f62ebf --- /dev/null +++ b/files/tr/web/javascript/reference/operatörler/super/index.html @@ -0,0 +1,165 @@ +--- +title: super +slug: Web/JavaScript/Reference/Operatörler/super +translation_of: Web/JavaScript/Reference/Operators/super +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>super, </strong>ebeveyn sınıftaki fonksiyonlara ulaşmak ve onları çağırmak için kullanılan bir ifadedir.</p> + +<p>The <code>super.prop</code> and <code>super[expr]</code> expressions are valid in any <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions">method definition</a> in both <a href="/en-US/docs/Web/JavaScript/Reference/Classes">classes</a> and <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer">object literals</a>.</p> + +<h2 id="Sözdizimi_Syntax">Sözdizimi (Syntax)</h2> + +<pre class="syntaxbox notranslate">super([arguments]); // ebeveyn sınıfın constructot'ını çağırır. +super.functionOnParent([arguments]); // ebeveyn sınıftaki functionOnParent fonksiyonunu çalıştırır. +</pre> + +<h2 id="Açıklama">Açıklama</h2> + +<p>Constructor içinde <code>super</code> ifadesi tek başına kullanılır ve <code>this</code> ifadesinden önce kullanılması zorunludur. Aynı zamanda <code>super</code> ifadesi ebeveyn sınıftaki fonksiyonları çağırmak için de kullanılabilir.</p> + +<h2 id="Örnekler">Örnekler</h2> + +<h3 id="Sınflarda_super_kullanımı">Sınflarda <code>super</code> kullanımı</h3> + +<p>This code snippet is taken from the <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>). Here <code>super()</code> is called to avoid duplicating the constructor parts' that are common between <code>Rectangle</code> and <code>Square</code>.</p> + +<pre class="brush: js notranslate">class Rectangle { + constructor(height, width) { + this.name = 'Rectangle'; + this.height = height; + this.width = width; + } + sayName() { + console.log('Hi, I am a ', this.name + '.'); + } + get area() { + return this.height * this.width; + } + set area(value) { + this._area = value; + } +} + +class Square extends Rectangle { + constructor(length) { + this.height; // ReferenceError, super needs to be called first! + + // Here, it calls the parent class's constructor with lengths + // provided for the Rectangle's width and height + super(length, length); + + // Note: In derived classes, super() must be called before you + // can use 'this'. Leaving this out will cause a reference error. + this.name = 'Square'; + } +}</pre> + +<h3 id="Super-calling_static_methods">Super-calling static methods</h3> + +<p>You are also able to call super on <a href="/en-US/docs/Web/JavaScript/Reference/Classes/static">static</a> methods.</p> + +<pre class="brush: js notranslate">class Rectangle { + static logNbSides() { + return 'I have 4 sides'; + } +} + +class Square extends Rectangle { + static logDescription() { + return super.logNbSides() + ' which are all equal'; + } +} +Square.logDescription(); // 'I have 4 sides which are all equal' +</pre> + +<h3 id="Deleting_super_properties_will_throw_an_error">Deleting super properties will throw an error</h3> + +<p>You cannot use the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete">delete operator</a> and <code>super.prop</code> or <code>super[expr]</code> to delete a parent class' property, it will throw a {{jsxref("ReferenceError")}}.</p> + +<pre class="brush: js notranslate">class Base { + foo() {} +} +class Derived extends Base { + delete() { + delete super.foo; // this is bad + } +} + +new Derived().delete(); // ReferenceError: invalid delete involving 'super'. </pre> + +<h3 id="super.prop_cannot_overwrite_non-writable_properties"><code>super.prop</code> cannot overwrite non-writable properties</h3> + +<p>When defining non-writable properties with e.g. {{jsxref("Object.defineProperty")}}, <code>super</code> cannot overwrite the value of the property.</p> + +<pre class="brush: js notranslate">class X { + constructor() { + Object.defineProperty(this, 'prop', { + configurable: true, + writable: false, + value: 1 + }); + } +} + +class Y extends X { + constructor() { + super(); + } + foo() { + super.prop = 2; // Cannot overwrite the value. + } +} + +var y = new Y(); +y.foo(); // TypeError: "prop" is read-only +console.log(y.prop); // 1 +</pre> + +<h3 id="Using_super.prop_in_object_literals">Using <code>super.prop</code> in object literals</h3> + +<p>Super can also be used in the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer">object initializer / literal</a> notation. In this example, two objects define a method. In the second object, <code>super</code> calls the first object's method. This works with the help of {{jsxref("Object.setPrototypeOf()")}} with which we are able to set the prototype of <code>obj2</code> to <code>obj1</code>, so that <code>super</code> is able to find <code>method1</code> on <code>obj1</code>.</p> + +<pre class="brush: js notranslate">var obj1 = { + method1() { + console.log('method 1'); + } +} + +var obj2 = { + method2() { + super.method1(); + } +} + +Object.setPrototypeOf(obj2, obj1); +obj2.method2(); // logs "method 1" +</pre> + +<h2 id="Özellikler">Özellikler</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-super-keyword', 'super')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Tarayıcı_uyumluluğu">Tarayıcı uyumluluğu</h2> + + + +<p>{{Compat("javascript.operators.super")}}</p> + +<h2 id="Ayrıca_bakınız">Ayrıca bakınız</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Classes">Classes</a></li> +</ul> diff --git a/files/tr/web/javascript/reference/operatörler/this/index.html b/files/tr/web/javascript/reference/operatörler/this/index.html new file mode 100644 index 0000000000..674e577187 --- /dev/null +++ b/files/tr/web/javascript/reference/operatörler/this/index.html @@ -0,0 +1,347 @@ +--- +title: this +slug: Web/JavaScript/Reference/Operatörler/this +translation_of: Web/JavaScript/Reference/Operators/this +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>Fonksiyon'un <code>this</code> anahtar kelimesi</strong> diğer dillere göre birazcık farklı davranır. Ayrıca <a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode">strict modu</a> ve non-strict modu arasında farklılıklar bulunur.</p> + +<p>Çoğunlukla, <code>this</code>'in değeri fonksiyonun çağrılma biçimine göre belirlenir. Çalışma esnasında değeri değiştirilemez, ve her fonksiyonu çağırışta farklı olabilir. ES5 bu adreste <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">bind</a></code> method to <a href="#The_bind_method">set the value of a function's <code>this</code> regardless of how it's called</a>.</p> + +<h2 id="Sözdizimi">Sözdizimi</h2> + +<pre class="syntaxbox">this</pre> + +<h2 id="Global_içerik">Global içerik</h2> + +<p>Global konumda (fonksiyon dışında), <code>this</code> global nesnesini referans gösterir, strict modunda olmak bu durumu değiştirmez..</p> + +<pre class="brush:js">console.log(this.document === document); // true + +// Web browserlerinde window objesi global objedir.: +console.log(this === window); // true + +this.a = 37; +console.log(window.a); // 37 +</pre> + +<h2 id="Function_içerik">Function içerik</h2> + +<p>Fonksiyon içerisinde, <code>this</code>'in değeri fonksiyonun nasıl çağrıldığına bağlıdır..</p> + +<h3 id="Basit_çağrı">Basit çağrı</h3> + +<pre class="brush:js">function f1(){ + return this; +} + +f1() === window; // global obje +</pre> + +<p>Bu durumda, <code>this</code>'in değeri çağrı ile ayarlanmaz. Kod strict modda olmadığı sürece, <code>this</code>'in değeri mutlaka obje olmalıdır bu yüzdende default değer olan global objesi döner.</p> + +<pre class="brush:js">function f2(){ + "use strict"; // strict modu içerisinde çalıştıralım + return this; +} + +f2() === undefined; +</pre> + +<p>Strict modu içerisinde, <code>this</code>'in değeri çalıştırılma içeriğine nasıl girdiyse o şekilde kalır. Eğer tanımlanmamışsa, undefined olarak kalır. Ayrıca tüm değerlere eşitlenebilir, örneğin <code>null</code> yada <code>42</code> yada <code>"I am not this"</code>.</p> + +<div class="note"><strong>Not:</strong> İkinci örnekte, <code>this</code> <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined"><code>undefined</code></a> olmalıdır, çünkü <code>f2</code> taban belirtilmeden çağrılmıştır. (örn: <code>window.f2()</code>). Bu özellik bazı browserlerde desteklenmemektedir. <a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode" title="Strict mode">strict mod</a> henüz geliştirme aşamasındayken çoğu browser yanlış davranarak <code>window</code> objesini döndürür.</div> + +<h3 id="Obje_methodu_cağrısı">Obje methodu cağrısı</h3> + +<p>Fonksiyon bir objenin methodu olarak çağrıldığında, <code>this</code> çağrıldığı obje olarak atanacaktır.</p> + +<p>In the following example, when <code>o.f()</code> is invoked, inside the function <code>this</code> is bound to the <code>o</code> object.</p> + +<pre class="brush:js">var o = { + prop: 37, + f: function() { + return this.prop; + } +}; + +console.log(o.f()); // logs 37 +</pre> + +<p>Note that this behavior is not at all affected by how or where the function was defined. In the previous example, we defined the function inline as the <code>f</code> member during the definition of <code>o</code>. However, we could have just as easily defined the function first and later attached it to <code>o.f</code>. Doing so results in the same behavior:</p> + +<pre class="brush:js">var o = {prop: 37}; + +function independent() { + return this.prop; +} + +o.f = independent; + +console.log(o.f()); // logs 37 +</pre> + +<p>This demonstrates that it matters only that the function was invoked from the <code>f</code> member of <code>o</code>.</p> + +<p>Similarly, the <code>this</code> binding is only affected by the most immediate member reference. In the following example, when we invoke the function, we call it as a method <code>g</code> of the object <code>o.b</code>. This time during execution, <code>this</code> inside the function will refer to <code>o.b</code>. The fact that the object is itself a member of <code>o</code> has no consequence; the most immediate reference is all that matters.</p> + +<pre class="brush:js">o.b = {g: independent, prop: 42}; +console.log(o.b.g()); // logs 42 +</pre> + +<h4 id="this_on_the_object's_prototype_chain"><code>this</code> on the object's prototype chain</h4> + +<p>The same notion holds true for methods defined somewhere on the object's prototype chain. If the method is on an object's prototype chain, <code>this</code> refers to the object the method was called on, as if the method was on the object.</p> + +<pre class="brush:js">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>In this example, the object assigned to the variable <code>p</code> doesn't have its own <code>f</code> property, it inherits it from its prototype. But it doesn't matter that the lookup for <code>f</code> eventually finds a member with that name on <code>o</code>; the lookup began as a reference to <code>p.f</code>, so <code>this</code> inside the function takes the value of the object referred to as <code>p</code>. That is, since <code>f</code> is called as a method of <code>p</code>, its <code>this</code> refers to <code>p</code>. This is an interesting feature of JavaScript's prototype inheritance.</p> + +<h4 id="this_with_a_getter_or_setter"><code>this</code> with a getter or setter</h4> + +<p>Again, the same notion holds true when a function is invoked from a getter or a setter. A function used as getter or setter has its <code>this</code> bound to the object from which the property is being set or gotten.</p> + +<pre class="brush:js">function modulus(){ + return Math.sqrt(this.re * this.re + this.im * this.im); +} + +var o = { + re: 1, + im: -1, + get phase(){ + return Math.atan2(this.im, this.re); + } +}; + +Object.defineProperty(o, 'modulus', { + get: modulus, enumerable:true, configurable:true}); + +console.log(o.phase, o.modulus); // logs -0.78 1.4142 +</pre> + +<h3 id="As_a_constructor">As a constructor</h3> + +<p>When a function is used as a constructor (with the <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/new">new</a></code> keyword), its <code>this</code> is bound to the new object being constructed.</p> + +<p>Note: 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> + +<pre class="brush:js">/* + * 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); // logs 37 + + +function C2(){ + this.a = 37; + return {a:38}; +} + +o = new C2(); +console.log(o.a); // logs 38 +</pre> + +<p>In the last example (<code>C2</code>), because an object was returned during construction, the new object that <code>this</code> was bound to simply gets discarded. (This essentially makes the statement "<code>this.a = 37;</code>" dead code. It's not exactly dead, because it gets executed, but it can be eliminated with no outside effects.)</p> + +<h3 id="call_and_apply"><code>call</code> and <code>apply</code></h3> + +<p>Where a function uses the <code>this</code> keyword in its body, its value can be bound to a particular object in the call using the <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call">call</a></code> or <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply">apply</a></code> methods that all functions inherit from <code>Function.prototype</code>.</p> + +<pre class="brush:js">function add(c, d){ + return this.a + this.b + c + d; +} + +var o = {a:1, b:3}; + +// The first parameter is the object to use as +// 'this', subsequent parameters are passed as +// arguments in the function call +add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16 + +// The first parameter is the object to use as +// 'this', the second is an array whose +// members are used as the arguments in the function call +add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34 +</pre> + +<p>Note that with <code>call</code> and <code>apply</code>, if the value passed as <code>this</code> is not an object, an attempt will be made to convert it to an object using the internal <code>ToObject</code> operation. So if the value passed is a primitive like <code>7</code> or <code>'foo'</code>, it will be converted to an Object using the related constructor, so the primitive number <code>7</code> is converted to an object as if by <code>new Number(7)</code> and the string <code>'foo'</code> to an object as if by <code>new String('foo')</code>, e.g.</p> + +<pre class="brush:js">function bar() { + console.log(Object.prototype.toString.call(this)); +} + +bar.call(7); // [object Number] +</pre> + +<h3 id="The_bind_method">The <code>bind</code> method</h3> + +<p>ECMAScript 5 introduced <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">Function.prototype.bind</a></code>. Calling <code>f.bind(someObject)</code> creates a new function with the same body and scope as <code>f</code>, but where <code>this</code> occurs in the original function, in the new function it is permanently bound to the first argument of <code>bind</code>, regardless of how the function is being used.</p> + +<pre class="brush:js">function f(){ + return this.a; +} + +var g = f.bind({a:"azerty"}); +console.log(g()); // azerty + +var o = {a:37, f:f, g:g}; +console.log(o.f(), o.g()); // 37, azerty +</pre> + +<h3 id="As_a_DOM_event_handler">As a DOM event handler</h3> + +<p>When a function is used as an event handler, its <code>this</code> is set to the element the event fired from (some browsers do not follow this convention for listeners added dynamically with methods other than <code>addEventListener</code>).</p> + +<pre class="brush:js">// When called as a listener, turns the related element blue +function bluify(e){ + // Always true + console.log(this === e.currentTarget); + // true when currentTarget and target are the same object + console.log(this === e.target); + this.style.backgroundColor = '#A5D9F3'; +} + +// Get a list of every element in the document +var elements = document.getElementsByTagName('*'); + +// Add bluify as a click listener so when the +// element is clicked on, it turns blue +for(var i=0 ; i<elements.length ; i++){ + elements[i].addEventListener('click', bluify, false); +}</pre> + +<h3 id="In_an_in–line_event_handler">In an in–line event handler</h3> + +<p>When code is called from an in–line handler, its <code>this</code> is set to the DOM element on which the listener is placed:</p> + +<pre class="brush:js"><button onclick="alert(this.tagName.toLowerCase());"> + Show this +</button> +</pre> + +<p>The above alert shows <code>button</code>. Note however that only the outer code has its <code>this</code> set this way:</p> + +<pre class="brush:js"><button onclick="alert((function(){return this}()));"> + Show inner this +</button> +</pre> + +<p>In this case, the inner function's <code>this</code> isn't set so it returns the global/window object (i.e. the default object in non–strict mode where <code>this</code> isn't set by the call).</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-this-keyword', 'The this keyword')}}</td> + <td>{{Spec2('ES6')}}</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="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</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/Functions_and_function_scope/Strict_mode">Strict mode</a></li> + <li><a href="http://bjorn.tipling.com/all-this">All this</a>, an article about <code>this</code> in different contexts</li> +</ul> diff --git a/files/tr/web/javascript/reference/operatörler/typeof/index.html b/files/tr/web/javascript/reference/operatörler/typeof/index.html new file mode 100644 index 0000000000..deccfd8925 --- /dev/null +++ b/files/tr/web/javascript/reference/operatörler/typeof/index.html @@ -0,0 +1,259 @@ +--- +title: typeof +slug: Web/JavaScript/Reference/Operatörler/typeof +translation_of: Web/JavaScript/Reference/Operators/typeof +--- +<div>{{jsSidebar("Operatörler")}}</div> + +<p><strong><kbd>Typeof</kbd></strong> operatörü, değerlendirilmemiş işlenenin türünü gösteren bir dize döndürür.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-typeof.html")}}</div> + + + +<h2 id="Sözdizimi">Sözdizimi</h2> + +<p>The <code>typeof</code> operator is followed by its operand:</p> + +<pre class="syntaxbox notranslate">typeof <em>operand +or +typeof (operand)</em> +</pre> + + + +<h3 id="Parametreler">Parametreler</h3> + +<p><code><em>operand</em></code> is an expression representing the object or {{Glossary("Primitive", "primitive")}} whose type is to be returned.</p> + +<p>Parantez isteğe bağlıdır.</p> + +<h2 id="Description">Description</h2> + +<p>The following table summarizes the possible return values of <code>typeof</code>. For more information about types and primitives, see also the <a href="/en-US/docs/Web/JavaScript/Data_structures">JavaScript data structure</a> page.</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Type</th> + <th scope="col">Result</th> + </tr> + </thead> + <tbody> + <tr> + <td>Undefined</td> + <td><code>"undefined"</code></td> + </tr> + <tr> + <td>Null</td> + <td><code>"object" </code>(see below)</td> + </tr> + <tr> + <td>Boolean</td> + <td><code>"boolean"</code></td> + </tr> + <tr> + <td>Number</td> + <td><code>"number"</code></td> + </tr> + <tr> + <td>String</td> + <td><code>"string"</code></td> + </tr> + <tr> + <td>Symbol (new in ECMAScript 2015)</td> + <td><code>"symbol"</code></td> + </tr> + <tr> + <td>Host object (provided by the JS environment)</td> + <td><em>Implementation-dependent</em></td> + </tr> + <tr> + <td>Function object (implements [[Call]] in ECMA-262 terms)</td> + <td><code>"function"</code></td> + </tr> + <tr> + <td>Any other object</td> + <td><code>"object"</code></td> + </tr> + </tbody> +</table> + +<h2 id="Örnekler">Örnekler</h2> + +<pre class="brush:js notranslate">// Sayılar +typeof 37 === 'number'; +typeof 3.14 === 'number'; +typeof(42) === '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! + + +// Metinler +typeof '' === 'string'; +typeof 'bla' === 'string'; +typeof '1' === 'string'; // note that a number within a string is still typeof 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'; + + +// Objeler +typeof {a: 1} === 'object'; + +// use <a href="/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'; + + +// Fonksiyonlar +typeof function() {} === 'function'; +typeof class C {} === 'function'; +typeof Math.sin === 'function'; +</pre> + +<h3 id="null"><code>null</code></h3> + +<pre class="brush:js notranslate">// This stands since the beginning of JavaScript +typeof null === 'object'; +</pre> + +<p>In the first implementation of JavaScript, JavaScript values were represented as a type tag and a value. The type tag for objects was 0. <code>null</code> was represented as the NULL pointer (0x00 in most platforms). Consequently, null had 0 as type tag, hence the bogus <code>typeof</code> return value. (<a href="http://www.2ality.com/2013/10/typeof-null.html">reference</a>)</p> + +<p>A fix was proposed for ECMAScript (via an opt-in), but <a class="external" href="http://wiki.ecmascript.org/doku.php?id=harmony:typeof_null">was rejected</a>. It would have resulted in <code>typeof null === 'null'</code>.</p> + +<h3 id="new_operatör_kullanımı"><code>new</code> operatör kullanımı</h3> + +<pre class="brush:js notranslate">// All constructor functions while instantiated with 'new' keyword will always be typeof 'object' +var str = new String('String'); +var num = new Number(100); + +typeof str; // It will return 'object' +typeof num; // It will return 'object' + +// But there is a exception in case of Function constructor of Javascript + +var func = new Function(); + +typeof func; // It will return 'function' +</pre> + +<h3 id="Parantezlere_ihtiyaç_var">Parantezlere ihtiyaç var</h3> + +<pre class="brush:js notranslate">// Parentheses will be very much useful to determine the data type for expressions. +var iData = 99; + +typeof iData + ' Wisen'; // It will return 'number Wisen' +typeof (iData + ' Wisen'); // It will return 'string' + + +</pre> + +<h3 id="Düzenli_İfadeler">Düzenli İfadeler</h3> + +<p>Callable regular expressions were a non-standard addition in some browsers.</p> + +<pre class="brush:js notranslate">typeof /s/ === 'function'; // Chrome 1-12 Non-conform to ECMAScript 5.1 +typeof /s/ === 'object'; // Firefox 5+ Conform to ECMAScript 5.1 +</pre> + +<h3 id="Temporal_Dead_Zone_errors">Temporal Dead Zone errors</h3> + +<p>Before ECMAScript 2015, <code>typeof</code> was always guaranteed to return a string for any operand it was supplied with. But with the addition of non-hoisted, block-scoped <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/let">let</a></code> and <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/const">const</a></code>, using <code>typeof</code> on <code>let</code> and <code>const</code> variables in a block before they are declared will throw a <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError">ReferenceError</a></code>. This is in contrast with undeclared variables, for which <code>typeof</code> will return 'undefined'. Block scoped variables are in a "<a href="/en-US/docs/Web/JavaScript/Reference/Statements/let#Temporal_Dead_Zone_and_errors_with_let">temporal dead zone</a>" from the start of the block until the initialization is processed, during which, it will throw an error if accessed.</p> + +<pre class="brush: js notranslate">typeof undeclaredVariable === 'undefined'; +typeof newLetVariable; let newLetVariable; // ReferenceError +typeof newConstVariable; const newConstVariable = 'hello'; // ReferenceError +</pre> + +<h3 id="İstisnalar">İstisnalar</h3> + +<p>All current browsers expose a non-standard host object {{domxref("document.all")}} with type Undefined.</p> + +<pre class="brush:js notranslate">typeof document.all === 'undefined'; +</pre> + +<p>Although the specification allows custom type tags for non-standard exotic objects, it requires those type tags to be different from the predefined ones. The case of <code>document.all</code> having type tag <code>'undefined'</code> must be classified as an exceptional violation of the rules.</p> + +<h2 id="Özellikler">Özellikler</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="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.operators.typeof")}}</p> + +<h2 id="IE_özel_notlar">IE özel notlar</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 notranslate">typeof alert === 'object'</pre> + +<h2 id="Bakabilirsiniz">Bakabilirsiniz</h2> + +<ul> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/instanceof">instanceof</a></code></li> + <li><a href="http://es-discourse.com/t/why-typeof-is-no-longer-safe/15">Why typeof is no longer "safe"</a></li> +</ul> diff --git a/files/tr/web/javascript/reference/statements/block/index.html b/files/tr/web/javascript/reference/statements/block/index.html new file mode 100644 index 0000000000..7d77ce73aa --- /dev/null +++ b/files/tr/web/javascript/reference/statements/block/index.html @@ -0,0 +1,179 @@ +--- +title: block +slug: Web/JavaScript/Reference/Statements/block +tags: + - Blok + - ifade +translation_of: Web/JavaScript/Reference/Statements/block +--- +<div>{{jsSidebar("Statements")}}</div> + +<p>Bir<strong> blok statement(ifade) </strong>(diğer bir deyişle <strong>birleşik ifade</strong>) sıfır ya da daha fazla ifadeyi gruplamak için kullanılır. Blok bir çift süslü parantezle sınırlandırılmakla beraber opsiyonel olarak {{jsxref("Statements/label", "etiketlenebilir")}}:</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">[<em>etiket</em>:] { + <em>statement_1</em>; + <em>statement_2;</em> + ... + <em>statement_n;</em> +} +</pre> + +<dl> + <dt><code>statement_1</code>, <code>statement_2</code>, <code>statement_n</code></dt> + <dd>İfadeler tek bir statement içinde sınırlandırılmıştır.</dd> + <dt><font face="Consolas, Liberation Mono, Courier, monospace">etiket</font></dt> + <dd>Görsel bir tanımlama yapmak ya da bir {{jsxref("Statements/break", "break(kırılım)")}}oluşturmak için opsiyonel bir {{jsxref("Statements/label", "etikettir.")}}.</dd> +</dl> + +<h2 id="Açıklama">Açıklama</h2> + +<p>Statement,sıklıkla akış tablolarıyla birlikte kullanılır. (örn. {{jsxref("Statements/if...else", "if...else")}}, {{jsxref("Statements/for", "for")}}, {{jsxref("Statements/while", "while")}}). Örnek:</p> + +<pre class="brush: js">while (x < 10) { + x++; +} +</pre> + +<p>Hatırlatma : statement noktalı virgül ile sonlanmaz.</p> + +<p>Block statement diğer dillerde birleşik ifade yani compound statement olarak ifade edilir. Javasacript tek bir statement beklerken, birden çok statement kullanmanızı sağlar. Blokların birleşmesi Javascript için yaygın bir kullanımdır. Bir diğer kullanım ise statement kullanmanız gereken ancak kullanmadığınız yerlerde boş bir statement kullanılmasıdır.</p> + +<h3 id="Block_Scoping_Rules">Block Scoping Rules</h3> + +<h4 id="With_var">With <code>var</code></h4> + +<p>Variables declared with <code>var</code> <strong>do not</strong> have block scope. Variables introduced with a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. In other words, block statements do not introduce a scope. Although "standalone" blocks are valid syntax, you do not want to use standalone blocks in JavaScript, because they don't do what you think they do, if you think they do anything like such blocks in C or Java. For example:</p> + +<pre class="brush: js example-bad">var x = 1; +{ + var x = 2; +} +console.log(x); // logs 2 +</pre> + +<p>Burada çıktı 2 oldu çünkü block için ayrı bir scope oluşmamıştır. C ya da Java'da çıktı 1 olur.</p> + +<h4 id="let_ve_const_ile"><code>let </code>ve <code>const</code> ile</h4> + +<p>Yukarıdakinin aksine {{jsxref("Statements/let", "let")}} ve {{jsxref("Statements/const", "const")}} ayrı bir scope olarak koşacaktır:</p> + +<pre class="brush: js">let x = 1; +{ + let x = 2; +} +console.log(x); // logs 1</pre> + +<p><code>x = 2</code> sınırlı bir statement içerisinde yer aldığından sadece o statement içerisinde geçerli olacaktır.</p> + +<p>Bu kural <code><strong>const</strong> içinde aynıdır</code>:</p> + +<pre class="brush: js">const c = 1; +{ + const c = 2; +} +console.log(c); // logs 1 and does not throw SyntaxError...</pre> + +<p>Dikkat edin sınırlı blocktaki <code>const c = 2</code> <em> </em>ifadesi <code>SyntaxError: Identifier 'c' zaten tanımlanmış </code>hatası vermedi çünkü, her blok içerisinde benzersiz olarak tanımlanır.</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-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="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>{{CompatVersionUnknown}}</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>Edge</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> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</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/tr/web/javascript/reference/statements/break/index.html b/files/tr/web/javascript/reference/statements/break/index.html new file mode 100644 index 0000000000..a929634f58 --- /dev/null +++ b/files/tr/web/javascript/reference/statements/break/index.html @@ -0,0 +1,117 @@ +--- +title: break +slug: Web/JavaScript/Reference/Statements/break +translation_of: Web/JavaScript/Reference/Statements/break +--- +<div>{{jsSidebar("Statements")}}</div> + +<p>Break ifadesi içinde bulunduğu döngüyü , {{jsxref("Statements/switch", "switch")}}, or {{jsxref("Statements/label", "label")}} ifadelerini sonlandırır ve programın kontrolünü sonlandırılan ifadeyi ardından takip eden ifadeye geçirir.</p> + +<div>{{EmbedInteractiveExample("pages/js/statement-break.html")}}</div> + + + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code>break [etiket];</code></pre> + +<dl> + <dt><code>etiket</code></dt> + <dd>İsteğe bağlıdır.İfade etiketini tanımlamakta kullanılır. Eğer belirtilen ifade bir döngü ya da {{jsxref("Statements/switch", "switch")}} değilse, mutlaka kullanılması gerekir.</dd> +</dl> + +<h2 id="Description">Description</h2> + +<p>The <code>break</code> statement includes an optional label that allows the program to break out of a labeled statement. The <code>break</code> statement needs to be nested within the referenced label. The labeled statement can be any {{jsxref("Statements/block", "block")}} statement; it does not have to be preceded by a loop statement.</p> + +<h2 id="Examples">Examples</h2> + +<p>The following function has a <code>break</code> statement that terminates the {{jsxref("Statements/while", "while")}} loop when <code>i</code> is 3, and then returns the value 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>The following code uses <code>break</code> statements with labeled blocks. A <code>break</code> statement must be nested within any label it references. Notice that <code>inner_block</code> is nested within <code>outer_block</code>.</p> + +<pre class="brush:js;highlight:[1,2,4];">outer_block: { + inner_block: { + console.log('1'); + break outer_block; // breaks out of both inner_block and outer_block + console.log(':-('); // skipped + } + console.log('2'); // skipped +} +</pre> + +<p>The following code also uses <code>break</code> statements with labeled blocks but generates a Syntax Error because its <code>break</code> statement is within <code>block_1</code> but references <code>block_2</code>. A <code>break</code> statement must always be nested within any label it references.</p> + +<pre class="brush:js;highlight:[1,3,6];">block_1: { + console.log('1'); + break block_2; // SyntaxError: label not found +} + +block_2: { + console.log('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('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="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.statements.break")}}</p> + +<h2 id="See_also">See also</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/tr/web/javascript/reference/statements/const/index.html b/files/tr/web/javascript/reference/statements/const/index.html new file mode 100644 index 0000000000..39f62e3144 --- /dev/null +++ b/files/tr/web/javascript/reference/statements/const/index.html @@ -0,0 +1,153 @@ +--- +title: const +slug: Web/JavaScript/Reference/Statements/const +translation_of: Web/JavaScript/Reference/Statements/const +--- +<div>{{jsSidebar("Statements")}}</div> + +<p>170 / 5000</p> + +<h2 id="Çeviri_sonuçları">Çeviri sonuçları</h2> + +<p>Sabit değerler(const), let anahtar sözcüğü kullanılarak bildirilen değişkenler gibi blok kapsamlıdır. Bir sabitin değeri yeniden atama yoluyla değiştirilemez ve yeniden beyan edilemez.</p> + +<div>{{EmbedInteractiveExample("pages/js/statement-const.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="Syntax">Syntax</h2> + +<pre class="syntaxbox notranslate">const <var>name1</var> = <var>value1</var> [, <var>name2</var> = <var>value2</var> [, ... [, <var>nameN</var> = <var>valueN</var>]]];</pre> + +<dl> + <dt><code><var>nameN</var></code></dt> + <dd>The constant's name, which can be any legal {{Glossary("identifier")}}.</dd> + <dt><code><var>valueN</var></code></dt> + <dd>The constant's value. This can be any legal <a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Expressions">expression</a>, including a function expression.</dd> +</dl> + +<p> The <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">Destructuring Assignment </a>syntax can also be used to declare variables.</p> + +<pre class="syntaxbox notranslate">const <var>{ bar }</var> = <em>foo</em>; // where foo = { bar:10, baz:12 }; +/* This creates a constant with the name 'bar', which has a value of 10 */</pre> + +<dl> +</dl> + +<h2 id="Description">Description</h2> + +<p>This declaration creates a constant whose scope can be either global or local to the block in which it is declared. Global constants do <strong>not</strong> become properties of the {{domxref("window")}} object, unlike {{jsxref("Statements/var", "var")}} variables.</p> + +<p>An initializer for a constant is required. You must specify its value in the same statement in which it's declared. (This makes sense, given that it can't be changed later.)</p> + +<p>The <strong><code>const</code> declaration</strong> creates a read-only reference to a value. It does <strong>not</strong> mean the value it holds is immutable—just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered.</p> + +<p>All the considerations about the "<a href="/en-US/docs/Web/JavaScript/Reference/Statements/let#Temporal_dead_zone">temporal dead zone</a>" apply to both {{jsxref("Statements/let", "let")}} and <code>const</code>.</p> + +<p>A constant cannot share its name with a function or a variable in the same scope.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Basic_const_usage">Basic const usage</h3> + +<p>Constants can be declared with uppercase or lowercase, but a common convention is to use all-uppercase letters.</p> + +<pre class="brush: js; notranslate">// define MY_FAV as a constant and give it the value 7 +const MY_FAV = 7; + +// this will throw an error - Uncaught TypeError: Assignment to constant variable. +MY_FAV = 20; + +// MY_FAV is 7 +console.log('my favorite number is: ' + MY_FAV); + +// trying to redeclare a constant throws an error +// Uncaught SyntaxError: Identifier 'MY_FAV' has already been declared +const MY_FAV = 20; + +// the name MY_FAV is reserved for constant above, so this will fail too +var MY_FAV = 20; + +// this throws an error too +let MY_FAV = 20; + +</pre> + +<h3 id="Block_scoping">Block scoping</h3> + +<p>It's important to note the nature of block scoping.</p> + +<pre class="brush: js notranslate">if (MY_FAV === 7) { + // this is fine and creates a block scoped MY_FAV variable + // (works equally well with let to declare a block scoped non const variable) + let MY_FAV = 20; + + // MY_FAV is now 20 + console.log('my favorite number is ' + MY_FAV); + + // this gets hoisted into the global context and throws an error + var MY_FAV = 20; +} + +// MY_FAV is still 7 +console.log('my favorite number is ' + MY_FAV); +</pre> + +<h3 id="const_needs_to_be_initialized">const needs to be initialized</h3> + +<pre class="brush: js notranslate">// throws an error +// Uncaught SyntaxError: Missing initializer in const declaration + +const FOO; +</pre> + +<h3 id="const_in_objects_and_arrays">const in objects and arrays</h3> + +<p>const also works on objects and arrays.</p> + +<pre class="brush: js notranslate">const MY_OBJECT = {'key': 'value'}; + +// Attempting to overwrite the object throws an error +// Uncaught TypeError: Assignment to constant variable. +MY_OBJECT = {'OTHER_KEY': 'value'}; + +// However, object keys are not protected, +// so the following statement is executed without problem +MY_OBJECT.key = 'otherValue'; // Use Object.freeze() to make object immutable + +// The same applies to arrays +const MY_ARRAY = []; +// It's possible to push items into the array +MY_ARRAY.push('A'); // ["A"] +// However, assigning a new array to the variable throws an error +// Uncaught TypeError: Assignment to constant variable. +MY_ARRAY = ['B'];</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-let-and-const-declarations', 'Let and Const Declarations')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.statements.const")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Statements/var", "var")}}</li> + <li>{{jsxref("Statements/let", "let")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Constants">Constants in the JavaScript Guide</a></li> +</ul> diff --git a/files/tr/web/javascript/reference/statements/export/index.html b/files/tr/web/javascript/reference/statements/export/index.html new file mode 100644 index 0000000000..ccc8dd657e --- /dev/null +++ b/files/tr/web/javascript/reference/statements/export/index.html @@ -0,0 +1,186 @@ +--- +title: export +slug: Web/JavaScript/Reference/Statements/export +translation_of: Web/JavaScript/Reference/Statements/export +--- +<div>{{jsSidebar("Statements")}}</div> + +<p><strong><code>export</code></strong> ifadesi JavaScript modülleri oluştururken fonksiyonların, nesnelerin ve temel değerlerin dışarı aktarılmasını sağlayarak, diğer programlar tarafından {{jsxref("Statements/import", "import")}} ifadesiyle kullanılmasını sağlar.</p> + +<div class="note"> +<p>Bu özellik şu an için yerel olarak sadece Safari'de uygulanmıştır. <a href="https://github.com/google/traceur-compiler">Traceur Compiler</a>, <a href="http://babeljs.io/">Babel</a> veya <a href="https://github.com/rollup/rollup">Rollup</a> gibi bir çok transpiler tarafından da uygulanmaktadır.</p> +</div> + +<h2 id="Sözdizim">Sözdizim</h2> + +<pre class="syntaxbox">export { <em>isim<var>1</var></em>, <em>isim</em><var>2</var>, …, <em>isim</em><var>N</var> }; +export { <var>degisken1</var> as <var>isim1</var>, <var>degisken2</var> as <var>isim2</var>, …, <var>isimN</var> }; +export let <var>isim1</var>, <var>isim2</var>, …, <var>isimN</var>; // ayrıca var, function +export let <var>isim1</var> = …, <var>isim2</var> = …, …, <var>isimN</var>; // ayrıca var, const + +export default <em>ifade</em>; +export default function (…) { … } // ayrıca class, function* +export default function isim1(…) { … } // ayrıca class, function* +export { <var>isim1</var> as default, … }; + +export * from …; +export { <em>isim</em><var>1</var>, <em>isim</em><var>2</var>, …, <em>isim</em><var>N</var> } from …; +export { <var>import1</var> as <var>isim1</var>, <var>import2</var> as <var>isim2</var>, …, <var>isimN</var> } from …;</pre> + +<dl> + <dt><code>isimN</code></dt> + <dd>Dışa aktarılacak belirleyici (böylece {{jsxref("Statements/import", "import")}} kullanılarak diğer programda içe aktarılabilir).</dd> +</dl> + +<h2 id="Açıklama">Açıklama</h2> + +<p>İki çeşit dışa aktarım vardır. Her biri aşağıdaki sözdizimlerden birine karşılık gelmektedir:</p> + +<ul> + <li>İsimlendirilmiş dışa aktarım: + <pre class="brush: js">// önceden tanımlı bir fonksiyonu dışa aktarır +export { birFonksiyon }; + +// bir sabiti dışa aktarır +export const karekok = Math.sqrt(2);</pre> + </li> + <li>Varsayılan dışa aktarım (fonksiyon): + <pre class="brush: js">export default function() {} </pre> + </li> + <li>Varsayılan dışa aktarım (sınıf): + <pre class="brush: js">export default class {} </pre> + </li> +</ul> + +<p>İsimlendirilmiş dışa aktarımlar birden fazla değeri dışarı aktarmak için kullanışlıdır. İçe aktarım sırasında, aynı isimle ve buna karşılık gelen değeri ile kullanılabilecektir.</p> + +<p>Varsayılan dışa aktarımla ilgili olarak, her bir modül için sadece bir adet varsayılan dışa aktarım vardır. Varsayılan dışa aktarım bir fonksiyon, bir sınıf, bir nesne veya başka bir şey olabilir. Dışa aktarımı en basit olacağından dolayı bu değer dışa aktarılan "ana" değer olarak nitelendirilecektir.</p> + +<p>Varsayılanların dışa aktarımı: Aşağıdaki sözdizimi varsayılan dışa aktarımı içe aktaran modülde gerçekleşmeyecektir:</p> + +<pre>export * from …;</pre> + +<p>Eğer varsayılanı dışa aktarmak isterseniz, aşağıdakini yazınız:</p> + +<pre>import mod from "mod"; +export default mod;</pre> + +<h2 id="Örnekler">Örnekler</h2> + +<h3 id="İsimlendirilmiş_dışa_aktarımları_kullanmak">İsimlendirilmiş dışa aktarımları kullanmak</h3> + +<p>Modül içerisinde, aşağıdaki kodu kullanabiliriz:</p> + +<pre class="brush: js">// modül "benim-modulum.js" +function kup(x) { + return x * x * x; +} +const deger = Math.PI + Math.SQRT2; +export { kup, deger }; +</pre> + +<p>Bu yolla, başka bir kod içerisinde (karşılaştır <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/import">import</a></code>), şunu yapabiliriz:</p> + +<pre class="brush: js">import { kup, deger } from 'benim-modulum'; +console.log(kup(3)); // 27 +console.log(deger); // 4.555806215962888</pre> + +<h3 id="Varsayılanın_dışa_aktarımının_kullanılması">Varsayılanın dışa aktarımının kullanılması</h3> + +<p>Eğer modülümüz için tek bir değeri dışa aktarmak istiyorsak veya bir son değere sahip olmak istiyorsak, varsayılan dışa aktarımı kullanabiliriz:</p> + +<pre class="brush: js">// modül "benim-modulum.js" +export default function kup(x) { + return x * x * x; +} +</pre> + +<p>Sonra, başka bir kod içerisinde, varsayılan dışa aktarımı içe aktarmak anlaşılır olacaktır:</p> + +<pre class="brush: js">import kup from 'benim-modulum'; +console.log(kup(3)); // 27 +</pre> + +<p>Dikkate alınız ki <code>var</code>, <code>let</code> veya <code>const</code> anahtar kelimelerini <code>export default</code> ile kullanamazsınız.</p> + +<h2 id="Spesifikasyonlar">Spesifikasyonlar</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Spesifikasyon</th> + <th scope="col">Durum</th> + <th scope="col">Açıklama</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-exports', 'Exports')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>İlk tanım.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-exports', 'Exports')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Tarayıcı_uyumluluğu">Tarayıcı uyumluluğu</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Özellik</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Temel destek</td> + <td>61 (60 w/ flag)</td> + <td>{{CompatNo}} (54 w/ flag)</td> + <td>{{CompatNo}} (15 w/flag)</td> + <td>{{CompatNo}}</td> + <td>10.1</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Özellik</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>Temel destek</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>10.3</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ayrıca_bakınız">Ayrıca bakınız</h2> + +<ul> + <li>{{jsxref("Statements/import", "import")}}</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/tr/web/javascript/reference/statements/index.html b/files/tr/web/javascript/reference/statements/index.html new file mode 100644 index 0000000000..b9fd7f94a0 --- /dev/null +++ b/files/tr/web/javascript/reference/statements/index.html @@ -0,0 +1,141 @@ +--- +title: Statements and declarations +slug: Web/JavaScript/Reference/Statements +tags: + - JavaScript + - NeedsTranslation + - Reference + - TopicStub + - statements +translation_of: Web/JavaScript/Reference/Statements +--- +<div>{{jsSidebar("Statements")}}</div> + +<p>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.</p> + +<h2 id="Statements_and_declarations_by_category">Statements and declarations by category</h2> + +<p>For an alphabetical listing see the sidebar on the left.</p> + +<h3 id="Control_flow">Control flow</h3> + +<dl> + <dt>{{jsxref("Statements/block", "Block")}}</dt> + <dd>A block statement is used to group zero or more statements. The block is delimited by a pair of curly brackets.</dd> + <dt>{{jsxref("Statements/break", "break")}}</dt> + <dd>Terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.</dd> + <dt>{{jsxref("Statements/continue", "continue")}}</dt> + <dd>Terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.</dd> + <dt>{{jsxref("Statements/Empty", "Empty")}}</dt> + <dd>An empty statement is used to provide no statement, although the JavaScript syntax would expect one.</dd> + <dt>{{jsxref("Statements/if...else", "if...else")}}</dt> + <dd>Executes a statement if a specified condition is true. If the condition is false, another statement can be executed.</dd> + <dt>{{jsxref("Statements/switch", "switch")}}</dt> + <dd>Evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.</dd> + <dt>{{jsxref("Statements/throw", "throw")}}</dt> + <dd>Throws a user-defined exception.</dd> + <dt>{{jsxref("Statements/try...catch", "try...catch")}}</dt> + <dd>Marks a block of statements to try, and specifies a response, should an exception be thrown.</dd> +</dl> + +<h3 id="Declarations">Declarations</h3> + +<dl> + <dt>{{jsxref("Statements/var", "var")}}</dt> + <dd>Declares a variable, optionally initializing it to a value.</dd> + <dt>{{jsxref("Statements/let", "let")}}</dt> + <dd>Declares a block scope local variable, optionally initializing it to a value.</dd> + <dt>{{jsxref("Statements/const", "const")}}</dt> + <dd>Declares a read-only named constant.</dd> +</dl> + +<h3 id="Functions_and_classes">Functions and classes</h3> + +<dl> + <dt>{{jsxref("Statements/function", "function")}}</dt> + <dd>Declares a function with the specified parameters.</dd> + <dt>{{jsxref("Statements/function*", "function*")}}</dt> + <dd>Generators functions enable writing <a href="/en-US/docs/Web/JavaScript/Guide/The_Iterator_protocol">iterators</a> more easily.</dd> + <dt>{{jsxref("Statements/return", "return")}}</dt> + <dd>Specifies the value to be returned by a function.</dd> + <dt>{{jsxref("Statements/class", "class")}}</dt> + <dd>Declares a class.</dd> +</dl> + +<h3 id="Iterations">Iterations</h3> + +<dl> + <dt>{{jsxref("Statements/do...while", "do...while")}}</dt> + <dd>Creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.</dd> + <dt>{{jsxref("Statements/for", "for")}}</dt> + <dd>Creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.</dd> + <dt>{{deprecated_inline}} {{non-standard_inline()}} {{jsxref("Statements/for_each...in", "for each...in")}}</dt> + <dd>Iterates a specified variable over all values of object's properties. For each distinct property, a specified statement is executed.</dd> + <dt>{{jsxref("Statements/for...in", "for...in")}}</dt> + <dd>Iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.</dd> + <dt>{{jsxref("Statements/for...of", "for...of")}}</dt> + <dd>Iterates over iterable objects (including {{jsxref("Global_Objects/Array","arrays","","true")}}, array-like objects, <a href="/en-US/docs/JavaScript/Guide/Iterators_and_Generators">iterators and generators</a>), invoking a custom iteration hook with statements to be executed for the value of each distinct property.</dd> + <dt>{{jsxref("Statements/while", "while")}}</dt> + <dd>Creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.</dd> +</dl> + +<h3 id="Others">Others</h3> + +<dl> + <dt>{{jsxref("Statements/debugger", "debugger")}}</dt> + <dd>Invokes any available debugging functionality. If no debugging functionality is available, this statement has no effect.</dd> + <dt>{{jsxref("Statements/export", "export")}}</dt> + <dd>Used to export functions to make them available for imports in external modules, another scripts.</dd> + <dt>{{jsxref("Statements/import", "import")}}</dt> + <dd>Used to import functions exported from an external module, another script.</dd> + <dt>{{jsxref("Statements/label", "label")}}</dt> + <dd>Provides a statement with an identifier that you can refer to using a <code>break</code> or <code>continue</code> statement.</dd> +</dl> + +<dl> + <dt>{{deprecated_inline}} {{jsxref("Statements/with", "with")}}</dt> + <dd>Extends the scope chain for a statement.</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('ES1', '#sec-12', 'Statements')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition</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>New: 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="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators">Operators</a></li> +</ul> diff --git a/files/tr/web/javascript/reference/statements/return/index.html b/files/tr/web/javascript/reference/statements/return/index.html new file mode 100644 index 0000000000..1a1188b3d5 --- /dev/null +++ b/files/tr/web/javascript/reference/statements/return/index.html @@ -0,0 +1,195 @@ +--- +title: return +slug: Web/JavaScript/Reference/Statements/return +tags: + - JavaScript + - fonksiyon durdurmak + - fonksiyon döndürmek + - komutlar + - return komutu +translation_of: Web/JavaScript/Reference/Statements/return +--- +<div>{{jsSidebar("Statements")}}</div> + +<p><strong><code>return</code></strong> komutu fonskiyonun çalışmasını bitirir ve fonksiyondan döndürülecek değeri belirler.</p> + +<h2 id="Sözdizimi">Sözdizimi</h2> + +<pre class="syntaxbox">return [[ifade]]; </pre> + +<dl> + <dt><code>ifade</code></dt> + <dd>Döndürülecek ifade. Eğer atlanırsa, <code>undefined</code> döndürülür.</dd> +</dl> + +<h2 id="Açıklama">Açıklama</h2> + +<p>Bir fonksiyonda <code><strong>return </strong></code>komutu çağırılırsa, o fonksiyonun çalışması durur. Eğer belirtilmişse, verilen değer fonksiyonu çağırana kadar döndürülür. Eğer ifade belirtilmemişse, <code>undefined döndürülür</code>. Aşağıdaki tüm <strong><code>return </code></strong>komutları çağırıldıkları fonksiyonun çalışmasını durdururlar:</p> + +<pre class="brush: js">return; +return true; +return false; +return x; +return x + y / 3; +</pre> + +<h3 id="Otomatik_Noktalı_Virgül_İlavesi">Otomatik Noktalı Virgül İlavesi</h3> + +<p><code><strong>return </strong></code>komutu <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion">otomatik noktalı virgül ilavesi (ASI)</a>'ne dahildir. <code><strong>return </strong></code>ile <code><strong>ifade</strong></code> aynı satırda olmalıdır. Aksi halde;</p> + +<pre class="brush: js">return +a + b; +</pre> + +<p>ASI tarafıdan aşağıdaki gibi değiştirilir:</p> + +<pre>return; +a + b; +</pre> + +<p>Ve konsol size şu uyarıyı verecektir:"unreachable code after return statement (<em>return komutundan sonra ulaşılamayan kod</em>)".</p> + +<div class="note"> "return komutundan sonra ulaşılamayan kod" uyarısı Gecko 40 {{geckoRelease(40)}} sürümü ile başlamıştır.</div> + +<h2 id="Örnekler">Örnekler</h2> + +<h3 id="Değer_döndürme">Değer döndürme</h3> + +<p>Aşağıdaki fonksiyon x argümanının (burada x bir sayıdır), karesini döndürür.</p> + +<pre class="brush: js">function square(x) { + return x * x; +} +</pre> + +<h3 id="Fonksiyonu_yarıda_kesme">Fonksiyonu yarıda kesme</h3> + +<p>return çağırıldığında, çağırıldığı noktada o fonksiyon anında durur .</p> + +<pre class="brush: js">function sayac() { + for (var sayim = 1; ; sayim++) { // sonsuz döngü + console.log(sayim + "A"); // 5'e kadar çıktı verir. + if (sayim === 5) { + return; + } + console.log(sayim + "B"); // 4'e kadar çıktı verir. + } + console.log(sayim + "C"); // hiçbir çıktı vermez. +} + +sayac(); + +// Çıktı: +// 1A +// 1B +// 2A +// 2B +// 3A +// 3B +// 4A +// 4B +// 5A +</pre> + +<h3 id="Bir_fonksiyonu_döndürme">Bir fonksiyonu döndürme</h3> + +<p>Kapsanımlar hakkındaki şu makaleye de bakınız: <a href="/en-US/docs/Web/JavaScript/Closures">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="Özellikler">Özellikler</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Özellik</th> + <th scope="col">Durum</th> + <th scope="col">Açıklama</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Ön-tanımlı.</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="Tarayıcı_Uyumluluğu">Tarayıcı Uyumluluğu</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Özellik</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Temel destek</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>Özellik</th> + <th>Android</th> + <th>Android için Chrome</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Temel destek</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="Ayrıca_Bakınız">Ayrıca Bakınız</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope" title="En/Core_JavaScript_1.5_Reference/Functions">Fonksiyonlar</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Closures">Kapsanımlar</a></li> +</ul> diff --git a/files/tr/web/javascript/reference/statements/throw/index.html b/files/tr/web/javascript/reference/statements/throw/index.html new file mode 100644 index 0000000000..5ad62b840f --- /dev/null +++ b/files/tr/web/javascript/reference/statements/throw/index.html @@ -0,0 +1,201 @@ +--- +title: throw +slug: Web/JavaScript/Reference/Statements/throw +translation_of: Web/JavaScript/Reference/Statements/throw +--- +<div>{{jsSidebar("Statements")}}</div> + +<p><code>Throw </code>ifadesi kullanıcı tanımlı bir istisna atar. Mevcut işlevin yürütülmesi durur (atmadan sonraki ifadeler yürütülmez) ve kontrol, çağrı yığındaki ilk yakalama blokuna geçirilir. Arayanlar arasında yakalama bloğu yoksa, program sonlanır.</p> + +<div>{{EmbedInteractiveExample("pages/js/statement-throw.html")}}</div> + +<p class="hidden">Bu interaktif örneğin için kaynak bir GitHub deposunda saklanır. Etkileşimli örnek projesine katkıda bulunmak isterseniz, lütfen <a href="/tr/docs/">https://github.com/mdn/interactive-examples</a> klonlayın ve bize bir request isteği gönderin.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox notranslate">throw <em>ifade</em>; </pre> + +<dl> + <dt><em>ifade</em></dt> + <dd>Hata fırlatmak için ifade.</dd> +</dl> + +<h2 id="Açıklama">Açıklama</h2> + +<p>Bir hata fırlatmak için <code>throw</code> ifadesini kullanın. Bir hata fırlatırken, ifade hatanın değerini belirtir. Aşağıdakilerin her biri bir hata fırlatır:</p> + +<pre class="brush: js notranslate">throw 'Error2'; // String bir ifade ile hata oluşturur. +throw 42; // Integer bir değerde hata oluşturur. +throw true; // Boolean bir ifade de hata oluşturur. +throw new Error('Required'); // `Required` adıyla bir hata nesnesi oluşturur. +</pre> + +<p>Also note that the <code>throw</code> statement is affected by <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion">automatic semicolon insertion (ASI)</a> as no line terminator between the <code>throw</code> keyword and the expression is allowed.</p> + +<h2 id="Örnek">Örnek</h2> + +<h3 id="İstisna_Nesnesi_Örneği">İstisna Nesnesi Örneği</h3> + +<p>Bir istisna atarken bir nesne belirtebilirsiniz. Daha sonra nesnenin özelliklerini <code>catch </code>bloğuna referansta bulabilirsiniz. Aşağıdaki örnek, <code>UserException </code>türünde bir nesne oluşturur ve bunu bir <code>throw </code>ifadesinde kullanır.</p> + +<pre class="brush: js notranslate">function UserException(message) { + this.message = message; + this.name = 'UserException'; +} +function getMonthName(mo) { + mo = mo - 1; // Dizi içinde bir ay sayısı belirlenir (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 { + // try bloğu + var myMonth = 15; // Bir yılda 15 ay bulunmaz. + var monthName = getMonthName(myMonth); +} catch (e) { + monthName = 'unknown'; + console.log(e.message, e.name); // catch bloğuna hata nesnesinin parametreleri giriliyor. +} +</pre> + +<h3 id="Bir_istisnayı_atmanın_başka_bir_örneği">Bir istisnayı atmanın başka bir örneği</h3> + +<p>Aşağıdaki örnek, ABD posta kodu için bir giriş dizesini sınar. Posta kodu geçersiz bir format kullanıyorsa, throw ifadesi bir nesne türü oluşturarak bir istisna atar .</p> + +<p><code>ZipCodeFormatException</code>.</p> + +<pre class="brush: js notranslate">/* + * Zip Kodu objesi oluşturulur. + * + * Kabul edilen zip kodları: + * 12345 + * 12345-6789 + * 123456789 + * 12345 6789 + * + * parametre kabul edilen zip kodlara uygun değilse + * bir istisna atılır. + */ + +function ZipCode(zip) { + zip = new String(zip); + pattern = /[0-9]{5}([- ]?[0-9]{4})?/; + if (pattern.test(zip)) { + // zip kodu değeri dizideki ilk eşleşme olacak + 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 = 'bir posta kodu için beklenen değerlerle uyuşmuyor'; + this.toString = function() { + return this.value + this.message; + }; +} + +/* + * Zip kodlarını doğrulayan bir komut bloğu olabilir. + */ + +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); // 95060 +b = verifyZipCode(9560); // -1 +c = verifyZipCode('a'); // -1 +d = verifyZipCode('95060'); // 95060 +e = verifyZipCode('95060 1234'); // 95060 1234 +</pre> + +<h3 id="Bir_istisnayı_tekrar_atmak">Bir istisnayı tekrar atmak</h3> + +<p>Hatayı yakaladıktan sonra bir özel durumu geri almak için <code>throw </code>kullanabilirsiniz. Aşağıdaki örnek,</p> + +<p>Seğer 50'nin üzerindeyse onu yeniden kullanır. Yeniden biçimlendirilmiş istisna, kullanıcının onu görebilmesi için kapama işlevine veya en üst düzeye kadar çoğalır..</p> + +<pre class="brush: js notranslate">try { + throw n; // integer bir değerde istisna atar +} catch (e) { + if (e <= 50) { + // değer 1 ile 50 arasında ise + } else { + // tekrar bir istisna atar + throw e; + } +} +</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('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td> + <p>Başlangıç</p> + + <p>Javascript 1.4</p> + </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="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.statements.throw")}}</p> + +<h2 id="See_also">See also</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/tr/web/javascript/reference/statements/while/index.html b/files/tr/web/javascript/reference/statements/while/index.html new file mode 100644 index 0000000000..e9135ab063 --- /dev/null +++ b/files/tr/web/javascript/reference/statements/while/index.html @@ -0,0 +1,79 @@ +--- +title: while +slug: Web/JavaScript/Reference/Statements/while +translation_of: Web/JavaScript/Reference/Statements/while +--- +<div>{{jsSidebar("Statements")}}</div> + +<p><strong>while ifadesi</strong> tanımlanan koşul gerçekleştiği sürece belirtilen kodu çalıştırmaya devam eden bir döngü oluşturur. Önce şart kontrol edilir, eğer şart sağlanıyorsa kod çalıştırılır.</p> + +<div>{{EmbedInteractiveExample("pages/js/statement-while.html")}}</div> + + + +<h2 id="Sözdizimi_Syntax">Sözdizimi (Syntax)</h2> + +<pre class="syntaxbox notranslate">while (<var>condition</var>) + <var>statement</var> +</pre> + +<dl> + <dt><code><var>condition</var></code></dt> + <dd>Döngüdeki her bir tekrarlamadan önce kontrol edilen koşul. Eğer koşul sağlanıyorsa (true) <code>statement</code> çalıştırılır. Ancak koşul sağlanmıyorsa (false) <code>statement</code> çalıştırılmaz ve <code>while</code> döngüsünden sonra yazılan kod bloğu ile program çalışmaya devam eder.</dd> + <dt><code><var>statement</var></code></dt> + <dd>Koşul sağlandığında çalıştırılacak olan kod. Döngü içerisinde birden fazla kod satırı çalıştırmak için <a href="/en-US/docs/JavaScript/Reference/Statements/block">block</a> (<code>{ ... }</code>) ifade şeklini kullanabilirsiniz. </dd> + <dd><br> + Not: <code>break</code> ifadesini kullanarak döngüyü dilediğiniz zaman sonlandırabilirsiniz.</dd> +</dl> + +<h2 id="Örnekler">Örnekler</h2> + +<h3 id="while_kullanımı">while kullanımı</h3> + +<p>Aşağıdaki örnekte bulunan (<code>n < 3</code>) ifadesi while döngüsünün koşulu yani <code>condition</code> kısmıdır. Süslü parantezler içerisinde bulunan kısım ise çalıştırılacak olan kod bloğu yani <code>statement</code> kısmıdır. Dolayısıyla aşağıdaki <code>while</code> döngüsü, <code>n</code> değişkeninin değeri üçten küçük olduğu sürece çalışmaya devam eder.</p> + +<pre class="brush:js notranslate">var n = 0; +var x = 0; + +while (n < 3) { + n++; + x += n; +}</pre> + +<p>Her tekrarlamada, döngü <code>n</code> değişkeninin değerini bir arttırır. Ardından <code>n</code> değişkeninin değerini <code>x</code> değişkeninin değerine ekler. Dolayısıyla, <code>x</code> ve <code>n</code> değişkenleri aşağıdaki değerlere sahip olurlar:</p> + +<ul> + <li>İlk tekrardan sonra: <code>n</code> = 1 ve <code>x</code> = 1</li> + <li>İkinci tekrardan sonra: <code>n</code> = 2 ve <code>x</code> = 3</li> + <li>Üçüncü tekrardan sonra: <code>n</code> = 3 ve <code>x</code> = 6</li> +</ul> + +<p>Üçüncü tekrardan sonra, <code>n</code> < 3 koşulu artık sağlanmadığı için döngü sonlanır.</p> + +<h2 id="Özellikler">Özellikler</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-while-statement', 'while statement')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Tarayıcı_uyumluluğu">Tarayıcı uyumluluğu</h2> + + + +<p>{{Compat("javascript.statements.while")}}</p> + +<h2 id="Ayrıca_bakınız">Ayrıca bakınız</h2> + +<ul> + <li>{{jsxref("Statements/do...while", "do...while")}}</li> + <li>{{jsxref("Statements/for", "for")}}</li> +</ul> diff --git a/files/tr/web/javascript/reference/strict_mode/index.html b/files/tr/web/javascript/reference/strict_mode/index.html new file mode 100644 index 0000000000..e87b630e1b --- /dev/null +++ b/files/tr/web/javascript/reference/strict_mode/index.html @@ -0,0 +1,363 @@ +--- +title: Sıkı mod +slug: Web/JavaScript/Reference/Strict_mode +translation_of: Web/JavaScript/Reference/Strict_mode +--- +<div>{{JsSidebar("More")}}</div> + +<div class="callout-box">Sometimes you'll see the default, non-strict mode referred to as <strong>"<a href="https://developer.mozilla.org/docs/Glossary/Sloppy_mode" id="sloppyModeId333">sloppy mode</a>"</strong>. This isn't an official term, but be aware of it, just in case.</div> + +<p>JavaScript's strict mode, introduced in ECMAScript 5, is a way to <em>opt in</em> to a restricted variant of JavaScript, thereby implicitly opting-out of "<a href="https://developer.mozilla.org/docs/Glossary/Sloppy_mode">sloppy mode</a>". Strict mode isn't just a subset: it <em>intentionally</em> has different semantics from normal code. Browsers not supporting strict mode will run strict mode code with different behavior from browsers that do, so don't rely on strict mode without feature-testing for support for the relevant aspects of strict mode. Strict mode code and non-strict mode code can coexist, so scripts can opt into strict mode incrementally.</p> + +<p>Strict mode makes several changes to normal JavaScript semantics:</p> + +<ol> + <li>Eliminates some JavaScript silent errors by changing them to throw errors.</li> + <li>Fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that's not strict mode.</li> + <li>Prohibits some syntax likely to be defined in future versions of ECMAScript.</li> +</ol> + +<p>See <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode/Transitioning_to_strict_mode">transitioning to strict mode</a>, if you want to change your code to work in the restricted variant of JavaScript.</p> + +<h2 id="Invoking_strict_mode">Invoking strict mode</h2> + +<p>Strict mode applies to <em>entire scripts</em> or to <em>individual functions</em>. It doesn't apply to block statements enclosed in <code>{}</code> braces; attempting to apply it to such contexts does nothing. <code>eval</code> code, <code>Function</code> code, event handler attributes, strings passed to <a href="/en-US/docs/Web/API/WindowTimers/setTimeout" title="The documentation about this has not yet been written; please consider contributing!"><code>WindowTimers.setTimeout()</code></a>, and related functions are entire scripts, and invoking strict mode in them works as expected.</p> + +<h3 id="Strict_mode_for_scripts">Strict mode for scripts</h3> + +<p>To invoke strict mode for an entire script, put the <em>exact</em> statement <code>"use strict";</code> (or <code>'use strict';</code>) before any other statements.</p> + +<pre class="brush: js">// Whole-script strict mode syntax +'use strict'; +var v = "Hi! I'm a strict mode script!"; +</pre> + +<p>This syntax has a trap that has <a class="link-https" href="https://bugzilla.mozilla.org/show_bug.cgi?id=579119">already bitten</a> <a class="link-https" href="https://bugzilla.mozilla.org/show_bug.cgi?id=627531">a major site</a>: it isn't possible to blindly concatenate conflicting scripts. Consider concatenating a strict mode script with a non-strict mode script: the entire concatenation looks strict! The inverse is also true: non-strict plus strict looks non-strict. Obviously, concatenation of scripts is never ideal, but if you must, consider enabling strict on a function-by-function basis.</p> + +<p>You can also take the approach of wrapping the entire contents of a script in a function and having that outer function use strict mode. This eliminates the concatenation problem and it means that you have to explicitly export any shared variables out of the function scope.</p> + +<h3 id="Strict_mode_for_functions">Strict mode for functions</h3> + +<p>Likewise, to invoke strict mode for a function, put the <em>exact</em> statement <code>"use strict";</code> (or <code>'use strict';</code>) in the function's body before any other statements.</p> + +<pre class="brush: js">function strict() { + // Function-level strict mode syntax + '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_for_modules">Strict mode for modules</h3> + +<p>ECMAScript 2015 introduced <a href="/en-US/docs/Web/JavaScript/Reference/Statements/export">JavaScript modules</a> and therefore a 3rd way to enter strict mode. The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.</p> + +<pre class="brush: js">function strict() { + // because this is a module, I'm strict by default +} +export default strict; +</pre> + +<h2 id="Changes_in_strict_mode">Changes in strict mode</h2> + +<p>Strict mode changes both syntax and runtime behavior. Changes generally fall into these categories: changes converting mistakes into errors (as syntax errors or at runtime), changes simplifying how the particular variable for a given use of a name is computed, changes simplifying <code>eval</code> and <code>arguments</code>, changes making it easier to write "secure" JavaScript, and changes anticipating future ECMAScript evolution.</p> + +<h3 id="Converting_mistakes_into_errors">Converting mistakes into errors</h3> + +<p>Strict mode changes some previously-accepted mistakes into errors. JavaScript was designed to be easy for novice developers, and sometimes it gives operations which should be errors non-error semantics. Sometimes this fixes the immediate problem, but sometimes this creates worse problems in the future. Strict mode treats these mistakes as errors so that they're discovered and promptly fixed.</p> + +<p>First, strict mode makes it impossible to accidentally create global variables. In normal JavaScript mistyping a variable in an assignment creates a new property on the global object and continues to "work" (although future failure is possible: likely, in modern JavaScript). Assignments, which would accidentally create global variables, instead throw an error in strict mode:</p> + +<pre class="brush: js">'use strict'; + // Assuming no global variable mistypedVariable exists +mistypeVariable = 17; // this line throws a ReferenceError due to the + // misspelling of variable +</pre> + +<p>Second, strict mode makes assignments which would otherwise silently fail to throw an exception. For example, <code>NaN</code> is a non-writable global variable. In normal code assigning to <code>NaN</code> does nothing; the developer receives no failure feedback. In strict mode assigning to <code>NaN</code> throws an exception. Any assignment that silently fails in normal code (assignment to a non-writable global or property, assignment to a getter-only property, assignment to a new property on a <a href="/en-US/Web/JavaScript/Reference/Global_Objects/Object/preventExtensions" title="en-US/JavaScript/Reference/Global Objects/Object/preventExtensions">non-extensible</a> object) will throw in strict mode:</p> + +<pre class="brush: js">'use strict'; + +// Assignment to a non-writable global +var undefined = 5; // throws a TypeError +var Infinity = 5; // throws a TypeError + +// Assignment to a non-writable property +var obj1 = {}; +Object.defineProperty(obj1, 'x', { value: 42, writable: false }); +obj1.x = 9; // throws a TypeError + +// Assignment to a getter-only property +var obj2 = { get x() { return 17; } }; +obj2.x = 5; // throws a TypeError + +// Assignment to a new property on a non-extensible object +var fixed = {}; +Object.preventExtensions(fixed); +fixed.newProp = 'ohai'; // throws a TypeError +</pre> + +<p>Third, strict mode makes attempts to delete undeletable properties throw (where before the attempt would simply have no effect):</p> + +<pre class="brush: js">'use strict'; +delete Object.prototype; // throws a TypeError +</pre> + +<p>Fourth, strict mode prior to Gecko 34 requires that all properties named in an object literal be unique. The normal code may duplicate property names, with the last one determining the property's value. But since only the last one does anything, the duplication is simply a vector for bugs, if the code is modified to change the property value other than by changing the last instance. Duplicate property names are a syntax error in strict mode:</p> + +<div class="note"> +<p>This is no longer the case in ECMAScript 2015 (<a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1041128">bug 1041128</a>).</p> +</div> + +<pre class="brush: js">'use strict'; +var o = { p: 1, p: 2 }; // !!! syntax error +</pre> + +<p>Fifth, strict mode requires that function parameter names be unique. In normal code the last duplicated argument hides previous identically-named arguments. Those previous arguments remain available through <code>arguments[i]</code>, so they're not completely inaccessible. Still, this hiding makes little sense and is probably undesirable (it might hide a typo, for example), so in strict mode duplicate argument names are a syntax error:</p> + +<pre class="brush: js">function sum(a, a, c) { // !!! syntax error + 'use strict'; + return a + a + c; // wrong if this code ran +} +</pre> + +<p>Sixth, a strict mode in ECMAScript 5 forbids octal syntax. The octal syntax isn't part of ECMAScript 5, but it's supported in all browsers by prefixing the octal number with a zero: <code>0644 === 420</code> and <code>"\045" === "%"</code>. In ECMAScript 2015 Octal number is supported by prefixing a number with "<code>0o</code>". i.e. </p> + +<pre class="brush: js">var a = 0o10; // ES2015: Octal</pre> + +<p>Novice developers sometimes believe a leading zero prefix has no semantic meaning, so they use it as an alignment device — but this changes the number's meaning! A leading zero syntax for the octals is rarely useful and can be mistakenly used, so strict mode makes it a syntax error:</p> + +<pre class="brush: js">'use strict'; +var sum = 015 + // !!! syntax error + 197 + + 142; + +var sumWithOctal = 0o10 + 8; +console.log(sumWithOctal); // 16 +</pre> + +<p>Seventh, strict mode in ECMAScript 2015 forbids setting properties on <a href="/en-US/docs/Glossary/primitive">primitive</a> values. Without strict mode, setting properties is simply ignored (no-op), with strict mode, however, a {{jsxref("TypeError")}} is thrown.</p> + +<pre class="brush: js">(function() { +'use strict'; + +false.true = ''; // TypeError +(14).sailing = 'home'; // TypeError +'with'.you = 'far away'; // TypeError + +})();</pre> + +<h3 id="Simplifying_variable_uses">Simplifying variable uses</h3> + +<p>Strict mode simplifies how variable names map to particular variable definitions in the code. Many compiler optimizations rely on the ability to say that variable <em>X</em> is stored in <em>that</em> location: this is critical to fully optimizing JavaScript code. JavaScript sometimes makes this basic mapping of name to variable definition in the code impossible to perform until runtime. Strict mode removes most cases where this happens, so the compiler can better optimize strict mode code.</p> + +<p>First, strict mode prohibits <code>with</code>. The problem with <code>with</code> is that any name inside the block might map either to a property of the object passed to it, or to a variable in surrounding (or even global) scope, at runtime: it's impossible to know which beforehand. Strict mode makes <code>with</code> a syntax error, so there's no chance for a name in a <code>with</code> to refer to an unknown location at runtime:</p> + +<pre class="brush: js">'use strict'; +var x = 17; +with (obj) { // !!! syntax error + // If this weren't strict mode, would this be var x, or + // would it instead be obj.x? It's impossible in general + // to say without running the code, so the name can't be + // optimized. + x; +} +</pre> + +<p>The simple alternative of assigning the object to a short name variable, then accessing the corresponding property on that variable, stands ready to replace <code>with</code>.</p> + +<p>Second, <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> of strict mode code does not introduce new variables into the surrounding scope</a>. In normal code <code>eval("var x;")</code> introduces a variable <code>x</code> into the surrounding function or the global scope. This means that, in general, in a function containing a call to <code>eval</code> every name not referring to an argument or local variable must be mapped to a particular definition at runtime (because that <code>eval</code> might have introduced a new variable that would hide the outer variable). In strict mode <code>eval</code> creates variables only for the code being evaluated, so <code>eval</code> can't affect whether a name refers to an outer variable or some local variable:</p> + +<pre class="brush: js">var x = 17; +var evalX = eval("'use strict'; var x = 42; x;"); +console.assert(x === 17); +console.assert(evalX === 42); +</pre> + +<p>If the function <code>eval</code> is invoked by an expression of the form <code>eval(...)</code> in strict mode code, the code will be evaluated as strict mode code. The code may explicitly invoke strict mode, but it's unnecessary to do so.</p> + +<pre class="brush: js">function strict1(str) { + 'use strict'; + return eval(str); // str will be treated as strict mode code +} +function strict2(f, str) { + 'use strict'; + return f(str); // not eval(...): str is strict if and only + // if it invokes strict mode +} +function nonstrict(str) { + return eval(str); // str is strict if and only + // if it invokes strict mode +} + +strict1("'Strict mode code!'"); +strict1("'use strict'; 'Strict mode code!'"); +strict2(eval, "'Non-strict code.'"); +strict2(eval, "'use strict'; 'Strict mode code!'"); +nonstrict("'Non-strict code.'"); +nonstrict("'use strict'; 'Strict mode code!'"); +</pre> + +<p>Thus names in strict mode <code>eval</code> code behave identically to names in strict mode code not being evaluated as the result of <code>eval</code>.</p> + +<p>Third, strict mode forbids deleting plain names. <code>delete name</code> in strict mode is a syntax error:</p> + +<pre class="brush: js">'use strict'; + +var x; +delete x; // !!! syntax error + +eval('var y; delete y;'); // !!! syntax error</pre> + +<h3 id="Making_eval_and_arguments_simpler">Making <code>eval</code> and <code>arguments</code> simpler</h3> + +<p>Strict mode makes <code>arguments</code> and <code>eval</code> less bizarrely magical. Both involve a considerable amount of magical behavior in normal code: <code>eval</code> to add or remove bindings and to change binding values, and <code>arguments</code> by its indexed properties aliasing named arguments. Strict mode makes great strides toward treating <code>eval</code> and <code>arguments</code> as keywords, although full fixes will not come until a future edition of ECMAScript.</p> + +<p>First, the names <code>eval</code> and <code>arguments</code> can't be bound or assigned in language syntax. All these attempts to do so are syntax errors:</p> + +<pre class="brush: js">'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>Second, strict mode code doesn't alias properties of <code>arguments</code> objects created within it. In normal code within a function whose first argument is <code>arg</code>, setting <code>arg</code> also sets <code>arguments[0]</code>, and vice versa (unless no arguments were provided or <code>arguments[0]</code> is deleted). <code>arguments</code> objects for strict mode functions store the original arguments when the function was invoked. <code>arguments[i]</code> does not track the value of the corresponding named argument, nor does a named argument track the value in the corresponding <code>arguments[i]</code>.</p> + +<pre class="brush: js">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>Third, <code>arguments.callee</code> is no longer supported. In normal code <code>arguments.callee</code> refers to the enclosing function. This use case is weak: simply name the enclosing function! Moreover, <code>arguments.callee</code> substantially hinders optimizations like inlining functions, because it must be made possible to provide a reference to the un-inlined function if <code>arguments.callee</code> is accessed. <code>arguments.callee</code> for strict mode functions is a non-deletable property which throws an error when set or retrieved:</p> + +<pre class="brush: js">'use strict'; +var f = function() { return arguments.callee; }; +f(); // throws a TypeError +</pre> + +<h3 id="Securing_JavaScript">"Securing" JavaScript</h3> + +<p>Strict mode makes it easier to write "secure" JavaScript. Some websites now provide ways for users to write JavaScript which will be run by the website <em>on behalf of other users</em>. JavaScript in browsers can access the user's private information, so such JavaScript must be partially transformed before it is run, to censor access to forbidden functionality. JavaScript's flexibility makes it effectively impossible to do this without many runtime checks. Certain language functions are so pervasive that performing runtime checks has a considerable performance cost. A few strict mode tweaks, plus requiring that user-submitted JavaScript be strict mode code and that it be invoked in a certain manner, substantially reduce the need for those runtime checks.</p> + +<p>First, the value passed as <code>this</code> to a function in strict mode is not forced into being an object (a.k.a. "boxed"). For a normal function, <code>this</code> is always an object: either the provided object if called with an object-valued <code>this</code>; the value, boxed, if called with a Boolean, string, or number <code>this</code>; or the global object if called with an <code>undefined</code> or <code>null</code> <code>this</code>. (Use <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>, or <a href="/en-US/Web/JavaScript/Reference/Global_Objects/Function/bind" title="en-US/JavaScript/Reference/Global_Objects/Function/bind"><code>bind</code></a> to specify a particular <code>this</code>.) Not only is automatic boxing a performance cost, but exposing the global object in browsers is a security hazard because the global object provides access to functionality that "secure" JavaScript environments must restrict. Thus for a strict mode function, the specified <code>this</code> is not boxed into an object, and if unspecified, <code>this</code> will be <code>undefined</code>:</p> + +<pre class="brush: js">'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>That means, among other things, that in browsers it's no longer possible to reference the <code>window</code> object through <code>this</code> inside a strict mode function.</p> + +<p>Second, in strict mode it's no longer possible to "walk" the JavaScript stack via commonly-implemented extensions to ECMAScript. In normal code with these extensions, when a function <code>fun</code> is in the middle of being called, <code>fun.caller</code> is the function that most recently called <code>fun</code>, and <code>fun.arguments</code> is the <code>arguments</code> for that invocation of <code>fun</code>. Both extensions are problematic for "secure" JavaScript because they allow "secured" code to access "privileged" functions and their (potentially unsecured) arguments. If <code>fun</code> is in strict mode, both <code>fun.caller</code> and <code>fun.arguments</code> are non-deletable properties which throw when set or retrieved:</p> + +<pre class="brush: js">function restricted() { + 'use strict'; + restricted.caller; // throws a TypeError + restricted.arguments; // throws a TypeError +} +function privilegedInvoker() { + return restricted(); +} +privilegedInvoker(); +</pre> + +<p>Third, <code>arguments</code> for strict mode functions no longer provide access to the corresponding function call's variables. In some old ECMAScript implementations <code>arguments.caller</code> was an object whose properties aliased variables in that function. This is a <a class="external" href="http://stuff.mit.edu/iap/2008/facebook/">security hazard</a> because it breaks the ability to hide privileged values via function abstraction; it also precludes most optimizations. For these reasons no recent browsers implement it. Yet because of its historical functionality, <code>arguments.caller</code> for a strict mode function is also a non-deletable property which throws when set or retrieved:</p> + +<pre class="brush: js">'use strict'; +function fun(a, b) { + 'use strict'; + var v = 12; + return arguments.caller; // throws a TypeError +} +fun(1, 2); // doesn't expose v (or a or b) +</pre> + +<h3 id="Paving_the_way_for_future_ECMAScript_versions">Paving the way for future ECMAScript versions</h3> + +<p>Future ECMAScript versions will likely introduce new syntax, and strict mode in ECMAScript 5 applies some restrictions to ease the transition. It will be easier to make some changes if the foundations of those changes are prohibited in strict mode.</p> + +<p>First, in strict mode, a short list of identifiers become reserved keywords. These words are <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>. In strict mode, then, you can't name or use variables or arguments with these names.</p> + +<pre class="brush: js">function package(protected) { // !!! + 'use strict'; + var implements; // !!! + + interface: // !!! + while (true) { + break interface; // !!! + } + + function private() { } // !!! +} +function fun(static) { 'use strict'; } // !!! + +</pre> + +<p>Two Mozilla-specific caveats: First, if your code is JavaScript 1.7 or greater (for example in chrome code or when using the right <code><script type=""></code>) and is strict mode code, <code>let</code> and <code>yield</code> have the functionality they've had since those keywords were first introduced. But strict mode code on the web, loaded with <code><script src=""></code> or <code><script>...</script></code>, won't be able to use <code>let</code>/<code>yield</code> as identifiers. Second, while ES5 unconditionally reserves the words <code>class</code>, <code>enum</code>, <code>export</code>, <code>extends</code>, <code>import</code>, and <code>super</code>, before Firefox 5 Mozilla reserved them only in strict mode.</p> + +<p>Second, <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>. In normal mode in browsers, function statements are permitted "everywhere". <em>This is not part of ES5 (or even ES3)!</em> It's an extension with incompatible semantics in different browsers. Note that function statements outside top level are permitted in ES2015.</p> + +<pre class="brush: js">'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>This prohibition isn't strict mode proper because such function statements are an extension of basic ES5. But it is the recommendation of the ECMAScript committee, and browsers will implement it.</p> + +<h2 id="Strict_mode_in_browsers">Strict mode in browsers</h2> + +<p>The major browsers now implement strict mode. However, don't blindly depend on it since there still are numerous <a class="external" 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> or do not support it at all (e.g. Internet Explorer below version 10!). <em>Strict mode changes semantics.</em> Relying on those changes will cause mistakes and errors in browsers which don't implement strict mode. Exercise caution in using strict mode, and back up reliance on strict mode with feature tests that check whether relevant parts of strict mode are implemented. Finally, make sure to <em>test your code in browsers that do and don't support strict mode</em>. If you test only in browsers that don't support strict mode, you're very likely to have problems in browsers that do, and vice versa.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-strict-mode-code', 'Strict Mode Code')}}</td> + </tr> + </tbody> +</table> + +<h2 id="See_also">See also</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> |