From 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:43:23 -0500 Subject: initial commit --- .../tr/web/javascript/reference/classes/index.html | 276 ++++++++++ .../javascript/reference/classes/static/index.html | 127 +++++ .../tr/web/javascript/reference/errors/index.html | 31 ++ .../missing_semicolon_before_statement/index.html | 71 +++ .../reference/functions/arrow_functions/index.html | 359 ++++++++++++ .../web/javascript/reference/functions/index.html | 596 ++++++++++++++++++++ .../global_objects/array/concat/index.html | 167 ++++++ .../global_objects/array/entries/index.html | 129 +++++ .../global_objects/array/every/index.html | 189 +++++++ .../global_objects/array/filter/index.html | 243 +++++++++ .../reference/global_objects/array/find/index.html | 205 +++++++ .../global_objects/array/findindex/index.html | 177 ++++++ .../global_objects/array/foreach/index.html | 308 +++++++++++ .../reference/global_objects/array/from/index.html | 258 +++++++++ .../global_objects/array/includes/index.html | 176 ++++++ .../reference/global_objects/array/index.html | 371 +++++++++++++ .../global_objects/array/indexof/index.html | 246 +++++++++ .../global_objects/array/isarray/index.html | 154 ++++++ .../reference/global_objects/array/join/index.html | 107 ++++ .../global_objects/array/length/index.html | 145 +++++ .../reference/global_objects/array/map/index.html | 307 +++++++++++ .../reference/global_objects/array/of/index.html | 98 ++++ .../reference/global_objects/array/pop/index.html | 117 ++++ .../global_objects/array/prototype/index.html | 205 +++++++ .../reference/global_objects/array/push/index.html | 152 ++++++ .../global_objects/array/reverse/index.html | 107 ++++ .../global_objects/array/shift/index.html | 112 ++++ .../reference/global_objects/array/sort/index.html | 251 +++++++++ .../global_objects/array/splice/index.html | 149 +++++ .../global_objects/array/unshift/index.html | 114 ++++ .../global_objects/array/values/index.html | 86 +++ .../global_objects/arraybuffer/index.html | 222 ++++++++ .../reference/global_objects/boolean/index.html | 159 ++++++ .../global_objects/boolean/prototype/index.html | 76 +++ .../global_objects/boolean/tosource/index.html | 51 ++ .../reference/global_objects/eval/index.html | 318 +++++++++++ .../global_objects/function/apply/index.html | 262 +++++++++ .../reference/global_objects/function/index.html | 189 +++++++ .../javascript/reference/global_objects/index.html | 178 ++++++ .../reference/global_objects/isfinite/index.html | 138 +++++ .../reference/global_objects/isnan/index.html | 170 ++++++ .../reference/global_objects/json/index.html | 205 +++++++ .../global_objects/json/stringify/index.html | 313 +++++++++++ .../reference/global_objects/map/index.html | 207 +++++++ .../global_objects/map/prototype/index.html | 84 +++ .../reference/global_objects/math/index.html | 191 +++++++ .../reference/global_objects/math/sign/index.html | 110 ++++ .../global_objects/object/assign/index.html | 311 +++++++++++ .../object/defineproperty/index.html | 391 +++++++++++++ .../global_objects/object/entries/index.html | 141 +++++ .../global_objects/object/freeze/index.html | 234 ++++++++ .../object/getprototypeof/index.html | 134 +++++ .../reference/global_objects/object/index.html | 213 ++++++++ .../global_objects/object/observe/index.html | 194 +++++++ .../global_objects/object/tostring/index.html | 161 ++++++ .../global_objects/object/values/index.html | 96 ++++ .../global_objects/promise/all/index.html | 234 ++++++++ .../global_objects/promise/catch/index.html | 201 +++++++ .../reference/global_objects/promise/index.html | 317 +++++++++++ .../reference/global_objects/regexp/index.html | 606 +++++++++++++++++++++ .../reference/global_objects/string/index.html | 316 +++++++++++ .../global_objects/string/substring/index.html | 149 +++++ files/tr/web/javascript/reference/index.html | 48 ++ .../reference/lexical_grammar/index.html | 379 +++++++++++++ .../arithmetic_operators/index.html" | 293 ++++++++++ .../bitwise_operators/index.html" | 564 +++++++++++++++++++ .../operat\303\266rler/function_star_/index.html" | 84 +++ .../reference/operat\303\266rler/index.html" | 277 ++++++++++ .../operat\303\266rler/instanceof/index.html" | 207 +++++++ .../mantiksal_operatorler/index.html" | 311 +++++++++++ .../reference/operat\303\266rler/super/index.html" | 165 ++++++ .../reference/operat\303\266rler/this/index.html" | 347 ++++++++++++ .../operat\303\266rler/typeof/index.html" | 259 +++++++++ .../reference/statements/block/index.html | 179 ++++++ .../reference/statements/break/index.html | 117 ++++ .../reference/statements/const/index.html | 153 ++++++ .../reference/statements/export/index.html | 186 +++++++ .../web/javascript/reference/statements/index.html | 141 +++++ .../reference/statements/return/index.html | 195 +++++++ .../reference/statements/throw/index.html | 201 +++++++ .../reference/statements/while/index.html | 79 +++ .../javascript/reference/strict_mode/index.html | 363 ++++++++++++ 82 files changed, 17152 insertions(+) create mode 100644 files/tr/web/javascript/reference/classes/index.html create mode 100644 files/tr/web/javascript/reference/classes/static/index.html create mode 100644 files/tr/web/javascript/reference/errors/index.html create mode 100644 files/tr/web/javascript/reference/errors/missing_semicolon_before_statement/index.html create mode 100644 files/tr/web/javascript/reference/functions/arrow_functions/index.html create mode 100644 files/tr/web/javascript/reference/functions/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/array/concat/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/array/entries/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/array/every/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/array/filter/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/array/find/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/array/findindex/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/array/foreach/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/array/from/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/array/includes/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/array/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/array/indexof/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/array/isarray/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/array/join/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/array/length/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/array/map/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/array/of/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/array/pop/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/array/prototype/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/array/push/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/array/reverse/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/array/shift/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/array/sort/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/array/splice/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/array/unshift/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/array/values/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/arraybuffer/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/boolean/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/boolean/prototype/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/boolean/tosource/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/eval/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/function/apply/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/function/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/isfinite/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/isnan/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/json/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/json/stringify/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/map/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/map/prototype/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/math/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/math/sign/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/object/assign/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/object/defineproperty/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/object/entries/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/object/freeze/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/object/getprototypeof/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/object/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/object/observe/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/object/tostring/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/object/values/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/promise/all/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/promise/catch/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/promise/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/regexp/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/string/index.html create mode 100644 files/tr/web/javascript/reference/global_objects/string/substring/index.html create mode 100644 files/tr/web/javascript/reference/index.html create mode 100644 files/tr/web/javascript/reference/lexical_grammar/index.html create mode 100644 "files/tr/web/javascript/reference/operat\303\266rler/arithmetic_operators/index.html" create mode 100644 "files/tr/web/javascript/reference/operat\303\266rler/bitwise_operators/index.html" create mode 100644 "files/tr/web/javascript/reference/operat\303\266rler/function_star_/index.html" create mode 100644 "files/tr/web/javascript/reference/operat\303\266rler/index.html" create mode 100644 "files/tr/web/javascript/reference/operat\303\266rler/instanceof/index.html" create mode 100644 "files/tr/web/javascript/reference/operat\303\266rler/mantiksal_operatorler/index.html" create mode 100644 "files/tr/web/javascript/reference/operat\303\266rler/super/index.html" create mode 100644 "files/tr/web/javascript/reference/operat\303\266rler/this/index.html" create mode 100644 "files/tr/web/javascript/reference/operat\303\266rler/typeof/index.html" create mode 100644 files/tr/web/javascript/reference/statements/block/index.html create mode 100644 files/tr/web/javascript/reference/statements/break/index.html create mode 100644 files/tr/web/javascript/reference/statements/const/index.html create mode 100644 files/tr/web/javascript/reference/statements/export/index.html create mode 100644 files/tr/web/javascript/reference/statements/index.html create mode 100644 files/tr/web/javascript/reference/statements/return/index.html create mode 100644 files/tr/web/javascript/reference/statements/throw/index.html create mode 100644 files/tr/web/javascript/reference/statements/while/index.html create mode 100644 files/tr/web/javascript/reference/strict_mode/index.html (limited to 'files/tr/web/javascript/reference') 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 +--- +
{{JsSidebar("Classes")}}
+ +

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.

+ +

Sınıf tanımlama

+ +


+ Aslında sınıflar class oluşturmak için kullanılan özel fonksiyonlardır. Javascript sınıfları klasik fonksiyon tanımladığınız gibi tanımlayabilir veya fonksiyonlar ile yapabildiğiniz gibi bir değişkene atayabilirsiniz.

+ +

Sınıf Tanımları

+ +

Bir sınıf tanımlamanın bir yolu class ifadesini sınıf adınızla birlikte kullanmaktır. (Örn: Dikdortgen)

+ +
class Dikdortgen {
+  constructor(yukseklik, genislik) {
+    this.yukseklik = yukseklik;
+    this.genislik = genislik;
+  }
+}
+ +

Erişim

+ +

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")}}:

+ +
var p = new Galeri(); // ReferenceError
+
+class Galeri {}
+
+ +

Class expressions

+ +

Bir class'ı tanımlamanın bir başka yolu ise "class" ifadesidir. Class ifadelerine isim verilebilir. İsimli olan bir class ifadesi class body'sinin localidir.

+ +

 

+ +
// 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;
+  }
+};
+
+ +

Class body and method definitions

+ +

The body of a class is the part that is in curly brackets {}. This is where you define class members, such as methods or constructors.

+ +

Strict mode

+ +

The bodies of class declarations and class expressions are executed in strict mode.

+ +

Constructor

+ +

The constructor method is a special method for creating and initializing an object created with a class. 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 constructor method.

+ +

A constructor can use the super keyword to call the constructor of a parent class.

+ +

Prototype methods

+ +

See also method definitions.

+ +
class Polygon {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+
+  get area() {
+    return this.calcArea();
+  }
+
+  calcArea() {
+    return this.height * this.width;
+  }
+}
+ +

Static methods

+ +

The static keyword defines a static method for a class. Static methods are called without instantiating their class and are also not callable when the class is instantiated. Static methods are often used to create utility functions for an application.

+ +
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));
+ +

Sub classing with extends

+ +

The extends keyword is used in class declarations or class expressions to create a class as a child of another class.

+ +
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.');
+  }
+}
+
+ +

Super class calls with super

+ +

The super keyword is used to call functions on an object's parent.

+ +
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.');
+  }
+}
+
+ +

Mix-ins

+ +

Abstract subclasses or mix-ins 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.

+ +

A function with a superclass as input and a subclass extending that superclass as output can be used to implement mix-ins in ECMAScript:

+ +
var CalculatorMixin = Base => class extends Base {
+  calc() { }
+};
+
+var RandomizerMixin = Base => class extends Base {
+  randomize() { }
+};
+
+ +

A class that uses these mix-ins can then be written like this:

+ +
class Foo { }
+class Bar extends CalculatorMixin(RandomizerMixin(Foo)) { }
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)EdgeInternet ExplorerOperaSafari
Basic support{{CompatChrome(42.0)}}[1]
+ {{CompatChrome(49.0)}}
4513{{CompatNo}}{{CompatNo}}{{CompatSafari(9.0)}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}45{{CompatUnknown}}{{CompatUnknown}}9{{CompatChrome(42.0)}}[1]
+ {{CompatChrome(49.0)}}
+
+ +

[1] Requires strict mode. Non-strict mode support is behind the flag "Enable Experimental JavaScript", disabled by default.

+ +

See also

+ + 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 +--- +
{{jsSidebar("Classes")}}
+ +

static anahtar kelimesi, bir sınıf için statik bir metod tanımlar.

+ +

Syntax

+ +
static metodAdi() { ... }
+ +

Description

+ +

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.

+ +

Examples

+ +

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. 

+ +
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'.
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(42.0)}}{{CompatGeckoDesktop(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatGeckoMobile(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(42.0)}}
+
+ +

See also

+ + 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 +--- +

{{jsSidebar("Errors")}}

+ +

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 name and a message.

+ +

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.

+ +

List of errors

+ +

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!

+ +

{{ListSubPages("/en-US/docs/Web/JavaScript/Reference/Errors")}}

+ +

See also

+ + 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 +--- +
+

{{jsSidebar("Errors")}}

+ +

Mesaj

+ +
Syntax Error: Missing ; before statement
+//Sentaks Hatası: ifadeden önce ; eksik
+
+ +

Hata Tipi

+ +

{{jsxref("SyntaxError")}}.

+ +

Ne Ters Gitti?

+ +

Kodunuzda bir yerlerde noktalı virgül (;) eksik. JavaScript ifadeleri noktalı virgül ile sonlandırılmalıdır. Bu ifadelerden bazılarına otomatik noktalı virgül eklenmektedir (ASI), fakat bu durumda, JavaScript'in kaynak kodunu doğru bir şekilde çözümleyebilmesi için noktalı virgülü sizin eklemeniz gerekmektedir. 

+ +

Bununla birlikte, çoğunlukla bu hata, başka bir hatanın sonucudur, var 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.
+  

+ +

Örnekler

+ +

Kaçınılan metin ifadeleri

+ +

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:

+ +
var foo = 'Tomris'in barı';
+Sentaks Hatası: ifadeden önce ; eksik
+ +

Çift tırnak kullanarak tek tırnağın yanlış kullanımından kaçınabilirsiniz. 

+ +
var foo = "Tomris'in barı";
+var foo = 'Tomris\'in barı';
+
+ +

var ile Özellikleri Deklare Etmek

+ +

var ile bir nesneye veya diziye ait bir özellik tanımlayamazsınız

+ +
var nesne = {};
+var nesne.foo = 'hey'; Sentaks Hatası: ifadeden önce ; eksik
+
+var dizi = [];
+var dizi[0] = 'selam'; Sentaks Hatası: ifadeden önce ; eksik
+
+ +

Bunun yerine, var anahtar sözcüğünü kaldırın:

+ +
var nesne = {};
+nesne.foo = 'hey';
+
+var dizi= [];
+dizi[0] = 'selam';
+
+ +

Ayrıca Göz Atın

+ + +
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 +--- +
{{jsSidebar("Functions")}}
+ +
Arrow fonksiyonlar normal fonksiyonların kısa yoldan yazılabilen türüdür ve kendi içerisinde this, arguments, super, ya da new.target erişimine sahip değildir. Bu fonksiyon tanımlaması özellikle methodsuz fonksiyonlar için çok uygundur. Constructor olarak kullanılamaz. 
+ +

Söz Dizimi

+ +

Temel Söz Dizimi

+ +
(param1, param2, …, paramN) => { statements }
+(param1, param2, …, paramN) => expression
+// buna eşittir: (param1, param2, …, paramN) => { return expression; }
+
+// Eğer tek parametre var ise parantezsiz kullanılabilir:
+(singleParam) => { statements }
+singleParam => { statements }
+singleParam => expression
+
+
+// Parametre beklenmeyen durumlarda parantez çifti kullanılmalıdır
+() => { statements }
+
+ +

İleri Düzey Söz Dizimi

+ +
// Parantez çifti kullanılarak obje tipi veri dönüşü yapılır.
+params => ({foo: bar})
+
+// Rest parameters ve default parameters desteklenmektedir
+(param1, param2, ...rest) => { statements }
+(param1 = defaultValue1, param2, …, paramN = defaultValueN) => { statements }
+
+// Destructuring parametre listesi içinde de desteklenir
+let f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
+f();
+// 6
+
+ +

Description

+ +

Şunu da inceleyin "ES6 In Depth: Arrow functions" on hacks.mozilla.org.

+ +

Arrow fonksiyonlarının iki dikkat çekici özelliği vardır: daha kısa fonksiyonlara ihtiyaç ve this anahtar kelimesinin kullanımı.

+ +

Kısa fonksiyonlar

+ +
var materials = [
+  'Hydrogen',
+  'Helium',
+  'Lithium',
+  'Beryllium'
+];
+
+materials.map(function(material) {
+  return material.length;
+}); // [8, 6, 7, 9]
+
+materials.map((material) => {
+  return material.length;
+}); // [8, 6, 7, 9]
+
+materials.map(({length}) => length); // [8, 6, 7, 9]
+
+ +

No separate this

+ +

Arrow fonksiyonlara kadar, her yeni fonksiyon nasıl çağrıldığına bağlı olarak kendi this değerini belirlerdi:

+ +

Constructor durumunda yeni bir nesne.
+ Strict mode fonksiyon çağrılması durumunda undefined.
+ Eğer fonksiyon "nesne metodu" olarak çağrılmışsa temel nesne.
+ etc.
+
+ Bu kullanım nesne-yönelimli programla içerisinde ideal kullanım değildi.

+ +
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();
+ +

ECMAScript 3/5'te bu this sorunu this değerinin başka bir değişkene atanarak aşılabilmekteydi.

+ +
function Person() {
+  var that = this;
+  that.age = 0;
+
+  setInterval(function growUp() {
+    // 'that' bir üstteki this değerine etki eder.
+    that.age++;
+  }, 1000);
+}
+ +

Alternatif olarak, bound function tanımlaması yaparak önceden atanmış this değeri growUp() fonksiyonuna bu işlevi kazandırabilir.

+ +

Fakat arrow fonksiyonlar kendi this değerine sahip değildir;  kapsayıcı yürütme fonksiyonunun this değeri kullanılır. Böylelikle aşağıdaki örnekte olduğu gibi setInterval'e atanmış arrow fonksiyon kendi this değeri olmadığı için Person() fonksiyonunun this değerine etki eder.

+ +
function Person(){
+  this.age = 0;
+
+  setInterval(() => {
+    this.age++; // |this| person objesine atıfta bulunur
+  }, 1000);
+}
+
+var p = new Person();
+ +

Strict mode ile ilişkisi

+ +

Kapsayıcı sözcüksel bağlamından gelen this değeri, strict mode kuralları uygulandığında görmezden gelinir

+ +
var f = () => { 'use strict'; return this; };
+f() === window; // or the global object
+ +

Diğer strict mode kuralları normal olarak geçerlidir.

+ +

Invoked through call or apply

+ +

Arrow fonksiyonların this değeri olmadığı için,  call() ve apply() methotları sadece parametre verilebilir. thisArg görmezden gelinir.

+ +
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
+ +

No binding of arguments

+ +

Arrow functions do not have their own arguments object. Thus, in this example, arguments is simply a reference to the the arguments of the enclosing scope:

+ +
var arguments = [1, 2, 3];
+var arr = () => arguments[0];
+
+arr(); // 1
+
+function foo(n) {
+  var f = () => arguments[0] + n; // foo's implicit arguments binding. arguments[0] is n
+  return f(10);
+}
+
+foo(1); // 2
+ +

Çoğu durumda rest parametreleriarguments nesnesinin iyi bir alternatifidir.

+ +
function foo(n) {
+  var f = (...args) => args[0] + n;
+  return f(10);
+}
+
+foo(1); // 11
+ +

Method olarak kullanılan Arrow fonksiyonları

+ +

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:

+ +
'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 {...}
+ +

Arrow functions do not have their own this. Another example involving {{jsxref("Object.defineProperty()")}}:

+ +
'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'
+  }
+});
+
+ +

new operatörü kullanımı

+ +

Arrow functions cannot be used as constructors and will throw an error when used with new.

+ +
var Foo = () => {};
+var foo = new Foo(); // TypeError: Foo is not a constructor
+ +

prototype özelliği kullanımı

+ +

Arrow fonksiyonlarının prototype özelliği yoktur.

+ +
var Foo = () => {};
+console.log(Foo.prototype); // undefined
+
+ +

yield anahtarının kullanımı

+ +

The yield 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.

+ +

Function body

+ +

Arrow functions can have either a "concise body" or the usual "block body".

+ +

In a concise body, only an expression is specified, which becomes the explicit return value. In a block body, you must use an explicit return statement.

+ +
var func = x => x * x;
+// concise body syntax, implied "return"
+
+var func = (x, y) => { return x + y; };
+// with block body, explicit "return" needed
+
+ +

Returning object literals

+ +

Keep in mind that returning object literals using the concise body syntax params => {object:literal} will not work as expected.

+ +
var func = () => { foo: 1 };
+// Calling func() returns undefined!
+
+var func = () => { foo: function() {} };
+// SyntaxError: function statement requires a name
+ +

This is because the code inside braces ({}) is parsed as a sequence of statements (i.e. foo is treated like a label, not a key in an object literal).

+ +

Remember to wrap the object literal in parentheses.

+ +
var func = () => ({foo: 1});
+ +

Line breaks

+ +

An arrow function cannot contain a line break between its parameters and its arrow.

+ +
var func = ()
+           => 1;
+// SyntaxError: expected expression, got '=>'
+ +

Parsing order

+ +

Although the arrow in an arrow function is not an operator, arrow functions have special parsing rules that interact differently with operator precedence compared to regular functions.

+ +
let callback;
+
+callback = callback || function() {}; // ok
+
+callback = callback || () => {};
+// SyntaxError: invalid arrow-function arguments
+
+callback = callback || (() => {});    // ok
+
+ +

More examples

+ +
// 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);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.functions.arrow_functions")}}

+
+ +

See also

+ + 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 +--- +
{{jsSidebar("Functions")}}
+ +

Generally speaking, a function is a "subprogram" that can be called 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 function body. Values can be passed to a function, and the function will return a value.

+ +

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 Function objects.

+ +

For more examples and explanations, see also the JavaScript guide about functions.

+ +

Description

+ +

Every function in JavaScript is a Function object. See {{jsxref("Function")}} for information on properties and methods of Function objects.

+ +

To return a value other than the default, a function must have a return statement that specifies the value to return. A function without a return statement will return a default value. In the case of a constructor called with the new keyword, the default value is the value of its this parameter. For all other functions, the default return value is {{jsxref("undefined")}}.

+ +

The parameters of a function call are the function's arguments. Arguments are passed to functions by value. 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:

+ +
/* 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);
+
+ +

The this keyword does not refer to the currently executing function, so you must refer to Function objects by name, even within the function body.

+ +

Defining functions

+ +

There are several ways to define functions:

+ +

The function declaration (function statement)

+ +

There is a special syntax for declaring functions (see function statement for details):

+ +
function name([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
+ +
+
statements
+
The statements comprising the body of the function.
+
+ +

The function expression (function expression)

+ +

A function expression is similar to and has the same syntax as a function declaration (see function expression 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 hoisted onto the beginning of the scope, therefore they cannot be used before they appear in the code.

+ +
function [name]([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
statements
+
The statements comprising the body of the function.
+
+ +

Here is an example of an anonymous function expression (the name is not used):

+ +
var myFunction = function() {
+    statements
+}
+ +

It is also possible to provide a name inside the definition in order to create a named function expression:

+ +
var myFunction = function namedFunction(){
+    statements
+}
+
+ +

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.

+ +

As we can see, both examples do not start with the function keyword. Statements involving functions which do not start with function are function expressions.

+ +

When functions are used only once, a common pattern is an IIFE (Immediately Invokable Function Expression).

+ +
(function() {
+    statements
+})();
+ +

IIFE are function expressions that are invoked as soon as the function is declared.

+ +

The generator function declaration (function* statement)

+ +

There is a special syntax for generator function declarations (see {{jsxref('Statements/function*', 'function* statement')}} for details):

+ +
function* name([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
+ +
+
statements
+
The statements comprising the body of the function.
+
+ +

The generator function expression (function* expression)

+ +

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):

+ +
function* [name]([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
statements
+
The statements comprising the body of the function.
+
+ +

The arrow function expression (=>)

+ +

An arrow function expression has a shorter syntax and lexically binds its this value (see arrow functions for details):

+ +
([param[, param]]) => {
+   statements
+}
+
+param => expression
+
+ +
+
param
+
The name of an argument. Zero arguments need to be indicated with ().  For only one argument, the parentheses are not required. (like foo => 1)
+
statements or expression
+
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.
+
+ +

The Function constructor

+ +
+

Note: Using the Function 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.

+
+ +

As all other objects, {{jsxref("Function")}} objects can be created using the new operator:

+ +
new Function (arg1, arg2, ... argN, functionBody)
+
+ +
+
arg1, arg2, ... argN
+
Zero or more names to be used by the function as formal parameters. Each must be a proper JavaScript identifier.
+
+ +
+
functionBody
+
A string containing the JavaScript statements comprising the function body.
+
+ +

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

+ +

The GeneratorFunction constructor

+ +
+

Note: GeneratorFunction is not a global object, but could be obtained from generator function instance (see {{jsxref("GeneratorFunction")}} for more detail).

+
+ +
+

Note: Using the GeneratorFunction 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.

+
+ +

As all other objects, {{jsxref("GeneratorFunction")}} objects can be created using the new operator:

+ +
new GeneratorFunction (arg1, arg2, ... argN, functionBody)
+
+ +
+
arg1, arg2, ... argN
+
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 "x", "theValue", or "a,b".
+
+ +
+
functionBody
+
A string containing the JavaScript statements comprising the function definition.
+
+ +

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

+ +

Function parameters

+ +

Default parameters

+ +

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed. For more details, see default parameters.

+ +

Rest parameters

+ +

The rest parameter syntax allows to represent an indefinite number of arguments as an array. For more details, see rest parameters.

+ +

The arguments object

+ +

You can refer to a function's arguments within the function by using the arguments object. See arguments.

+ + + +

Defining method functions

+ +

Getter and setter functions

+ +

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.

+ +
+
get
+
+

Binds an object property to a function that will be called when that property is looked up.

+
+
set
+
Binds an object property to a function to be called when there is an attempt to set that property.
+
+ +

Method definition syntax

+ +

Starting with ECMAScript 2015, you are able to define own methods in a shorter syntax, similar to the getters and setters. See method definitions for more information.

+ +
var obj = {
+  foo() {},
+  bar() {}
+};
+ +

Constructor vs. declaration vs. expression

+ +

Compare the following:

+ +

A function defined with the Function constructor assigned to the variable multiply:

+ +
var multiply = new Function('x', 'y', 'return x * y');
+ +

A function declaration of a function named multiply:

+ +
function multiply(x, y) {
+   return x * y;
+} // there is no semicolon here
+
+ +

A function expression of an anonymous function assigned to the variable multiply:

+ +
var multiply = function(x, y) {
+   return x * y;
+};
+
+ +

A function expression of a function named func_name assigned to the variable multiply:

+ +
var multiply = function func_name(x, y) {
+   return x * y;
+};
+
+ +

Differences

+ +

All do approximately the same thing, with a few subtle differences:

+ +

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 undefined if the function name was previously declared via a var statement). For example:

+ +
var y = function x() {};
+alert(x); // throws an error
+
+ +

The function name also appears when the function is serialized via Function's toString method.

+ +

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.

+ +

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:

+ +

A function defined by 'new Function' does not have a function name. However, in the SpiderMonkey JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, alert(new Function()) outputs:

+ +
function anonymous() {
+}
+
+ +

Since the function actually does not have a name, anonymous is not a variable that can be accessed within the function. For example, the following would result in an error:

+ +
var foo = new Function("alert(anonymous);");
+foo();
+
+ +

Unlike functions defined by function expressions or by the Function constructor, a function defined by a function declaration can be used before the function declaration itself. For example:

+ +
foo(); // alerts FOO!
+function foo() {
+   alert('FOO!');
+}
+
+ +

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 Function constructor does not inherit any scope other than the global scope (which all functions inherit).

+ +
/*
+ * 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)
+ */
+
+ +

Functions defined by function expressions and function declarations are parsed only once, while those defined by the Function constructor are not. That is, the function body string passed to the Function 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 "new Function(...)". Therefore the Function constructor should generally be avoided whenever possible.

+ +

It should be noted, however, that function expressions and function declarations nested within the function generated by parsing a Function constructor 's string aren't parsed repeatedly. For example:

+ +
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.
+ +

A function declaration is very easily (and often unintentionally) turned into a function expression. A function declaration ceases to be one when it either:

+ + + +
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
+   }
+}
+
+ +

Examples

+ +
// 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() {}
+   }
+}
+
+ +

Block-level functions

+ +

In strict mode, starting with ES2015, functions inside blocks are now scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.

+ +
'use strict';
+
+function f() {
+  return 1;
+}
+
+{
+  function f() {
+    return 2;
+  }
+}
+
+f() === 1; // true
+
+// f() === 2 in non-strict mode
+
+ +

Block-level functions in non-strict code

+ +

In a word: Don't.

+ +

In non-strict code, function declarations inside blocks behave strangely. For example:

+ +
if (shouldDefineZero) {
+   function zero() {     // DANGER: compatibility risk
+      console.log("This is zero.");
+   }
+}
+
+ +

ES2015 says that if shouldDefineZero is false, then zero 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 zero whether the block executed or not.

+ +

In strict mode, all browsers that support ES2015 handle this the same way: zero is defined only if shouldDefineZero is true, and only in the scope of the if-block.

+ +

A safer way to define functions conditionally is to assign a function expression to a variable:

+ +
var zero;
+if (shouldDefineZero) {
+   zero = function() {
+      console.log("This is zero.");
+   };
+}
+
+ +

Examples

+ +

Returning a formatted number

+ +

The following function returns a string containing the formatted representation of a number padded with leading zeros.

+ +
// 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;
+}
+
+ +

The following statements call the padZeros function.

+ +
var result;
+result = padZeros(42,4); // returns "0042"
+result = padZeros(42,2); // returns "42"
+result = padZeros(5,4);  // returns "0005"
+
+ +

Determining whether a function exists

+ +

You can determine whether a function exists by using the typeof operator. In the following example, a test is performed to determine if the window object has a property called noFunc that is a function. If so, it is used; otherwise some other action is taken.

+ +
 if ('function' === typeof window.noFunc) {
+   // use noFunc()
+ } else {
+   // do something else
+ }
+
+ +

Note that in the if test, a reference to noFunc is used—there are no brackets "()" after the function name so the actual function is not called.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0
{{SpecName('ES5.1', '#sec-13', 'Function Definition')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ES6')}}New: Arrow functions, Generator functions, default parameters, rest parameters.
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.functions")}}

+ +

See also

+ + 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 +--- +
{{JSRef("Global_Objects", "Array")}}
+ +

Özet

+ +

concat() metodu eklendigi dizi ile parametre olarak aldığı dizi(leri) birleştirerek yeni bir dizi döndürür.

+ +

Söz Dizimi

+ +
var new_array = old_array.concat(value1[, value2[, ...[, valueN]]])
+ +

Parmetreler

+ +
+
valueN
+
Yeni diziye eklenecek dizi ve/veya değerler. Detaylar için aşağıdaki açıklamayı okuyunuz.
+
+ +

Açıklama

+ +

concat ç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.

+ +

concat , this 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:

+ + + +
+

Not: 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.

+
+ +

Örnekler

+ +

Örnek: İki diziyi birleştirme

+ +

Aşağıdaki kod iki diziyi birleştiriyor:

+ +
var alpha = ['a', 'b', 'c'],
+    numeric = [1, 2, 3];
+
+var alphaNumeric = alpha.concat(numeric);
+
+console.log(alphaNumeric); // Result: ['a', 'b', 'c', 1, 2, 3]
+
+ +

Örnek: Üç diziyi birleştirme

+ +

Aşağıdaki kod üç diziyi birleştiriyor:

+ +
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]
+
+ +

Örnek: Değerleri dizi ile birleştirme

+ +

Aşağıdaki kod değerler ile diziyi birleştiriyor:

+ +
var alpha = ['a', 'b', 'c'];
+
+var alphaNumeric = alpha.concat(1, [2, 3]);
+
+console.log(alphaNumeric); // Result: ['a', 'b', 'c', 1, 2, 3]
+
+ +

Özellikler

+ + + + + + + + + + + + + + + + + + + + + + + + +
ÖzelliklerDurumYorumlar
ECMAScript 3rd EditionStandardInitial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.4', 'Array.prototype.concat')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.concat', 'Array.prototype.concat')}}{{Spec2('ES6')}} 
+ +

Tarayıcı Uyumluluğu

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
ÖzellikChromeFirefox (Gecko)Internet ExplorerOperaSafari
Temel destek{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
ÖzellikAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Temel destek{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ayrıca Bakınız

+ + 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 +--- +
{{JSRef}}
+ +

entries() metodu, içerisinde, her bir elemanı için anahtar/değer çifti içeren yeni bir Gezinilebilir Dizi nesnesi döndürür.

+ +
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']
+
+ +

Söz dizimi

+ +
a.entries()
+ +

Dönüş değeri

+ +

Yeni bir gezinilebilir {{jsxref("Array")}} nesnesi.

+ +

Örnekler

+ +

Bir for…of döngüsü kullanımı

+ +
var a = ['a', 'b', 'c'];
+var iterator = a.entries();
+
+for (let e of iterator) {
+  console.log(e);
+}
+// [0, 'a']
+// [1, 'b']
+// [2, 'c']
+
+ +

Tanımlamalar

+ + + + + + + + + + + + + + + + + + + +
TanımlamaDurumYorum
{{SpecName('ES2015', '#sec-array.prototype.entries', 'Array.prototype.entries')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.entries', 'Array.prototype.entries')}}{{Spec2('ESDraft')}} 
+ +

Tarayıcı uyumluluğu

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
ÖzellikChromeFirefox (Gecko)Internet ExplorerOperaSafari
Temel destekli{{CompatChrome("38")}}{{CompatGeckoDesktop("28")}}{{CompatNo}}{{CompatOpera("25")}}{{CompatSafari("7.1")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Temel destekli{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("28")}}{{CompatNo}}{{CompatNo}}8.0
+
+ +

Ayrıca bknz.

+ + 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 +--- +
{{JSRef}}
+ +
every() 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. 
+ +
+

Note: Test edilen array boş ise bu metot true deger döndürür.

+
+ +
{{EmbedInteractiveExample("pages/js/array-every.html")}}
+ + + +

Söz dizimi

+ +
arr.every(callback(element[, index[, array]])[, thisArg])
+ +

Parametreler

+ +
+
callback
+
Her elemanı test eden üç değişken alan bir fonksiyon: +
+
element
+
İşlemde olan geçerli dizi elemanı.
+
index{{Optional_inline}}
+
İşlemde olan geçerli dizi elemanın indeksi .
+
array{{Optional_inline}}
+
every tarafından çağrılan dizi.
+
+
+
thisArg{{Optional_inline}}
+
Geri dönüş yapıldığında this olarak kullanıcak bir değer.
+
+ +

Dönüş değeri

+ +

Geri dönüş fonksiyonu her bir dizi elemanı için bir {{Glossary("truthy")}} deger dondürse true. Aksi takdirde, false.

+ +

Description

+ +

The every method executes the provided callback function once for each element present in the array until it finds the one where callback returns a {{Glossary("falsy")}} value. If such an element is found, the every method immediately returns false. Otherwise, if callback returns a {{Glossary("truthy")}} value for all elements, every returns true. callback 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.

+ +

callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.

+ +

If a thisArg parameter is provided to every, it will be used as callback's this value. Otherwise, the value undefined will be used as its this value.  The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.

+ +

every does not mutate the array on which it is called.

+ +

The range of elements processed by every is set before the first invocation of callback. Therefore, callback will not run on elements that are appended to the array after the call to every begins. If existing elements of the array are changed, their value as passed to callback will be the value at the time every visits them. Elements that are deleted are not visited.

+ +

every acts like the "for all" quantifier in mathematics. In particular, for an empty array, it returns true. (It is vacuously true that all elements of the empty set satisfy any given condition.)

+ +

Örnekler

+ +

Tüm dizi elemanlarının büyüklüğünün test edilmesi

+ +

Aşağıdaki örnekte tüm dizi elemanlarının 10'dan büyük yada eşit olma durumu test edilir.

+ +
function isBigEnough(element, index, array) {
+  return element >= 10;
+}
+[12, 5, 8, 130, 44].every(isBigEnough);   // false
+[12, 54, 18, 130, 44].every(isBigEnough); // true
+
+ +

Ok fonksiyonlarını kullanma

+ +

Ok fonksiyonları aynı testin daha kısa söz dizimi ile yapılmasını sağlar.

+ +
[12, 5, 8, 130, 44].every(x => x >= 10); // false
+[12, 54, 18, 130, 44].every(x => x >= 10); // true
+ +

Polyfill

+ +

every 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 every in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming Object and TypeError have their original values and that callbackfn.call evaluates to the original value of {{jsxref("Function.prototype.call")}}

+ +
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;
+  };
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.4.16', 'Array.prototype.every')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.every', 'Array.prototype.every')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.every', 'Array.prototype.every')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Array.every")}}

+
+ +

See also

+ + 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 +--- +
{{JSRef}}
+ +
 
+ +

filter() metotu sağlanan işlev tarafından uygulanan testi geçen tüm öğelerle birlikte yeni bir dizi oluşturur.

+ +
{{EmbedInteractiveExample("pages/js/array-filter.html")}}
+ + + +

Söz Dizimi

+ +
var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])
+ +

Parametreler

+ +
+
callback
+
Function , dizinin her öğesini sınamak için bir yordamdır. Öğeyi saklamak için true , aksi takdirde false değerini döndürün. Üç argümanı kabul eder:
+
+
+
element
+
Dizide işlenen mevcut elementtir.
+
index{{optional_inline}}
+
Dizide işlenen geçerli öğenin dizini
+
array{{optional_inline}}
+
The array filter was called upon.
+
+
+
thisArg{{optional_inline}}
+
callback  çalıştığı zaman this olarak kullanmak için değerdir.
+
+ +

Dönüş değer

+ +

Testi geçen öğeler içeren yeni bir dizi. Hiçbir öğe testi geçemezse, boş bir dizi döndürülür.

+ +

Açıklama

+ +

filter (), 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.

+ +

Geri Çağırma (callback)  3 argüman ile çağırılır.

+ +
    +
  1. elementin değeri
  2. +
  3. elementin indeksi
  4. +
  5. Array nesnesinin geçişi
  6. +
+ +

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. 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.

+ +

filter() çağrıldığı diziyi değiştirmez.

+ +

filter() tarafından işlenen elemanların aralığı, ilk geri çağırma callback çağrısından önce ayarlanır. filter() çağrısı başladıktan sonra diziye eklenen öğeler, geri çağırma  callback tarafından ziyaret edilmeyecektir. Dizinin mevcut elemanları değiştirilir veya silinirse, geri çağırmaya callback iletilen değerleri filter() tarafından ziyaret edilen zamanın değeri olacaktır; silinen öğeler ziyaret edilmez.

+ +

Örnekler

+ +

Tüm küçük değerleri filtrelemek

+ +

Aşağıdaki örnek, tüm öğeleri 10'dan daha küçük değerlere sahip filtreli bir dizi oluşturmak için filter() kullanır.

+ +
function isBigEnough(value) {
+  return value >= 10;
+}
+
+var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
+// filtered is [12, 130, 44]
+
+ +

JSON'dan geçersiz girişleri filtrelemek

+ +

Aşağıdaki örnek, 0 olmayan,numeric id olan tüm öğelerin filtrelenmiş bir jsonunu oluşturmak için filter() işlevini kullanır. 

+ +
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
+
+ +

Array içinde arama yapmak

+ +

 

+ +

Aşağıdaki örnek, arama keriterlerine göre dizi içeriğini filtrelemek için filter() işlevini kullanır

+ +

 

+ +
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']
+ +

ES2015 İmplementasyonu

+ +
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']
+
+
+ +

Polyfill

+ +

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

+ +
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;
+  };
+}
+ +

 

+ +

Özellikler

+ + + + + + + + + + + + + + + + + + + + + + + + +
ÖzelliklerStatülerYorumlar
{{SpecName('ES5.1', '#sec-15.4.4.20', 'Array.prototype.filter')}}{{Spec2('ES5.1')}}İlk tanım JavaScript 1.6'da uygulanmıştır.
{{SpecName('ES2015', '#sec-array.prototype.filter', 'Array.prototype.filter')}}{{Spec2('ES2015')}} 
{{SpecName('ESDraft', '#sec-array.prototype.filter', 'Array.prototype.filter')}}{{Spec2('ESDraft')}} 
+ +

Tarayıcı uyumluluğu

+ +
+ + +

{{Compat("javascript.builtins.Array.filter")}}

+
+ +

Ayrıca bakınız

+ + 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 +--- +
{{JSRef}}
+ +

find() metodu parametre olarak verilen, true/false değer döndüren test fonksiyonunu karşılayan dizi içerisindeki ilk elemanın değerini döndürür. Aksi halde {{jsxref("undefined")}} döndürür.

+ +
function yeterinceBuyuk(eleman) {
+  return eleman >= 15;
+}
+
+[12, 5, 8, 130, 44].find(yeterinceBuyuk); // 130
+ +

Ayrıca {{jsxref("Array.findIndex", "findIndex()")}} metoduna bakınız, bu metod dizi içerisinde bulunan elemanın değeri yerine indeksini döndürür.

+ +

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.

+ +

Sözdizim

+ +
arr.find(gericagrim[, thisArg])
+ +

Parametreler

+ +
+
gericagrim
+
Dizi içerisindeki her bir değer için çalıştırılacak fonksiyon, üç parametre alır: +
+
eleman
+
Dizideki işlenen mevcut eleman.
+
indeks
+
Dizideki işlenen mevcut elemanın indeksi.
+
dizi
+
find metodunun çağırıldığı dizi.
+
+
+
thisArg {{Optional_inline}}
+
 gericagrim çalıştığında this olarak kullanılan nesne.
+
+ +

Dönüş değeri

+ +

Eğer test doğrulanırsa dizi içerisindeki bir değer; değilse, {{jsxref("undefined")}}.

+ +

Açıklama

+ +

find metodu gericagrim fonksiyonu doğru bir değer döndürene kadar her bir indeks için bir sefer gericagrim fonksiyonunu çalıştırır. Eğer böyle bir eleman bulunduysa, find derhal bu elemanın değerini döndürür. Aksi halde, find {{jsxref("undefined")}} döndürür. gericagrim 0 dan  length - 1 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. 

+ +

gericagrim üç parametre ile çağırılır: dizi elemanının değeri, dizi elemanının indeksi, ve geçilen dizi nesnesi.

+ +

Eğer bir thisArg parametresi find için sağlanırsa, bu parametre gericagrim fonksiyonunun her çağırılışı için this olarak kullanılacaktır. Eğer sağlanmazsa, {{jsxref("undefined")}} kullanılır.

+ +

find üzerinde çağırıldığı diziyi değiştirmez.

+ +

find tarafından işlenilen elemanların aralığı gericagrim fonksiyonunun ilk çağırılışından önce atanır. find çağırılmaya başlandığından sonra diziye eklenen elemanlar gericagrim tarafından ziyaret edilmeyecektir. Eğer varolan, ziyaret edilmeyen eleman gericagrim tarafından değiştirilirse, bu elemanı ziyaret eden gericagrim fonkisyonuna aktarılan değeri find metodunun bu elemanın indeksini ziyaret edeceği andaki değer olacaktır; silenen elemanlar yine de ziyaret edilecektir.

+ +

Örnekler

+ +

Dizi içerisindeki nesneyi bir özelliğinden bulmak

+ +
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 }
+ +

Dizi içerisindeki bir asal sayıyı bulmak

+ +

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).

+ +
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
+
+ +

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.

+ +
// İ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);
+});
+
+
+ +

Polyfill

+ +

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 Array.prototype.find polyfill yapabilirsiniz:

+ +
// 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;
+    }
+  });
+}
+
+ +

Eğer Object.defineProperty desteği bulunmayan tamamen eskimiş JavaScript motorları için ihtiyacınız varsa, Array.prototype metodlarını polyfill yapmamanız en doğrusudur, çünkü bu metodlar numaralandırılabilir olmayan metodlardır.

+ +

Spesifikasyonlar

+ + + + + + + + + + + + + + + + + + + +
SpesifikasyonDurumAçıklama
{{SpecName('ES2015', '#sec-array.prototype.find', 'Array.prototype.find')}}{{Spec2('ES2015')}}İlk tanım.
{{SpecName('ESDraft', '#sec-array.prototype.find', 'Array.prototype.find')}}{{Spec2('ESDraft')}} 
+ +

Tarayıcı uyumluluğu

+ +
+ + +

{{Compat("javascript.builtins.Array.find")}}

+
+ +

Ayrıca bakınız

+ + 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 +--- +
{{JSRef}}
+ +

FindIndex () yöntemi, sağlanan test işlevini karşılayan dizideki ilk öğenin dizinini döndürür. Aksi takdirde -1 iade edilir.

+ +
{{EmbedInteractiveExample("pages/js/array-findindex.html")}}
+ + + +
 
+ +

Ayrıca, dizinde bulunan dizinin yerine bulunan bir öğenin değerini döndüren {{jsx ref ("Array.find", "find ()")}} yöntemine de bakın.

+ +

Syntax

+ +
arr.findIndex(callback[, thisArg])
+ +

Parameters

+ +
+
callback
+
Function to execute on each value in the array, taking three arguments: +
+
element
+
The current element being processed in the array.
+
index{{optional_inline}}
+
The index of the current element being processed in the array.
+
array{{optional_inline}}
+
The array findIndex was called upon.
+
+
+
thisArg{{optional_inline}}
+
Optional. Object to use as this when executing callback.
+
+ +

Return value

+ +

An index in the array if an element passes the test; otherwise, -1.

+ +

Description

+ +

The findIndex method executes the callback function once for every array index 0..length-1 (inclusive) in the array until it finds one where callback returns a truthy value (a value that coerces to true). If such an element is found, findIndex immediately returns the index for that iteration. If the callback never returns a truthy value or the array's length is 0, findIndex returns -1. Unlike some other array methods such as Array#some, in sparse arrays the callback is called even for indexes of entries not present in the array.

+ +

callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.

+ +

If a thisArg parameter is provided to findIndex, it will be used as the this for each invocation of the callback. If it is not provided, then {{jsxref("undefined")}} is used.

+ +

findIndex does not mutate the array on which it is called.

+ +

The range of elements processed by findIndex is set before the first invocation of callback. Elements that are appended to the array after the call to findIndex begins will not be visited by callback. If an existing, unvisited element of the array is changed by callback, its value passed to the visiting callback will be the value at the time that findIndex visits that element's index; elements that are deleted are still visited.

+ +

Examples

+ +

Find the index of a prime number in an array

+ +

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).

+ +
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
+
+ +

Find index using arrow function

+ +

The following example finds the index of a fruit using an arrow function.

+ +
const fruits = ["apple", "banana", "cantaloupe", "blueberries", "grapefruit"];
+
+const index = fruits.findIndex(fruit => fruit === "blueberries");
+
+console.log(index); // 3
+console.log(fruits[index]); // blueberries
+
+ +

Polyfill

+ +
// 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
+  });
+}
+
+ +

If you need to support truly obsolete JavaScript engines that don't support Object.defineProperty, it's best not to polyfill Array.prototype methods at all, as you can't make them non-enumerable.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-array.prototype.findindex', 'Array.prototype.findIndex')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.findIndex', 'Array.prototype.findIndex')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Array.findIndex")}}

+
+ +

See also

+ + 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 +--- +
{{JSRef}}
+ +

forEach() metodu dizideki her eleman için verilen metodu çalıştırır.

+ +
{{EmbedInteractiveExample("pages/js/array-foreach.html")}}
+ + + +

Syntax

+ +
arr.forEach(function callback(currentValue[, index[, array]]) {
+    //your iterator
+}[, thisArg]);
+ +

Parametreler

+ +
+
callback
+
Aşağıdaki üç parametreyi alan ve dizinin her elemanı için çalışan fonksiyon.
+
+
+
currentValue{{optional_inline}}
+
İşlenmekte olan dizi elemanı.
+
index{{optional_inline}}
+
İşlenmekte olan dizi elemanının indeksi, yani dizideki sırası.
+
array{{optional_inline}}
+
forEach() in uygulanmakta olduğu dizi.
+
+
+
thisArg {{Optional_inline}}
+
+

callback fonksiyonu çağırılırken, fonksiyon içerisinde this yerine kullanılılabilecek değer.

+
+
+ +

Dönüş Değeri

+ +

{{jsxref("undefined")}}.

+ +

Tanım

+ +

forEach() tanımlanmış olan callback 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).

+ +

Dizinin

+ +

callback çağırılırken aşağıdaki üç parametre kullanılır:

+ + + +

If a thisArg parameter is provided to forEach(), it will be used as callback's this value.  Otherwise, the value {{jsxref("undefined")}} will be used as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.

+ +

The range of elements processed by forEach() is set before the first invocation of callback. Elements that are appended to the array after the call to forEach() begins will not be visited by callback. If the values of existing elements of the array are changed, the value passed to callback will be the value at the time forEach() 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.

+ +

forEach() executes the callback 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.

+ +

forEach() does not mutate the array on which it is called (although callback, if invoked, may do so).

+ +
+

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

+ +

Early termination may be accomplished with:

+ + + +

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.

+
+ +

Examples

+ +

Converting a for loop to forEach

+ +

before

+ +
const items = ['item1', 'item2', 'item3'];
+const copy = [];
+
+for (let i=0; i<items.length; i++) {
+  copy.push(items[i])
+}
+
+ +

after

+ +
const items = ['item1', 'item2', 'item3'];
+const copy = [];
+
+items.forEach(function(item){
+  copy.push(item)
+});
+
+
+ +

 

+ +

Printing the contents of an array

+ +

The following code logs a line for each element in an array:

+ +
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
+
+ +

Using thisArg

+ +

The following (contrived) example updates an object's properties from each entry in the array:

+ +
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
+
+ +

Since the thisArg parameter (this) is provided to forEach(), it is passed to callback each time it's invoked, for use as its this value.

+ +
+

If passing the function argument using an arrow function expression the thisArg parameter can be omitted as arrow functions lexically bind the {{jsxref("Operators/this", "this")}} value.

+
+ +

An object copy function

+ +

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 Array.prototype.forEach() works by using ECMAScript 5 Object.* meta property functions.

+ +
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
+
+ +

If the array is modified during iteration, other elements might be skipped.

+ +

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. forEach() does not make a copy of the array before iterating.

+ +
var words = ['one', 'two', 'three', 'four'];
+words.forEach(function(word) {
+  console.log(word);
+  if (word === 'two') {
+    words.shift();
+  }
+});
+// one
+// two
+// four
+
+ +

Polyfill

+ +

forEach() 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 forEach() 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 callback.call() evaluates to the original value of {{jsxref("Function.prototype.call()")}}.

+ +
// 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.
+  };
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.4.18', 'Array.prototype.forEach')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Array.forEach")}}

+
+ +

See also

+ + 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 +--- +
{{JSRef}}
+ +

Array.from() metodu bir dizi-benzeri veya gezinilebilir bir nesneden yeni bir Dizi örneği oluşturur.

+ +
Array.from("birşey");
+// ["b", "i", "r", "ş", "e", "y"]
+ +

Söz dizimi

+ +
Array.from(arrayLike[, mapFn[, thisArg]])
+
+ +

Parametreler

+ +
+
arrayLike
+
Diziye çevrilecek olan dizi-benzeri ya da gezinilebilir nesnedir.
+
mapFn
+
İsteğe bağlı. Map fonksiyonu tüm dizi öğeleri için çağrılır.
+
thisArg
+
İsteğe bağlı. mapFn fonksiyonu işletilirken kullanılacak olan this argüman değeridir.
+
+ +

Dönüş değeri

+ +

Yeni bir {{jsxref("Array")}} örneği.

+ +

Açıklama

+ +

Array.from(), aşağıdaki yapılardan Diziler oluşturmanıza izin verir:

+ + + +

Array.from() has an optional parameter mapFn, 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, Array.from(obj, mapFn, thisArg) has the same result as Array.from(obj).map(mapFn, thisArg), except that it does not create an intermediate array. This is especially important for certain array subclasses, like typed arrays, since the intermediate array would necessarily have values truncated to fit into the appropriate type.

+ +

The length property of the from() method is 1.

+ +

In ES2015, the class syntax allows for sub-classing of both built-in and user defined classes; as a result, static methods such as Array.from are "inherited" by subclasses of Array and create new instances of the subclass, not Array.

+ +

Örnekler

+ +

Bir metinden Dizi oluşturma

+ +
Array.from("birşey");
+// ["b", "i", "r", "ş", "e", "y"]
+ +

Bir Set nesnesinden Dizi oluşturma

+ +
var s = new Set(["birşey", window]);
+Array.from(s);
+// ["birşey", window]
+ +

Bir Map nesnesinden Dizi oluşturma

+ +
var m = new Map([[1, 2], [2, 4], [4, 8]]);
+Array.from(m);
+// [[1, 2], [2, 4], [4, 8]]
+ +

Bir dizi-benzeri nesneden dizi oluşturma (argümanlar)

+ +
function f() {
+  return Array.from(arguments);
+}
+
+f(1, 2, 3);
+
+// [1, 2, 3]
+ +

Ok işlevleri ve Array.from kullanma

+ +
// 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]
+
+ +

Polyfill

+ +

Array.from 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 Array.from in implementations that don't natively support it.  This algorithm is exactly the one specified in ECMA-262, 6th edition, assuming Object and TypeError have their original values and that callback.call 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.

+ +
// 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;
+    };
+  }());
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-array.from', 'Array.from')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.from', 'Array.from')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)EdgeInternet ExplorerOperaSafari
Basic support{{CompatChrome("45")}}{{CompatGeckoDesktop("32")}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}9.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("32")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

See also

+ + 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 +--- +
{{JSRef}}
+ +

includes() metodu bir dizinin belirli bir elemanı içerip içermediğini belirler, içeriyorsa true içermiyorsa false değeri döndürür. Aranan öğenin bulunup bulunmadığını belirlemek için sameValueZero algoritmasını kullanır.

+ +
var a = [1, 2, 3];
+a.includes(2); // true
+a.includes(4); // false
+
+ +

{{EmbedInteractiveExample("pages/js/array-includes.html")}} 

+ +
+ +
+ +

Söz Dizimi

+ +
arr.includes(searchElement)
+arr.includes(searchElement, fromIndex)
+
+ +

Parametreler

+ +
+
searchElement
+
Aranan eleman.
+
fromIndex {{optional_inline}}
+
Dizide searchElement için aramanın başlatılacağı indis. Negatif bir değer, dizinin sonundan aramaya başlar. Varsayılan değer 0'dır.
+
+ +

Return value

+ +

A {{jsxref("Boolean")}}.

+ +

Örnekler

+ +
[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
+
+ +

fromIndex dizi uzunluğundan büyük veya eşitse

+ +

Eğer fromIndex dizinin uzunluğundan büyük veya eşitse, false döndürülür. Dizi aranmaz.

+ +
var arr = ['a', 'b', 'c'];
+
+arr.includes('c', 3);   //false
+arr.includes('c', 100); // false
+ +

Hesaplanan indis 0'dan küçükse

+ +

Eğer fromIndex negatifse, hesaplanan indis, searchElement için aramaya başlanacak konum olarak belirlenir. Hesaplanmış indis 0'dan küçükse, dizinin tamamı aranır.

+ +
// 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
+ +

includes() genel bir yöntem olarak kullanılması

+ +

includes() yöntemi kasıtlı olarak geneldir. this 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 argümanlar nesnesi için uygulanan includes() metodunu göstermektedir.

+ +
(function() {
+  console.log([].includes.call(arguments, 'a')); // true
+  console.log([].includes.call(arguments, 'd')); // false
+})('a','b','c');
+ +

Polyfill

+ +
// 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;
+    }
+  });
+}
+
+ +

Object.defineProperty desteklemeyen eski JavaScript motorlarını desteklemeniz gerekiyorsa, Array.prototype metodlarını non-enumerable yapamadığımız için polyfill uygulamamak daha iyidir.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES7', '#sec-array.prototype.includes', 'Array.prototype.includes')}}{{Spec2('ES7')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.includes', 'Array.prototype.includes')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Array.includes")}}

+
+ +

See also

+ + 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 +--- +
{{JSRef}}
+ +

JavaScript Array nesnesi, üst düzey, liste benzeri dizi yapıları için kullanılan genel bir nesnedir.

+ +

Bir dizi oluşturma

+ +
var meyveler = ["Elma", "Muz"];
+
+console.log(meyveler.length);
+// 2
+ +

Dizideki (indeks ile) elemana ulaşma

+ +
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
+ +

Bir dizi üzerinde döngü kurma

+ +
meyveler.forEach(function (item, index, array) {
+  console.log(item, index);
+});
+// Elma 0
+// Muz 1
+ +

Dizinin sonuna eleman ekleme

+ +
var yeniDizi = meyveler.push("Portakal");
+// ["Elma", "Muz", "Portakal"]
+ +

Dizi sonundan eleman kaldırma

+ +
var son = meyveler.pop(); // Portakal elemanını kaldır(sondan)
+// ["Elma", "Muz"];
+ +

Dizi başından eleman kaldırma

+ +
var ilk = fruits.shift(); // Elma elemanını kaldır(baştan)
+// ["Muz"];
+ +

Dizi başına eleman ekleme

+ +
var yeniDizi = fruits.unshift("Çilek") // Başa ekle
+// ["Çilek", "Muz"];
+ +

Dizideki elemanın kaçıncı sırada olduğunu bulma

+ +
meyveler.push("Mango");
+// ["Çilek", "Muz", "Mango"]
+
+var pos = meyveler.indexOf("Muz");
+// 1
+ +

Belirli bir sıradaki elemanı silme

+ +
var silinenEleman = meyveler.splice(pos, 1); // bir elemanı kaldırma
+// ["Çilek", "Mango"]
+
+ +

Dizi kopyalama

+ +
var kopyalananDizi = meyveler.slice(); //
+// ["Çilek", "Mango"]
+ +

Söz Dizimi

+ +
[element0, element1, ..., elementN]
+new Array(element0, element1, ..., elementN)
+new Array(diziUzunlugu)
+
+ +
+

Not: N + 1 = dizi uzunluğu

+
+ +
+
element0, element1, ..., elementN
+
Bir dizi new Array() 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 new Array() nesnesiyle (Array Constructor) oluşturulan dizilere uygulanabilir, köşeli parantezler ( [ ve ] ) ile oluşturulan dizilere uygulanamaz.
+
arrayLength (dizi uzunluğu)
+
array nesnesinden sadece 0 ve 232-1 (dahil) arasındaki tam sayılardan biri argüman olarak geçirilebilir.
+
If the only argument passed to the Array constructor is an integer between 0 and 232-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.
+
+ +

Tanım

+ +

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.

+ +

Note that you shouldn't use an array as an associative array. You can use plain {{jsxref("Global_Objects/Object", "objects")}} instead, although doing so comes with its own caveats. See the post Lightweight JavaScript dictionaries with arbitrary keys as an example.

+ +

Dizi nesnelerine erişme

+ +

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.

+ +
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
+
+ +

Dizi öğeleri, {{jsxref("Array.toString", "toString")}} gibi sadece nesne özellikleridir. Geçersiz index numarası ile eleman çağırdığınız zaman undefined 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.

+ +
console.log(arr.0); // bir söz dizimi hatasıdır
+
+ +

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.

+ +
var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010];
+console.log(years.0);   // söz dizimi hatası
+console.log(years[0]);  // çalışır
+
+ +
renderer.3d.setTexture(model, "character.png");     // söz dizimi hatası
+renderer["3d"].setTexture(model, "character.png");  // çalışır
+
+ +

Note that in the 3d example, "3d" had to be quoted. It's possible to quote the JavaScript array indexes as well (e.g., years["2"] instead of years[2]), although it's not necessary. The 2 in years[2] eventually gets coerced into a string by the JavaScript engine, anyway, through an implicit toString conversion. It is for this reason that "2" and "02" would refer to two different slots on the years object and the following example logs true:

+ +
console.log(years["2"] != years["02"]);
+
+ +

Similarly, object properties which happen to be reserved words(!) can only be accessed as string literals in bracket notation:

+ +
var promise = {
+  'var'  : 'text',
+  'array': [1, 2, 3, 4]
+};
+
+console.log(promise['array']);
+ +

Uzunluk ve sayısal özellikler arasındaki ilişki

+ +

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.

+ +
var meyveler = [];
+meyveler.push("muz", "elma", "şeftali");
+
+console.log(meyveler.length); // 3
+ +

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.

+ +
fruits[3] = "mango";
+console.log(fruits[3]);
+console.log(fruits.length); // 4
+ +

Uzunluk özelliğini doğrudan ayarlamak, özel bir davranışa neden olur.

+ +
fruits.length = 10;
+console.log(fruits);        // Dizi, tanımsız olarak doldurulur
+console.log(fruits.length); // 10
+
+ +

Bu özellik {{jsxref("Array.length")}} sayfasında daha ayrıntılı olarak anlatılmıştır.

+ +

Bir diziyi eşleşen bir sonuç ile oluşturmak

+ +

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.

+ +
// 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");
+
+ +

Eşleşen sonucun öğeleri ve özellikleri aşağıdaki gibidir:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Özellik/ÖğeAçıklamaÖrnek
inputDüzenli ifadeye yollanan metni işaret eden salt-okunur bir özelliktir.cdbBdbsbz
indexDüzenli ifadeye yollanan metindeki eşleşmenin sıfır-tabanlı ve salt-okunur index özelliğidir.1
[0]Son eşleşen karakteri belirten salt-okunur bir özelliktir.dbBd
[1], ...[n]Read-only elements that specify the parenthesized substring matches, if included in the regular expression. The number of possible parenthesized substrings is unlimited.[1]: bB
+ [2]: d
+ +

Özellikler

+ +
+
{{jsxref("Array.length")}}
+
The Array constructor's length property whose value is 1.
+
{{jsxref("Array.prototype")}}
+
Allows the addition of properties to all array objects.
+
+ +

Yöntemler

+ +
+
{{jsxref("Array.from()")}} {{experimental_inline}}
+
Bir dizi benzeri veya bir yinelenebilir nesneden yeni bir Dizi örneği oluşturur.
+
{{jsxref("Array.isArray()")}}
+
Eğer bir dizi ise true, değilse false döndürür.
+
{{jsxref("Array.observe()")}} {{experimental_inline}}
+
Asynchronously observes changes to Arrays, similar to {{jsxref("Object.observe()")}} for objects. It provides a stream of changes in order of occurrence.
+
{{jsxref("Array.of()")}} {{experimental_inline}}
+
Creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments.
+
+ +

Dizi örnekleri

+ +

Tüm dizi örnekleri, {{jsxref("Array.prototype")}} 'dan türer. The prototype object of the Array constructor can be modified to affect all Array instances.

+ +

Özellikler

+ +
{{page('/tr/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Properties')}}
+ +

Metodlar

+ +

Mutator methods

+ +
{{page('tr/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Mutator_methods')}}
+ +

Accessor methods

+ +
{{page('tr/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Accessor_methods')}}
+ +

Iteration methods

+ +
{{page('tr/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Iteration_methods')}}
+ +

Array generic methods

+ +

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 str is a letter, you would write:

+ +
function isLetter(character) {
+  return (character >= "a" && character <= "z");
+}
+
+if (Array.prototype.every.call(str, isLetter))
+  alert("The string '" + str + "' contains only letters!");
+
+ +

This notation is rather wasteful and JavaScript 1.6 introduced a generic shorthand:

+ +
if (Array.every(isLetter, str))
+  alert("The string '" + str + "' contains only letters!");
+
+ +

{{jsxref("Global_Objects/String", "Generics", "#String_generic_methods", 1)}} are also available on {{jsxref("Global_Objects/String", "String")}}.

+ +

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:

+ +
// 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]);
+    }
+}());
+ +

Örnekler

+ +

Bir dizi oluşturmak

+ +

Aşağıdaki örnekte uzunluğu [0] olan bir dizi tanımlanıyor(msgArray), daha sonra msgArray[0] ve msgArray[99] indexlerine değer atanıyor ve böylece dizinin uzunluğu 100'e çıkıyor.

+ +
var msgArray = new Array();
+msgArray[0] = "Hello";
+msgArray[99] = "world";
+
+if (msgArray.length == 100)
+   print("The length is 100.");
+
+ +

2 boyutlu dizi oluşturmak

+ +

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ş.

+ +
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'));
+
+ +

Çıktı:

+ +
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
+
+ +

Tarayıcı Uyumluluk Tablosu

+ +

{{Compat("javascript.builtins.Array")}}

+ +

Daha fazlası

+ + 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 +--- +
{{JSRef}}
+ +

indexOf() 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.

+ +
var a = [2, 9, 9];
+a.indexOf(2); // 0
+a.indexOf(7); // -1
+
+if (a.indexOf(7) === -1) {
+  // eleman array de bulunmamaktadır.
+}
+
+ +

Yazım

+ +
arr.indexOf(aranacakEleman)
+arr.indexOf(aranacakEleman, aramayaBaşlanacakİndex)
+
+ +

Parametreler

+ +
+
aranacakEleman
+
Array içerisinde aranacak elemanı karşılayacak metod parametresidir.
+
aramayaBaşlanacakİndex{{optional_inline}}
+
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).
+
+ +

Dönüş değeri

+ +

Elemanın array de ilk görüldüğü index; eğer eleman bulunamazsa -1 dir.

+ +

Açıklama

+ +

indexOf() aranacakEleman'ı katı eşitlik ilkesine göre dizi elemanları ile karşılaştırır (aynı yöntem === veya üç eşittir operatörü tarafından da kullanılır).

+ +

Örnekler

+ +

indexOf()'u kullanma

+ +

Aşağıdaki örnekte indexOf() metodu kullanılarak, değerlerin bir dizideki konumları bulunuyor.

+ +
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
+
+ +

Bir öğenin tüm konumlarını bulma

+ +
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]
+
+ +

Bir öğenin dizide olup olmadığını öğrenme ve diziyi güncelleme

+ +
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.
+
+ +

Polyfill

+ +

indexOf() 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 indexOf() 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.

+ +
// 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;
+  };
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.4.14', 'Array.prototype.indexOf')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.indexof', 'Array.prototype.indexOf')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.indexof', 'Array.prototype.indexOf')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.8")}}{{CompatIE("9")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.8")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Compatibility notes

+ + + +

See also

+ + 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 +--- +
{{JSRef}}
+ +

Array.isArray() metodu değerin Array olup olmadığını kontrol eder. 

+ +

Söz dizimi

+ +
Array.isArray(obj)
+ +

Parametreler

+ +
+
obj
+
Kontrol edilecek nesne.
+
+ +

Açıklamalar

+ +

Nesne eğer {{jsxref("Array")}} ise true değilse false döndürür.

+ +

Daha fazla detay için makaleye göz atın:  “Determining with absolute accuracy whether or not a JavaScript object is an array” 

+ +

Örnekler

+ +
// 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 });
+
+ +

Kod Parçası

+ +

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.

+ +
if (!Array.isArray) {
+  Array.isArray = function(arg) {
+    return Object.prototype.toString.call(arg) === '[object Array]';
+  };
+}
+
+ +

Tanımlamalar

+ + + + + + + + + + + + + + + + + + + + + + + + +
TanımlamaDurumAçıklama
{{SpecName('ES5.1', '#sec-15.4.3.2', 'Array.isArray')}}{{Spec2('ES5.1')}}İlk tanım. JavaScript 1.8.5 sürümünde uygulamaya koyuldu.
{{SpecName('ES6', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ESDraft')}} 
+ +

Tarayıcı uyumluluğu

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
ÖzellikChromeFirefox (Gecko)Internet ExplorerOperaSafari
Temel Destek{{CompatChrome("5")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("9")}}{{CompatOpera("10.5")}}{{CompatSafari("5")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
ÖzellikAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
+ + + + + + + +
Temel Destek 
+
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ayrıca bakınız

+ + 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 +--- +
{{JSRef}}
+ +

join() metodu bir array içerisinde yer alan bütün elemanları birleştirerek string bir ifade olarak geri döndürür. (veya array benzeri bir obje 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.

+ +
{{EmbedInteractiveExample("pages/js/array-join.html")}}
+ + + +

Sözdizimi (Syntax)

+ +
arr.join([separator])
+ +

Parametreler

+ +
+
ayıraç {{optional_inline}}
+
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.
+
+ +

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.

+ +

Açıklamalar

+ +

Dizi (array) içerisinde yer alan bütün elemanları tek bir ifade (string) haline getirir.

+ +

 

+ +
+

Eğer dizi içerisinde yer alan elemanlardan birinin değeri undefined veya null ise, o eleman boş ifadeye ("") dönüştürülür.

+
+ +

Örnekler

+ +

Bir arrayi birleştirmenin dört farklı yolu

+ +

Aşağıda yer alan örnekte örnekte üç elemandan oluşan a 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

+ +
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ş'
+ +

Array benzeri obje nasıl birleştirlir ?

+ +

Aşağıda yer alan örnekte array benzeri obje olarak bilinen (argümanlar), yapıyı Array.prototype.join üzerinden call {{jsxref("Function.prototype.call")}} metodu kullanarak birleştireceğiz. 

+ +
function f(a, b, c) {
+  var s = Array.prototype.join.call(arguments);
+  console.log(s); // '1,a,true'
+}
+f(1, 'a', true);
+//expected output: "1,a,true"
+
+ +

Özellikler

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.4.4.5', 'Array.prototype.join')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.join', 'Array.prototype.join')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.join', 'Array.prototype.join')}}{{Spec2('ESDraft')}} 
+ +

Tarayıcı Uyumluluğu

+ + + +

{{Compat("javascript.builtins.Array.join")}}

+ +

See also

+ + 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 +--- +
{{JSRef}}
+ +
Dizinin length ö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.
+ +
 
+ +
var elemanlar = ["ayakkabılar", "gömlekler", "çoraplar", "kazaklar"];
+elemanlar.length;
+
+// 4 döndürür
+ +

Açıklama

+ +

Uzunluk(length) özellik değeri, artı işaretli bir tam sayıdır ve değeri 2'nin 32. kuvvetinden küçüktür (232).

+ +

Uzunluk(length) özellik değerini ayarlayarak bir diziyi istenen bir zamanda budayabilirsiniz. Bir diziyi length ö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, length özelliğinin her zaman dizideki tanımlı öğe sayısını göstermesi şart değildir. Ayrıca bkz. Bir diziyi eşleşen bir sonuç ile oluşturmak.

+ +

{{js_property_attributes(1, 0, 0)}}

+ +

Örnekler

+ +

Bir dizi üzerinde gezinim

+ +

Aşağıdaki örnekte, numaralar dizisinde, length özelliği kullanılarak gezinim yapılıyor. Her öğe değeri ikiye katlanıyor.

+ +
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
+
+ +

Bir diziyi kısaltmak

+ +

Aşağıdaki örnekte numaralar dizi uzunluğu 3'ten büyükse, dizi kısaltılıyor.

+ +
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
+
+ +

Tanımlamalar

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TanımlamaDurumYorum
{{SpecName('ES1')}}{{Spec2('ES1')}}İlk tanım.
{{SpecName('ES5.1', '#sec-15.4.5.2', 'Array.length')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-array-instances-length', 'Array.length')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-properties-of-array-instances-length', 'Array.length')}}{{Spec2('ESDraft')}} 
+ +

Tarayıcı uyumluluğu

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ayrıca bakınız

+ + 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 +--- +
{{JSRef}}
+ +

map() , dizinin her elemanı için, parametre olarak verilen fonksiyonu çağırır ve oluşan sonuçlarla da yeni bir dizi oluşturur.

+ +
{{EmbedInteractiveExample("pages/js/array-map.html")}}
+ + + +

Sözdizimi

+ +
var new_array = arr.map(function callback(currentValue[, index[, array]]) {
+    // Return element for new_array
+}[, thisArg])
+ +

Parameters

+ +
+
callback
+
Yeni oluşan dizinin elemanlarını döndürdüğü değerlerle oluşturur, üç parametre alır: +
+
 
+
currentValue
+
Dizinin o anda işlem yapılan elemanı.
+
index{{optional_inline}}
+
Dizinin o anda işlem yapılan elemanının indeksi.
+
array{{optional_inline}}
+
map tarafından çağırılan dizi.
+
+
+
thisArg{{optional_inline}}
+
callback fonsiyonu çalışırken kullanacağı this değeri.
+
+ +

Return value

+ +

Elemanları, callback fonksiyonunun sonuçları olan yeni bir dizi.

+ +

Açıklama

+ +

map, kendisine özel tahsis edilmiş geri çağırma (callback) fonksiyonunu çağırarak, sıraya uygun olarak döngüye giren her eleman için sonuçtan yeni bir dizi(array) inşa eder. callback sadece değere tanımlanmış dizinin indeksleri için tetiklenir, undefined de buna dahildir. Dizinin kayıp elemanları için çağrılmaz ( kayıp elemanlar: silinmiş veya hiçbir değere eşitlenmemiş veya oluşmamış indeksleri ifade eder. )

+ +

callback şu üç argüman ile tetiklenir; Elemanın değeri, elemanın indeks numarası ve elemanları gezilecek olan dizi objesi...

+ +
dizi.map( (deger, index) => /* yapılacak işlem */ ) 
+ +

If a thisArg parameter is provided to map, it will be used as callback's this value. Otherwise, the value {{jsxref("undefined")}} will be used as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.

+ +

map does not mutate the array on which it is called (although callback, if invoked, may do so).

+ +

The range of elements processed by map is set before the first invocation of callback. Elements which are appended to the array after the call to map begins will not be visited by callback. If existing elements of the array are changed, their value as passed to callback will be the value at the time map visits them. Elements that are deleted after the call to map begins and before being visited are not visited.
+
+ 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.

+ +

Examples

+ +

Mapping an array of numbers to an array of square roots

+ +

The following code takes an array of numbers and creates a new array containing the square roots of the numbers in the first array.

+ +
var numbers = [1, 4, 9];
+var roots = numbers.map(Math.sqrt);
+// roots is now [1, 2, 3]
+// numbers is still [1, 4, 9]
+
+ +

Using map to reformat objects in an array

+ +

The following code takes an array of objects and creates a new array containing the newly reformatted objects.

+ +
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}]
+
+ +

Mapping an array of numbers using a function containing an argument

+ +

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.

+ +
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]
+
+ +

Using map generically

+ +

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:

+ +
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]
+
+ +

Using map generically querySelectorAll

+ +

This example shows how to iterate through a collection of objects collected by querySelectorAll. In this case we get all selected options on the screen and printed on the console:

+ +
var elems = document.querySelectorAll('select option:checked');
+var values = Array.prototype.map.call(elems, function(obj) {
+  return obj.value;
+});
+
+ +

Easier way would be using {{jsxref("Array.from()")}} method.

+ +

Tricky use case

+ +

(inspired by this blog post)

+ +

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.

+ +
// 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]
+
+ +

One alternative output of the map method being called with parseInt as a parameter runs as follows:

+ +
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.
+ +

Polyfill

+ +

map 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 map 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 callback.call evaluates to the original value of {{jsxref("Function.prototype.call")}}.

+ +
// 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;
+  };
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.4.19', 'Array.prototype.map')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.map', 'Array.prototype.map')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.map', 'Array.prototype.map')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Array.map")}}

+
+ +

See also

+ + 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 +--- +
{{JSRef}}
+ +

Array.of() metodu, verilen argümanları içeren yeni bir dizi (Array) oluşturur. Argüman sayısı ve tipi konusunda herhangi bir kısıtı yoktur.

+ +

Array.of() ile Array yapıcı (constructor) arasındaki fark, sayısal argümanları kullanma biçimidir: Array.of(7) tek öğesi 7 olan bir dizi oluştururken, Array(7), 7 öğe kapasiteli -length özelliği 7 olan- boş bir dizi oluşturur (Not: Bu ifade 7 boş yeri olan bir dizi oluştur, kapasitesi kadar tanımsız öğe içeren bir dizi değil).

+ +
Array.of(7);       // [7]
+Array.of(1, 2, 3); // [1, 2, 3]
+
+Array(7);          // [ , , , , , , ]
+Array(1, 2, 3);    // [1, 2, 3]
+
+ +

Sözdizimi

+ +
Array.of(element0[, element1[, ...[, elementN]]])
+ +

Parametreler

+ +
+
elementN
+
Diziyi oluşturacak öğeler.
+
+ +

Dönüş değeri

+ +

Yeni bir {{jsxref("Array")}} örneği.

+ +

Açıklama

+ +

Bu fonksiyon ECMAScript 2015 standardının bir parçasıdır. Daha fazla bilgi için Array.of ve Array.from proposal ve Array.of polyfill linklerine bakabilirsiniz.

+ +

Örnekler

+ +
Array.of(1);         // [1]
+Array.of(1, 2, 3);   // [1, 2, 3]
+Array.of(undefined); // [undefined]
+
+ +

Polyfill

+ +

Eğer Array.of() doğal olarak mevcut değilse, aşağıdaki kodu diğer kodlardan önce çalıştırarak oluşturabilirsiniz.

+ +
if (!Array.of) {
+  Array.of = function() {
+    return Array.prototype.slice.call(arguments);
+  };
+}
+
+ +

Şartnameler

+ + + + + + + + + + + + + + + + + + + +
ŞartnameDurumYorum
{{SpecName('ES2015', '#sec-array.of', 'Array.of')}}{{Spec2('ES2015')}}İlk tanım.
{{SpecName('ESDraft', '#sec-array.of', 'Array.of')}}{{Spec2('ESDraft')}} 
+ +

Tarayıcı Uyumu

+ +
+ + +

{{Compat("javascript.builtins.Array.of")}}

+
+ +

Ayrıca bakınız

+ + 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 +--- +
{{JSRef}}
+ +

pop() yöntemi, bir dizideki son öğeyi kaldırır ve o öğeyi döndürür. Bu yöntem dizinin uzunluğunu değiştirir.

+ + + +
{{EmbedInteractiveExample("pages/js/array-pop.html")}}
+ + + +

Syntax

+ +
arr.pop()
+ +

Return value

+ +

The removed element from the array; {{jsxref("undefined")}} if the array is empty.

+ +

Description

+ +

The pop method removes the last element from an array and returns that value to the caller.

+ +

pop 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 length property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner.

+ +

If you call pop() on an empty array, it returns {{jsxref("undefined")}}.

+ +

{{jsxref("Array.prototype.shift()")}} has similar behavior to pop, but applied to the first element in an array.

+ +

Examples

+ +

Removing the last element of an array

+ +

The following code creates the myFish array containing four elements, then removes its last element.

+ +
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
+
+var popped = myFish.pop();
+
+console.log(myFish); // ['angel', 'clown', 'mandarin' ]
+
+console.log(popped); // 'sturgeon'
+ + + +

Using apply( ) or call ( ) on array-like objects

+ +

The following code creates the myFish array-like object containing four elements and a length parameter, then removes its last element and decrements the length parameter.

+ +
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'
+
+ + + +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.6', 'Array.prototype.pop')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.pop', 'Array.prototype.pop')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.pop', 'Array.prototype.pop')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Array.pop")}}

+
+ +

See also

+ + + +
+
+
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 +--- +
{{JSRef("Global_Objects", "Array")}}
+ +

Summary

+ +

The Array.prototype property represents the prototype for the {{jsxref("Global_Objects/Array", "Array")}} constructor.

+ +
{{js_property_attributes(0, 0, 0)}}
+ +

Description

+ +

{{jsxref("Global_Objects/Array", "Array")}} instances inherit from Array.prototype. As with all constructors, you can change the constructor's prototype object to make changes to all {{jsxref("Global_Objects/Array", "Array")}} instances.

+ +

Little known fact: Array.prototype itself is an {{jsxref("Global_Objects/Array", "Array")}}:

+ +
Array.isArray(Array.prototype); // true
+
+ +

Properties

+ +
+
Array.prototype.constructor
+
Specifies the function that creates an object's prototype.
+
{{jsxref("Array.prototype.length")}}
+
Reflects the number of elements in an array.
+
+ +

Methods

+ +

Mutator methods

+ +

These methods modify the array:

+ +
+
{{jsxref("Array.prototype.copyWithin()")}} {{experimental_inline}}
+
Copies a sequence of array elements within the array.
+
{{jsxref("Array.prototype.fill()")}} {{experimental_inline}}
+
Fills all the elements of an array from a start index to an end index with a static value.
+
{{jsxref("Array.prototype.pop()")}}
+
Removes the last element from an array and returns that element.
+
{{jsxref("Array.prototype.push()")}}
+
Adds one or more elements to the end of an array and returns the new length of the array.
+
{{jsxref("Array.prototype.reverse()")}}
+
Reverses the order of the elements of an array in place — the first becomes the last, and the last becomes the first.
+
{{jsxref("Array.prototype.shift()")}}
+
Removes the first element from an array and returns that element.
+
{{jsxref("Array.prototype.sort()")}}
+
Sorts the elements of an array in place and returns the array.
+
{{jsxref("Array.prototype.splice()")}}
+
Adds and/or removes elements from an array.
+
{{jsxref("Array.prototype.unshift()")}}
+
Adds one or more elements to the front of an array and returns the new length of the array.
+
+ +

Accessor methods

+ +

These methods do not modify the array and return some representation of the array.

+ +
+
{{jsxref("Array.prototype.concat()")}}
+
Returns a new array comprised of this array joined with other array(s) and/or value(s).
+
{{jsxref("Array.prototype.includes()")}} {{experimental_inline}}
+
Determines whether an array contains a certain element, returning true or false as appropriate.
+
{{jsxref("Array.prototype.join()")}}
+
Joins all elements of an array into a string.
+
{{jsxref("Array.prototype.slice()")}}
+
Extracts a section of an array and returns a new array.
+
{{jsxref("Array.prototype.toSource()")}} {{non-standard_inline}}
+
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.
+
{{jsxref("Array.prototype.toString()")}}
+
Returns a string representing the array and its elements. Overrides the {{jsxref("Object.prototype.toString()")}} method.
+
{{jsxref("Array.prototype.toLocaleString()")}}
+
Returns a localized string representing the array and its elements. Overrides the {{jsxref("Object.prototype.toLocaleString()")}} method.
+
{{jsxref("Array.prototype.indexOf()")}}
+
Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
+
{{jsxref("Array.prototype.lastIndexOf()")}}
+
Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.
+
+ +

Iteration methods

+ +

Several methods take as arguments functions to be called back while processing the array. When these methods are called, the length 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.

+ +
+
{{jsxref("Array.prototype.forEach()")}}
+
Calls a function for each element in the array.
+
{{jsxref("Array.prototype.entries()")}} {{experimental_inline}}
+
Returns a new Array Iterator object that contains the key/value pairs for each index in the array.
+
{{jsxref("Array.prototype.every()")}}
+
Returns true if every element in this array satisfies the provided testing function.
+
{{jsxref("Array.prototype.some()")}}
+
Returns true if at least one element in this array satisfies the provided testing function.
+
{{jsxref("Array.prototype.filter()")}}
+
Creates a new array with all of the elements of this array for which the provided filtering function returns true.
+
{{jsxref("Array.prototype.find()")}} {{experimental_inline}}
+
Returns the found value in the array, if an element in the array satisfies the provided testing function or undefined if not found.
+
{{jsxref("Array.prototype.findIndex()")}} {{experimental_inline}}
+
Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found.
+
{{jsxref("Array.prototype.keys()")}} {{experimental_inline}}
+
Returns a new Array Iterator that contains the keys for each index in the array.
+
{{jsxref("Array.prototype.map()")}}
+
Creates a new array with the results of calling a provided function on every element in this array.
+
{{jsxref("Array.prototype.reduce()")}}
+
Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value.
+
{{jsxref("Array.prototype.reduceRight()")}}
+
Apply a function against an accumulator and each value of the array (from right-to-left) as to reduce it to a single value.
+
{{jsxref("Array.prototype.values()")}} {{experimental_inline}}
+
Returns a new Array Iterator object that contains the values for each index in the array.
+
{{jsxref("Array.prototype.@@iterator()", "Array.prototype[@@iterator]()")}} {{experimental_inline}}
+
Returns a new Array Iterator object that contains the values for each index in the array.
+
+ +

Generic methods

+ +

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 length property, and which can usefully be accessed using numeric property names (as with array[5] indexing). 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")}}. Some methods, such as {{jsxref("Array.join", "join")}}, only read the length and numeric properties of the object they are called on. Others, like {{jsxref("Array.reverse", "reverse")}}, require that the object's numeric properties and length be mutable; these methods can therefore not be called on objects like {{jsxref("Global_Objects/String", "String")}}, which does not permit its length property or synthesized numeric properties to be set.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
ECMAScript 1st Edition.StandardInitial definition.
{{SpecName('ES5.1', '#sec-15.4.3.1', 'Array.prototype')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype', 'Array.prototype')}}{{Spec2('ES6')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + 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 +--- +
{{JSRef}}
+ +

push() metotu dizinin sonuna bir yada daha fazla element ekler ve dizinin yeni uzunluğunu geri döndürür.

+ +

Söz dizimi

+ +
arr.push(element1, ..., elementN)
+ +

Parametreler

+ +
+
elementN
+
Dizinin sonuna eklenecek elementler.
+
+ +

Geri döndürür

+ +

Nesnenin yeni {{jsxref("Array.length", "length")}} özelliğini metotun çağrılması üzerine geri döndürür.

+ +

Tanım

+ +

push metotu değerleri bir diziye ekler.

+ +

push kasıtlı olarak genelleyicidir. Bu metot benzeyen nesnelerin dizilerinde {{jsxref("Function.call", "call()")}} veya {{jsxref("Function.apply", "apply()")}} ile kullanılabilir. push metotu verilen değerleri eklemeye nereden başlayacağını tespit etmek için length özelliğine dayanır. Eğer length özelliği bir sayıya dönüştürülemezse indeks 0 kabul edilir. Bu durum length özelliğinin bulunmama ihtimalini de kapsar, bu durumda length ayrıca oluşturulacaktır.

+ +

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.

+ +

Örnekler

+ +

Bir diziye element ekleme

+ +

Aşağıda bulunan kod iki elementi bulunan sports dizisini oluşturuyor, daha sonra iki diziye iki element daha ekliyor. total değişkeni dizinin yeni uzunluğunu tutuyor.

+ +
var sports = ['soccer', 'baseball'];
+var total = sports.push('football', 'swimming');
+
+console.log(sports); // ['soccer', 'baseball', 'football', 'swimming']
+console.log(total);  // 4
+
+ +

İki diziyi birleştirme

+ +

Bu örnek ikinci bir diziden bütün elemanları eklemek için {{jsxref("Function.apply", "apply()")}} kullanıyor.

+ +
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']
+
+ +

Şartnameler

+ + + + + + + + + + + + + + + + + + + + + + + + +
ŞartnameDurumYorum
{{SpecName('ES3')}}{{Spec2('ES3')}}İlk tanım. JavaScript 1.2'de uygulandı.
{{SpecName('ES5.1', '#sec-15.4.4.7', 'Array.prototype.push')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.push', 'Array.prototype.push')}}{{Spec2('ES6')}} 
+ +

Tarayıcı uyumu

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
ÖzellikChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basit destek{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
ÖzellikAndroidAndroid için ChromeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basit destek{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ayrıca göz at

+ + 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 +--- +
{{JSRef}}
+ +

reverse() metodu dizi elemanlarını tersten sıralar . Dizinin ilk elemanı son eleman olur, son elemanı ilk eleman olur.

+ +
{{EmbedInteractiveExample("pages/js/array-reverse.html")}}
+ + + +

Syntax

+ +
a.reverse()
+ +

Dönen Değer

+ +

Ters dizi.

+ +

Açıklama

+ +

reverse metodu dizinin olduğu halini kalıcı olarak değiştirir ve değiştirilmiş diziyi döndürür.

+ +

reverse bilinçli olarak generic metodtur; bu şekilde dizilere benzeyen nesneler çağrılabilir veya uygulanabilir. Bir dizi ardışık, sıfır tabanlı sayısal özellikte sonuncuyu yansıtan length özelliği içermeyen nesneler anlamlı bir şekilde davranmayabilir.

+ +

Örnekler

+ +

Bir dizideki öğeleri tersine çevirme

+ +

Aşağıdaki örnek, üç öğe içeren bir a dizisi oluşturur, ardından diziyi tersine çevirir. reverse() çağrısı, ters çevrilmiş a dizisine bir referans döndürür.

+ +
const a = [1, 2, 3];
+
+console.log(a); // [1, 2, 3]
+
+a.reverse();
+
+console.log(a); // [3, 2, 1]
+
+
+ +

Dizi benzeri bir nesnedeki öğeleri tersine çevirme

+ +

Aşağıdaki örnek, üç öğe ve length özelliği içeren dizi benzeri bir nesne a oluşturur, sonra dizi benzeri nesneyi tersine çevirir. reverse () çağrısı, ters dizi benzeri nesneye a bir referans döndürür.

+ +
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}
+
+ +

Özellikler

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ÖzellikDurumYorum
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.4.4.8', 'Array.prototype.reverse')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}{{Spec2('ESDraft')}}
+ +

Tarayıcı Uyumluluğu

+ +
+ + +

{{Compat("javascript.builtins.Array.reverse")}}

+
+ +

See also

+ + 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 +--- +
{{JSRef}}
+ +

shift() metodu bir dizinin ilk elementini diziden kaldırır ve kaldırılmış bu elementi geri döndürür. Bu metod dizinin boyunu değiştirir.

+ +
{{EmbedInteractiveExample("pages/js/array-shift.html")}}
+ + + +

Dildizimi

+ +
arr.shift()
+ +

Dönen değer

+ +

Diziden kaldırılan element; eğer dizi boş ise de {{jsxref("undefined")}} değerini döndürür.

+ +

Tanımlama

+ +

shift 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.

+ +

shift ö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 length özelliği bulundurmayan nesneler, anlamli bir davranış göstermeyebilirler.

+ +

Örnekler

+ +

Bir diziden bir elementi kaldırmak

+ +

Aşağıdaki kod  myFish dizisinin ilk elementini kaldırmadan önceki ve kaldırdıktan sonraki halini göstermektedir. Aynı zamanda kaldırılan elementi de gösterir:

+ +
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
+
+ +

shift() metodunu while döngüsü içerisinde kullanmak

+ +

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:

+ +
var isimler = ["Andrew", "Edward", "Paul", "Chris" ,"John"];
+
+while( (i = isimler.shift()) !== undefined ) {
+    console.log(i);
+}
+// Andrew, Edward, Paul, Chris, John
+
+ +

Özellikler

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ÖzellikDurumAçıklama
{{SpecName('ES3')}}{{Spec2('ES3')}}İlk tanımlama. JavaScript 1.2. de uygulandı.
{{SpecName('ES5.1', '#sec-15.4.4.9', 'Array.prototype.shift')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.shift', 'Array.prototype.shift')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.shift', 'Array.prototype.shift')}}{{Spec2('ESDraft')}} 
+ +

Tarayıcı uyumluluğu

+ +
+ + +

{{Compat("javascript.builtins.Array.shift")}}

+
+ +

Ayrıca bakınız

+ + 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 +--- +
{{JSRef}}
+ +

sort() 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.

+ +

The time and space complexity of the sort cannot be guaranteed as it depends on the implementation.

+ +
{{EmbedInteractiveExample("pages/js/array-sort.html")}}
+ + + +

Syntax

+ +
arr.sort([compareFunction])
+
+ +

Parametreler

+ +
+
compareFunction {{optional_inline}}
+
Specifies a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value. +
+
firstEl
+
The first element for comparison.
+
secondEl
+
The second element for comparison.
+
+
+
+ +

Geri dönen değer

+ +

The sorted array. Note that the array is sorted in place, and no copy is made.

+ +

Açıklama

+ +

If compareFunction is not supplied, all non-undefined 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 undefined elements are sorted to the end of the array.

+ +
+

Note : In UTF-16, Unicode characters above \uFFFF are encoded as two surrogate code units, of the range \uD800-\uDFFF. The value of each code unit is taken separately into account for the comparison. Thus the character formed by the surrogate pair \uD655\uDE55 will be sorted before the character \uFF3A.

+
+ +

If compareFunction is supplied, all non-undefined array elements are sorted according to the return value of the compare function (all undefined elements are sorted to the end of the array, with no call to compareFunction). If a and b are two elements being compared, then:

+ + + +

So, the compare function has the following form:

+ +
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;
+}
+
+ +

To compare numbers instead of strings, the compare function can simply subtract b from a. The following function will sort the array in ascending order (if it doesn't contain Infinity and NaN):

+ +
function compareNumbers(a, b) {
+  return a - b;
+}
+
+ +

The sort method can be conveniently used with {{jsxref("Operators/function", "function expressions", "", 1)}}:

+ +
var numbers = [4, 2, 5, 1, 3];
+numbers.sort(function(a, b) {
+  return a - b;
+});
+console.log(numbers);
+
+// [1, 2, 3, 4, 5]
+
+ +

ES2015 provides {{jsxref("Functions/Arrow_functions", "arrow function expressions", "", 1)}} with even shorter syntax.

+ +
let numbers = [4, 2, 5, 1, 3];
+numbers.sort((a, b) => a - b);
+console.log(numbers);
+
+// [1, 2, 3, 4, 5]
+ +

Objects can be sorted, given the value of one of their properties.

+ +
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;
+});
+ +

Örnekler

+ +

Creating, displaying, and sorting an array

+ +

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.

+ +
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));
+
+ +

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.

+ +
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
+
+ +

ASCII olmayan karakterleri sıralama

+ +

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.

+ +
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é']
+
+ +

Map ile sıralama

+ +

The compareFunction can be invoked multiple times per element within the array. Depending on the compareFunction's nature, this may yield a high overhead. The more work a compareFunction does and the more elements there are to sort, it may be more efficient to use map 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.

+ +
// 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];
+});
+
+ +

There is an open source library available called mapsort which applies this approach.

+ +

Specifications

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-array.prototype.sort', 'Array.prototype.sort')}}
+ +

Tarayıcı uyumluluğu

+ +
+ + +

{{Compat("javascript.builtins.Array.sort")}}

+
+ +

Bunlarada göz at

+ + 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 +--- +
{{JSRef}}
+ +

splice() metodu; bir Dizi'nin içeriklerini, diziye ait öğeleri kaldırarak veya yeni öğeler ekleyerek ve/veya mevcut öğeleri silerek değiştirir.

+ +
{{EmbedInteractiveExample("pages/js/array-splice.html")}}
+ +

Syntax

+ +
array.splice(başlangıç[, silinecekAdet[, item1[, item2[, ...]]]])
+
+ +

Parametreler

+ +
+
başlangıç
+
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.
+
silinecekAdet {{optional_inline}}
+
Eski Dizi'nden silinecek öğelerin sayısını belirten bir tamsayı.
+
silinecekAdet belirlenmemiş ise, veya değeri dizi.uzunluk - başlangıç 'tan büyük ise (daha sade bir tanımı,  başlangıç başlayarak, Dizi'nde kalmış öğelerin toplam sayısından fazla ise), start sayısından Dizi'nin sonuna kadar yer alan bütün öğeler silinecek.
+
silinecekAdet 0 veya negatif ise, hiçbir öğe silinmeyecek. Bu durumda, en az yeni bir öğe tanımlamalısın (aşağı bkz.).
+
item1, item2, ... {{optional_inline}}
+
Dizi'ne eklenecek olan öğeler, başlangıç indeksinden başlayarak. hiçbir öğe tanımlamaz isen, splice() sadece Dizi'den öğeleri kaldıracak.
+
+ +

Geri dönüş değeri

+ +

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.

+ +

Açıklama

+ +

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.

+ +

Örnekler

+ +

2 indeksinden önce 0 öğe sil, ve "drum" öğesini ekle

+ +
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
+
+ +

3 indeksinden 1 öğe sil

+ +
var myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon'];
+var removed = myFish.splice(3, 1);
+
+// silinen ["mandarin"]
+// myFish Dizi'si ["angel", "clown", "drum", "sturgeon"]
+
+ +

2 indeksinden 1 öğe sil, ve "trumpet" öğesini ekle

+ +
var myFish = ['angel', 'clown', 'drum', 'sturgeon'];
+var silinen = myFish.splice(2, 1, 'trumpet');
+
+// myFish is ["angel", "clown", "trumpet", "sturgeon"]
+// silinen ["drum"]
+ +

0 indeksinden başlayarak 2 öğe sil, "parrot", "anemone" ve "blue" öğelerini ekle

+ +
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"]
+ +

2 indeksinden 2 öğe sil

+ +
var myFish = ['parrot', 'anemone', 'blue', 'trumpet', 'sturgeon'];
+var silinen = myFish.splice(myFish.length - 3, 2);
+
+// myFish is ["parrot", "anemone", "sturgeon"]
+// silinen ["blue", "trumpet"]
+ +

-2 indeksinden 1 öğe sil

+ +
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
+var silinen = myFish.splice(-2, 1);
+
+// myFish ["angel", "clown", "sturgeon"]
+// silinen ["mandarin"]
+ +

2 indeksinden sonra bütün öğeleri sil (2 indeksi de dahil)

+ +
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
+var silinen = myFish.splice(2);
+
+// myFish ["angel", "clown"]
+// silinen ["mandarin", "sturgeon"]
+ +

Özellikler

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ÖzellikDurumYorum
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.12', 'Array.prototype.splice')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.splice', 'Array.prototype.splice')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.splice', 'Array.prototype.splice')}}{{Spec2('ESDraft')}}
+ +

Tarayıcı Uyumluluğu

+ +
+ + +

{{Compat("javascript.builtins.Array.splice")}}

+
+ +

Bkz.

+ + 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 +--- +
{{JSRef}}
+ +

unshift() metodu dizinin başına bir veya daha fazla element ekler ve yeni dizinin uzunluğunu size geri döndürür.

+ +
{{EmbedInteractiveExample("pages/js/array-unshift.html")}}
+ +

Sözdizimi Kuralları

+ +
dizi.unshift(element1[, ...[, elementN]])
+ +

Parametreler

+ +
+
elementN
+
Dizinin başına eklenecek değer.
+
+ +

Döndürülen değer

+ +

Üzerinde işlem yapılan dizinin yeni {{jsxref("Array.length", "length")}} değerini verir.

+ +

Açıklama

+ +

unshift, girilen değerleri bir dizinin başına ekler.

+ +

unshiftkasıtlı olarak geneldir; bu yöntem, benzer nesnelere {{jsxref("Function.call", "called", "", 1)}} veya {{jsxref("Function.apply", "applied", "", 1)}} olabilir. diziler. Birbirini length ardışık, sıfıra dayalı sayısal özellikler dizisinde sonuncuyu yansıtan bir özellik içermeyen nesneler , anlamlı şekilde davranamazlar.

+ +

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.

+ +
let dizi = [4, 5, 6];
+dizi.unshift(1, 2, 3);
+console.log(dizi);
+// [1, 2, 3, 4, 5, 6]
+
+dizi = [4, 5, 6]; // dizi sıfırlanır.
+
+dizi.unshift(1);
+dizi.unshift(2);
+dizi.unshift(3);
+
+console.log(dizi);
+// [3, 2, 1, 4, 5, 6]
+
+ +

Örnekler

+ +
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 ]
+
+ +

Özellikler

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ÖzellikDurumAçıklama
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.13', 'Array.prototype.unshift')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.unshift', 'Array.prototype.unshift')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.unshift', 'Array.prototype.unshift')}}{{Spec2('ESDraft')}}
+ +

Tarayıcı desteği

+ +
+ + +

{{Compat("javascript.builtins.Array.unshift")}}

+
+ +

Benzer Makaleler

+ + 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 +--- +
{{JSRef}}
+ +
 
+ +

values() methodu dizideki tüm elemanları içeren yeni bir (Dizi yineleyici)  nesnesi döner

+ +
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
+
+
+ +

Sintaks

+ +
arr.values()
+ +

Dönüş değeri

+ +

Yeni bir {{jsxref("Array")}} yineleyici nesne.

+ +

Örnekler

+ +

for...of loop ile yineleme

+ +
var arr = ['e', 'l', 'm', 'a'];
+var yineleyici = arr.values();
+
+for (let harf of yineleyici) {
+  console.log(harf);
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-array.prototype.values', 'Array.prototype.values')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.values', 'Array.prototype.values')}}{{Spec2('ESDraft')}} 
+ +

Web tarayıcı uyumluluğu

+ +
+ + +

{{Compat("javascript.builtins.Array.values")}}

+
+ +

See also

+ + 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 +--- +
{{JSRef}}
+ +

Bir ArrayBuffer 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, yazılmış dizi nesnelerini 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.

+ +

Syntax

+ +
new ArrayBuffer(length)
+
+ +

Parametreler

+ +
+
length
+
Byte cinsinden, oluşturulan array buffer'ın boyutudur.
+
+ +

Döndürülen Değer

+ +

Belirlenen boyutta yeni bir ArrayBuffer nesnesi. İçeriği 0 atanmış durumdadır.

+ +

İstisnalar

+ +

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.

+ +

Tanım

+ +

ArrayBuffer constructor'ı, byte cinsinden verilen boyutta yeni bir ArrayBuffer oluşturur.

+ +

Var olan bir data'dan array buffer çekmek

+ + + +

Özellikler

+ +
+
ArrayBuffer.length
+
ArrayBuffer constructor'ının 1 değerine sahip uzunluk özelliği.
+
{{jsxref("ArrayBuffer.@@species", "get ArrayBuffer[@@species]")}}
+
Türetilmiş nesneleri oluşturmak için kullanılan constructor fonksiyonu.
+
{{jsxref("ArrayBuffer.prototype")}}
+
Bütün ArrayBuffer nesnelerine özellik eklemeye izin verir.
+
+ +

Metodlar

+ +
+
{{jsxref("ArrayBuffer.isView", "ArrayBuffer.isView(arg)")}}
+
Eğer arg bir ArrayBuffer view'i ise true döndürür, tıpkı yazılmış dizi nesneleri veya bir {{jsxref("DataView")}}gibi. Aksi halde false döndürür.
+
{{jsxref("ArrayBuffer.transfer", "ArrayBuffer.transfer(oldBuffer [, newByteLength])")}} {{experimental_inline}}
+
+
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.
+
+
+ +

ArrayBuffer oluşumları

+ +

Bütün ArrayBuffer oluşumları {{jsxref("ArrayBuffer.prototype")}} tarafından miras alınır.

+ +

Özellikler

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/prototype','Properties')}}

+ +

Metodlar

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/prototype','Methods')}}

+ +
+
{{jsxref("ArrayBuffer.slice()")}} {{non-standard_inline}}
+
{{jsxref("ArrayBuffer.prototype.slice()")}} ile aynı fonksiyonelliğe sahiptir.
+
+ +

Örnek

+ +

Bu örnekte,  {{jsxref("Global_Objects/Int32Array", "Int32Array")}} view'i aracılığıyla 8-byte'lık bir buffer oluştururuz.

+ +
var buffer = new ArrayBuffer(8);
+var view   = new Int32Array(buffer);
+ +

Belirtmeler

+ + + + + + + + + + + + + + + + + + + + + + + + +
BelirtmeDurumYorumlar
{{SpecName('Typed Array')}}{{Spec2('Typed Array')}}ECMAScript 6 tarafından yenilenmiştir.
{{SpecName('ES6', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}{{Spec2('ES6')}}Bir ECMA standardı için başlangıç tanımı. new'in gerekli olduğu belirtilmiştir.
{{SpecName('ESDraft', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}{{Spec2('ESDraft')}} 
+ +

Tarayıcı Uyumluluğu

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ÖzellikChromeFirefox (Gecko)Internet ExplorerOperaSafari
Temel Destek7.0{{CompatGeckoDesktop("2")}}1011.65.1
ArrayBuffer() new fırlatmadan{{CompatUnknown}}{{CompatGeckoDesktop("44")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ArrayBuffer.slice() {{non-standard_inline}}{{CompatNo}}{{CompatVersionUnknown}}
+ {{CompatNo}} {{CompatGeckoDesktop("53")}}
{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ÖzellikAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Temel Destek4.0{{CompatVersionUnknown}}{{CompatGeckoMobile("2")}}1011.64.2
ArrayBuffer() new fırlatmadan{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("44")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ArrayBuffer.slice() {{non-standard_inline}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}
+ {{CompatNo}} {{CompatGeckoMobile("53")}}
{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
+
+ +

Uyumluluk Notları

+ +

 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. Artık new fonksiyonu kullanmadan bir ArrayBuffer constructor'ı çağırmak, bir  {{jsxref("TypeError")}} fırlatacaktır.

+ +
var dv = ArrayBuffer(10);
+// TypeError:new komutu olmadan
+// Gömülü bir ArrayBuffer constructor'u çağırmak 
+ +
var dv = new ArrayBuffer(10);
+ +

Ayrıca Bakınız

+ + 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 +--- +
{{JSRef}}
+ +

Boolean nesnesi, bir boolean değeri için bir nesne sarmalayıcıdır.

+ +

Sözdizimi

+ +
new Boolean([değer])
+ +

Parametreler

+ +
+
değer
+
Opsiyonel. Boolean nesnesinin başlangıç değeri.
+
+ +

Açıklama

+ +

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.

+ +

İlkel Boolean değerlerini true ve false ile Boolean nesnesinin true ve false değerleriyle karıştırmayın.

+ +

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:

+ +
var x = new Boolean(false);
+if (x) {
+  // bu kod gerçekleşti.
+}
+
+ +

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:

+ +
var x = false;
+if (x) {
+  // bu kod gerçekleşmedi.
+}
+
+ +

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:

+ +
var x = Boolean(expression);     // tercih edilen
+var x = new Boolean(expression); // kullanma
+
+ +

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.

+ +
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
+
+ +

Boolean ilkelinin yerine bir Boolean nesnesi kullanmayın.

+ +

Özellikleri

+ +
+
Boolean.length
+
Uzunluk özelliğinin değeri 1.
+
{{jsxref("Boolean.prototype")}}
+
Boolean yapıcısının prototipini temsil eder.
+
+ +

Metodlar

+ +

Genel Boolean nesnesi kendine özgü bir yöntem içermese de, prototip zinciri boyunca bazı yöntemleri devralır:

+ +

Boolean örnekleri

+ +

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.

+ +

Özellikleri

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean/prototype', 'Properties')}}
+ +

Metodlar

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean/prototype', 'Methods')}}
+ +

Örnekler

+ +

ilk değeri false olan Boolean nesnesi oluşturma 

+ +
var bNoParam = new Boolean();
+var bZero = new Boolean(0);
+var bNull = new Boolean(null);
+var bEmptyString = new Boolean('');
+var bfalse = new Boolean(false);
+
+ +

ilk değeri true olan Boolean nesnesi oluşturma

+ +
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({});
+
+ +

Özellikler

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ÖzellikDurumYorum
{{SpecName('ES1')}}{{Spec2('ES1')}}İlk tanım. JavaScript 1.0'da uygulanmaktadır.
{{SpecName('ES5.1', '#sec-15.6', 'Boolean')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-boolean-objects', 'Boolean')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-boolean-objects', 'Boolean')}}{{Spec2('ESDraft')}} 
+ +

Tarayıcı Uyumluluğu

+ +
+ + +

{{Compat("javascript.builtins.Boolean")}} 

+
+ +


+ Ayrıca bakınız

+ + 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 +--- +
{{JSRef}}
+ +

Boolean.prototype özelliği {{jsxref ("Boolean")}} yapıcı methodunun prototipini temsil eder.

+ +
{{js_property_attributes(0, 0, 0)}}
+ +
{{EmbedInteractiveExample("pages/js/boolean-constructor.html")}}
+ + + +

 

+ +

{{jsxref("Boolean")}} instances inherit from Boolean.prototype. You can use the constructor's prototype object to add properties or methods to all {{jsxref("Boolean")}} instances.

+ +

Properties

+ +
+
Boolean.prototype.constructor
+
Bir örneğin prototipini oluşturan fonksiyonu döndürür. Bu varsayılan olarak {{jsxref ("Boolean")}} işlevidir.
+
+ +

Methods

+ +
+
{{jsxref("Boolean.prototype.toSource()")}} {{non-standard_inline}}
+
{{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.
+
{{jsxref("Boolean.prototype.toString()")}}
+
Nesnenin değerine bağlı olarak "true" ya da "false" dizesini döndürür. {{Jsxref ("Object.prototype.toString ()")}} methodunu geçersiz kılar.
+
{{jsxref("Boolean.prototype.valueOf()")}}
+
{{Jsxref ("Boolean")}} nesnesinin temel değerini döndürür. {{Jsxref ("Object.prototype.valueOf ()")}} methodunu geçersiz kılar.
+
+ +

Özellikler

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ÖzelliklerDurumAçıklama
{{SpecName('ES1')}}{{Spec2('ES1')}}İlk tanım. JavaScript 1.0'da uygulanmaktadır.
{{SpecName('ES5.1', '#sec-15.6.3.1', 'Boolean.prototype')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-boolean.prototype', 'Boolean.prototype')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-boolean.prototype', 'Boolean.prototype')}}{{Spec2('ESDraft')}} 
+ +

Tarayıcı Uyumluluğu

+ +
+ + +

{{Compat("javascript.builtins.Boolean.prototype")}}

+
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 +--- +
{{JSRef}} {{non-standard_header}}
+ +

ToSource () metodu, nesnenin kaynak kodunu temsil eden bir dize döndürür.

+ +

Sözdizimi

+ +
booleanObj.toSource()
+Boolean.toSource()
+ +

Return değeri

+ +

Nesnenin kaynak kodunu temsil eden bir dize.

+ +

Açıklama

+ +

toSource metodu aşağıdaki değerleri döndürür:

+ + + +

This method is usually called internally by JavaScript and not explicitly in code.

+ +

Özellikler

+ +

Herhangi bir standardın parçası değil. JavaScript 1.3'te uygulandı. 1.3.

+ +

Tarayıcı Uyumluluğu

+ +
+ + +

{{Compat("javascript.builtins.Boolean.toSource")}}

+
+ +

Ayrıca Bakınız

+ + 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 +--- +
{{jsSidebar("Objects")}}
+ +

eval() fonksiyonu JavaScript kodunu bir String gibi değerlendirir.

+ +
{{EmbedInteractiveExample("pages/js/globalprops-eval.html")}}
+ + + +

Sözdizimi

+ +
eval(string)
+ +

Parametreler

+ +
+
string
+
A string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects.
+
+ +

Return değeri

+ +

The completion value of evaluating the given code. If the completion value is empty, {{jsxref("undefined")}} is returned.

+ +

Description

+ +

eval() is a function property of the global object.

+ +

The argument of the eval() function is a string. If the string represents an expression, eval() evaluates the expression. If the argument represents one or more JavaScript statements, eval() evaluates the statements. Do not call eval() to evaluate an arithmetic expression; JavaScript evaluates arithmetic expressions automatically.

+ +

If you construct an arithmetic expression as a string, you can use eval() to evaluate it at a later time. For example, suppose you have a variable x. You can postpone evaluation of an expression involving x by assigning the string value of the expression, say "3 * x + 2", to a variable, and then calling eval() at a later point in your script.

+ +

If the argument of eval() is not a string, eval() returns the argument unchanged. In the following example, the String constructor is specified and eval() returns a String object rather than evaluating the string.

+ +
eval(new String('2 + 2')); // returns a String object containing "2 + 2"
+eval('2 + 2');             // returns 4
+
+ +

You can work around this limitation in a generic fashion by using toString().

+ +
var expression = new String('2 + 2');
+eval(expression.toString());            // returns 4
+
+ +

If you use the eval function indirectly, by invoking it via a reference other than evalas of ECMAScript 5 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.

+ +
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
+}
+
+ +

Do not ever use eval!

+ +

eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() 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 eval() was invoked, which can lead to possible attacks in ways to which the similar {{jsxref("Global_Objects/Function", "Function")}} is not susceptible.

+ +

eval() is also slower than the alternatives, since it has to invoke the JS interpreter, while many other constructs are optimized by modern JS engines.

+ +

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 eval() 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 window.Function. As an example of how you convert code using evil eval() to using  Function(), see below.

+ +

Bad code with eval:

+ +
function looseJsonParse(obj){
+    return eval(obj);
+}
+console.log(looseJsonParse(
+   "{a:(4-1), b:function(){}, c:new Date()}"
+))
+
+ +

Better code without eval:

+ +
function looseJsonParse(obj){
+    return Function('"use strict";return (' + obj + ')')();
+}
+console.log(looseJsonParse(
+   "{a:(4-1), b:function(){}, c:new Date()}"
+))
+
+ +

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 c: new Date() 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 Date refers to window.Date instead of a local variable called Date. But, in the code using eval(), the browser cannot assume this since what if your code looked like the following:

+ +
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()}"
+))
+
+ +

Thus, in the eval() 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 Date(). This is incredibly inefficient compared to Function().

+ +

In a related circumstance, what if you actually wanted your Date function to be able to be called from the code inside Function(). Should you just wimp out and fall back to eval()? Absolutely not, never ever. Instead try the approach below.

+ +
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) }"
+))
+
+ +

The code above may seem inefficiently slow because of the triple nested function, but let's analyse the benefits of the above efficient method:

+ +

1. It allows the code in the string passed to runCodeWithDateFunction to be minified.

+ +

2. Function call overhead is minimal, making the far smaller code size well worth the benefit

+ +

3. Function() more easily allows your code to utilize the performance buttering "use strict";

+ +

4. The code does not use eval(), making it orders of magnitude faster than otherwise.

+ +

Lastly, let's examine minification. With using  Function() as shown above, you can minify the code string passed to runCodeWithDateFunction far more efficiently because the function arguments names can be minified too as seen in the minified code below.

+ +
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]}));
+ +

There are also additional safer (and faster!) alternatives to eval() or Function() for common use-cases.

+ +

Accessing member properties

+ +

You should not use eval() 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:

+ +
var obj = { a: 20, b: 30 };
+var propName = getPropName();  // returns "a" or "b"
+
+eval( 'var result = obj.' + propName );
+
+ +

However, eval() is not necessary here. In fact, its use here is discouraged. Instead, use the property accessors, which are much faster and safer:

+ +
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
+ +

You can even use this method to access descendant properties. Using eval() this would look like:

+ +
var obj = {a: {b: {c: 0}}};
+var propPath = getPropPath();  // returns e.g. "a.b.c"
+
+eval( 'var result = obj.' + propPath );
+
+ +

Avoiding eval() here could be done by splitting the property path and looping through the different properties:

+ +
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);
+ +

Setting a property that way works similarly:

+ +
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
+ +

Use functions instead of evaluating snippets of code

+ +

JavaScript has first-class functions, 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:

+ +
// instead of setTimeout(" ... ", 1000) use:
+setTimeout(function() { ... }, 1000);
+
+// instead of elt.setAttribute("onclick", "...") use:
+elt.addEventListener('click', function() { ... } , false); 
+ +

Closures are also helpful as a way to create parameterized functions without concatenating strings.

+ +

Parsing JSON (converting strings to JavaScript objects)

+ +

If the string you're calling eval() on contains data (for example, an array: "[1, 2, 3]"), as opposed to code, you should consider switching to JSON, which allows the string to use a subset of JavaScript syntax to represent data. See also Downloading JSON and JavaScript in extensions.

+ +

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.

+ +

Pass data instead of code

+ +

For example, an extension designed to scrape contents of web-pages could have the scraping rules defined in XPath instead of JavaScript code.

+ +

Run code with limited privileges

+ +

If you must run the code, consider running it with reduced privileges. This advice applies mainly to extensions and XUL applications, which can use Components.utils.evalInSandbox for this.

+ +

Examples

+ +

Using eval

+ +

In the following code, both of the statements containing eval() return 42. The first evaluates the string "x + y + 1"; the second evaluates the string "42".

+ +
var x = 2;
+var y = 39;
+var z = '42';
+eval('x + y + 1'); // returns 42
+eval(z);           // returns 42
+
+ +

Using eval to evaluate a string of JavaScript statements

+ +

The following example uses eval() to evaluate the string str. This string consists of JavaScript statements that open an alert dialog box and assign z a value of 42 if x is five, and assigns 0 to z otherwise. When the second statement is executed, eval() will cause these statements to be performed, and it will also evaluate the set of statements and return the value that is assigned to z.

+ +
var x = 5;
+var str = "if (x == 5) {console.log('z is 42'); z = 42;} else z = 0;";
+
+console.log('z is ', eval(str));
+ +

If you define multiple values then the last value is returned.

+ +
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
+
+ + + +

Last expression is evaluated

+ +

eval() returns the value of the last expression evaluated.

+ +
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);
+ +

eval as a string defining function requires "(" and ")" as prefix and suffix

+ +
var fctStr1 = 'function a() {}'
+var fctStr2 = '(function a() {})'
+var fct1 = eval(fctStr1)  // return undefined
+var fct2 = eval(fctStr2)  // return a function
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.1.2.1', 'eval')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-eval-x', 'eval')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-eval-x', 'eval')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.eval")}}

+ +

Firefox-specific notes

+ + + +

See also

+ + 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 +--- +
{{JSRef}}
+ +

apply() 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.

+ +
+

Not: call() , apply() syntaxları sizin de dikkat ettiğiniz gibi aynıdır. farkları şudur: call() : bir argüman listesini argüman olarak alırken, apply() argümanlardan oluşmuş bir array'ı argüman olarak kabul alır.  

+
+ +

Syntax

+ +
fun.apply(thisArg, [argsArray])
+ +

Parametreler

+ +
+
thisArg
+
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.
+
argsArray
+
+

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.

+
+
+ +

Dönen değer

+ +

this değeri ve argümanlar ile çağrılan fonksiyonun sonucu.

+ +

Açıklama

+ +

Varolan bir fonksiyonu çağırdığınızda farklı bir this objesi atayabilirsiniz. Burada this geçerli nesneyi (çağıran objeyi ) ifade eder. Apply ile bir kez yazılmış bir methodu  başka bir objeden miras alarak aynı fonksiyonu tekrar yazmaktan kurtulmuş  olursunuz.  

+ +

apply 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 apply, you can use an array literal, for example, fun.apply(this, ['eat', 'bananas']), or an {{jsxref("Array")}} object, for example, fun.apply(this, new Array('eat', 'bananas')).

+ +

You can also use {{jsxref("Functions/arguments", "arguments")}} for the argsArray parameter. arguments 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 apply method. You can use arguments to pass all the arguments to the called object. The called object is then responsible for handling the arguments.

+ +

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 length and integer properties in the range (0...length-1). As an example you can now use a {{domxref("NodeList")}} or a custom object like { 'length': 2, '0': 'eat', '1': 'bananas' }.

+ +
+

Most browsers, including Chrome 14 and Internet Explorer 9, still do not accept array-like objects and will throw an exception.

+
+ +

Examples

+ +

Using apply to chain constructors

+ +

You can use apply 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 construct, which will enable you to use an array-like object with a constructor instead of an arguments list.

+ +
Function.prototype.construct = function (aArgs) {
+  var oNew = Object.create(this.prototype);
+  this.apply(oNew, aArgs);
+  return oNew;
+};
+
+ +
+

Note: The Object.create() method used above is relatively new. For an alternative method using closures, please consider the following alternative:

+ +
Function.prototype.construct = function(aArgs) {
+  var fConstructor = this, fNewConstr = function() {
+    fConstructor.apply(this, aArgs);
+  };
+  fNewConstr.prototype = fConstructor.prototype;
+  return new fNewConstr();
+};
+
+ +

Example usage:

+ +
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'
+
+ +
+

Note: This non-native Function.construct 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: [2012, 11, 4]; in this case you have to write something like: new (Function.prototype.bind.apply(Date, [null].concat([2012, 11, 4])))() — anyhow this is not the best way to do things and probably should not be used in any production environment).

+
+ +

Using apply and built-in functions

+ +

Clever usage of apply 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 Math.max/Math.min to find out the maximum/minimum value in an array.

+ +
// 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];
+  }
+}
+
+ +

But beware: in using apply 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 argument limit of 65536), 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 5, 6, 2, 3 had been passed to apply 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:

+ +
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]);
+
+ +

Using apply in "monkey-patching"

+ +

Apply can be the best way to monkey-patch a built-in function of Firefox, or JS libraries. Given someobject.foo function, you can modify the function in a somewhat hacky way, like so:

+ +
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.
+}
+
+ +

This method is especially handy where you want to debug events, or interface with something that has no API like the various .on([event]... events, such as those usable on the Devtools Inspector).

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.3.4.3', 'Function.prototype.apply')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function.prototype.apply', 'Function.prototype.apply')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-function.prototype.apply', 'Function.prototype.apply')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
ES 5.1 generic array-like object as {{jsxref("Functions/arguments", "arguments")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
ES 5.1 generic array-like object as {{jsxref("Functions/arguments", "arguments")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

See also

+ + 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 +--- +
{{JSRef}}
+ +

Fonksiyon yapıcısı yeni bir Fonksiyon nesnesi yaratır. JavaScript'de her fonksiyon aslında bir Fonksiyon nesnesidir.

+ +

Syntax

+ +
new Function ([arg1[, arg2[, ...argN]],] functionBody)
+ +

Parametreler

+ +
+
arg1, arg2, ... argN
+
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 "x", "theValue", or "a,b".
+
functionBody
+
A string containing the JavaScript statements comprising the function definition.
+
+ +

Açıklama

+ +

Function objects created with the Function constructor are parsed when the function is created. This is less efficient than declaring a function with a function expression or function statement and calling it within your code, because such functions are parsed with the rest of the code.

+ +

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.

+ +

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

+ +

Properties and Methods of Function

+ +

The global Function 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")}}.

+ +

Function prototype object

+ +

Properties

+ +
{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Properties')}}
+ +

Methods

+ +
{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Methods')}}
+ +

Function instances

+ +

Function 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 Function instances.

+ +

Examples

+ +

Specifying arguments with the Function constructor

+ +

The following code creates a Function object that takes two arguments.

+ +
// 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
+
+ +

The arguments "a" and "b" are formal argument names that are used in the function body, "return a + b".

+ +

Difference between Function constructor and function declaration

+ +

Functions created with the Function 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 Function constructor was called. This is different from using {{jsxref("eval")}} with code for a function expression.

+ +
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
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.3', 'Function')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-objects', 'Function')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-function-objects', 'Function')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + 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 +--- +
{{jsSidebar("Objects")}}
+ +

This chapter documents all of JavaScript's standard, built-in objects, including their methods and properties.

+ +
+

The term "global objects" (or standard built-in objects) here is not to be confused with the global object. Here, global objects refer to objects in the global scope (but only if ECMAScript 5 strict mode is not used; in that case it returns undefined). The global object itself can be accessed using the {{jsxref("Operators/this", "this")}} operator in the global scope. In fact, the global scope consists of the properties of the global object, including inherited properties, if any.

+ +

Other objects in the global scope are either created by the user script or provided by the host application. The host objects available in browser contexts are documented in the API reference. For more information about the distinction between the DOM and core JavaScript, see JavaScript technologies overview.

+ +

Standard objects (by category)

+ +

Value properties

+ +

These global properties return a simple value; they have no properties or methods.

+ + + +

Function properties

+ +

These global functions—functions which are called globally rather than on an object—directly return their results to the caller.

+ + + +

Fundamental objects

+ +

These are the fundamental, basic objects upon which all other objects are based. This includes objects that represent general objects, functions, and errors.

+ + + +

Numbers and dates

+ +

These are the base objects representing numbers, dates, and mathematical calculations.

+ + + +

Text processing

+ +

These objects represent strings and support manipulating them.

+ + + +

Indexed collections

+ +

These objects represent collections of data which are ordered by an index value. This includes (typed) arrays and array-like constructs.

+ + + +

Keyed collections

+ +

These objects represent collections which use keys; these contain elements which are iterable in the order of insertion.

+ + + +

Vector collections

+ +

{{Glossary("SIMD")}} vector data types are objects where data is arranged into lanes.

+ + + +

Structured data

+ +

These objects represent and interact with structured data buffers and data coded using JavaScript Object Notation (JSON).

+ + + +

Control abstraction objects

+ + + +

Reflection

+ + + +

Internationalization

+ +

Additions to the ECMAScript core for language-sensitive functionalities.

+ + + +

Non-standard objects

+ + + +

Other

+ + +
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 +--- +
{{jsSidebar("Objects")}}
+ +

Global isFinite() fonksiyonu girilen değerin sonlu sayı olup olmadığını kararlaştırır. Gerekliyse, parametre ilk önce sayıya çevrilir.

+ +

Söz Dizimi

+ +
isFinite(testDegeri)
+ +

Parametreler

+ +
+
testDegeri
+
Sonluluğu test edilecek sayı.
+
+ +

Açıklama

+ +

isFinite en üst seviye fonksiyondur ve herhangi bir nesne ile ilişkilendirilemez.

+ +

Bu fonksiyonu bir sayının sonlu olup olmadığını kararlaştırmak için kullanabilirsiniz. isFinite fonksiyonu argümanı olan sayıyı sorgular. Eğer argümanın değeri NaN, pozitif sonsuz veya negatif sonsuz ise, metod false döndürür; değilse, true döndürür.

+ +

Örnekler

+ +
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ı.
+
+ +

Tanımlamalar

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TanımDurumAçıklama
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.1.2.5', 'isFinite')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-isfinite-number', 'isFinite')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-isfinite-number', 'isFinite')}}{{Spec2('ESDraft')}} 
+ +

Tarayıcı Uyumluluğu

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
ÖzellikChromeFirefox (Gecko)Internet ExplorerOperaSafari
Temel Destek{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
ÖzellikAndroidAndroid için ChromeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Temel Destek{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ayrıca Bakınız

+ + 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 +--- +
{{jsSidebar("Objects")}}
+ +

isNaN() bir değerin NaN olup olmadığını belirler. Not: isNaN işlevi içindeki zorlamanın ilginç kuralları vardır; alternatif olarak ECMAScript 2015'te tanımlandığı gibi Number.isNaN() yöntemini kullanmak isteyebilirsiniz.

+ +
{{EmbedInteractiveExample("pages/js/globalprops-isnan.html")}}
+ +

Sözdizimi

+ +
isNaN(deger)
+ +

Parametre(ler)

+ +
+
değer
+
Test edilecek değer.
+
+ +

Verilecek değer

+ +

Verilen değer {{jsxref("NaN")}} ise true; değilse false.

+ +

Açıklama

+ +

isNaN işlevi gerekliliği

+ +

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 false olarak değerlendirilir. BU yüzden isNaN işlevi.

+ +

NaN değerlerinin kaynağı

+ +

NaN değerleri, aritmetik işlemler tanımsız (undefined) veya tekrarlanamayan değerlerle sonuçlandığında üretilir. Bu tür değerler mutlaka taşma koşullarını temsil etmez. NaN ayrıca, ilkel sayısal değerin bulunmadığı sayısal olmayan değerlerin sayısal değerlerine zorlama girişiminden de kaynaklanır.

+ +

Örneğin, sıfıra sıfıra bölmek bir NaN ile sonuçlanır - ancak diğer sayıları sıfıra bölmek olmaz.

+ +

Özel durum davranışlarını karıştırmak

+ +

İsNaN 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 Number 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 NaN 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), "false" 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.

+ +

ECMAScript 2015, {{jsxref ("Number.isNaN ()")}} işlevini içerir. Number.isNaN(x), x'in NaN olup olmadığını test etmenin güvenilir bir yoludur. Bununla birlikte, Number.isNaN ile bile, NaN'nin anlamı, basitçe "bir sayı değil", kesin sayısal anlam olarak kalır. Alternatif olarak, Number.isNaN yokluğunda, (x != x) ifadesi, x değişkeninin NaN olup olmadığını test etmenin daha güvenilir bir yoludur, çünkü sonuç isNaN'yi güvenilir olmayan sahte pozitiflere tabi değildir.

+ +

isNaN için bir çoklu dolgu (çoklu dolgu, NaN'nin kendine özgü asla eşit olmayan özelliğini kullanır):

+ +
var isNaN = function(deger) {
+    var n = Number(deger);
+    return n !== n;
+};
+ +

Examples

+ +
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
+ +

Faydalı özel durum davranışı

+ +

İsNaN() yöntemini düşünmek için daha çok kullanıma yönelik bir yol vardır: isNaN(x) false değerini döndürürse, ifadeyi NaN döndürmeyen bir aritmetik ifadede x kullanabilirsiniz. true değerini döndürürse, x her aritmetik ifadeyi NaN döndürür. Bu, JavaScript'te, isNaN(x) == true değerinin, NaN döndüren x - 0'a eşdeğer olduğu anlamına gelir (JavaScript x - 0 == NaN'de her zaman false döndürür, bu nedenle test edemezsiniz). Aslında, isNaN(x), isNaN(x - 0), isNaN(Number(x)), Number.isNaN(x - 0) ve Number.isNaN(Number(x)) her zaman aynı döndürür ve JavaScript isNaN(x) bu terimlerin her birini ifade etmek için mümkün olan en kısa biçimdir.

+ +

Ö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.

+ +

Örnekler

+ +
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
+
+ +

Özellikler

+ + + + + + + + + + +
Şartname
{{SpecName('ESDraft', '#sec-isnan-number', 'isNaN')}}
+ +

Tarayıcı Uyumluluğu

+ + + +

{{Compat("javascript.builtins.isNaN")}}

+ +

Ayrıca bakınız

+ + 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 +--- +
{{JSRef}}
+ +

JSON nesnesi, JavaScript Object Notasyonunu çö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.

+ +

Açıklama

+ +

JavaScript Obje Notasyonu

+ +

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: JSON: The JavaScript subset that isn't.

+ + + + + + + + + + + + + + + + + + + + + + + +
JavaScript ve JSON farklılıkları
JavaScript tipiJSON farklılıkları
Nesneler ve DizilerProperty isimleri çift tırnaklı dizeler olmalıdır; sona konulan virgüller yasaktır.
SayılarÖ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.
Dizeler +

Sadece sınırlı sayıda karakterin kaçmasına izin verilebilir; belli kontrol karakterleri yasaklanmıştır; Unicode satır ayırıcı (U+2028) ve paragraf ayırıcı (U+2029) 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:

+ +
+var code = '"\u2028\u2029"';
+JSON.parse(code); // düzgün çalışıyor.
+eval(code); // hata veriyor.
+
+
+ +

Tüm JSON söz dizimi aşağıdaki gibidir:

+ +
JSON = null
+    or true or false
+    or JSONNumber
+    or JSONString
+    or JSONObject
+    or JSONArray
+
+JSONNumber = - PositiveNumber
+          or PositiveNumber
+PositiveNumber = DecimalNumber
+              or DecimalNumber . Digits
+              or DecimalNumber . Digits ExponentPart
+              or DecimalNumber ExponentPart
+DecimalNumber = 0
+             or OneToNine Digits
+ExponentPart = e Exponent
+            or E Exponent
+Exponent = Digits
+        or + Digits
+        or - Digits
+Digits = Digit
+      or Digits Digit
+Digit = 0 through 9
+OneToNine = 1 through 9
+
+JSONString = ""
+          or " StringCharacters "
+StringCharacters = StringCharacter
+                or StringCharacters StringCharacter
+StringCharacter = any character
+                  except " or \ or U+0000 through U+001F
+               or EscapeSequence
+EscapeSequence = \" or \/ or \\ or \b or \f or \n or \r or \t
+              or \u HexDigit HexDigit HexDigit HexDigit
+HexDigit = 0 through 9
+        or A through F
+        or a through f
+
+JSONObject = { }
+          or { Members }
+Members = JSONString : JSON
+       or Members , JSONString : JSON
+
+JSONArray = [ ]
+         or [ ArrayElements ]
+ArrayElements = JSON
+             or ArrayElements , JSON
+
+ +

Önemsiz boşluklar; JSONNumber ve JSONString 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 (U+0009), satırbaşı (U+000D), line feed (U+000A), ve boşluk (U+0020) karakterleri tek kabul edilen boşluk karakterleridir.

+ +

Metotlar

+ +
+
{{jsxref("JSON.parse()")}}
+
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.
+
{{jsxref("JSON.stringify()")}}
+
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.
+
+ +

Polyfill

+ +

JSON 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 JSON nesnesinin kullanımına izin verilmiş olur (Internet Explorer 6 gibi).

+ +

Aşağıdaki algoritma asıl JSON nesnesinin bir taklididir.

+ +
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) + '"';
+      };
+    })()
+  };
+}
+
+ +

JSON nesnesi için daha karmaşık ve bilindik polyfilller ise: JSON2 ve JSON3'tür.

+ +

Özellikler

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.12', 'JSON')}}{{Spec2('ES5.1')}}İlk tanım.
{{SpecName('ES6', '#sec-json-object', 'JSON')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-json-object', 'JSON')}}{{Spec2('ESDraft')}} 
+ +

Tarayıcı uyumluluğu

+ +
+
+ + +

{{Compat("javascript.builtins.JSON")}}

+
+
+ +

Ayrıca Bakınız

+ + 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 +--- +
{{JSRef}}
+ +

JSON.stringify() 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.

+ +
{{EmbedInteractiveExample("pages/js/json-stringify.html")}}
+ + + +

Syntax

+ +
JSON.stringify(value[, replacer[, space]])
+ +

Parameters

+ +
+
value
+
The value to convert to a JSON string.
+
replacer {{optional_inline}}
+
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.
+
space {{optional_inline}}
+
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 Number, 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 String, 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.
+
+ +

Return value

+ +

A JSON string representing the given value.

+ +

Exceptions

+ +

Throws a {{jsxref("TypeError")}} ("cyclic object value") exception when a circular reference is found.

+ +

Description

+ +

JSON.stringify() converts a value to JSON notation representing it:

+ + + +
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"}'
+
+ +

The replacer parameter

+ +

The replacer 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 this 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:

+ + + +
Note: You cannot use the replacer function to remove values from an array. If you return undefined or a function then null is used instead.
+ +
Note: 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).
+ +

Example with a function

+ +
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}'
+
+ +

Example with an array

+ +

If replacer 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.

+ +
JSON.stringify(foo, ['week', 'month']);
+// '{"week":45,"month":7}', only keep "week" and "month" properties
+
+ +

The space argument

+ +

The space 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).

+ +
JSON.stringify({ a: 2 }, null, ' ');
+// '{
+//  "a": 2
+// }'
+
+ +

Using a tab character mimics standard pretty-print appearance:

+ +
JSON.stringify({ uno: 1, dos: 2 }, null, '\t');
+// returns the string:
+// '{
+//     "uno": 1,
+//     "dos": 2
+// }'
+
+ +

toJSON() behavior

+ +

If an object being stringified has a property named toJSON whose value is a function, then the toJSON() method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON() method when called will be serialized. JSON.stringify() calls toJSON with one parameter:

+ + + +

For example:

+ +
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'"]'
+
+ +

Issue with JSON.stringify() when serializing circular references

+ +

Note that since the JSON format doesn't support object references (although an IETF draft exists), a {{jsxref("TypeError")}} will be thrown if one attempts to encode an object with circular references.

+ +
const circularReference = {};
+circularReference.myself = circularReference;
+
+// Serializing circular references throws "TypeError: cyclic object value"
+JSON.stringify(circularReference);
+
+ +

To serialize circular references you can use a library that supports them (e.g. cycle.js by Douglas Crockford) or implement a solution by yourself, which will require finding and replacing (or removing) the cyclic references by serializable values.

+ +

Issue with plain JSON.stringify for use as JavaScript

+ +

Note that JSON is not a completely strict subset of JavaScript, 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 JSONP, the following utility can be used:

+ +
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"}
+ +

Example of using JSON.stringify() with localStorage

+ +

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 JSON.stringify():

+ +
// 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);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.12.3', 'JSON.stringify')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.7.
{{SpecName('ES6', '#sec-json.stringify', 'JSON.stringify')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-json.stringify', 'JSON.stringify')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.JSON.stringify")}}

+
+ +

See also

+ + 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 +--- +
{{JSRef}}
+ +

The Map object holds key-value pairs. Any value (both objects and {{Glossary("Primitive", "primitive values")}}) may be used as either a key or a value.

+ +

Syntax

+ +
new Map([iterable])
+ +

Parameters

+ +
+
iterable
+
An {{jsxref("Array")}} or other iterable object whose elements are key-value pairs (arrays with two elements, e.g. [[ 1, 'one' ],[ 2, 'two' ]]). Each key-value pair is added to the new Map; null values are treated as undefined.
+
+ +

Description

+ +

A Map object iterates its elements in insertion order — a {{jsxref("Statements/for...of", "for...of")}} loop returns an array of [key, value] for each iteration.
+
+ It should be noted that a Map 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.

+ +

Key equality

+ +

Key equality is based on the "SameValueZero" algorithm: NaN is considered the same as NaN (even though NaN !== NaN) and all other values are considered equal according to the semantics of the === operator. In the current ECMAScript specification -0 and +0 are considered equal, although this was not so in earlier drafts. See "Value equality for -0 and 0" in the browser compatibility table for details.

+ +

Objects and maps compared

+ +

{{jsxref("Object", "Objects")}} are similar to Maps 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), Objects have been used as Maps historically; however, there are important differences that make using a Map preferable in certain cases:

+ + + +

Properties

+ +
+
Map.length
+
The value of the length property is 0.
+
{{jsxref("Map.@@species", "get Map[@@species]")}}
+
The constructor function that is used to create derived objects.
+
{{jsxref("Map.prototype")}}
+
Represents the prototype for the Map constructor. Allows the addition of properties to all Map objects.
+
+ +

Map instances

+ +

All Map instances inherit from {{jsxref("Map.prototype")}}.

+ +

Properties

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Map/prototype','Properties')}}

+ +

Methods

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Map/prototype','Methods')}}

+ +

Examples

+ +

Using the Map object

+ +
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 () {}
+
+ +

Using NaN as Map keys

+ +

NaN can also be used as a key. Even though every NaN is not equal to itself (NaN !== NaN is true), the following example works because NaNs are indistinguishable from each other:

+ +
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"
+
+ +

Iterating Maps with for..of

+ +

Maps can be iterated using a for..of loop:

+ +
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
+
+ +

Iterating Maps with forEach()

+ +

Maps can be iterated using the forEach() method:

+ +
myMap.forEach(function(value, key) {
+  console.log(key + ' = ' + value);
+});
+// Will show 2 logs; first with "0 = zero" and second with "1 = one"
+
+ +

Relation with Array objects

+ +
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"]
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-map-objects', 'Map')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-map-objects', 'Map')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Map")}}

+ +

See also

+ + 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 +--- +
{{JSRef}}
+ +

Map.prototype özelliği {{jsxref("Map")}} kurucusunun prototipini temsil eder.

+ +
{{js_property_attributes(0,0,0)}}
+ +

Tanım

+ +

{{jsxref("Map")}} örnekleri {{jsxref("Map.prototype")}}'den miras alınır. Tüm Map örneklerine özellikler veya yöntemler eklemek için yapıcının prototip nesnesini kullanabilirsiniz.

+ +

Özellikleri

+ +
+
Map.prototype.constructor
+
Bir örneğin prototipini oluşturan işlevi döndürür. Bu, varsayılan olarak {{jsxref("Map")}} işlevidir.
+
{{jsxref("Map.prototype.size")}}
+
Map nesnesindeki anahtar / değer çiftlerinin sayısını döndürür.
+
+ +

Yöntemler

+ +
+
{{jsxref("Map.prototype.clear()")}}
+
Tüm anahtar / değer çiftlerini Map objesinden siler.
+
{{jsxref("Map.delete", "Map.prototype.delete(key)")}}
+
Map nesnesindeki bir öge varsa ve kaldırılmışsa true öge yoksa false döndürür. Map.prototype.has(key) daha sonra false döndürür.
+
{{jsxref("Map.prototype.entries()")}}
+
Ekleme sırasındaki Map nesnesindeki her öge için [anahtar, değer] dizisini içeren yeni bir Iterator nesnesini döndürür.
+
{{jsxref("Map.forEach", "Map.prototype.forEach(callbackFn[, thisArg])")}}
+
Map 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.
+
{{jsxref("Map.get", "Map.prototype.get(key)")}}
+
key ile ilişkilendirilmiş değeri veya hiçbir şey yoksa undefined değerini döndürür.
+
{{jsxref("Map.has", "Map.prototype.has(key)")}}
+
Map nesnesindeki bir değerin key ile ilişkili olup olmadığını belirten bir boolean döndürür.
+
{{jsxref("Map.prototype.keys()")}}
+
Map nesnesindeki her bir ögenin anahtarlarını ekleme sırasına göre içeren yeni bir Iterator nesnesi döndürür.
+
{{jsxref("Map.set", "Map.prototype.set(key, value)")}}
+
Mapnesnesindeki key değerini ayarlar. Map nesnesini döndürür.
+
{{jsxref("Map.prototype.values()")}}
+
Map nesnesindeki her bir ögenin değerlerini ekleme sırasına göre içeren yeni bir  Iterator nesnesi döndürür.
+
{{jsxref("Map.@@iterator", "Map.prototype[@@iterator]()")}}
+
Ekleme sırasındaki Map nesnesindeki her bir öge için[anahtar, değer] dizisini içeren yeni bir Iterator nesnesini döndürür.
+
+ +

Şartlar

+ + + + + + + + + + + + + + + + + + + +
ŞartDurumAçıklama
{{SpecName('ES2015', '#sec-map.prototype', 'Map.prototype')}}{{Spec2('ES2015')}} +

İlk tanım

+
{{SpecName('ESDraft', '#sec-map.prototype', 'Map.prototype')}}{{Spec2('ESDraft')}} 
+ +

Tarayıcı Uyumluluğu

+ + + +

{{Compat("javascript.builtins.Map.prototype")}}

+ +

Ayrıca Bakınız

+ + 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 +--- +
+ +
{{JSRef}}
+ +

Math is a built-in object that has properties and methods for mathematical constants and functions. It’s not a function object.

+ +

Math works with the {{jsxref("Number")}} type. It doesn't work with {{jsxref("BigInt")}}.

+ +

Description

+ +

Unlike many other global objects, Math is not a constructor. All properties and methods of Math are static. You refer to the constant pi as Math.PI and you call the sine function as Math.sin(x), where x is the method’s argument. Constants are defined with the full precision of real numbers in JavaScript.

+ +
+

Note: Many Math functions have a precision that’s implementation-dependent.

+ +

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!

+
+ +

Static properties

+ +
+
{{jsxref("Math.E")}}
+
Euler's constant and the base of natural logarithms; approximately 2.718.
+
{{jsxref("Math.LN2")}}lllllđđlđ
+
lllllđđ vili ga ti tu of 2; approximately 0.693.
+
{{jsxref("Math.LN10")}}
+
Natural logarithm of 10; approximately 2.303.
+
{{jsxref("Math.LOG2E")}}
+
Base-2 logarithm of E; approximately 1.443.
+
{{jsxref("Math.LOG10E")}}
+
Base-10 logarithm of E; approximately 0.434.
+
{{jsxref("Math.PI")}}
+
Ratio of the a circle's circumference to its diameter; approximately 3.14159.
+
{{jsxref("Math.SQRT1_2")}}
+
Square root of ½ (or equivalently, 1/√2); approximately 0.707.
+
{{jsxref("Math.SQRT2")}}
+
Square root of 2; approximately 1.414.
+
+ +

Static methods

+ +
+
{{jsxref("Global_Objects/Math/abs", "Math.abs(x)")}}
+
Returns the absolute value of x.
+
{{jsxref("Global_Objects/Math/acos", "Math.acos(x)")}}
+
Returns the arccosine of x.
+
{{jsxref("Global_Objects/Math/acosh", "Math.acosh(x)")}}
+
Returns the hyperbolic arccosine of x.
+
{{jsxref("Global_Objects/Math/asin", "Math.asin(x)")}}
+
Returns the arcsine of x.
+
{{jsxref("Global_Objects/Math/asinh", "Math.asinh(x)")}}
+
Returns the hyperbolic arcsine of a number.
+
{{jsxref("Global_Objects/Math/atan", "Math.atan(x)")}}
+
Returns the arctangent of x.
+
{{jsxref("Global_Objects/Math/atanh", "Math.atanh(x)")}}
+
Returns the hyperbolic arctangent of x.
+
{{jsxref("Global_Objects/Math/atan2", "Math.atan2(y, x)")}}
+
Returns the arctangent of the quotient of its arguments.
+
{{jsxref("Global_Objects/Math/cbrt", "Math.cbrt(x)")}}
+
Returns the cube root of x.
+
{{jsxref("Global_Objects/Math/ceil", "Math.ceil(x)")}}
+
Returns the smallest integer greater than or equal to x.
+
{{jsxref("Global_Objects/Math/clz32", "Math.clz32(x)")}}
+
Returns the number of leading zeroes of the 32-bit integer x.
+
{{jsxref("Global_Objects/Math/cos", "Math.cos(x)")}}
+
Returns the cosine of x.
+
{{jsxref("Global_Objects/Math/cosh", "Math.cosh(x)")}}
+
Returns the hyperbolic cosine of x.
+
{{jsxref("Global_Objects/Math/exp", "Math.exp(x)")}}
+
Returns Ex, where x is the argument, and E is Euler's constant (2.718…, the base of the natural logarithm).
+
{{jsxref("Global_Objects/Math/expm1", "Math.expm1(x)")}}
+
Returns subtracting 1 from exp(x).
+
{{jsxref("Global_Objects/Math/floor", "Math.floor(x)")}}
+
Returns the largest integer less than or equal to x.
+
{{jsxref("Global_Objects/Math/fround", "Math.fround(x)")}}
+
Returns the nearest single precision float representation of x.
+
{{jsxref("Global_Objects/Math/hypot", "Math.hypot([x[, y[, …]]])")}}
+
Returns the square root of the sum of squares of its arguments.
+
{{jsxref("Global_Objects/Math/imul", "Math.imul(x, y)")}}
+
Returns the result of the 32-bit integer multiplication of x and y.
+
{{jsxref("Global_Objects/Math/log", "Math.log(x)")}}
+
Returns the natural logarithm (㏒e; also, ㏑) of x.
+
{{jsxref("Global_Objects/Math/log1p", "Math.log1p(x)")}}
+
Returns the natural logarithm (㏒e; also ㏑) of 1 + x for the number x.
+
{{jsxref("Global_Objects/Math/log10", "Math.log10(x)")}}
+
Returns the base-10 logarithm of x.
+
{{jsxref("Global_Objects/Math/log2", "Math.log2(x)")}}
+
Returns the base-2 logarithm of x.
+
{{jsxref("Global_Objects/Math/max", "Math.max([x[, y[, …]]])")}}
+
Returns the largest of zero or more numbers.
+
{{jsxref("Global_Objects/Math/min", "Math.min([x[, y[, …]]])")}}
+
Returns the smallest of zero or more numbers.
+
{{jsxref("Global_Objects/Math/pow", "Math.pow(x, y)")}}
+
Returns base x to the exponent power y (that is, xy).
+
{{jsxref("Global_Objects/Math/random", "Math.random()")}}
+
Returns a pseudo-random number between 0 and 1.
+
{{jsxref("Global_Objects/Math/round", "Math.round(x)")}}
+
Returns the value of the number x rounded to the nearest integer.
+
{{jsxref("Global_Objects/Math/sign", "Math.sign(x)")}}
+
Returns the sign of the x, indicating whether x is positive, negative, or zero.
+
{{jsxref("Global_Objects/Math/sin", "Math.sin(x)")}}
+
Returns the sine of x.
+
{{jsxref("Global_Objects/Math/sinh", "Math.sinh(x)")}}
+
Returns the hyperbolic sine of x.
+
{{jsxref("Global_Objects/Math/sqrt", "Math.sqrt(x)")}}
+
Returns the positive square root of x.
+
{{jsxref("Global_Objects/Math/tan", "Math.tan(x)")}}
+
Returns the tangent of x.
+
{{jsxref("Global_Objects/Math/tanh", "Math.tanh(x)")}}
+
Returns the hyperbolic tangent of x.
+
{{jsxref("Global_Objects/Math/trunc", "Math.trunc(x)")}}
+
Returns the integer portion of x, removing any fractional digits.
+
+ +

Examples

+ +

Converting between degrees and radians

+ +

The trigonometric functions sin(), cos(), tan(), asin(), acos(), atan(), and atan2() expect (and return) angles in radians.

+ +

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:

+ +
function degToRad(degrees) {
+  return degrees * (Math.PI / 180);
+};
+
+function radToDeg(rad) {
+  return rad / (Math.PI / 180);
+};
+ +

Calculating the height of an equalateral triangle

+ +

If we want to calculate the height of an equalateral triangle, and we know its side length is 100, we can use the formulae length of the adjacent multiplied by the tangent of the angle is equal to the opposite.

+ +

+ +

In JavaScript, we can do this with the following:

+ +
50 * Math.tan(degToRad(60)).
+ +

We use our degToRad() function to convert 60 degrees to radians, as Math.tan() expects an input value in radians.

+ +

Returning a random integer between two bounds

+ +

This can be achieved with a combination of Math.random() and Math.floor():

+ +
function random(min, max) {
+  const num = Math.floor(Math.random() * (max - min + 1)) + min;
+  return num;
+}
+
+random(1, 10);
+ +

Specifications

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-math-object', 'Math')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Math")}}

+ +

See also

+ + 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 +--- +
{{JSRef}}
+ +
Math.sign() 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.
+ +
+ +
{{EmbedInteractiveExample("pages/js/math-sign.html")}}
+ + + +

Syntax

+ +
Math.sign(x)
+ +

Parameters

+ +
+
x
+
A number. If this argument is not a number, it is implicitly converted to one.
+
+ +

Return value

+ +

A number representing the sign of the given argument:

+ + + +

Description

+ +

Because sign() is a static method of Math, you always use it as Math.sign(), rather than as a method of a Math object you created (Math is not a constructor).

+ +

Polyfill

+ +
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
+  };
+}
+
+ +

In the above polyfill, no extra type-coercing is needed to make (x > 0) or (x < 0) numbers because subtracting them from each other forces a type conversion from booleans to numbers.

+ +

Examples

+ +

Using Math.sign()

+ +
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
+
+ +

Specifications

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-math.sign', 'Math.sign')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Math.sign")}}

+ +

See also

+ + 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 +--- +
{{JSRef}}
+ +

Object.assign() metodu bir 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.

+ +

Yazım Şekli

+ +
Object.assign(hedef_nesne, ...kaynak_nesneler)
+ +

Değişkenler

+ +
+
hedef_nesne
+
Kaydedilecek olan hedef nesne.
+
kaynak_nesneler
+
Kaynak nesne(ler).
+
+ +

Dönüş Değeri

+ +

Hedef nesne.

+ +

Açıklama

+ +

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.

+ +

Object.assign() metodu bir kaynak nesnesinden bir hedef nesnesine sadece sayılabilir ve sahip olduğu özellikleri kopyalar. Kaynak nesne için [[Get]] ve hedef nesne için [[Set]]'i kullanır, böylelikle getter ve setter metodlarını çağırır. Bu nedenle yeni özellikleri sadece kopyalama ya da tanımlamaya karşı hedef nesneye atama yapar. Birleştirme kaynakları getter 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.

+ +

{{jsxref("String")}} ve  {{jsxref("Symbol")}}  özelliklerin her ikisi de kopyalanır.

+ +

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.

+ +

Object.assign() metodu kaynak nesnelerdeki {{jsxref("null")}} ya da {{jsxref("undefined")}} durumlarını fırlatmayacağını not ediniz.

+ +

Örnekler

+ +

Nesne klonlama

+ +
var obj = { a: 1 };
+var copy = Object.assign({}, obj);
+console.log(copy); // { a: 1 }
+
+ +

Derin Klonlamada Bir Uyarı

+ +

Derin klonlama(kopyalama) için, diğer alternatiflere ihtiyacımız vardır. Çünkü Object.assign() özellikleri kopyalar. Eğer kaynak değeri bir nesnenin referansı ise sadece referans değerini kopyalar.

+ +
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();
+ +

Nesneleri Birleştirme

+ +
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.
+ +

Nesneleri Aynı Özelliklerde Birleştirme

+ +
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 }
+
+ +

Özellikler diğer nesneler tarafından parametreler içindeki sonra gelen aynı özelliklerdeki nesnelerin özellikleri olarak üzerine yazıldı.

+ +

Sembol-Tipdeki Özellikleri Kopyalama 

+ +
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)]
+
+
+ +

Prototipteki Zincirleme Özellikler ve Sayılamayan Özellikler Kopyalanamaz

+ +
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 }
+
+
+ +

Değişken Tipleri Objelere Sarmalanır

+ +
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" }
+
+
+ +

Hatalar Devam Eden Kopyalama İşlemlerini Kesintiye Uğratır

+ +
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.
+
+ +

Erişimcileri Kopyalama

+ +
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 } }
+
+ +

Polyfill

+ +

 ES5 sembol özelliğine sahip olmadığından {{Glossary("Polyfill","polyfill")}} sembol özelliği  desteklenmez:

+ +
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;
+  };
+}
+
+ +

Belirtimler

+ + + + + + + + + + + + + + + + + + + +
BelirtimDurumlarAçıklama
{{SpecName('ES2015', '#sec-object.assign', 'Object.assign')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-object.assign', 'Object.assign')}}{{Spec2('ESDraft')}}
+ +

Tarayıcı Destekleme Durumu

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerEdgeOperaSafari
Basic support{{CompatChrome("45")}}{{CompatGeckoDesktop("34")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatOpera("32")}}{{CompatSafari("9")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome("45")}}{{CompatGeckoMobile("34")}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}
+
+ +

Daha Fazlası İçin

+ + 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 +--- +
{{JSRef}}
+ +

The Object.defineProperty() method defines a new property directly on an object, or modifies an existing property on an object, and returns the object.

+ +

Syntax

+ +
Object.defineProperty(obj, prop, descriptor)
+ +

Parameters

+ +
+
obj
+
The object on which to define the property.
+
prop
+
The name of the property to be defined or modified.
+
descriptor
+
The descriptor for the property being defined or modified.
+
+ +

Description

+ +

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 Object.defineProperty() are immutable.

+ +

Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A data descriptor is a property that has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both.

+ +

Both data and accessor descriptors are objects. They share the following required keys:

+ +
+
configurable
+
true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.
+ Defaults to false.
+
enumerable
+
true if and only if this property shows up during enumeration of the properties on the corresponding object.
+ Defaults to false.
+
+ +

A data descriptor also has the following optional keys:

+ +
+
value
+
The value associated with the property. Can be any valid JavaScript value (number, object, function, etc).
+ Defaults to {{jsxref("undefined")}}.
+
writable
+
true if and only if the value associated with the property may be changed with an {{jsxref("Operators/Assignment_Operators", "assignment operator", "", 1)}}.
+ Defaults to false.
+
+ +

An accessor descriptor also has the following optional keys:

+ +
+
get
+
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.
+ Defaults to {{jsxref("undefined")}}.
+
set
+
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.
+ Defaults to {{jsxref("undefined")}}.
+
+ +

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.

+ +
// 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);
+
+ +

Examples

+ +

If you want to see how to use the Object.defineProperty method with a binary-flags-like syntax, see additional examples.

+ +

Creating a property

+ +

When the property specified doesn't exist in the object, Object.defineProperty() 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 false. The value, get, and set fields default to {{jsxref("undefined")}}. A property which is defined without get/set/value/writable is called “generic” and is “typed” as a data descriptor.

+ +
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
+
+ +

Modifying a property

+ +

When the property already exists, Object.defineProperty() attempts to modify the property according to the values in the descriptor and the object's current configuration. If the old descriptor had its configurable attribute set to false (the property is said to be “non-configurable”), then no attribute besides writable can be changed. In that case, it is also not possible to switch back and forth between the data and accessor property types.

+ +

If a property is non-configurable, its writable attribute can only be changed to false.

+ +

A {{jsxref("TypeError")}} is thrown when attempts are made to change non-configurable property attributes (besides the writable attribute) unless the current and new values are the same.

+ +

Writable attribute

+ +

When the writable property attribute is set to false, the property is said to be “non-writable”. It cannot be reassigned.

+ +
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.
+
+ +

As seen in the example, trying to write into the non-writable property doesn't change it but doesn't throw an error either.

+ +

Enumerable attribute

+ +

The enumerable property attribute defines whether the property shows up in a {{jsxref("Statements/for...in", "for...in")}} loop and {{jsxref("Object.keys()")}} or not.

+ +
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
+
+ +

Configurable attribute

+ +

The configurable attribute controls at the same time whether the property can be deleted from the object and whether its attributes (other than writable) can be changed.

+ +
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
+
+ +

If the configurable attribute of o.a had been true, none of the errors would be thrown and the property would be deleted at the end.

+ +

Adding properties and default values

+ +

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 Object.defineProperty(), as shown in the example below.

+ +
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
+});
+
+ +

Custom Setters and Getters

+ +

Example below shows how to implement a self-archiving object. When temperature property is set, the archive array gets a log entry.

+ +
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 }]
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.2.3.6', 'Object.defineProperty')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.defineproperty', 'Object.defineProperty')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.defineproperty', 'Object.defineProperty')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop("2")}}{{CompatChrome("5")}}{{CompatIE("9")}} [1]{{CompatOpera("11.60")}}{{CompatSafari("5.1")}} [2]
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatGeckoMobile("2")}}{{CompatVersionUnknown}}{{CompatIE("9")}}{{CompatOperaMobile("11.5")}}{{CompatVersionUnknown}}
+
+ +

[1] In Internet Explorer 8 only on DOM objects and with some non-standard behaviors.

+ +

[2] Also supported in Safari 5, but not on DOM objects.

+ +

Compatibility notes

+ +

Redefining the length property of an Array object

+ +

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.

+ +

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.

+ +

Versions of Chrome which implement Object.defineProperty() 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.

+ +

Versions of Safari which implement Object.defineProperty() ignore a length 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.

+ +

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 can rely on it, there's really no good reason to do so.

+ +

Internet Explorer 8 specific notes

+ +

Internet Explorer 8 implemented a Object.defineProperty() method that could only be used on DOM objects. A few things need to be noted:

+ + + +

See also

+ + 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 +--- +
{{JSRef}}
+ +

The Object.entries() metodu, verilen bir nesnenin sıralanabilir [anahtar, değer] ç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.

+ +
{{EmbedInteractiveExample("pages/js/object-entries.html")}}
+ + + +

Sözdizimi

+ +
Object.entries(obj)
+ +

Parametreler

+ +
+
obj
+
Sıralanabilir özellik çiftleri [key, value] dönülecek olan nesne.
+
+ +

Dönüş değeri

+ +

Verilen nesnenin sıralanabilir özellik çiftlerini [key, value] içeren dizi

+ +

Tanım

+ +

Object.entries() elemanları object nesnesinin sıralanabilir özellik çiftlerine [key, value] 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.

+ +

Örnekler

+ +
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"
+});
+
+ +

Bir Object'in bir Map'e dönüştürülmesi

+ +

{{jsxref("Map", "new Map()")}} yapıcısı, entries üzerinde ilerlenebilir nesnesini ister. Object.entries ile, {{jsxref("Object")}}'ten {{jsxref("Map")}}'e kolayca dönüşüm yapabilirsiniz:

+ +
const obj = { foo: 'bar', baz: 42 };
+const map = new Map(Object.entries(obj));
+console.log(map); // Map { foo: "bar", baz: 42 }
+
+ +

Bir Object'in üzerinde ilerlemek

+ +

Array Destructuring kullanarak, nesnelerin üzerinde kolayca ilerleyebilirsiniz.

+ +
const obj = { foo: 'bar', baz: 42 };
+Object.entries(obj).forEach(([key, value]) => console.log(`${key}: ${value}`)); // "foo: bar", "baz: 42"
+
+ +

Polyfill

+ +

Doğal olarak desteklemeyen eski ortamlara Object.entries desteği eklemek için, Object.entries'in gösterme amaçlı gerçeklemesini tc39/proposal-object-values-entries'de (IE desteğine ihtiyacınız yoksa), es-shims/Object.entries repertuarındaki polyfill ile, veya aşağıdaki gibi kullanıma hazır basit polyfill kullanabilirsiniz.

+ +

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; };

+ +

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)

+ +

Şartnameler

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-object.entries', 'Object.entries')}}{{Spec2('ESDraft')}}İlk tanım.
{{SpecName('ES8', '#sec-object.entries', 'Object.entries')}}{{Spec2('ES8')}} 
+ +

Gezgin uyumluluğu

+ +
+ + +

{{Compat("javascript.builtins.Object.entries")}}

+
+ +

Ayrıca bakınız

+ + 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 +--- +
{{JSRef}}
+ +

Object.freeze() metodu bir objeyi dondurmak 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. freeze() metodu kendisine verilen objeyi dondurulmuş olarak geri döndürür ancak gelen değişkenin yeniden atanması zorunlu değildir.  freeze() 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. 

+ +
{{EmbedInteractiveExample("pages/js/object-freeze.html")}}
+ + + +

Syntax

+ +
Object.freeze(obje)
+ +

Parametreler

+ +
+
obje
+
Dondurmak istediğiniz obje.
+
+ +

Dönüt

+ +

Metoda gönderilen obje dondurularak geri döndürülür

+ +

Description

+ +

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).

+ +

Dondurulmuş bir objeye ait değer değiştirilemez, writeable ve configurable özellikleri false 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.

+ +

freeze() returns the same object that was passed into the function. It does not create a frozen copy.

+ +

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.

+ +
> Object.freeze(1)
+TypeError: 1 is not an object // ES5 code
+
+> Object.freeze(1)
+1                             // ES2015 code
+
+ +

An ArrayBufferView with elements will cause a {{jsxref("TypeError")}}, as they are views over memory and will definitely cause other possible issues:

+ +
> 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
+
+ +

Note that; as the standard three properties (buf.byteLength, buf.byteOffset and buf.buffer) are read-only (as are those of an {{jsxref("ArrayBuffer")}} or {{jsxref("SharedArrayBuffer")}}), there is no reason for attempting to freeze these properties.

+ +

Comparison to Object.seal()

+ +

Objects sealed with {{jsxref("Object.seal()")}} can have their existing properties changed. Existing properties in objects frozen with Object.freeze() are made immutable.

+ +

Examples

+ +

Freezing objects

+ +
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 }
+
+ +

Freezing arrays

+ +
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
+ +

The object being frozen is immutable. However, it is not necessarily constant. The following example shows that a frozen object is not constant (freeze is shallow).

+ +
obj1 = {
+  internal: {}
+};
+
+Object.freeze(obj1);
+obj1.internal.a = 'aValue';
+
+obj1.internal.a // 'aValue'
+ +

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 state (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.

+ +

What is "shallow freeze"?

+ +

The result of calling Object.freeze(object) only applies to the immediate properties of object itself and will prevent future property addition, removal or value re-assignment operations only on object. 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.

+ +
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"
+
+ +

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 cycles in the reference graph, otherwise an endless loop will be triggered. An enhancement to deepFreeze() would be to have an internal function that receives a path (e.g. an Array) argument so you can suppress calling deepFreeze() 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].

+ +
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
+
+ +

Specifications

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-object.freeze', 'Object.freeze')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Object.freeze")}}

+ +

See also

+ + 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 +--- +
{{JSRef}}
+ +

Object.getPrototypeOf() metodu, belirtilen nesnenin prototipini döndürür.

+ +

Syntax

+ +
Object.getPrototypeOf(nesne)
+ +

Parametreler

+ +
+
nesne
+
Prototipi döndürülecek olan nesne.
+
+ +

Örnekler

+ +
var proto = {};
+var nesne = Object.create(proto);
+Object.getPrototypeOf(nesne) === proto; // true
+
+ +

Notlar

+ +

ES5'te, nesne parametresi bir nesne değilse sistem bir {{jsxref("TypeError")}} fırlatır. ES6'da ise, parametre bir nesne olmaya zorlanır.

+ +
Object.getPrototypeOf("foo");
+// TypeError: "foo" bir nesne değil (ES5 kodu)
+Object.getPrototypeOf("foo");
+// String.prototype                 (ES6 kodu)
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationDurumYorum
{{SpecName('ES5.1', '#sec-15.2.3.2', 'Object.getPrototypeOf')}}{{Spec2('ES5.1')}}İlk tanımlama.
{{SpecName('ES6', '#sec-object.getprototypeof', 'Object.getProtoypeOf')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.getprototypeof', 'Object.getProtoypeOf')}}{{Spec2('ESDraft')}} 
+ +

Tarayıcı Uyumluluğu

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
ÖzellikChromeFirefox (Gecko)Internet ExplorerOperaSafari
Temel destek{{CompatChrome("5")}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("9")}}{{CompatOpera("12.10")}}{{CompatSafari("5")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
ÖzellikAndroidAndroid için ChromeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Temel destek{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Opera'ya özel notlar

+ +

Eski Opera versiyonları Object.getPrototypeOf() fonksiyonunu desteklemiyor olsa da, Opera, 10.50 sürümünden beri standartlarda yer almayan {{jsxref("Object.proto", "__proto__")}} özelliğini desteklemektedir.

+ +

Bunlara da göz atın

+ + 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 +--- +
{{JSRef}}
+ +

The Object constructor creates an object wrapper.

+ +

Syntax

+ +
// Object initialiser or literal
+{ [ nameValuePair1[, nameValuePair2[, ...nameValuePairN] ] ] }
+
+// Called as a constructor
+new Object([value])
+ +

Parameters

+ +
+
nameValuePair1, nameValuePair2, ... nameValuePairN
+
Pairs of names (strings) and values (any value) where the name is separated from the value by a colon.
+
value
+
Any value.
+
+ +

Description

+ +

The Object 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.

+ +

When called in a non-constructor context, Object behaves identically to new Object().

+ +

See also the object initializer / literal syntax.

+ +

Properties of the Object constructor

+ +
+
Object.length
+
Has a value of 1.
+
{{jsxref("Object.prototype")}}
+
Allows the addition of properties to all objects of type Object.
+
+ +

Methods of the Object constructor

+ +
+
{{jsxref("Object.assign()")}} {{experimental_inline}}
+
Creates a new object by copying the values of all enumerable own properties from one or more source objects to a target object.
+
{{jsxref("Object.create()")}}
+
Creates a new object with the specified prototype object and properties.
+
{{jsxref("Object.defineProperty()")}}
+
Adds the named property described by a given descriptor to an object.
+
{{jsxref("Object.defineProperties()")}}
+
Adds the named properties described by the given descriptors to an object.
+
{{jsxref("Object.freeze()")}}
+
Freezes an object: other code can't delete or change any properties.
+
{{jsxref("Object.getOwnPropertyDescriptor()")}}
+
Returns a property descriptor for a named property on an object.
+
{{jsxref("Object.getOwnPropertyNames()")}}
+
Returns an array containing the names of all of the given object's own enumerable and non-enumerable properties.
+
{{jsxref("Object.getOwnPropertySymbols()")}} {{ experimental_inline() }}
+
Returns an array of all symbol properties found directly upon a given object.
+
{{jsxref("Object.getPrototypeOf()")}}
+
Returns the prototype of the specified object.
+
{{jsxref("Object.is()")}} {{ experimental_inline() }}
+
Compares if two values are distinguishable (ie. the same)
+
{{jsxref("Object.isExtensible()")}}
+
Determines if extending of an object is allowed.
+
{{jsxref("Object.isFrozen()")}}
+
Determines if an object was frozen.
+
{{jsxref("Object.isSealed()")}}
+
Determines if an object is sealed.
+
{{jsxref("Object.keys()")}}
+
Returns an array containing the names of all of the given object's own enumerable properties.
+
{{jsxref("Object.observe()")}} {{experimental_inline}}
+
Asynchronously observes changes to an object.
+
{{jsxref("Object.preventExtensions()")}}
+
Prevents any extensions of an object.
+
{{jsxref("Object.seal()")}}
+
Prevents other code from deleting properties of an object.
+
{{jsxref("Object.setPrototypeOf()")}} {{experimental_inline}}
+
Sets the prototype (i.e., the internal [[Prototype]] property)
+
+ +

Object instances and Object prototype object

+ +

All objects in JavaScript are descended from Object; all objects inherit methods and properties from {{jsxref("Object.prototype")}}, although they may be overridden. For example, other constructors' prototypes override the constructor property and provide their own toString() methods. Changes to the Object prototype object are propagated to all objects unless the properties and methods subject to those changes are overridden further along the prototype chain.

+ +

Properties

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Properties') }}
+ +

Methods

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Methods') }}
+ +

Examples

+ +

Example: Using Object given undefined and null types

+ +

The following examples store an empty Object object in o:

+ +
var o = new Object();
+
+ +
var o = new Object(undefined);
+
+ +
var o = new Object(null);
+
+ +

Example: Using Object to create Boolean objects

+ +

The following examples store {{jsxref("Global_Objects/Boolean", "Boolean")}} objects in o:

+ +
// equivalent to o = new Boolean(true);
+var o = new Object(true);
+
+ +
// equivalent to o = new Boolean(false);
+var o = new Object(Boolean());
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
ECMAScript 1st Edition.StandardInitial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2', 'Object')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object-objects', 'Object')}}{{Spec2('ES6')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + 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 +--- +
{{JSRef("Global_Objects", "Object")}}
+ +

Özet

+ +

Object.observe() 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.

+ +

Söz Dizimi

+ +
Object.observe(objcallback[, acceptList])
+ +

Parametreler

+ +
+
obj
+
İzlenecek Obje.
+
callback
+
Değişiklikler her gerçekleştiğinde çağırılacak fonksiyon. Aşağıdaki argümanlar ile çağırılır, +
+
changes
+
Her bir değişikliği temsilen bir objenin bulunduğu bir dizi döner. Objenin elemanları; +
    +
  • name:  Değişen elemanın adı.
  • +
  • object: Objenin yeni hali.
  • +
  • type: Metin türünde değişim. Bu metin "add", "update", ve "delete" olabilir.
  • +
  • oldValue: Eğer değiştirme ve ya silme işlemi gerçekleşti ise değişimden önceki değeri içerir.
  • +
+
+
+
+
acceptList
+
The list of types of changes to be observed on the given object for the given callback. If omitted, the array ["add", "update", "delete", "reconfigure", "setPrototype", "preventExtensions"] will be used.
+
+ +

Açıklama

+ +

callback fonksiyonu objede gerçekleşen her değişimde çağırılır. Bir dizi içerisinde değişiklikleri içeren objeler bulunur.

+ +

Örnekler

+ +

Örnelk: 6 farklı tipi kayıt altına alma

+ +
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'}
+// ]
+
+ +

Örnek: Veri bağlama

+ +
// 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();
+    }
+  });
+});
+
+ +

Örnek: Özel değişim türü

+ +
// 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
+
+ +

Özellikler

+ +

Strawman proposal for ECMAScript 7.

+ +

Tarayıcılar Arası Uyumluluk

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
ÖzellikChromeFirefox (Gecko)Internet ExplorerOperaSafari
Temel Destek{{CompatChrome("36")}}{{CompatNo}}{{CompatNo}}{{CompatOpera("23")}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
ÖzellikAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Temel Destek{{CompatNo}}{{CompatChrome("36")}}{{CompatNo}}{{CompatNo}}{{CompatOpera("23")}}{{CompatNo}}
+
+ +

Ayrıca bakınız

+ + 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 +--- +
{{JSRef}}
+ +

toString() methodu verilen nesneyi String'e dönüştürür.

+ +

Syntax

+ +
obj.toString()
+ +

Açıklama

+ +

Every object has a toString() 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 toString() method is inherited by every object descended from Object. If this method is not overridden in a custom object, toString() returns "[object type]", where type is the object type. The following code illustrates this:

+ +
var o = new Object();
+o.toString(); // returns [object Object]
+
+ +
+

Note: Starting in JavaScript 1.8.5 toString() called on {{jsxref("null")}} returns [object Null], and {{jsxref("undefined")}} returns [object Undefined], 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")}}.

+
+ +

Examples

+ +

Overriding the default toString method

+ +

You can create a function to be called in place of the default toString() method. The toString() method takes no arguments and should return a string. The toString() method you create can be any value you want, but it will be most useful if it carries information about the object.

+ +

The following code defines the Dog object type and creates theDog, an object of type Dog:

+ +
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');
+
+ +

If you call the toString() method on this custom object, it returns the default value inherited from {{jsxref("Object")}}:

+ +
theDog.toString(); // returns [object Object]
+
+ +

The following code creates and assigns dogToString() to override the default toString() method. This function generates a string containing the name, breed, color, and sex of the object, in the form "property = value;".

+ +
Dog.prototype.toString = function dogToString() {
+  var ret = 'Dog ' + this.name + ' is a ' + this.sex + ' ' + this.color + ' ' + this.breed;
+  return ret;
+}
+
+ +

With the preceding code in place, any time theDog is used in a string context, JavaScript automatically calls the dogToString() function, which returns the following string:

+ +
"Dog Gabby is a female chocolate Lab"
+
+ +

Using toString() to detect object class

+ +

toString() can be used with every object and allows you to get its class. To use the Object.prototype.toString() 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 thisArg.

+ +
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]
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2.4.2', 'Object.prototype.toString')}}{{Spec2('ES5.1')}}Call on {{jsxref("Global_Objects/null", "null")}} returns [object Null], and {{jsxref("Global_Objects/undefined", "undefined")}} returns [object Undefined]
{{SpecName('ES6', '#sec-object.prototype.tostring', 'Object.prototype.toString')}}{{Spec2('ES6')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + 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 +--- +
{{JSRef}}
+ +

Object.values()  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).

+ +

Sözdizimi

+ +
Object.values(obj)
+ +

Parametre

+ +
+
Nesne, sayısız numaralandırılabilir kendi özellikleri döndürülendir.
+
+ +

Return değeri

+ +

Diziler verilen nesnenin kendi numaralandırılabilir özellik değerlerini içerir.

+ +

Tanım

+ +

Object.values() 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.

+ +

Örnekler

+ +
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']
+
+ +

Polyfill

+ +

Uyumlu Object.values eklemek için doğal olarak desteklenmeyen daha eski ortamları destekler. Siz şu adreste " tc39/proposal-object-values-entries " veya "es-shims/Object.values "repositorilerde bir polyfill bulabilirsiniz.

+ +

Specificatsupport in older environments that do not natively support it, you can find a Polyfill in the ions

+ + + + + + + + + + + + + + + + + + + +
TanımKonumYorum
{{SpecName('ESDraft', '#sec-object.values', 'Object.values')}}{{Spec2('ESDraft')}}Ilk tanım.
{{SpecName('ES8', '#sec-object.values', 'Object.values')}}{{Spec2('ES8')}} 
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Object.values")}}

+
+ +

See also

+ + 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 +--- +
{{JSRef}}
+ +

The Promise.all() 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.

+ +
{{EmbedInteractiveExample("pages/js/promise-all.html")}}
+ + + +

Söz dizimi

+ +
Promise.all(iterable);
+ +

Parametreler

+ +
+
iterable
+
{{jsxref("Array")}} yada {{jsxref("String")}} gibi iterable nesnesi.
+
+ +

Dönen değer

+ + + +

Açıklama

+ +

This method can be useful for aggregating the results of multiple promises.

+ +

Fulfillment

+ +

The returned promise is fulfilled with an array containing all the values of the iterable passed as argument (also non-promise values).

+ + + +

Rejection

+ +

If any of the passed-in promises reject, Promise.all asynchronously rejects with the value of the promise that rejected, whether or not the other promises have resolved.

+ +

Örnekler

+ +

Promise.all Kullanımı

+ +

Promise.all tüm işlemler yerine getirilene kadar bekler (yada ilk reddedilmeye kadar).

+ +
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"]
+});
+ +

If the iterable contains non-promise values, they will be ignored, but still counted in the returned promise array value (if the promise is fulfilled):

+ +
// 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 }
+ +

Asynchronicity or synchronicity of Promise.all

+ +

This following example demonstrates the asynchronicity (or synchronicity, if the iterable passed is empty) of Promise.all:

+ +
// 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] }
+
+ +

The same thing happens if Promise.all rejects:

+ +
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 }
+
+ +

But, Promise.all resolves synchronously if and only if the iterable passed is empty:

+ +
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] }
+
+ +

Promise.all fail-fast behaviour

+ +

Promise.all 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 Promise.all will reject immediately.

+ +
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"
+
+
+ +

It is possible to change this behaviour by handling possible rejections:

+ +
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"
+})
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-promise.all', 'Promise.all')}}{{Spec2('ES2015')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.all', 'Promise.all')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Promise.all")}}

+ +

See also

+ + 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 +--- +
{{JSRef}}
+ +

The catch() method returns a Promise and deals with rejected cases only. It behaves the same as calling {{jsxref("Promise.then", "Promise.prototype.then(undefined, onRejected)")}} (in fact, calling obj.catch(onRejected) internally calls obj.then(undefined, onRejected)). This means, that you have to provide onRejected function even if you want to fallback to undefined result value - for example obj.catch(() => {}).

+ +
{{EmbedInteractiveExample("pages/js/promise-catch.html")}}
+ + + + + + + +

Sözdizimi

+ +
p.catch(onRejected);
+
+p.catch(function(reason) {
+   // rejection
+});
+
+ +

Parametreler

+ +
+
onRejected
+
A {{jsxref("Function")}} called when the Promise is rejected. This function has one argument: +
+
reason
+
The rejection reason.
+
+ The Promise returned by catch() is rejected if onRejected throws an error or returns a Promise which is itself rejected; otherwise, it is resolved.
+
+ +

Dönen değer

+ +

Internally calls Promise.prototype.then on the object upon which is called, passing the parameters undefined and the onRejected handler received; then returns the value of that call (which is a {{jsxref("Promise")}}).

+ +
+

Note the examples below are throwing instances of Error. 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.

+
+ +

Demonstration of the internal call:

+ +
// 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()]
+
+ +

Açıklama

+ +

The catch method can be useful for error handling in your promise composition.

+ +

Örnekler

+ +

Using and chaining the catch method

+ +
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');
+});
+
+ +

Gotchas when throwing errors

+ +
// 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
+});
+ +

If it is resolved

+ +
//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);
+});
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}{{Spec2('ES2015')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}{{Spec2('ESDraft')}} 
+ +

Tarayıcı uyumluluğu

+ + + +

{{Compat("javascript.builtins.Promise.catch")}}

+ +

Ayrıca bakınız

+ + 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 +--- +
{{JSRef}}
+ +
Promise nesnesi eşzamansız olan ve ertelenen işlemlerde kullanılır. Bir Promise nesnesi henüz işlemin tamamlamadığını ama sonradan tamamlanabileceğini gösterir.
+ +
+ +

Sözdizimi

+ +
new Promise(function(resolve, reject) { ... });
+ +

Parametreler

+ +
+
executor
+
resolve ve reject 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.
+
+ +

Açıklama

+ +

Oluşturulan bir promise başka bir promise için proxy görevi görür.
+ 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 promise döndürür.

+ +

Bir Promise şu durumları içerir:

+ + + +

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.)

+ +

As the {{jsxref("Promise.then", "Promise.prototype.then()")}} and {{jsxref("Promise.catch", "Promise.prototype.catch()")}} methods return promises, bunlar zincirlenebilirler—an operation called composition.

+ +

+ +
+

Note: A promise is said to be settled if it is either fulfilled or rejected, but not pending. You will also hear the term resolved used with promises — this means that the promise is settled, or it is locked into a promise chain. Domenic Denicola's States and fates contains more details about promise terminology.

+
+ +

Özellikler

+ +
+
Promise.length
+
Değeri 1 olan Length özelliği (constructor argümanları sayısı).
+
{{jsxref("Promise.prototype")}}
+
Represents the prototype for the Promise constructor.
+
+ +

Metodlar

+ +
+
{{jsxref("Promise.all", "Promise.all(iterable)")}}
+
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.
+
{{jsxref("Promise.race", "Promise.race(iterable)")}}
+
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.
+
+ +
+
{{jsxref("Promise.reject", "Promise.reject(reason)")}}
+
Belirtilen bir nedenden dolayı reddedilen Promise nesnesini döndürür.
+
+ +
+
{{jsxref("Promise.resolve", "Promise.resolve(value)")}}
+
Returns a Promise object that is resolved with the given value. If the value is a thenable (i.e. has a then 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.
+
+ +

Promise prototype

+ +

Özellikler

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Properties')}}

+ +

Metodlar

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Methods')}}

+ +

Örnekler

+ +

Promise Oluşturma

+ + + +

Bu küçük örnek Promise mekanizmasını gösterir. {{HTMLElement("button")}} her tıklandığında testPromise() 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 Promise() constructor is used to create the promise.

+ +

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.

+ +
'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/>');
+}
+ + + +

Bu örnek buton'a tıkladığınızda çalışır. Promise 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.

+ +

{{EmbedLiveSample("Creating_a_Promise", "500", "200")}}

+ +

new XMLHttpRequest() Kullanım Örneği

+ +

Promise Oluşturma

+ +

Bu örnekte {{domxref("XMLHttpRequest")}} nesnesinin başarılı yada başarısız durumunu Promise kullanarak nasıl raporlanabildiğini göstermektedir.

+ +
'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);
+
+ +

XHR ile görsel yükleme

+ +

Another simple example using Promise and XMLHttpRequest to load an image is available at the MDN GitHub promise-test repository. You can also see it in action. Each step is commented and allows you to follow the Promise and XHR architecture closely.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationDurumYorum
{{SpecName('ES6', '#sec-promise-objects', 'Promise')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise-objects', 'Promise')}}{{Spec2('ESDraft')}}
+ +

Tarayıcı uyumluluğu

+ + + +
+ + +

{{Compat("javascript.builtins.Promise")}}

+
+ + + +

Ayrıca bakınız

+ + 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 +--- +
{{JSRef}}
+ +

The RegExp constructor creates a regular expression object for matching text with a pattern.

+ +

For an introduction to regular expressions, read the Regular Expressions chapter in the JavaScript Guide.

+ +

Syntax

+ +

Literal, constructor, and factory notations are possible:

+ +
/pattern/flags
+new RegExp(pattern[, flags])
+RegExp(pattern[, flags])
+
+ +

Parameters

+ +
+
pattern
+
Duzenli ifadenin metni.
+
flags
+
+

If specified, flags can have any combination of the following values:

+ +
+
g
+
global match; find all matches rather than stopping after the first match
+
i
+
ignore case
+
m
+
multiline; treat beginning and end characters (^ and $) as working over multiple lines (i.e., match the beginning or end of each line (delimited by \n or \r), not only the very beginning or end of the whole input string)
+
u
+
unicode; treat pattern as a sequence of unicode code points
+
y
+
sticky; matches only from the index indicated by the lastIndex property of this regular expression in the target string (and does not attempt to match from any later indexes).
+
+
+
+ +

Description

+ +

There are 2 ways to create a RegExp 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:

+ +
/ab+c/i;
+new RegExp('ab+c', 'i');
+new RegExp(/ab+c/, 'i');
+
+ +

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.

+ +

The constructor of the regular expression object, for example, new RegExp('ab+c'), 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.

+ +

Starting with ECMAScript 6, new RegExp(/ab+c/, 'i') no longer throws a {{jsxref("TypeError")}} ("can't supply flags when constructing one RegExp from another") when the first argument is a RegExp and the second flags argument is present. A new RegExp from the arguments is created instead.

+ +

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:

+ +
var re = /\w+/;
+var re = new RegExp('\\w+');
+
+ +

Düzenli İfadelerde (Regular Expressions) Özel Karakterlerin Anlamları

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Karakter Sınıfları
KarakterAnlamı
. +

(The dot, the decimal point) matches any single character except line terminators: \n, \r, \u2028 or \u2029.

+ +

Inside a character set, the dot loses its special meaning and matches a literal dot.

+ +

Note that the m multiline flag doesn't change the dot behavior. So to match a pattern across multiple lines, the character set [^] can be used (if you don't mean an old version of IE, of course), it will match any character including newlines.

+ +

For example, /.y/ matches "my" and "ay", but not "yes", in "yes make my day".

+
\d +

Matches any digit (Arabic numeral). Equivalent to [0-9].

+ +

For example, /\d/ or /[0-9]/ matches "2" in "B2 is the suite number".

+
\D +

Matches any character that is not a digit (Arabic numeral). Equivalent to [^0-9].

+ +

For example, /\D/ or /[^0-9]/ matches "B" in "B2 is the suite number".

+
\w +

Matches any alphanumeric character from the basic Latin alphabet, including the underscore. Equivalent to [A-Za-z0-9_].

+ +

For example, /\w/ matches "a" in "apple", "5" in "$5.28", and "3" in "3D".

+
\W +

Matches any character that is not a word character from the basic Latin alphabet. Equivalent to [^A-Za-z0-9_].

+ +

For example, /\W/ or /[^A-Za-z0-9_]/ matches "%" in "50%".

+
\s +

Matches a single white space character, including space, tab, form feed, line feed and other Unicode spaces. Equivalent to [ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff].

+ +

For example, /\s\w*/ matches " bar" in "foo bar".

+
\S +

Matches a single character other than white space. Equivalent to [^ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff].

+ +

For example, /\S\w*/ matches "foo" in "foo bar".

+
\tMatches a horizontal tab.
\rMatches a carriage return.
\nMatches a linefeed.
\vMatches a vertical tab.
\fMatches a form-feed.
[\b]Matches a backspace. (Not to be confused with \b)
\0Matches a NUL character. Do not follow this with another digit.
\cX +

Where X is a letter from A - Z. Matches a control character in a string.

+ +

For example, /\cM/ matches control-M in a string.

+
\xhhMatches the character with the code hh (two hexadecimal digits).
\uhhhhMatches a UTF-16 code-unit with the value hhhh (four hexadecimal digits).
\u{hhhh} or \u{hhhhh}(only when u flag is set) Matches the character with the Unicode value U+hhhh or U+hhhhh (hexadecimal digits).
\ +

For characters that are usually treated literally, indicates that the next character is special and not to be interpreted literally.

+ +

For example, /b/ matches the character "b". By placing a backslash in front of "b", that is by using /\b/, the character becomes special to mean match a word boundary.

+ +

or

+ +

For characters that are usually treated specially, indicates that the next character is not special and should be interpreted literally.

+ +

For example, "*" is a special character that means 0 or more occurrences of the preceding character should be matched; for example, /a*/ means match 0 or more "a"s. To match * literally, precede it with a backslash; for example, /a\*/ matches "a*".

+
Karakter Kümeleri
KarakterAnlamı
[xyz]
+ [a-c]
+

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.

+ +

For example, [abcd] is the same as [a-d]. They match the "b" in "brisket" and the "c" in "chop".

+ +

For example, [abcd-] and [-abcd] match the "b" in "brisket", the "c" in "chop" and the "-" (hyphen) in "non-profit".

+ +

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".

+
+

[^xyz]
+ [^a-c]

+
+

A negated or complemented character set. That is, it matches anything that is not enclosed in the brackets. You can specify a range of characters by using a hyphen, but if the hyphen appears as the first or last character enclosed in the square brackets it is taken as a literal hyphen to be included in the character set as a normal character.

+ +

For example, [^abc] is the same as [^a-c]. They initially match "o" in "bacon" and "h" in "chop".

+
Değişim
KarakterAnlamı
x|y +

Matches either x or y.

+ +

For example, /green|red/ matches "green" in "green apple" and "red" in "red apple".

+
Kısıtlar
KarakterAnlamı
^ +

Matches beginning of input. If the multiline flag is set to true, also matches immediately after a line break character.

+ +

For example, /^A/ does not match the "A" in "an A", but does match the first "A" in "An A".

+
$ +

Matches end of input. If the multiline flag is set to true, also matches immediately before a line break character.

+ +

For example, /t$/ does not match the "t" in "eater", but does match it in "eat".

+
\b +

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.

+ +

Examples:
+ /\bm/ matches the 'm' in "moon" ;
+ /oo\b/ does not match the 'oo' in "moon", because 'oo' is followed by 'n' which is a word character;
+ /oon\b/ matches the 'oon' in "moon", because 'oon' is the end of the string, thus not followed by a word character;
+ /\w\b\w/ will never match anything, because a word character can never be followed by both a non-word and a word character.

+
\B +

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.

+ +

For example, /\Bon/ matches "on" in "at noon", and /ye\B/ matches "ye" in "possibly yesterday".

+
Gruplama ve Referansa Geri Dönme
KarakterAnlamı
(x) +

Matches x and remembers the match. These are called capturing groups.

+ +

For example, /(foo)/ matches and remembers "foo" in "foo bar". 

+ +

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 [1], ..., [n] or from the predefined RegExp object's properties $1, ..., $9.

+ +

Capturing groups have a performance penalty. If you don't need the matched substring to be recalled, prefer non-capturing parentheses (see below).

+
\n +

Where n is a positive integer. A back reference to the last substring matching the n parenthetical in the regular expression (counting left parentheses).

+ +

For example, /apple(,)\sorange\1/ matches "apple, orange," in "apple, orange, cherry, peach". A more complete example follows this table.

+
(?:x)Matches x 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 [1], ..., [n] or from the predefined RegExp object's properties $1, ..., $9.
Niceleyiciler
KarakterAnlamı
x* +

Matches the preceding item x 0 or more times.

+ +

For example, /bo*/ matches "boooo" in "A ghost booooed" and "b" in "A bird warbled", but nothing in "A goat grunted".

+
x+ +

Matches the preceding item x 1 or more times. Equivalent to {1,}.

+ +

For example, /a+/ matches the "a" in "candy" and all the "a"'s in "caaaaaaandy".

+
x? +

Matches the preceding item x 0 or 1 time.

+ +

For example, /e?le?/ matches the "el" in "angel" and the "le" in "angle."

+ +

If used immediately after any of the quantifiers *, +, ?, or {}, 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).

+
x{n} +

Where n is a positive integer. Matches exactly n occurrences of the preceding item x.

+ +

For example, /a{2}/ 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".

+
x{n,} +

Where n is a positive integer. Matches at least n occurrences of the preceding item x.

+ +

For example, /a{2,}/ doesn't match the "a" in "candy", but matches all of the a's in "caandy" and in "caaaaaaandy".

+
x{n,m} +

Where n and m are positive integers. Matches at least n and at most m occurrences of the preceding item x.

+ +

For example, /a{1,3}/ 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.

+
+

x*?
+ x+?
+ x??
+ x{n}?
+ x{n,}?
+ x{n,m}?

+
+

Matches the preceding item x like *, +, ?, and {...} from above, however the match is the smallest possible match.

+ +

For example, /<.*?>/ matches "<foo>" in "<foo> <bar>", whereas /<.*>/ matches "<foo> <bar>".

+ +

Quantifiers without ? are said to be greedy. Those with ? are called "non-greedy".

+
Onaylamalar
KarakterAnlamı
x(?=y) +

Matches x only if x is followed by y.

+ +

For example, /Jack(?=Sprat)/ matches "Jack" only if it is followed by "Sprat".
+ /Jack(?=Sprat|Frost)/ matches "Jack" only if it is followed by "Sprat" or "Frost". However, neither "Sprat" nor "Frost" is part of the match results.

+
x(?!y) +

Matches x only if x is not followed by y.

+ +

For example, /\d+(?!\.)/ matches a number only if it is not followed by a decimal point.
+ /\d+(?!\.)/.exec('3.141') matches "141" but not "3.141".

+
+ +

Properties

+ +
+
{{jsxref("RegExp.prototype")}}
+
Allows the addition of properties to all objects.
+
RegExp.length
+
The value of RegExp.length is 2.
+
{{jsxref("RegExp.@@species", "get RegExp[@@species]")}}
+
The constructor function that is used to create derived objects.
+
{{jsxref("RegExp.lastIndex")}}
+
The index at which to start the next match.
+
+ +

Methods

+ +

The global RegExp object has no methods of its own, however, it does inherit some methods through the prototype chain.

+ +

RegExp prototype objects and instances

+ +

Properties

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/prototype', 'Properties')}}
+ +

Methods

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/prototype', 'Methods')}}
+ +

Examples

+ +

Using a regular expression to change data format

+ +

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 first last and output it in the format last, first. In the replacement text, the script uses $1 and $2 to indicate the results of the corresponding matching parentheses in the regular expression pattern.

+ +
var re = /(\w+)\s(\w+)/;
+var str = 'John Smith';
+var newstr = str.replace(re, '$2, $1');
+console.log(newstr);
+
+ +

This displays "Smith, John".

+ +

Using regular expression to split lines with different line endings/ends of line/line breaks

+ +

The default line ending varies depending on the platform (Unix, Windows, etc.). The line splitting provided in this example works on all platforms.

+ +
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' ]
+
+ +

Note that the order of the patterns in the regular expression matters.

+ +

Using regular expression on multiple lines

+ +
var s = 'Please yes\nmake my day!';
+s.match(/yes.*day/);
+// Returns null
+s.match(/yes[^]*day/);
+// Returns ["yes\nmake my day"]
+
+ +

Using a regular expression with the sticky flag

+ +

The sticky flag indicates that the regular expression performs sticky matching in the target string by attempting to match starting at {{jsxref("RegExp.prototype.lastIndex")}}.

+ +
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)
+ +

Regular expression and Unicode characters

+ +

As mentioned above, \w or \W 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 \uhhhh, where "hhhh" is the character's Unicode value in hexadecimal. This example demonstrates how one can separate out Unicode characters from a word.

+ +
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
+
+ +

Here's an external resource for getting the complete Unicode block range for different scripts: Regexp-unicode-block.

+ +

Extracting sub-domain name from URL

+ +
var url = 'http://xxx.domain.com';
+console.log(/[^.]+/.exec(url)[0].substr(7)); // logs 'xxx'
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.10', 'RegExp')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-regexp-regular-expression-objects', 'RegExp')}}{{Spec2('ES6')}}The RegExp constructor no longer throws when the first argument is a RegExp and the second argument is present. Introduces Unicode and sticky flags.
{{SpecName('ESDraft', '#sec-regexp-regular-expression-objects', 'RegExp')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.RegExp")}}

+
+ +

Firefox-specific notes

+ +

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 undefined instead of an empty string:

+ +
// 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'
+
+ +

Note that due to web compatibility, RegExp.$N will still return an empty string instead of undefined ({{bug(1053944)}}).

+ +

See also

+ + 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 +--- +
{{JSRef}}
+ +

Genel bir nesne olan String, dizgi veya karakter dizilerinin yapıcısıdır.

+ +

 

+ +

Sözdizimi

+ +

String literals take the forms:

+ +
'string text'
+"string text"
+"中文 español deutsch Türkçe हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ 한국어 தமிழ் עברית"
+ +

Strings can also be created using the String global object directly:

+ +
String(thing)
+ +

Parameters

+ +
+
thing
+
Anything to be converted to a string.
+
+ +

Template literals

+ +

Starting with ECMAScript 2015, string literals can also be so-called Template literals:

+ +
`hello world`
+`hello!
+ world!`
+`hello ${who}`
+escape `<a>${who}</a>`
+ +
+
+ +

Escape notation

+ +

Beside regular, printable characters, special characters can be encoded using escape notation:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CodeOutput
\0the NULL character
\'single quote
\"double quote
\\backslash
\nnew line
\rcarriage return
\vvertical tab
\ttab
\bbackspace
\fform feed
\uXXXXunicode codepoint
\u{X} ... \u{XXXXXX}unicode codepoint {{experimental_inline}}
\xXXthe Latin-1 character
+ +
+

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.

+
+ +
+
+ +

Long literal strings

+ +

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.

+ +

You can use the + operator to append multiple strings together, like this:

+ +
let longString = "This is a very long string which needs " +
+                 "to wrap across multiple lines because " +
+                 "otherwise my code is unreadable.";
+
+ +

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:

+ +
let longString = "This is a very long string which needs \
+to wrap across multiple lines because \
+otherwise my code is unreadable.";
+
+ +

Both of these result in identical strings being created.

+ +

Description

+ +

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 + and += string operators, 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.

+ +

Character access

+ +

There are two ways to access an individual character in a string. The first is the {{jsxref("String.prototype.charAt()", "charAt()")}} method:

+ +
return 'cat'.charAt(1); // returns "a"
+
+ +

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:

+ +
return 'cat'[1]; // returns "a"
+
+ +

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.)

+ +

Comparing strings

+ +

C developers have the strcmp() function for comparing strings. In JavaScript, you just use the less-than and greater-than operators:

+ +
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.');
+}
+
+ +

A similar result can be achieved using the {{jsxref("String.prototype.localeCompare()", "localeCompare()")}} method inherited by String instances.

+ +

Distinction between string primitives and String objects

+ +

Note that JavaScript distinguishes between String objects and primitive string values. (The same is true of {{jsxref("Boolean")}} and {{jsxref("Global_Objects/Number", "Numbers")}}.)

+ +

String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., without using the {{jsxref("Operators/new", "new")}} keyword) are primitive strings. JavaScript automatically converts primitives to String objects, so that it's possible to use String 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.

+ +
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"
+
+ +

String primitives and String objects also give different results when using {{jsxref("Global_Objects/eval", "eval()")}}. Primitives passed to eval are treated as source code; String objects are treated as all other objects are, by returning the object. For example:

+ +
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"
+
+ +

For these reasons, code may break when it encounters String objects when it expects a primitive string instead, although generally authors need not worry about the distinction.

+ +

A String object can always be converted to its primitive counterpart with the {{jsxref("String.prototype.valueOf()", "valueOf()")}} method.

+ +
console.log(eval(s2.valueOf())); // returns the number 4
+
+ +
Note: For another possible approach to strings in JavaScript, please read the article about StringView — a C-like representation of strings based on typed arrays.
+ +

Properties

+ +
+
{{jsxref("String.prototype")}}
+
Allows the addition of properties to a String object.
+
+ +

Methods

+ +
+
{{jsxref("String.fromCharCode()")}}
+
Returns a string created by using the specified sequence of Unicode values.
+
{{jsxref("String.fromCodePoint()")}} {{experimental_inline}}
+
Returns a string created by using the specified sequence of code points.
+
{{jsxref("String.raw()")}} {{experimental_inline}}
+
Returns a string created from a raw template string.
+
+ +

String generic methods

+ +
+

String generics are non-standard, deprecated and will get removed near future.

+
+ +

The String instance methods are also available in Firefox as of JavaScript 1.6 (not part of the ECMAScript standard) on the String object for applying String methods to any object:

+ +
var num = 15;
+console.log(String.replace(num, /5/, '2'));
+
+ +

For migrating away from String generics, see also Warning: String.x is deprecated; use String.prototype.x instead.

+ +

{{jsxref("Global_Objects/Array", "Generics", "#Array_generic_methods", 1)}} are also available on {{jsxref("Array")}} methods.

+ +

String instances

+ +

Properties

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Properties')}}
+ +

Methods

+ +

Methods unrelated to HTML

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Methods_unrelated_to_HTML')}}
+ +

HTML wrapper methods

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'HTML_wrapper_methods')}}
+ +

Examples

+ +

String conversion

+ +

It's possible to use String as a "safer" {{jsxref("String.prototype.toString()", "toString()")}} alternative, although it still normally calls the underlying toString(). It also works for {{jsxref("null")}}, {{jsxref("undefined")}}, and for {{jsxref("Symbol", "symbols")}}. For example:

+ +
var outputStrings = [];
+for (var i = 0, n = inputValues.length; i < n; ++i) {
+  outputStrings.push(String(inputValues[i]));
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.5', 'String')}}{{Spec2('ES5.1')}} 
{{SpecName('ES2015', '#sec-string-objects', 'String')}}{{Spec2('ES2015')}} 
{{SpecName('ESDraft', '#sec-string-objects', 'String')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.String.String")}}

+ +

See also

+ + 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 +--- +
{{JSRef}}
+ +

The substring() method returns a subset of a string between one index and another, or through the end of the string.

+ +

Syntax

+ +
str.substring(indexStart[, indexEnd])
+ +

Parametreler

+ +
+
indexStart
+
An integer between 0 and the length of the string, specifying the offset into the string of the first character to include in the returned substring.
+
indexEnd
+
Optional. An integer between 0 and the length of the string, which specifies the offset into the string of the first character not to include in the returned substring.
+
+ +

Dönen değer

+ +

A new string containing the extracted section of the given string.

+ +

Açıklama

+ +

substring() extracts characters from indexStart up to but not including indexEnd. In particular:

+ + + +

If indexStart is greater than indexEnd, then the effect of substring() is as if the two arguments were swapped; for example, str.substring(1, 0) == str.substring(0, 1).

+ +

Örnekler

+ +

Using substring()

+ +

The following example uses substring() to display characters from the string 'Mozilla':

+ +
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));
+
+ +

Using substring() with length property

+ +

The following example uses the substring() 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.

+ +
// 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);
+
+ +

Replacing a substring within a string

+ +

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 'Brave New World' into 'Brave New Web'.

+ +
// 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');
+
+ +

Note that this can result in an infinite loop if oldS is itself a substring of newS — for example, if you attempted to replace 'World' with 'OtherWorld' here. A better method for replacing strings is as follows:

+ +
function replaceString(oldS, newS, fullS) {
+  return fullS.split(oldS).join(newS);
+}
+
+ +

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()")}}.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.4.15', 'String.prototype.substring')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.substring', 'String.prototype.substring')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.substring', 'String.prototype.substring')}}{{Spec2('ESDraft')}} 
+ +

Tarayıcı uyumluluğu

+ + + +

{{Compat("javascript.builtins.String.substring")}}

+ +

Ayrıca bakınız

+ + 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 +--- +
{{JsSidebar}}
+ +

This part of the JavaScript section on MDN serves as a repository of facts about the JavaScript language. Read more about this reference.

+ +

Global Objects

+ +

This chapter documents all the JavaScript standard built-in objects, along with their methods and properties.

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects', 'Standard objects (by category)')}}
+ +

Statements

+ +

This chapter documents all the JavaScript statements and declarations.

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Statements', 'Statements_and_declarations_by_category')}}
+ +

Expressions and operators

+ +

This chapter documents all the JavaScript expressions and operators.

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Operators', 'Expressions_and_operators_by_category')}}
+ +

Functions

+ +

This chapter documents how to work with JavaScript functions to develop your applications.

+ + + +

Additional reference pages

+ + 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 +--- +

{{JsSidebar ("Daha çox")}}

+ +

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.

+ +

Nəzarət simvolları
+ İdarəetmə simvollarının vizual nümayəndəliyi yoxdur, ancaq mətnin şərhini idarə etmək üçün istifadə olunur.

+ +

Unicode formatına nəzarət simvolları
+ Kod nöqtəsi Adı Qısaldılması Təsviri
+ 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).
+ 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.
+ 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.
+ Ağ boşluq
+ 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.

+ +

Ağ boşluq simvolları
+ Kod nöqtəsi Adı Qısaldılması Təsvir Escape ardıcıllığı
+ U + 0009 Xarakter cədvəli <HT> Üfüqi cədvəl \ t
+ U + 000B Xətt cədvəli <VT> Şaquli cədvəl \ v
+ U + 000C Forma yemi <FF> Səhifəni pozan idarəetmə xarakteri (Wikipedia). \ f
+ U + 0020 Məkan <SP> Normal yer
+ U + 00A0 Arası olmayan yer <NBSP> Normal yer, lakin xəttin qırıla biləcəyi nöqtə yoxdur
+ Digərləri Digər Unicode kosmik simvolları <USP> Wikipedia'dakı Unicode'dakı boşluqlar
+ Xətt terminatorları
+ 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.

+ +

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).

+ +

Xətt terminatoru simvolları
+ Kod nöqtəsi Adı Qısaldılması Təsvir Escape ardıcıllığı
+ U + 000A Line Feed <LF> UNIX sistemlərində yeni xətt xarakteri. \ n
+ U + 000D Daşımanın qaytarılması <CR> Commodore və erkən Mac sistemlərində yeni xətt xarakteri. \ r
+ U + 2028 Xət ayırıcı <LS> Vikipediya
+ U + 2029 Paraqraf ayırıcı <PS> Wikipedia
+ Şərhlər
+ Şə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.

+ +

JavaScript'də şərhə əlavə etmək üçün uzun müddətdir davam edən iki yol var.

+ +

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:

+ +

funksiya comment () {
+   // Bu bir xəttli JavaScript şərhidir
+   console.log ('Salam dünya!');
+ }
+ Şərh();
+ İkinci yol daha çevik olan / * * / üslubdur.

+ +

Məsələn, bir xəttdə istifadə edə bilərsiniz:

+ +

funksiya comment () {
+   / * Bu bir xəttli JavaScript şərhidir * /
+   console.log ('Salam dünya!');
+ }
+ Şərh();
+ Bununla yanaşı, çox sətirli şərhlər edə bilərsiniz:

+ +

funksiya comment () {
+   / * Bu şərh çox sətri əhatə edir. Xəbərdarlıq
+      başa çatana qədər şərhə son qoymaq lazım deyil. * /
+   console.log ('Salam dünya!');
+ }
+ Şərh();
+ İ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:

+ +

funksiya şərhi (x) {
+   console.log ('Salam' + x / * x * / + '!' dəyərini daxil edin);
+ }
+ şərh ('dünya');
+ Bundan əlavə, kodu bir şərhə bağlayaraq işə salmamaq üçün kodu deaktiv etmək üçün istifadə edə bilərsiniz:

+ +

funksiya comment () {
+   / * console.log ('Salam dünya!'); * /
+ }
+ Şərh();
+ 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.

+ +

Hashbang şərhləri
+ 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).

+ +

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.

+ +

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:

+ +

#! / usr / bin / env node

+ +

console.log ("Salam dünya");
+ 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.

+ +

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

+ +

qabıqdan.

+ +

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.

+ +

Açar sözlər
+ ECMAScript 2015 kimi qorunan açar sözlər
+ {{jsxref ("Bəyanatlar / break", "break")}}
+ {{jsxref ("Bəyanatlar / keçid", "dava")}}
+ {{jsxref ("Bəyanatlar / çalışın ... tutun", "tutun")}}
+ {{jsxref ("Bəyanatlar / sinif", "sinif")}}
+ {{jsxref ("Bəyanatlar / const", "const")}}
+ {{jsxref ("Bəyanatlar / davam et", "davam et")}}
+ {{jsxref ("Bəyanatlar / debugger", "debugger")}}
+ {{jsxref ("Bəyanatlar / default", "default")}}
+ {{jsxref ("Operatorlar / silmək", "Sil")}}
+ {{jsxref ("Bəyanatlar / etmək ... edərkən", "etmək")}}
+ {{jsxref ("Bəyanatlar / əgər ... başqa", "başqa")}}
+ {{jsxref ("Bəyanatlar / ixrac", "ixrac")}}
+ {{jsxref ("Bəyanatlar / sinif", "uzanır")}}
+ {{jsxref ("Bəyanatlar / cəhd edin ... tutun", "nəhayət")}}
+ {{jsxref ("Bəyanatlar / üçün", "üçün")}}
+ {{jsxref ("Bildirişlər / funksiya", "funksiya")}}
+ {{jsxref ("Bəyanatlar / əgər ... başqa", "əgər")}}
+ {{jsxref ("Bəyanatlar / idxal", "idxal")}}
+ {{jsxref ("Operatorlar / ilə", "in")}}
+ {{jsxref ("Əməliyyatçılar / instanceof", "instanceof")}}
+ {{jsxref ("Operatorlar / yeni", "yeni")}}
+ {{jsxref ("Bəyanatlar / qayıt", "qayıt")}}
+ {{jsxref ("Əməliyyatçılar / super", "super")}}
+ {{jsxref ("Bəyanatlar / keçid", "keçid")}}
+ {{jsxref ("Əməliyyatçılar / bu", "bu")}}
+ {{jsxref ("Bəyanatlar / atmaq", "atmaq")}}
+ {{jsxref ("Bəyanatlar / cəhd edin ... tutun", "cəhd edin")}}
+ {{jsxref ("Operatorlar / typeof", "typeof")}}
+ {{jsxref ("Bəyanatlar / var", "var")}}
+ {{jsxref ("Operatorlar / etibarsız", "etibarsız")}}
+ {{jsxref ("Bəyanatlar / edərkən", "isə")}}
+ {{jsxref ("Bəyanatlar / ilə", "ilə")}}
+ {{jsxref ("Əməliyyatçılar / məhsuldarlıq", "gəlir")}}
+ Gələcək qorunan açar sözlər
+ 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.

+ +

Bunlar həmişə qorunur:

+ +

enum
+ Aşağıdakılar yalnız ciddi rejim kodlarında tapıldıqda qorunur:

+ +

tətbiq edir
+ interfeysi
+ {{jsxref ("Bəyanatlar / qoy", "qoy")}}
+ paket
+ özəl
+ qorunur
+ ictimai
+ statik
+ Aşağıdakılar yalnız modul kodu tapdıqda qorunur:

+ +

gözləmək
+ Gələcəkdə köhnə standartlarda qorunan açar sözlər
+ 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).

+ +

mücərrəd
+ boolean
+ bayt
+ char
+ ikiqat
+ final
+ sal
+ getmək
+ int
+ uzun
+ doğma
+ qısa
+ sinxronizasiya olunur
+ atır
+ keçici
+ uçucu
+ Bundan əlavə, null, əsl və yalnış hərflər ECMAScript-də identifikator kimi istifadə edilə bilməz.

+ +

Ehtiyat söz istifadəsi
+ 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.

+ +

a.import
+ a ['idxal']
+ a = {idxal: 'test'}.
+ 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.

+ +

funksiya import () {} // qeyri-qanuni.
+ Xüsusi mənaları olan identifikatorlar
+ 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:

+ +

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".

+ +

var n = 0O755; // 493
+ var m = 0o644; // 420

+ +

// Yalnız bir aparıcı sıfır ilə mümkündür (yuxarıdakı onluğa dair qeydə baxın)
+ 0755
+ 0644
+ Altıbucaqlıdır
+ 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".

+ +

0xFFFFFFFFFFFFFFFFF // 295147905179352830000
+ 0x123456789ABCDEF // 81985529216486900
+ 0XA // 10
+ BigInt hərfi
+ {{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.

+ +

123456789123456789n // 123456789123456789
+ 0o777777777777n // 68719476735
+ 0x123456789ABCDEFn // 81985529216486895
+ 0b11101001010101010101n // 955733
+ 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:

+ +

// 0755n
+ // SyntaxError: etibarsız BigInt sintaksisi
+ 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:

+ +

0o755n
+ BigInt haqqında daha çox məlumat üçün JavaScript məlumat strukturlarına da baxın.

+ +

Sayısal ayırıcılar
+ 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

+ +

// onluq sayda ayırıcılar
+ 1_000_000_000_000
+ 1_050.95

+ +

// ikili nömrələrdə ayırıcılar
+ 0b1010_0001_1000_0101

+ +

// səkkizbucaqlı ədədlərdə ayrıcılar
+ 0o2_2_5_6

+ +

// hex ədədlərindəki ayırıcılar
+ 0xA0_B0_C0

+ +

// BigInts-də ayırıcılar
+ 1_000_000_000_000_000_000_000n
+ Bu məhdudiyyətlərə diqqət yetirin:

+ +

// Bir dəfədən çox alt qeyd etməyə icazə verilmir
+ 100__000; // Söz düzümü səhvi

+ +

// Rəqəmsal hərflərin sonunda icazə verilmir
+ 100_; // Söz düzümü səhvi

+ +

// 0-dan sonra istifadə edilə bilməz
+ 0_1; // Söz düzümü səhvi
+ Obyekt hərfləri
+ Əlavə məlumat üçün {{jsxref ("Obyekt")}} və Obyekt başlatıcısına da baxın.

+ +

var o = {a: 'foo', b: 'bar', c: 42};

+ +

// stenoqram notation. ES2015-də yenidir
+ var a = 'foo', b = 'bar', c = 42;
+ var o = {a, b, c};

+ +

// əvəzinə
+ var o = {a: a, b: b, c: c};
+ Sıra hərfləri
+ Əlavə məlumat üçün {{jsxref ("Array")}} da baxın.

+ +

[1954, 1974, 1990, 2014]
+ Simli hərflər
+ 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:

+ +

U + 005C \ (arxa cığır),
+ U + 000D <CR>,
+ və U + 000A <LF>.
+ 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.

+ +

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.

+ +

'foo'
+ "bar"
+ Hexadecimal escape ardıcıllığı
+ 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.

+ +

'\ xA9' // "©"
+ Unicode qaçış ardıcıllığı
+ 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.

+ +

Buna da baxın: {{jsxref ("String.fromCharCode ()")}} və {{jsxref ("String.prototype.charCodeAt ()")}}.

+ +

'\ u00A9' // "©" (U + A9)
+ Unicode kod nöqtəsi qaçır
+ 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.

+ +

Buna da baxın: {{jsxref ("String.fromCodePoint ()")}} və {{jsxref ("String.prototype.codePointAt ()")}}.

+ +

'\ u {2F804}' // CJK uyğunluğu İDEOĞRAF-2F804 (U + 2F804)

+ +

// eyni xarakterli bir surroqat cütü olaraq təmsil olunur
+ '\ uD87E \ uDC04'
+ Daimi ifadə hərfi
+ Əlavə məlumat üçün {{jsxref ("RegExp")}} də baxın.

+ +

/ ab + c / g

+ +

// Bir "boş" müntəzəm ifadə
+ // Boş tutmayan qrup lazımdır
+ // tək sətirli şərhlərlə qeyri-müəyyənliyə yol verməmək.
+ / (?:) /
+ Şablon hərfləri
+ Daha çox məlumat üçün şablon iplərinə baxın.

+ +

`simli mətn`

+ +

`simli mətn xətti 1
+  simli mətn xətti 2`

+ +

`string mətni $ {ifadə} simli mətn '

+ +

etiketli "string mətni $ {ifadə} string mətni"
+ Avtomatik nöqtəli vergül
+ Bəzi JavaScript ifadələri nöqtəli vergul ilə dayandırılmalı və buna görə də

+ +

avtomatik nöqtəli vergül daxil edilməsindən təsirləndi (ASI):

+ +

Boş bəyanat
+ qoy, const, dəyişən bir ifadə
+ idxal, ixrac, modul bəyannaməsi
+ İfadə ifadəsi
+ debugger
+ davam etmək, qırmaq, atmaq
+ qayıtmaq
+ ECMAScript spesifikasiyası nöqtəli vergül daxil edilməsinin üç qaydasını xatırladır.

+ +

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.

+ +

{1 2} 3

+ +

// ASI tərəfindən çevrilir

+ +

{1 2;} 3;
+ 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.

+ +

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.

+ +

a = b
+ ++ c

+ +

// ASI tərəfindən dəyişdirilir

+ +

a = b;
+ ++ c;
+ 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:

+ +

Postfiks İfadə (++ və -)
+ davam edin
+ fasilə
+ qayıtmaq
+ gəlir, gəlir *
+ modul
+ qayıtmaq
+ a + b

+ +

// ASI tərəfindən çevrilir

+ +

qayıtmaq;
+ a + b;
+ Texniki şərtlər
+ Xüsusiyyət
+ {{SpecName ('ESDraft', '# sec-ecmascript-language-leksik-qrammatika', 'Leksik qrammatika')}}
+ Brauzer uyğunluğu
+ 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.
+ {{Compat ("javascript.grammar")}}

+ +

İcra Tərəqqi
+ 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.

+ +

{{EmbedTest262ReportResultsTable ("hashbang")}}
+ Həmçinin bax
+ Jeff Walden: İkili və səkkizbucaqlı ədədlər
+ Mathias Bynens: JavaScript xarakter qaçış ardıcıllığı
+ {{jsxref ("Boolean")}}
+ {{jsxref ("Sayı")}}
+ {{jsxref ("RegExp")}}
+ {{jsxref ("Sətir")}}

+ + diff --git "a/files/tr/web/javascript/reference/operat\303\266rler/arithmetic_operators/index.html" "b/files/tr/web/javascript/reference/operat\303\266rler/arithmetic_operators/index.html" new file mode 100644 index 0000000000..e78a71c2d9 --- /dev/null +++ "b/files/tr/web/javascript/reference/operat\303\266rler/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 +--- +
{{jsSidebar("Operators")}}
+ +

Aritmetik operatörler 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 (/).

+ +
{{EmbedInteractiveExample("pages/js/expressions-arithmetic.html")}}
+ + + +

Toplama (+)

+ +

Toplama işleci, sayısal değişkenlerin veya dize birleşiminin toplamını üretir.

+ +

Syntax

+ +
Operator: x + y
+
+ +

Examples

+ +
// 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"
+
+ +

Çıkarma (-)

+ +

Çıkarma işleci (operator), iki değişkeni çıkarır ve farklarını üretir.

+ +

Söz Dizimi

+ +
Operator: x - y
+
+ +

Örnekler

+ +
5 - 3 // 2
+3 - 5 // -2
+'foo' - 3 // NaN(Sayı Değil)
+ +

Bölme (/)

+ +

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.

+ +

Söz Dizimi

+ +
Operator: x / y
+
+ +

Örnekler

+ +
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
+ +

Çarpma (*)

+ +

Çarpma operatörü değişkenlerin ürününü üretir.

+ +

Söz Dizimi

+ +
Operator: x * y
+
+ +

Örnekler

+ +
2 * 2 // 4
+-2 * 2 // -4
+Infinity * 0 // NaN(Sayı Değil1)
+Infinity * Infinity // Sonsuz
+'foo' * 2 // NaN
+
+ +

Kalan (%)

+ +

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.

+ +

Söz Dizimi

+ +
Operator: var1 % var2
+
+ +

Örnekler

+ +
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
+
+ +

Üs (**)

+ +

The exponentiation operator returns the result of raising first operand to the power second operand. That is, var1var2, in the preceding statement, where var1 and var2 are variables. Exponentiation operator is right associative. a ** b ** c is equal to a ** (b ** c).

+ +

Syntax

+ +
Operator: var1 ** var2
+
+ +

Notes

+ +

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 (+/-/~/!/delete/void/typeof) immediately before the base number.

+ +
-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.
+
+ +

Examples

+ +
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
+
+ +

To invert the sign of the result of an exponentiation expression:

+ +
-(2 ** 2) // -4
+
+ +

To force the base of an exponentiation expression to be a negative number:

+ +
(-2) ** 2 // 4
+
+ +
+

Note: JavaScript also has a bitwise operator ^ (logical XOR). ** and ^ are different (for example : 2 ** 3 === 8 when 2 ^ 3 === 1.)

+
+ +

Artırma (++)

+ +

Artış operatörü işlenenini artırır (bir ekler) ve bir değer döndürür.

+ + + +

Söz Dizimi

+ +
Operator: x++ yada ++x
+
+ +

Örnekler

+ +
// Postfix
+var x = 3;
+y = x++; // y = 3, x = 4
+
+// Prefix
+var a = 2;
+b = ++a; // a = 3, b = 3
+
+ +

Azaltma (--)

+ +

The decrement operator decrements (subtracts one from) its operand and returns a value.

+ + + +

Syntax

+ +
Operator: x-- or --x
+
+ +

Examples

+ +
// Postfix
+var x = 3;
+y = x--; // y = 3, x = 2
+
+// Prefix
+var a = 2;
+b = --a; // a = 1, b = 1
+
+ +

Unary negation (-)

+ +

The unary negation operator precedes its operand and negates it.

+ +

Syntax

+ +
Operator: -x
+
+ +

Examples

+ +
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
+
+ +

Unary plus (+)

+ +

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 true, false, and null. 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")}}.

+ +

Syntax

+ +
Operator: +x
+
+ +

Examples

+ +
+3     // 3
++'3'   // 3
++true  // 1
++false // 0
++null  // 0
++function(val){ return val } // NaN
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-additive-operators', 'Additive operators')}}
{{SpecName('ESDraft', '#sec-postfix-expressions', 'Postfix expressions')}}
{{SpecName('ESDraft', '#sec-11.5', 'Multiplicative operators')}}
{{SpecName('ESDraft', '#sec-11.4', 'Unary operator')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.operators.arithmetic")}}

+ +

See also

+ + diff --git "a/files/tr/web/javascript/reference/operat\303\266rler/bitwise_operators/index.html" "b/files/tr/web/javascript/reference/operat\303\266rler/bitwise_operators/index.html" new file mode 100644 index 0000000000..d2ad12abff --- /dev/null +++ "b/files/tr/web/javascript/reference/operat\303\266rler/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 +--- +
{{jsSidebar("Operators")}}
+ +

Bitsel işleçler işlediği elemanlara ondalık, onaltılık veya sayılar 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.

+ +

Aşağıdaki tablo JavaScript'in bitsel işleçlerini özetler:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OperatorUsageDescription
Bitwise ANDa & bBitsel 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.
Bitwise ORa | bBitsel işleçin iki tarafının karşılık gelen bitlerinden en az biri 1 ise 1 döndürür.
Bitwise XORa ^ bBitsel işleçin iki tarafının karşılık gelen bitlerinden ancak bir tanesi 1 ise, 1 döndürür.
Bitwise NOT~ aİşlenenin bitlerini ters çevirir.
Left shifta << ba sayısının ikili haline, sağına b (< 32) adet bit 0 ekleyerek sola doğru kaydırır.
Sign-propagating right shifta >> ba sayısının ikili halini b (< 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.
Zero-fill right shifta >>> ba sayısının ikili gösterimine b (< 32) bit sağa kaydırır, a sayısının pozitif negatif olmasına bakmadan sayının soluna b adet 0 ekler.
+ +

İşaretli 32-bit integer sayılar

+ +

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:

+ +
00000000000000000000000100111010
+
+ +

The following encodes ~314, i.e. the ones' complement of -314:

+ +
11111111111111111111111011000101
+
+ +

Finally, the following encodes -314, i.e. the two's complement of -314:

+ +
11111111111111111111111011000110
+
+ +

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 sign bit.

+ +

The number 0 is the integer that is composed completely of 0 bits.

+ +
0 (base 10) = 00000000000000000000000000000000 (base 2)
+
+ +

The number -1 is the integer that is composed completely of 1 bits.

+ +
-1 (base 10) = 11111111111111111111111111111111 (base 2)
+
+ +

The number -2147483648 (hexadecimal representation: -0x80000000) is the integer that is composed completely of 0 bits except the first (left-most) one.

+ +
-2147483648 (base 10) = 10000000000000000000000000000000 (base 2)
+
+ +

The number 2147483647 (hexadecimal representation: 0x7fffffff) is the integer that is composed completely of 1 bits except the first (left-most) one.

+ +
2147483647 (base 10) = 01111111111111111111111111111111 (base 2)
+
+ +

The numbers -2147483648 and 2147483647 are the minimum and the maximum integers representable through a 32bit signed number.

+ +

Bitwise logical operators

+ +

Conceptually, the bitwise logical operators work as follows:

+ + + +

& (Bitwise AND)

+ +

Performs the AND operation on each pair of bits. a AND b yields 1 only if both a and b are 1. The truth table for the AND operation is:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
aba AND b
000
010
100
111
+ +
.    9 (base 10) = 00000000000000000000000000001001 (base 2)
+    14 (base 10) = 00000000000000000000000000001110 (base 2)
+                   --------------------------------
+14 & 9 (base 10) = 00000000000000000000000000001000 (base 2) = 8 (base 10)
+
+ +

Bitwise ANDing any number x with 0 yields 0. Bitwise ANDing any number x with -1 yields x.

+ +

| (Bitwise OR)

+ +

Performs the OR operation on each pair of bits. a OR b yields 1 if either a or b is 1. The truth table for the OR operation is:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
aba OR b
000
011
101
111
+ +
.    9 (base 10) = 00000000000000000000000000001001 (base 2)
+    14 (base 10) = 00000000000000000000000000001110 (base 2)
+                   --------------------------------
+14 | 9 (base 10) = 00000000000000000000000000001111 (base 2) = 15 (base 10)
+
+ +

Bitwise ORing any number x with 0 yields x. Bitwise ORing any number x with -1 yields -1.

+ +

^ (Bitwise XOR)

+ +

Performs the XOR operation on each pair of bits. a XOR b yields 1 if a and b are different. The truth table for the XOR operation is:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
aba XOR b
000
011
101
110
+ +
.    9 (base 10) = 00000000000000000000000000001001 (base 2)
+    14 (base 10) = 00000000000000000000000000001110 (base 2)
+                   --------------------------------
+14 ^ 9 (base 10) = 00000000000000000000000000000111 (base 2) = 7 (base 10)
+
+ +

Bitwise XORing any number x with 0 yields x. Bitwise XORing any number x with -1 yields ~x.

+ +

~ (Bitwise NOT)

+ +

Performs the NOT operator on each bit. NOT a yields the inverted value (a.k.a. one's complement) of a. The truth table for the NOT operation is:

+ + + + + + + + + + + + + + + + +
aNOT a
01
10
+ +
 9 (base 10) = 00000000000000000000000000001001 (base 2)
+               --------------------------------
+~9 (base 10) = 11111111111111111111111111110110 (base 2) = -10 (base 10)
+
+ +

Bitwise NOTing any number x yields -(x + 1). For example, ~-5 yields 4.

+ +

Example with indexOf:

+ +
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
+
+ +

Bitwise shift operators

+ +

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.

+ +

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.

+ +

<< (Left shift)

+ +

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.

+ +

For example, 9 << 2 yields 36:

+ +
.    9 (base 10): 00000000000000000000000000001001 (base 2)
+                  --------------------------------
+9 << 2 (base 10): 00000000000000000000000000100100 (base 2) = 36 (base 10)
+
+ +

Bitwise shifting any number x to the left by y bits yields x * 2^y.

+ +

>> (Sign-propagating right shift)

+ +

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".

+ +

For example, 9 >> 2 yields 2:

+ +
.    9 (base 10): 00000000000000000000000000001001 (base 2)
+                  --------------------------------
+9 >> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
+
+ +

Likewise, -9 >> 2 yields -3, because the sign is preserved:

+ +
.    -9 (base 10): 11111111111111111111111111110111 (base 2)
+                   --------------------------------
+-9 >> 2 (base 10): 11111111111111111111111111111101 (base 2) = -3 (base 10)
+
+ +

>>> (Zero-fill right shift)

+ +

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.

+ +

For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result. For example, 9 >>> 2 yields 2, the same as 9 >> 2:

+ +
.     9 (base 10): 00000000000000000000000000001001 (base 2)
+                   --------------------------------
+9 >>> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
+
+ +

However, this is not the case for negative numbers. For example, -9 >>> 2 yields 1073741821, which is different than -9 >> 2 (which yields -3):

+ +
.     -9 (base 10): 11111111111111111111111111110111 (base 2)
+                    --------------------------------
+-9 >>> 2 (base 10): 00111111111111111111111111111101 (base 2) = 1073741821 (base 10)
+
+ +

Examples

+ +

Flags and bitmasks

+ +

The bitwise logical operators are often used to create, manipulate, and read sequences of flags, 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).

+ +

Suppose there are 4 flags:

+ + + +

These flags are represented by a sequence of bits: DCBA. When a flag is set, it has a value of 1. When a flag is cleared, it has a value of 0. Suppose a variable flags has the binary value 0101:

+ +
var flags = 5;   // binary 0101
+
+ +

This value indicates:

+ + + +

Since bitwise operators are 32-bit, 0101 is actually 00000000000000000000000000000101, but the preceding zeroes can be neglected since they contain no meaningful information.

+ +

A bitmask is a sequence of bits that can manipulate and/or read flags. Typically, a "primitive" bitmask for each flag is defined:

+ +
var FLAG_A = 1; // 0001
+var FLAG_B = 2; // 0010
+var FLAG_C = 4; // 0100
+var FLAG_D = 8; // 1000
+
+ +

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:

+ +
var mask = FLAG_A | FLAG_B | FLAG_D; // 0001 | 0010 | 1000 => 1011
+
+ +

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 masks 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:

+ +
// if we own a cat
+if (flags & FLAG_C) { // 0101 & 0100 => 0100 => true
+   // do stuff
+}
+
+ +

A bitmask with multiple set flags acts like an "either/or". For example, the following two are equivalent:

+ +
// 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
+}
+
+ +
// 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
+}
+
+ +

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:

+ +
// yes, we own a cat and a duck
+var mask = FLAG_C | FLAG_D; // 0100 | 1000 => 1100
+flags |= mask;   // 0101 | 1100 => 1101
+
+ +

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:

+ +
// 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
+
+ +

The mask could also have been created with ~FLAG_A & ~FLAG_C (De Morgan's law):

+ +
// 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
+
+ +

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:

+ +
// 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
+
+ +

Finally, the flags can all be flipped with the NOT operator:

+ +
// entering parallel universe...
+flags = ~flags;    // ~1010 => 0101
+
+ +

Conversion snippets

+ +

Convert a binary String to a decimal Number:

+ +
var sBinString = '1011';
+var nMyNumber = parseInt(sBinString, 2);
+alert(nMyNumber); // prints 11, i.e. 1011
+
+ +

Convert a decimal Number to a binary String:

+ +
var nMyNumber = 11;
+var sBinString = nMyNumber.toString(2);
+alert(sBinString); // prints 1011, i.e. 11
+
+ +

Automate Mask Creation

+ +

You can create multiple masks from a set of Boolean values, like this:

+ +
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
+
+ +

Reverse algorithm: an array of booleans from a mask

+ +

If you want to create an Array of Booleans from a mask you can use this code:

+ +
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
+
+ +

You can test both algorithms at the same time…

+ +
var nTest = 19; // our custom mask
+var nResult = createMask.apply(this, arrayFromMask(nTest));
+
+alert(nResult); // 19
+
+ +

For didactic purpose only (since there is the Number.toString(2) method), we show how it is possible to modify the arrayFromMask algorithm in order to create a String containing the binary representation of a Number, rather than an Array of Booleans:

+ +
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
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-11.7')}}{{Spec2('ES5.1')}}Defined in several sections of the specification: Bitwise NOT operator, Bitwise shift operators, Binary bitwise operators
{{SpecName('ES6', '#sec-bitwise-shift-operators')}}{{Spec2('ES6')}}Defined in several sections of the specification: Bitwise NOT operator, Bitwise shift operators, Binary bitwise operators
{{SpecName('ESDraft', '#sec-bitwise-shift-operators')}}{{Spec2('ESDraft')}}Defined in several sections of the specification: Bitwise NOT operator, Bitwise shift operators, Binary bitwise operators
+ +

Browser compatibility

+ + + +

{{Compat("javascript.operators.bitwise")}}

+ +

See also

+ + diff --git "a/files/tr/web/javascript/reference/operat\303\266rler/function_star_/index.html" "b/files/tr/web/javascript/reference/operat\303\266rler/function_star_/index.html" new file mode 100644 index 0000000000..193e00f205 --- /dev/null +++ "b/files/tr/web/javascript/reference/operat\303\266rler/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* +--- +
{{jsSidebar("Operators")}}
+ +

The function* keyword can be used to define a generator function inside an expression.

+ +
{{EmbedInteractiveExample("pages/js/expressions-functionasteriskexpression.html")}}
+ + + +

Syntax

+ +
function* [name]([param1[, param2[, ..., paramN]]]) {
+   statements
+}
+ +

Parametreler

+ +
+
name
+
The function name. Can be omitted, in which case the function is anonymous. The name is only local to the function body.
+
paramN
+
Argüman adıdır, bir fonksiyon maxiumum 255 argüman alır.
+
statements
+
Fonksiyon kodları.
+
+ +

Açıklama

+ +

A function* expression is very similar to and has almost the same syntax as a {{jsxref('Statements/function*', 'function* statement')}}. The main difference between a function* expression and a function* statement is the function name, which can be omitted in function* expressions to create anonymous generator functions. See also the chapter about functions for more information.

+ +

Örnekler

+ +

Aşağıdaki adlandırılmamış fonksiyondur ve gelen değer karesini verir.

+ +
var x = function*(y) {
+   yield y * y;
+};
+
+ +

Özellikler

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#', 'function*')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#', 'function*')}}{{Spec2('ESDraft')}} 
+ +

Tarayıcı uyumluluğu

+ + + +

{{Compat("javascript.operators.function_star")}}

+ +

Bakabilirsiniz

+ + diff --git "a/files/tr/web/javascript/reference/operat\303\266rler/index.html" "b/files/tr/web/javascript/reference/operat\303\266rler/index.html" new file mode 100644 index 0000000000..f42305b092 --- /dev/null +++ "b/files/tr/web/javascript/reference/operat\303\266rler/index.html" @@ -0,0 +1,277 @@ +--- +title: İfadeler ve operatörler +slug: Web/JavaScript/Reference/Operatörler +translation_of: Web/JavaScript/Reference/Operators +--- +
{{jsSidebar("Operators")}}
+ +

Bu döküman bütün JavaScript ifadelerini,operatörlerini ve anahtar kelimeleri içerir.

+ +

Expressions and operators by category

+ +

For an alphabetical listing see the sidebar on the left.

+ +

Birincil İfadeler

+ +

Genel İfadeler ve basit anahtar kelimeler.

+ +
+
{{jsxref("Operators/this", "this")}}
+
The this keyword refers to the function's execution context.
+
{{jsxref("Operators/function", "function")}}
+
The function keyword defines a function expression.
+
{{experimental_inline}} {{jsxref("Operators/class", "class")}}
+
The class keyword defines a class expression.
+
{{experimental_inline}} {{jsxref("Operators/function*", "function*")}}
+
The function* keyword defines a generator function expression.
+
{{experimental_inline}} {{jsxref("Operators/yield", "yield")}}
+
Pause and resume a generator function
+
{{experimental_inline}} {{jsxref("Operators/yield*", "yield*")}}
+
Delegate to another generator function or iterable object.
+
{{jsxref("Global_Objects/Array", "[]")}}
+
Array initializer/literal syntax.
+
{{jsxref("Operators/Object_initializer", "{}")}}
+
Object initializer/literal syntax.
+
{{jsxref("Global_Objects/RegExp", "/ab+c/i")}}
+
Regular expression literal syntax.
+
{{experimental_inline}} {{jsxref("Operators/Array_comprehensions", "[for (x of y) x]")}}
+
Array comprehensions.
+
{{experimental_inline}} {{jsxref("Operators/Generator_comprehensions", "(for (x of y) y)")}}
+
Generator comprehensions.
+
{{jsxref("Operators/Grouping", "( )")}}
+
Grouping operator.
+
+ +

Left-hand-side expressions

+ +

Left values are the destination of an assignment.

+ +
+
{{jsxref("Operators/Property_accessors", "Property accessors", "", 1)}}
+
Member operators provide access to a property or method of an object
+ (object.property and object["property"]).
+
{{jsxref("Operators/new", "new")}}
+
The new operator creates an instance of a constructor.
+
{{experimental_inline}} {{jsxref("Operators/super", "super")}}
+
The super keyword calls the parent constructor.
+
{{experimental_inline}} {{jsxref("Operators/Spread_operator", "...obj")}}
+
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.
+
+ +

Increment and decrement

+ +

Postfix/prefix increment and postfix/prefix decrement operators.

+ +
+
{{jsxref("Operators/Arithmetic_Operators", "A++", "#Increment")}}
+
Postfix increment operator.
+
{{jsxref("Operators/Arithmetic_Operators", "A--", "#Decrement")}}
+
Postfix decrement operator.
+
{{jsxref("Operators/Arithmetic_Operators", "++A", "#Increment")}}
+
Prefix increment operator.
+
{{jsxref("Operators/Arithmetic_Operators", "--A", "#Decrement")}}
+
Prefix decrement operator.
+
+ +

Unary operators

+ +

A unary operation is operation with only one operand.

+ +
+
{{jsxref("Operators/delete", "delete")}}
+
The delete operator deletes a property from an object.
+
{{jsxref("Operators/void", "void")}}
+
The void operator discards an expression's return value.
+
{{jsxref("Operators/typeof", "typeof")}}
+
The typeof operator determines the type of a given object.
+
{{jsxref("Operators/Arithmetic_Operators", "+", "#Unary_plus")}}
+
The unary plus operator converts its operand to Number type.
+
{{jsxref("Operators/Arithmetic_Operators", "-", "#Unary_negation")}}
+
The unary negation operator converts its operand to Number type and then negates it.
+
{{jsxref("Operators/Bitwise_Operators", "~", "#Bitwise_NOT")}}
+
Bitwise NOT operator.
+
{{jsxref("Operators/Logical_Operators", "!", "#Logical_NOT")}}
+
Logical NOT operator.
+
+ +

Arithmetic operators

+ +

Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.

+ +
+
{{jsxref("Operators/Arithmetic_Operators", "+", "#Addition")}}
+
Addition operator.
+
{{jsxref("Operators/Arithmetic_Operators", "-", "#Subtraction")}}
+
Subtraction operator.
+
{{jsxref("Operators/Arithmetic_Operators", "/", "#Division")}}
+
Division operator.
+
{{jsxref("Operators/Arithmetic_Operators", "*", "#Multiplication")}}
+
Multiplication operator.
+
{{jsxref("Operators/Arithmetic_Operators", "%", "#Remainder")}}
+
Remainder operator.
+
+ +

Relational operators

+ +

A comparison operator compares its operands and returns a Boolean value based on whether the comparison is true.

+ +
+
{{jsxref("Operators/in", "in")}}
+
The in operator determines whether an object has a given property.
+
{{jsxref("Operators/instanceof", "instanceof")}}
+
The instanceof operator determines whether an object is an instance of another object.
+
{{jsxref("Operators/Comparison_Operators", "<", "#Less_than_operator")}}
+
Less than operator.
+
{{jsxref("Operators/Comparison_Operators", ">", "#Greater_than_operator")}}
+
Greater than operator.
+
{{jsxref("Operators/Comparison_Operators", "<=", "#Less_than_or_equal_operator")}}
+
Less than or equal operator.
+
{{jsxref("Operators/Comparison_Operators", ">=", "#Greater_than_or_equal_operator")}}
+
Greater than or equal operator.
+
+ +

Equality operators

+ +

The result of evaluating an equality operator is always of type Boolean based on whether the comparison is true.

+ +
+
{{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}
+
Equality operator.
+
{{jsxref("Operators/Comparison_Operators", "!=", "#Inequality")}}
+
Inequality operator.
+
{{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}
+
Identity operator.
+
{{jsxref("Operators/Comparison_Operators", "!==", "#Nonidentity")}}
+
Nonidentity operator.
+
+ +

Bitwise shift operators

+ +

Operations to shift all bits of the operand.

+ +
+
{{jsxref("Operators/Bitwise_Operators", "<<", "#Left_shift")}}
+
Bitwise left shift operator.
+
{{jsxref("Operators/Bitwise_Operators", ">>", "#Right_shift")}}
+
Bitwise right shift operator.
+
{{jsxref("Operators/Bitwise_Operators", ">>>", "#Unsigned_right_shift")}}
+
Bitwise unsigned right shift operator.
+
+ +

Binary bitwise operators

+ +

Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.

+ +
+
{{jsxref("Operators/Bitwise_Operators", "&", "#Bitwise_AND")}}
+
Bitwise AND.
+
{{jsxref("Operators/Bitwise_Operators", "|", "#Bitwise_OR")}}
+
Bitwise OR.
+
{{jsxref("Operators/Bitwise_Operators", "^", "#Bitwise_XOR")}}
+
Bitwise XOR.
+
+ +

Binary logical operators

+ +

Logical operators are typically used with boolean (logical) values, and when they are, they return a boolean value.

+ +
+
{{jsxref("Operators/Logical_Operators", "&&", "#Logical_AND")}}
+
Logical AND.
+
{{jsxref("Operators/Logical_Operators", "||", "#Logical_OR")}}
+
Logical OR.
+
+ +

Conditional (ternary) operator

+ +
+
{{jsxref("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}
+
+

The conditional operator returns one of two values based on the logical value of the condition.

+
+
+ +

Assignment operators

+ +

An assignment operator assigns a value to its left operand based on the value of its right operand.

+ +
+
{{jsxref("Operators/Assignment_Operators", "=", "#Assignment")}}
+
Assignment operator.
+
{{jsxref("Operators/Assignment_Operators", "*=", "#Multiplication_assignment")}}
+
Multiplication assignment.
+
{{jsxref("Operators/Assignment_Operators", "/=", "#Division_assignment")}}
+
Division assignment.
+
{{jsxref("Operators/Assignment_Operators", "%=", "#Remainder_assignment")}}
+
Remainder assignment.
+
{{jsxref("Operators/Assignment_Operators", "+=", "#Addition_assignment")}}
+
Addition assignment.
+
{{jsxref("Operators/Assignment_Operators", "-=", "#Subtraction_assignment")}}
+
Subtraction assignment
+
{{jsxref("Operators/Assignment_Operators", "<<=", "#Left_shift_assignment")}}
+
Left shift assignment.
+
{{jsxref("Operators/Assignment_Operators", ">>=", "#Right_shift_assignment")}}
+
Right shift assignment.
+
{{jsxref("Operators/Assignment_Operators", ">>>=", "#Unsigned_right_shift_assignment")}}
+
Unsigned right shift assignment.
+
{{jsxref("Operators/Assignment_Operators", "&=", "#Bitwise_AND_assignment")}}
+
Bitwise AND assignment.
+
{{jsxref("Operators/Assignment_Operators", "^=", "#Bitwise_XOR_assignment")}}
+
Bitwise XOR assignment.
+
{{jsxref("Operators/Assignment_Operators", "|=", "#Bitwise_OR_assignment")}}
+
Bitwise OR assignment.
+
{{experimental_inline}} {{jsxref("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}
+ {{experimental_inline}} {{jsxref("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}
+
+

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.

+
+
+ +

Comma operator

+ +
+
{{jsxref("Operators/Comma_Operator", ",")}}
+
The comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression.
+
+ +

Non-standard features

+ +
+
{{non-standard_inline}} {{jsxref("Operators/Legacy_generator_function", "Legacy generator function", "", 1)}}
+
The function 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.
+
{{non-standard_inline}} {{jsxref("Operators/Expression_closures", "Expression closures", "", 1)}}
+
The expression closure syntax is a shorthand for writing simple function.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
ECMAScript 1st Edition.StandardInitial definition.
{{SpecName('ES5.1', '#sec-11', 'Expressions')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}{{Spec2('ES6')}}New: Spread operator, destructuring assignment, super keyword, Array comprehensions, Generator comprehensions
+ +

See also

+ + diff --git "a/files/tr/web/javascript/reference/operat\303\266rler/instanceof/index.html" "b/files/tr/web/javascript/reference/operat\303\266rler/instanceof/index.html" new file mode 100644 index 0000000000..3434ea34b9 --- /dev/null +++ "b/files/tr/web/javascript/reference/operat\303\266rler/instanceof/index.html" @@ -0,0 +1,207 @@ +--- +title: instanceof +slug: Web/JavaScript/Reference/Operatörler/instanceof +translation_of: Web/JavaScript/Reference/Operators/instanceof +--- +
{{jsSidebar("Operators")}}
+ +

Instanceof operatorü bir nesne'nin prototip (prototype) zincirinin, belirli bir prototipin kurucu(constructor) metodu olup olmadığını testeder.

+ +

Syntax

+ +
object instanceof constructor
+ +

Parametreler

+ +
+
object
+
Test edilecek nesne
+
+ +
+
constructor
+
Test edilecek karşı kurucu fonksiyon
+
+ +

Açıklama

+ +

Instanceof operatorü nesnenin prototip zincirinde 'constructor.prototype' varlığını testeder.

+ +
// 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
+
+ +

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.

+ +

instanceof ve çoklu bağlam (multiple context) (e.g. frames or windows)

+ +

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.

+ +
Mozilla geliştiricleri için not: + +

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.

+
+ +

Examples

+ +

Demonstrating that String and Date are of type Object and exceptional cases

+ +

The following code uses instanceof to demonstrate that String and Date objects are also of type Object (they are derived from Object).

+ +

However, objects created with the object literal notation are an exception here: Although the prototype is undefined, instanceof Object returns true.

+ +
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
+
+ +

Demonstrating that mycar is of type Car and type Object

+ +

The following code creates an object type Car and an instance of that object type, mycar. The instanceof operator demonstrates that the mycar object is of type Car and of type Object.

+ +
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
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-relational-operators', 'Relational Operators')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-relational-operators', 'Relational Operators')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.8.6', 'The instanceof operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-11.8.6', 'The instanceof operator')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.4.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git "a/files/tr/web/javascript/reference/operat\303\266rler/mantiksal_operatorler/index.html" "b/files/tr/web/javascript/reference/operat\303\266rler/mantiksal_operatorler/index.html" new file mode 100644 index 0000000000..b283f9e06c --- /dev/null +++ "b/files/tr/web/javascript/reference/operat\303\266rler/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 +--- +
{{jsSidebar("Operators")}}
+ +

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, && ve || 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.

+ +

Açıklama

+ +

Mantıksal operatörler aşağıdaki tabloda açıklanıyor:

+ + + + + + + + + + + + + + + + + + + + + + + + +
OperatörKullanımAçıklama
Mantıksal VE (&&)expr1 && expr2Eğer expr1 false değerine dönüştürülebilirse, expr1  döndürülür. Aksi halde, expr2 döndürülür. Böylece, Boolean değerleri ile kullanıldıklarında, && her iki operand true ise true ; aksi halde, false döndürür.
Mantıksal YA DA (||)expr1 || expr2Eğer expr1 true değerine dönüştürülebilirse, expr1 döndürülür, aksi halde, expr2 döndürülür. Böylece, Boolean değerleri ile kullanıldıklarında, || her iki operanddan herhangi biri true ise true döndürür.
Mantıksal DEĞİL (!)!exprEğer operandın değeri true is false döndürür, aksi alde true döndürür.
+ +

Eğer bir değer true değerine dönüştürülebiliyorsa, ona {{Glossary("truthy")}} ismi verilir. Eğer bir değer false değerine dönüştürülebiliyorsa, ona {{Glossary("falsy")}} denir.

+ +

False değerine dönüştürülebilen ifadelere örnekler:

+ + + +

&& ve || operatörleri Boolean olmayan değerler ile kullanılabiliyor olmasına rağmen, döndürdükleri değerler her zaman Boolean değerlerine çevirilebildiğinden, halen Boolean operatörleri olarak düşünülebilirler.

+ +

Kısa-devre değerlendirmeleri

+ +

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:

+ + + +

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 (herhangi) kısmının tamamıyla bir mantıksal ifadeye eşit olduğuna dikkat edin. (parantezler ile gösterildiği gibi).

+ +

Örneğin, aşağıdaki iki fonksiyon birbirinin aynısıdır.

+ +
function shortCircuitEvaluation() {
+  doSomething() || doSomethingElse()
+}
+
+function equivalentEvaluation() {
+  var flag = doSomething();
+  if (!flag) {
+    doSomethingElse();
+  }
+}
+
+ +

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).

+ +
false && true  || true      // returns true
+false && (true || true)     // returns false
+ +

Mantıksal VE (&&)

+ +

Aşağıdaki kod && (mantıksal VE) operatörüyle ilgili örnekleri gösterir.

+ +
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
+
+ +

Mantıksal YA DA (||)

+ +

Aşağıdaki kod || (mantıksal YA DA) operatörüyle ilgili örnekleri gösterir.

+ +
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 ""
+
+ +

Mantıksal DEĞİL (!)

+ +

Aşağıdaki kod ! (mantıksal DEĞİL) operatörüyle ilgili örnekleri gösterir.

+ +
n1 = !true              // !t returns false
+n2 = !false             // !f returns true
+n3 = !"Cat"             // !t returns false
+
+ +

Dönüşüm kuralları

+ +

VE operatörünü YA DA operatörüne dönüştürmek

+ +

Booleanları içeren aşağıdaki ifade:

+ +
bCondition1 && bCondition2
+ +

her zaman şuna eşittir:

+ +
!(!bCondition1 || !bCondition2)
+ +

YA DA operatörünü VE operatörüne çevirmek

+ +

Booleanları içeren aşağıdaki ifade:

+ +
bCondition1 || bCondition2
+ +

her zaman şuna eşittir:

+ +
!(!bCondition1 && !bCondition2)
+ +

DEĞİL operatörleri arasında dönüşüm yapmak

+ +

Booleanları içeren aşağıdaki ifade:

+ +
!!bCondition
+ +

her zaman şuna eşittir: 

+ +
bCondition
+ +

İç içe geçmiş parantezleri kaldırmak

+ +

Mantıksal operatörlerin soldan sağa değerlendirilmesi durumunda, kompleks bir ifadeden parantezleri bazı kuralları takip ederek kaldırmak mümkündür.

+ +

İç içe geçmiş VE operatörünü kaldırmak

+ +

Aşağıda, Boolean içeren bu bileşik işlem:

+ +
bCondition1 || (bCondition2 && bCondition3)
+ +

her zaman şuna eşittir:

+ +
bCondition1 || bCondition2 && bCondition3
+ +

İç içe geçmiş YA DA operatörünü kaldırmak

+ +

Aşağıda, Boolean içeren bu bileşik ifade:

+ +
bCondition1 && (bCondition2 || bCondition3)
+ +

her zaman şuna eşittir:

+ +
!(!bCondition1 || !bCondition2 && !bCondition3)
+ +

Özellikler

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ÖzellikDurumAçıklama
{{SpecName('ES1')}}{{Spec2('ES1')}}İlk tanım.
{{SpecName('ES5.1', '#sec-11.11')}}{{Spec2('ES5.1')}}Tarifnamenin birkaç bölümünde tanımlandı: Logical NOT Operator, Binary Logical Operators
{{SpecName('ES6', '#sec-binary-logical-operators')}}{{Spec2('ES6')}}Tarifnamenin birkaç bölümünde tanımlandı: Logical NOT Operator, Binary Logical Operators
{{SpecName('ESDraft', '#sec-binary-logical-operators')}}{{Spec2('ESDraft')}}Tarifnamenin birkaç bölümünde tanımlandı: Logical NOT Operator, Binary Logical Operators
+ +

Tarayıcı Uyumluluğu

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Mantıksal VE (&&){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+

Mantıksal YA DA (||)

+
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Mantıksal DEĞİL (!){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ÖzellikAndroidAndroid üzerinde ChromeFirefox Mobil (Gecko)IE MobilOpera MobilSafari Mobil
Logical AND (&&){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Logical OR (||){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Logical NOT (!){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ayrıca bakın

+ + diff --git "a/files/tr/web/javascript/reference/operat\303\266rler/super/index.html" "b/files/tr/web/javascript/reference/operat\303\266rler/super/index.html" new file mode 100644 index 0000000000..3dd3f62ebf --- /dev/null +++ "b/files/tr/web/javascript/reference/operat\303\266rler/super/index.html" @@ -0,0 +1,165 @@ +--- +title: super +slug: Web/JavaScript/Reference/Operatörler/super +translation_of: Web/JavaScript/Reference/Operators/super +--- +
{{jsSidebar("Operators")}}
+ +

super, ebeveyn sınıftaki fonksiyonlara ulaşmak ve onları çağırmak için kullanılan bir ifadedir.

+ +

The super.prop and super[expr] expressions are valid in any method definition in both classes and object literals.

+ +

Sözdizimi (Syntax)

+ +
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.
+
+ +

Açıklama

+ +

Constructor içinde super ifadesi tek başına kullanılır ve this ifadesinden önce kullanılması zorunludur. Aynı zamanda super ifadesi ebeveyn sınıftaki fonksiyonları çağırmak için de kullanılabilir.

+ +

Örnekler

+ +

Sınflarda super kullanımı

+ +

This code snippet is taken from the classes sample (live demo). Here super() is called to avoid duplicating the constructor parts' that are common between Rectangle and Square.

+ +
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';
+  }
+}
+ +

Super-calling static methods

+ +

You are also able to call super on static methods.

+ +
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'
+
+ +

Deleting super properties will throw an error

+ +

You cannot use the delete operator and super.prop or super[expr] to delete a parent class' property, it will throw a {{jsxref("ReferenceError")}}.

+ +
class Base {
+  foo() {}
+}
+class Derived extends Base {
+  delete() {
+    delete super.foo; // this is bad
+  }
+}
+
+new Derived().delete(); // ReferenceError: invalid delete involving 'super'. 
+ +

super.prop cannot overwrite non-writable properties

+ +

When defining non-writable properties with e.g. {{jsxref("Object.defineProperty")}}, super cannot overwrite the value of the property.

+ +
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
+
+ +

Using super.prop in object literals

+ +

Super can also be used in the object initializer / literal notation. In this example, two objects define a method. In the second object, super 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 obj2 to obj1, so that super is able to find method1 on obj1.

+ +
var obj1 = {
+  method1() {
+    console.log('method 1');
+  }
+}
+
+var obj2 = {
+  method2() {
+    super.method1();
+  }
+}
+
+Object.setPrototypeOf(obj2, obj1);
+obj2.method2(); // logs "method 1"
+
+ +

Özellikler

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-super-keyword', 'super')}}
+ +

Tarayıcı uyumluluğu

+ + + +

{{Compat("javascript.operators.super")}}

+ +

Ayrıca bakınız

+ + diff --git "a/files/tr/web/javascript/reference/operat\303\266rler/this/index.html" "b/files/tr/web/javascript/reference/operat\303\266rler/this/index.html" new file mode 100644 index 0000000000..674e577187 --- /dev/null +++ "b/files/tr/web/javascript/reference/operat\303\266rler/this/index.html" @@ -0,0 +1,347 @@ +--- +title: this +slug: Web/JavaScript/Reference/Operatörler/this +translation_of: Web/JavaScript/Reference/Operators/this +--- +
{{jsSidebar("Operators")}}
+ +

Fonksiyon'un this anahtar kelimesi diğer dillere göre birazcık farklı davranır. Ayrıca strict modu ve non-strict modu arasında farklılıklar bulunur.

+ +

Çoğunlukla, this'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 bind method to set the value of a function's this regardless of how it's called.

+ +

Sözdizimi

+ +
this
+ +

Global içerik

+ +

Global konumda (fonksiyon dışında), this global nesnesini referans gösterir, strict modunda olmak bu durumu değiştirmez..

+ +
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
+
+ +

Function içerik

+ +

Fonksiyon içerisinde, this'in değeri fonksiyonun nasıl çağrıldığına bağlıdır..

+ +

Basit çağrı

+ +
function f1(){
+  return this;
+}
+
+f1() === window; // global obje
+
+ +

Bu durumda, this'in değeri çağrı ile ayarlanmaz. Kod strict modda olmadığı sürece, this'in değeri mutlaka obje olmalıdır bu yüzdende default değer olan global objesi döner.

+ +
function f2(){
+  "use strict"; // strict modu içerisinde çalıştıralım
+  return this;
+}
+
+f2() === undefined;
+
+ +

Strict modu içerisinde, this'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 null yada 42 yada "I am not this".

+ +
Not: İkinci örnekte, this undefined olmalıdır, çünkü f2 taban belirtilmeden çağrılmıştır. (örn: window.f2()). Bu özellik bazı browserlerde desteklenmemektedir. strict mod henüz geliştirme aşamasındayken çoğu browser yanlış davranarak window objesini döndürür.
+ +

Obje methodu cağrısı

+ +

Fonksiyon bir objenin methodu olarak çağrıldığında, this çağrıldığı obje olarak atanacaktır.

+ +

In the following example, when o.f() is invoked, inside the function this is bound to the o object.

+ +
var o = {
+  prop: 37,
+  f: function() {
+    return this.prop;
+  }
+};
+
+console.log(o.f()); // logs 37
+
+ +

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 f member during the definition of o. However, we could have just as easily defined the function first and later attached it to o.f. Doing so results in the same behavior:

+ +
var o = {prop: 37};
+
+function independent() {
+  return this.prop;
+}
+
+o.f = independent;
+
+console.log(o.f()); // logs 37
+
+ +

This demonstrates that it matters only that the function was invoked from the f member of o.

+ +

Similarly, the this 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 g of the object o.b. This time during execution, this inside the function will refer to o.b. The fact that the object is itself a member of o has no consequence; the most immediate reference is all that matters.

+ +
o.b = {g: independent, prop: 42};
+console.log(o.b.g()); // logs 42
+
+ +

this on the object's prototype chain

+ +

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, this refers to the object the method was called on, as if the method was on the object.

+ +
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
+
+ +

In this example, the object assigned to the variable p doesn't have its own f property, it inherits it from its prototype. But it doesn't matter that the lookup for f eventually finds a member with that name on o; the lookup began as a reference to p.f, so this inside the function takes the value of the object referred to as p. That is, since f is called as a method of p, its this refers to p. This is an interesting feature of JavaScript's prototype inheritance.

+ +

this with a getter or setter

+ +

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 this bound to the object from which the property is being set or gotten.

+ +
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
+
+ +

As a constructor

+ +

When a function is used as a constructor (with the new keyword), its this is bound to the new object being constructed.

+ +

Note: while the default for a constructor is to return the object referenced by this, it can instead return some other object (if the return value isn't an object, then the this object is returned).

+ +
/*
+ * 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
+
+ +

In the last example (C2), because an object was returned during construction, the new object that this was bound to simply gets discarded. (This essentially makes the statement "this.a = 37;" dead code. It's not exactly dead, because it gets executed, but it can be eliminated with no outside effects.)

+ +

call and apply

+ +

Where a function uses the this keyword in its body, its value can be bound to a particular object in the call using the call or apply methods that all functions inherit from Function.prototype.

+ +
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
+
+ +

Note that with call and apply, if the value passed as this is not an object, an attempt will be made to convert it to an object using the internal ToObject operation. So if the value passed is a primitive like 7 or 'foo', it will be converted to an Object using the related constructor, so the primitive number 7 is converted to an object as if by new Number(7) and the string 'foo' to an object as if by new String('foo'), e.g.

+ +
function bar() {
+  console.log(Object.prototype.toString.call(this));
+}
+
+bar.call(7); // [object Number]
+
+ +

The bind method

+ +

ECMAScript 5 introduced Function.prototype.bind. Calling f.bind(someObject) creates a new function with the same body and scope as f, but where this occurs in the original function, in the new function it is permanently bound to the first argument of bind, regardless of how the function is being used.

+ +
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
+
+ +

As a DOM event handler

+ +

When a function is used as an event handler, its this is set to the element the event fired from (some browsers do not follow this convention for listeners added dynamically with methods other than addEventListener).

+ +
// 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);
+}
+ +

In an in–line event handler

+ +

When code is called from an in–line handler, its this is set to the DOM element on which the listener is placed:

+ +
<button onclick="alert(this.tagName.toLowerCase());">
+  Show this
+</button>
+
+ +

The above alert shows button. Note however that only the outer code has its this set this way:

+ +
<button onclick="alert((function(){return this}()));">
+  Show inner this
+</button>
+
+ +

In this case, the inner function's this isn't set so it returns the global/window object (i.e. the default object in non–strict mode where this isn't set by the call).

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-this-keyword', 'The this keyword')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.1.1', 'The this keyword')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-11.1.1', 'The this keyword')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-11.1.1', 'The this keyword')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git "a/files/tr/web/javascript/reference/operat\303\266rler/typeof/index.html" "b/files/tr/web/javascript/reference/operat\303\266rler/typeof/index.html" new file mode 100644 index 0000000000..deccfd8925 --- /dev/null +++ "b/files/tr/web/javascript/reference/operat\303\266rler/typeof/index.html" @@ -0,0 +1,259 @@ +--- +title: typeof +slug: Web/JavaScript/Reference/Operatörler/typeof +translation_of: Web/JavaScript/Reference/Operators/typeof +--- +
{{jsSidebar("Operatörler")}}
+ +

Typeof operatörü, değerlendirilmemiş işlenenin türünü gösteren bir dize döndürür.

+ +
{{EmbedInteractiveExample("pages/js/expressions-typeof.html")}}
+ + + +

Sözdizimi

+ +

The typeof operator is followed by its operand:

+ +
typeof operand
+or
+typeof (operand)
+
+ + + +

Parametreler

+ +

operand is an expression representing the object or {{Glossary("Primitive", "primitive")}} whose type is to be returned.

+ +

Parantez isteğe bağlıdır.

+ +

Description

+ +

The following table summarizes the possible return values of typeof. For more information about types and primitives, see also the JavaScript data structure page.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TypeResult
Undefined"undefined"
Null"object" (see below)
Boolean"boolean"
Number"number"
String"string"
Symbol (new in ECMAScript 2015)"symbol"
Host object (provided by the JS environment)Implementation-dependent
Function object (implements [[Call]] in ECMA-262 terms)"function"
Any other object"object"
+ +

Örnekler

+ +
// 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 Array.isArray 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';
+
+ +

null

+ +
// This stands since the beginning of JavaScript
+typeof null === 'object';
+
+ +

In the first implementation of JavaScript, JavaScript values were represented as a type tag and a value. The type tag for objects was 0. null was represented as the NULL pointer (0x00 in most platforms). Consequently, null had 0 as type tag, hence the bogus typeof return value. (reference)

+ +

A fix was proposed for ECMAScript (via an opt-in), but was rejected. It would have resulted in typeof null === 'null'.

+ +

new operatör kullanımı

+ +
// 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'
+
+ +

Parantezlere ihtiyaç var

+ +
// 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'
+
+
+
+ +

Düzenli İfadeler

+ +

Callable regular expressions were a non-standard addition in some browsers.

+ +
typeof /s/ === 'function'; // Chrome 1-12 Non-conform to ECMAScript 5.1
+typeof /s/ === 'object';   // Firefox 5+  Conform to ECMAScript 5.1
+
+ +

Temporal Dead Zone errors

+ +

Before ECMAScript 2015, typeof was always guaranteed to return a string for any operand it was supplied with. But with the addition of non-hoisted, block-scoped let and const, using typeof on let and const variables in a block before they are declared will throw a ReferenceError. This is in contrast with undeclared variables, for which typeof will return 'undefined'. Block scoped variables are in a "temporal dead zone" from the start of the block until the initialization is processed, during which, it will throw an error if accessed.

+ +
typeof undeclaredVariable === 'undefined';
+typeof newLetVariable; let newLetVariable; // ReferenceError
+typeof newConstVariable; const newConstVariable = 'hello'; // ReferenceError
+
+ +

İstisnalar

+ +

All current browsers expose a non-standard host object {{domxref("document.all")}} with type Undefined.

+ +
typeof document.all === 'undefined';
+
+ +

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 document.all having type tag 'undefined' must be classified as an exceptional violation of the rules.

+ +

Özellikler

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-typeof-operator', 'The typeof Operator')}}{{Spec2('ESDraft')}}
{{SpecName('ES6', '#sec-typeof-operator', 'The typeof Operator')}}{{Spec2('ES6')}}
{{SpecName('ES5.1', '#sec-11.4.3', 'The typeof Operator')}}{{Spec2('ES5.1')}}
{{SpecName('ES3', '#sec-11.4.3', 'The typeof Operator')}}{{Spec2('ES3')}}
{{SpecName('ES1', '#sec-11.4.3', 'The typeof Operator')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
+ +

Browser compatibility

+ + + +

{{Compat("javascript.operators.typeof")}}

+ +

IE özel notlar

+ +

On IE 6, 7, and 8 a lot of host objects are objects and not functions. For example:

+ +
typeof alert === 'object'
+ +

Bakabilirsiniz

+ + 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 +--- +
{{jsSidebar("Statements")}}
+ +

Bir blok statement(ifade) (diğer bir deyişle birleşik ifade) 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")}}:

+ +

Syntax

+ +
[etiket:] {
+  statement_1;
+  statement_2;
+  ...
+  statement_n;
+}
+
+ +
+
statement_1, statement_2, statement_n
+
İfadeler tek bir statement içinde sınırlandırılmıştır.
+
etiket
+
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.")}}.
+
+ +

Açıklama

+ +

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:

+ +
while (x < 10) {
+  x++;
+}
+
+ +

Hatırlatma : statement noktalı virgül ile sonlanmaz.

+ +

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.

+ +

Block Scoping Rules

+ +

With var

+ +

Variables declared with var do not 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:

+ +
var x = 1;
+{
+  var x = 2;
+}
+console.log(x); // logs 2
+
+ +

Burada çıktı 2 oldu çünkü block için ayrı bir scope oluşmamıştır. C ya da Java'da çıktı 1 olur.

+ +

let ve const ile

+ +

Yukarıdakinin aksine {{jsxref("Statements/let", "let")}} ve {{jsxref("Statements/const", "const")}} ayrı bir scope olarak koşacaktır:

+ +
let x = 1;
+{
+  let x = 2;
+}
+console.log(x); // logs 1
+ +

x = 2 sınırlı bir statement içerisinde yer aldığından sadece o statement içerisinde geçerli olacaktır.

+ +

Bu kural const içinde aynıdır:

+ +
const c = 1;
+{
+  const c = 2;
+}
+console.log(c); // logs 1 and does not throw SyntaxError...
+ +

Dikkat edin sınırlı blocktaki  const c = 2  ifadesi SyntaxError: Identifier 'c' zaten tanımlanmış hatası vermedi çünkü, her blok içerisinde benzersiz olarak tanımlanır.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-block', 'Block statement')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-block', 'Block statement')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-12.1', 'Block statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-12.1', 'Block statement')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-12.1', 'Block statement')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + 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 +--- +
{{jsSidebar("Statements")}}
+ +

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.

+ +
{{EmbedInteractiveExample("pages/js/statement-break.html")}}
+ + + +

Syntax

+ +
break [etiket];
+ +
+
etiket
+
İ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.
+
+ +

Description

+ +

The break statement includes an optional label that allows the program to break out of a labeled statement. The break 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.

+ +

Examples

+ +

The following function has a break statement that terminates the {{jsxref("Statements/while", "while")}} loop when i is 3, and then returns the value 3 * x.

+ +
function testBreak(x) {
+  var i = 0;
+
+  while (i < 6) {
+    if (i == 3) {
+      break;
+    }
+    i += 1;
+  }
+
+  return i * x;
+}
+ +

The following code uses break statements with labeled blocks. A break statement must be nested within any label it references. Notice that inner_block is nested within outer_block.

+ +
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
+}
+
+ +

The following code also uses break statements with labeled blocks but generates a Syntax Error because its break statement is within block_1 but references block_2. A break statement must always be nested within any label it references.

+ +
block_1: {
+  console.log('1');
+  break block_2; // SyntaxError: label not found
+}
+
+block_2: {
+  console.log('2');
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Unlabeled version.
{{SpecName('ES3')}}{{Spec2('ES3')}}Labeled version added.
{{SpecName('ES5.1', '#sec-12.8', 'Break statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-break-statement', 'Break statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-break-statement', 'Break statement')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.statements.break")}}

+ +

See also

+ + 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 +--- +
{{jsSidebar("Statements")}}
+ +

170 / 5000

+ +

Çeviri sonuçları

+ +

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.

+ +
{{EmbedInteractiveExample("pages/js/statement-const.html")}}
+ + + +

Syntax

+ +
const name1 = value1 [, name2 = value2 [, ... [, nameN = valueN]]];
+ +
+
nameN
+
The constant's name, which can be any legal {{Glossary("identifier")}}.
+
valueN
+
The constant's value. This can be any legal expression, including a function expression.
+
+ +

 The Destructuring Assignment syntax can also be used to declare variables.

+ +
const { bar } = foo; // where foo = { bar:10, baz:12 };
+/* This creates a constant with the name 'bar', which has a value of 10 */
+ +
+
+ +

Description

+ +

This declaration creates a constant whose scope can be either global or local to the block in which it is declared. Global constants do not become properties of the {{domxref("window")}} object, unlike {{jsxref("Statements/var", "var")}} variables.

+ +

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.)

+ +

The const declaration creates a read-only reference to a value. It does not 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.

+ +

All the considerations about the "temporal dead zone" apply to both {{jsxref("Statements/let", "let")}} and const.

+ +

A constant cannot share its name with a function or a variable in the same scope.

+ +

Examples

+ +

Basic const usage

+ +

Constants can be declared with uppercase or lowercase, but a common convention is to use all-uppercase letters.

+ +
// 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;
+
+
+ +

Block scoping

+ +

It's important to note the nature of block scoping.

+ +
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);
+
+ +

const needs to be initialized

+ +
// throws an error
+// Uncaught SyntaxError: Missing initializer in const declaration
+
+const FOO;
+
+ +

const in objects and arrays

+ +

const also works on objects and arrays.

+ +
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'];
+ +

Specifications

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-let-and-const-declarations', 'Let and Const Declarations')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.statements.const")}}

+ +

See also

+ + 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 +--- +
{{jsSidebar("Statements")}}
+ +

export 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.

+ +
+

Bu özellik şu an için yerel olarak sadece Safari'de uygulanmıştır. Traceur Compiler, Babel veya Rollup gibi bir çok transpiler tarafından da uygulanmaktadır.

+
+ +

Sözdizim

+ +
export { isim1, isim2, …, isimN };
+export { degisken1 as isim1, degisken2 as isim2, …, isimN };
+export let isim1, isim2, …, isimN; // ayrıca var, function
+export let isim1 = …, isim2 = …, …, isimN; // ayrıca var, const
+
+export default ifade;
+export default function (…) { … } // ayrıca class, function*
+export default function isim1(…) { … } // ayrıca class, function*
+export { isim1 as default, … };
+
+export * from …;
+export { isim1, isim2, …, isimN } from …;
+export { import1 as isim1, import2 as isim2, …, isimN } from …;
+ +
+
isimN
+
Dışa aktarılacak belirleyici (böylece {{jsxref("Statements/import", "import")}} kullanılarak diğer programda içe aktarılabilir).
+
+ +

Açıklama

+ +

İki çeşit dışa aktarım vardır. Her biri aşağıdaki sözdizimlerden birine karşılık gelmektedir:

+ + + +

İ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.

+ +

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.

+ +

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:

+ +
export * from …;
+ +

Eğer varsayılanı dışa aktarmak isterseniz, aşağıdakini yazınız:

+ +
import mod from "mod";
+export default mod;
+ +

Örnekler

+ +

İsimlendirilmiş dışa aktarımları kullanmak

+ +

Modül içerisinde, aşağıdaki kodu kullanabiliriz:

+ +
// modül "benim-modulum.js"
+function kup(x) {
+  return x * x * x;
+}
+const deger = Math.PI + Math.SQRT2;
+export { kup, deger };
+
+ +

Bu yolla, başka bir kod içerisinde (karşılaştır import), şunu yapabiliriz:

+ +
import { kup, deger } from 'benim-modulum';
+console.log(kup(3)); // 27
+console.log(deger); // 4.555806215962888
+ +

Varsayılanın dışa aktarımının kullanılması

+ +

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:

+ +
// modül "benim-modulum.js"
+export default function kup(x) {
+  return x * x * x;
+}
+
+ +

Sonra, başka bir kod içerisinde,  varsayılan dışa aktarımı içe aktarmak anlaşılır olacaktır:

+ +
import kup from 'benim-modulum';
+console.log(kup(3)); // 27
+
+ +

Dikkate alınız ki var, let veya const anahtar kelimelerini export default ile kullanamazsınız.

+ +

Spesifikasyonlar

+ + + + + + + + + + + + + + + + + + + +
SpesifikasyonDurumAçıklama
{{SpecName('ES2015', '#sec-exports', 'Exports')}}{{Spec2('ES2015')}}İlk tanım.
{{SpecName('ESDraft', '#sec-exports', 'Exports')}}{{Spec2('ESDraft')}} 
+ +

Tarayıcı uyumluluğu

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
ÖzellikChromeFirefox (Gecko)Internet ExplorerOperaSafari
Temel destek61 (60 w/ flag){{CompatNo}} (54 w/ flag){{CompatNo}} (15 w/flag){{CompatNo}}10.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
ÖzellikAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Temel destek{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}10.3
+
+ +

Ayrıca bakınız

+ + 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 +--- +
{{jsSidebar("Statements")}}
+ +

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.

+ +

Statements and declarations by category

+ +

For an alphabetical listing see the sidebar on the left.

+ +

Control flow

+ +
+
{{jsxref("Statements/block", "Block")}}
+
A block statement is used to group zero or more statements. The block is delimited by a pair of curly brackets.
+
{{jsxref("Statements/break", "break")}}
+
Terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.
+
{{jsxref("Statements/continue", "continue")}}
+
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.
+
{{jsxref("Statements/Empty", "Empty")}}
+
An empty statement is used to provide no statement, although the JavaScript syntax would expect one.
+
{{jsxref("Statements/if...else", "if...else")}}
+
Executes a statement if a specified condition is true. If the condition is false, another statement can be executed.
+
{{jsxref("Statements/switch", "switch")}}
+
Evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.
+
{{jsxref("Statements/throw", "throw")}}
+
Throws a user-defined exception.
+
{{jsxref("Statements/try...catch", "try...catch")}}
+
Marks a block of statements to try, and specifies a response, should an exception be thrown.
+
+ +

Declarations

+ +
+
{{jsxref("Statements/var", "var")}}
+
Declares a variable, optionally initializing it to a value.
+
{{jsxref("Statements/let", "let")}}
+
Declares a block scope local variable, optionally initializing it to a value.
+
{{jsxref("Statements/const", "const")}}
+
Declares a read-only named constant.
+
+ +

Functions and classes

+ +
+
{{jsxref("Statements/function", "function")}}
+
Declares a function with the specified parameters.
+
{{jsxref("Statements/function*", "function*")}}
+
Generators functions enable writing iterators more easily.
+
{{jsxref("Statements/return", "return")}}
+
Specifies the value to be returned by a function.
+
{{jsxref("Statements/class", "class")}}
+
Declares a class.
+
+ +

Iterations

+ +
+
{{jsxref("Statements/do...while", "do...while")}}
+
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.
+
{{jsxref("Statements/for", "for")}}
+
Creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.
+
{{deprecated_inline}} {{non-standard_inline()}} {{jsxref("Statements/for_each...in", "for each...in")}}
+
Iterates a specified variable over all values of object's properties. For each distinct property, a specified statement is executed.
+
{{jsxref("Statements/for...in", "for...in")}}
+
Iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.
+
{{jsxref("Statements/for...of", "for...of")}}
+
Iterates over iterable objects (including {{jsxref("Global_Objects/Array","arrays","","true")}}, array-like objects, iterators and generators), invoking a custom iteration hook with statements to be executed for the value of each distinct property.
+
{{jsxref("Statements/while", "while")}}
+
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.
+
+ +

Others

+ +
+
{{jsxref("Statements/debugger", "debugger")}}
+
Invokes any available debugging functionality. If no debugging functionality is available, this statement has no effect.
+
{{jsxref("Statements/export", "export")}}
+
Used to export functions to make them available for imports in external modules, another scripts.
+
{{jsxref("Statements/import", "import")}}
+
Used to import functions exported from an external module, another script.
+
{{jsxref("Statements/label", "label")}}
+
Provides a statement with an identifier that you can refer to using a break or continue statement.
+
+ +
+
{{deprecated_inline}} {{jsxref("Statements/with", "with")}}
+
Extends the scope chain for a statement.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1', '#sec-12', 'Statements')}}{{Spec2('ES1')}}Initial definition
{{SpecName('ES3', '#sec-12', 'Statements')}}{{Spec2('ES3')}} 
{{SpecName('ES5.1', '#sec-12', 'Statements')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}{{Spec2('ES6')}}New: function*, let, for...of, yield, class
{{SpecName('ESDraft', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}{{Spec2('ESDraft')}} 
+ +

See also

+ + 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 +--- +
{{jsSidebar("Statements")}}
+ +

return komutu fonskiyonun çalışmasını bitirir ve fonksiyondan döndürülecek değeri belirler.

+ +

Sözdizimi

+ +
return [[ifade]]; 
+ +
+
ifade
+
Döndürülecek ifade. Eğer atlanırsa, undefined döndürülür.
+
+ +

Açıklama

+ +

Bir fonksiyonda return 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, undefined döndürülür. Aşağıdaki tüm return komutları çağırıldıkları fonksiyonun çalışmasını durdururlar:

+ +
return;
+return true;
+return false;
+return x;
+return x + y / 3;
+
+ +

Otomatik Noktalı Virgül İlavesi

+ +

return komutu otomatik noktalı virgül ilavesi (ASI)'ne dahildir. return ile ifade aynı satırda olmalıdır. Aksi halde;

+ +
return
+a + b;
+
+ +

ASI tarafıdan aşağıdaki gibi değiştirilir:

+ +
return;
+a + b;
+
+ +

Ve konsol size şu uyarıyı verecektir:"unreachable code after return statement (return komutundan sonra ulaşılamayan kod)".

+ +
 "return komutundan sonra ulaşılamayan kod"  uyarısı Gecko 40 {{geckoRelease(40)}} sürümü ile başlamıştır.
+ +

Örnekler

+ +

Değer döndürme

+ +

Aşağıdaki fonksiyon x argümanının (burada x bir sayıdır), karesini döndürür.

+ +
function square(x) {
+   return x * x;
+}
+
+ +

Fonksiyonu yarıda kesme

+ +

return çağırıldığında, çağırıldığı noktada o fonksiyon anında durur .

+ +
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
+
+ +

Bir fonksiyonu döndürme

+ +

Kapsanımlar hakkındaki şu makaleye de bakınız: Closures.

+ +
function magic(x) {
+  return function calc(x) { return x * 42 };
+}
+
+var answer = magic();
+answer(1337); // 56154
+
+ +

Özellikler

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ÖzellikDurumAçıklama
{{SpecName('ES1')}}{{Spec2('ES1')}}Ön-tanımlı.
{{SpecName('ES5.1', '#sec-12.9', 'Return statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-return-statement', 'Return statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-return-statement', 'Return statement')}}{{Spec2('ESDraft')}} 
+ +

Tarayıcı Uyumluluğu

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
ÖzellikChromeFirefox (Gecko)Internet ExplorerOperaSafari
Temel destek{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
ÖzellikAndroidAndroid için ChromeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Temel destek{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ayrıca Bakınız

+ + 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 +--- +
{{jsSidebar("Statements")}}
+ +

Throw 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.

+ +
{{EmbedInteractiveExample("pages/js/statement-throw.html")}}
+ + + +

Syntax

+ +
throw ifade; 
+ +
+
ifade
+
Hata fırlatmak için ifade.
+
+ +

Açıklama

+ +

Bir hata fırlatmak için throw ifadesini kullanın. Bir hata fırlatırken, ifade hatanın değerini belirtir. Aşağıdakilerin her biri bir hata fırlatır:

+ +
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.
+
+ +

Also note that the throw statement is affected by automatic semicolon insertion (ASI) as no line terminator between the throw keyword and the expression is allowed.

+ +

Örnek

+ +

İstisna Nesnesi Örneği

+ +

Bir istisna atarken bir nesne belirtebilirsiniz. Daha sonra nesnenin özelliklerini catch bloğuna referansta bulabilirsiniz. Aşağıdaki örnek, UserException türünde bir nesne oluşturur ve bunu bir throw ifadesinde kullanır.

+ +
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.
+}
+
+ +

Bir istisnayı atmanın başka bir örneği

+ +

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 .

+ +

​​​​​​ZipCodeFormatException.

+ +
/*
+ * 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
+
+ +

Bir istisnayı tekrar atmak

+ +

Hatayı yakaladıktan sonra bir özel durumu geri almak için throw kullanabilirsiniz. Aşağıdaki örnek,

+ +

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..

+ +
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;
+   }
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}} +

Başlangıç

+ +

Javascript 1.4

+
{{SpecName('ES5.1', '#sec-12.13', 'throw statement')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-throw-statement', 'throw statement')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-throw-statement', 'throw statement')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.statements.throw")}}

+ +

See also

+ + 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 +--- +
{{jsSidebar("Statements")}}
+ +

while ifadesi 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.

+ +
{{EmbedInteractiveExample("pages/js/statement-while.html")}}
+ + + +

Sözdizimi (Syntax)

+ +
while (condition)
+  statement
+
+ +
+
condition
+
Döngüdeki her bir tekrarlamadan önce kontrol edilen koşul. Eğer koşul sağlanıyorsa (true) statement çalıştırılır. Ancak koşul sağlanmıyorsa (false) statement çalıştırılmaz ve while döngüsünden sonra yazılan kod bloğu ile program çalışmaya devam eder.
+
statement
+
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 block ({ ... }) ifade şeklini kullanabilirsiniz. 
+

+ Not: break ifadesini kullanarak döngüyü dilediğiniz zaman sonlandırabilirsiniz.
+
+ +

Örnekler

+ +

while kullanımı

+ +

Aşağıdaki örnekte bulunan (n < 3) ifadesi while döngüsünün koşulu yani condition kısmıdır. Süslü parantezler içerisinde bulunan kısım ise çalıştırılacak olan kod bloğu yani statement kısmıdır. Dolayısıyla aşağıdaki while döngüsü, n değişkeninin değeri üçten küçük olduğu sürece çalışmaya devam eder.

+ +
var n = 0;
+var x = 0;
+
+while (n < 3) {
+  n++;
+  x += n;
+}
+ +

Her tekrarlamada, döngü n değişkeninin değerini bir arttırır. Ardından n değişkeninin değerini x değişkeninin değerine ekler. Dolayısıyla, x ve n değişkenleri aşağıdaki değerlere sahip olurlar:

+ + + +

Üçüncü tekrardan sonra, n < 3 koşulu artık sağlanmadığı için döngü sonlanır.

+ +

Özellikler

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-while-statement', 'while statement')}}
+ +

Tarayıcı uyumluluğu

+ + + +

{{Compat("javascript.statements.while")}}

+ +

Ayrıca bakınız

+ + 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 +--- +
{{JsSidebar("More")}}
+ +
Sometimes you'll see the default, non-strict mode referred to as "sloppy mode". This isn't an official term, but be aware of it, just in case.
+ +

JavaScript's strict mode, introduced in ECMAScript 5, is a way to opt in to a restricted variant of JavaScript, thereby implicitly opting-out of "sloppy mode". Strict mode isn't just a subset: it intentionally 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.

+ +

Strict mode makes several changes to normal JavaScript semantics:

+ +
    +
  1. Eliminates some JavaScript silent errors by changing them to throw errors.
  2. +
  3. 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.
  4. +
  5. Prohibits some syntax likely to be defined in future versions of ECMAScript.
  6. +
+ +

See transitioning to strict mode, if you want to change your code to work in the restricted variant of JavaScript.

+ +

Invoking strict mode

+ +

Strict mode applies to entire scripts or to individual functions. It doesn't apply to block statements enclosed in {} braces; attempting to apply it to such contexts does nothing. eval code, Function code, event handler attributes, strings passed to WindowTimers.setTimeout(), and related functions are entire scripts, and invoking strict mode in them works as expected.

+ +

Strict mode for scripts

+ +

To invoke strict mode for an entire script, put the exact statement "use strict"; (or 'use strict';) before any other statements.

+ +
// Whole-script strict mode syntax
+'use strict';
+var v = "Hi! I'm a strict mode script!";
+
+ +

This syntax has a trap that has already bitten a major site: 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.

+ +

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.

+ +

Strict mode for functions

+ +

Likewise, to invoke strict mode for a function, put the exact statement "use strict"; (or 'use strict';) in the function's body before any other statements.

+ +
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."; }
+
+ +

Strict mode for modules

+ +

ECMAScript 2015 introduced JavaScript modules 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.

+ +
function strict() {
+    // because this is a module, I'm strict by default
+}
+export default strict;
+
+ +

Changes in strict mode

+ +

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 eval and arguments, changes making it easier to write "secure" JavaScript, and changes anticipating future ECMAScript evolution.

+ +

Converting mistakes into errors

+ +

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.

+ +

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:

+ +
'use strict';
+                       // Assuming no global variable mistypedVariable exists
+mistypeVariable = 17;  // this line throws a ReferenceError due to the
+                       // misspelling of variable
+
+ +

Second, strict mode makes assignments which would otherwise silently fail to throw an exception. For example, NaN is a non-writable global variable. In normal code assigning to NaN does nothing; the developer receives no failure feedback. In strict mode assigning to NaN 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 non-extensible object) will throw in strict mode:

+ +
'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
+
+ +

Third, strict mode makes attempts to delete undeletable properties throw (where before the attempt would simply have no effect):

+ +
'use strict';
+delete Object.prototype; // throws a TypeError
+
+ +

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:

+ +
+

This is no longer the case in ECMAScript 2015 (bug 1041128).

+
+ +
'use strict';
+var o = { p: 1, p: 2 }; // !!! syntax error
+
+ +

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 arguments[i], 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:

+ +
function sum(a, a, c) { // !!! syntax error
+  'use strict';
+  return a + a + c; // wrong if this code ran
+}
+
+ +

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: 0644 === 420 and "\045" === "%". In ECMAScript 2015 Octal number is supported by prefixing a number with "0o". i.e. 

+ +
var a = 0o10; // ES2015: Octal
+ +

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:

+ +
'use strict';
+var sum = 015 + // !!! syntax error
+          197 +
+          142;
+
+var sumWithOctal = 0o10 + 8;
+console.log(sumWithOctal); // 16
+
+ +

Seventh, strict mode in ECMAScript 2015 forbids setting properties on primitive values. Without strict mode, setting properties is simply ignored (no-op), with strict mode, however, a {{jsxref("TypeError")}} is thrown.

+ +
(function() {
+'use strict';
+
+false.true = '';         // TypeError
+(14).sailing = 'home';   // TypeError
+'with'.you = 'far away'; // TypeError
+
+})();
+ +

Simplifying variable uses

+ +

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 X is stored in that 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.

+ +

First, strict mode prohibits with. The problem with with 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 with a syntax error, so there's no chance for a name in a with to refer to an unknown location at runtime:

+ +
'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;
+}
+
+ +

The simple alternative of assigning the object to a short name variable, then accessing the corresponding property on that variable, stands ready to replace with.

+ +

Second, eval of strict mode code does not introduce new variables into the surrounding scope. In normal code eval("var x;") introduces a variable x into the surrounding function or the global scope. This means that, in general, in a function containing a call to eval every name not referring to an argument or local variable must be mapped to a particular definition at runtime (because that eval might have introduced a new variable that would hide the outer variable). In strict mode eval creates variables only for the code being evaluated, so eval can't affect whether a name refers to an outer variable or some local variable:

+ +
var x = 17;
+var evalX = eval("'use strict'; var x = 42; x;");
+console.assert(x === 17);
+console.assert(evalX === 42);
+
+ +

If the function eval is invoked by an expression of the form eval(...) 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.

+ +
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!'");
+
+ +

Thus names in strict mode eval code behave identically to names in strict mode code not being evaluated as the result of eval.

+ +

Third, strict mode forbids deleting plain names. delete name in strict mode is a syntax error:

+ +
'use strict';
+
+var x;
+delete x; // !!! syntax error
+
+eval('var y; delete y;'); // !!! syntax error
+ +

Making eval and arguments simpler

+ +

Strict mode makes arguments and eval less bizarrely magical. Both involve a considerable amount of magical behavior in normal code: eval to add or remove bindings and to change binding values, and arguments by its indexed properties aliasing named arguments. Strict mode makes great strides toward treating eval and arguments as keywords, although full fixes will not come until a future edition of ECMAScript.

+ +

First, the names eval and arguments can't be bound or assigned in language syntax. All these attempts to do so are syntax errors:

+ +
'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;");
+
+ +

Second, strict mode code doesn't alias properties of arguments objects created within it. In normal code within a function whose first argument is arg, setting arg also sets arguments[0], and vice versa (unless no arguments were provided or arguments[0] is deleted). arguments objects for strict mode functions store the original arguments when the function was invoked. arguments[i] does not track the value of the corresponding named argument, nor does a named argument track the value in the corresponding arguments[i].

+ +
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);
+
+ +

Third, arguments.callee is no longer supported. In normal code arguments.callee refers to the enclosing function. This use case is weak: simply name the enclosing function! Moreover, arguments.callee substantially hinders optimizations like inlining functions, because it must be made possible to provide a reference to the un-inlined function if arguments.callee is accessed. arguments.callee for strict mode functions is a non-deletable property which throws an error when set or retrieved:

+ +
'use strict';
+var f = function() { return arguments.callee; };
+f(); // throws a TypeError
+
+ +

"Securing" JavaScript

+ +

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 on behalf of other users. 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.

+ +

First, the value passed as this to a function in strict mode is not forced into being an object (a.k.a. "boxed"). For a normal function, this is always an object: either the provided object if called with an object-valued this; the value, boxed, if called with a Boolean, string, or number this; or the global object if called with an undefined or null this. (Use call, apply, or bind to specify a particular this.) 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 this is not boxed into an object, and if unspecified, this will be undefined:

+ +
'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);
+
+ +

That means, among other things, that in browsers it's no longer possible to reference the window object through this inside a strict mode function.

+ +

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 fun is in the middle of being called, fun.caller is the function that most recently called fun, and fun.arguments is the arguments for that invocation of fun. Both extensions are problematic for "secure" JavaScript because they allow "secured" code to access "privileged" functions and their (potentially unsecured) arguments. If fun is in strict mode, both fun.caller and fun.arguments are non-deletable properties which throw when set or retrieved:

+ +
function restricted() {
+  'use strict';
+  restricted.caller;    // throws a TypeError
+  restricted.arguments; // throws a TypeError
+}
+function privilegedInvoker() {
+  return restricted();
+}
+privilegedInvoker();
+
+ +

Third, arguments for strict mode functions no longer provide access to the corresponding function call's variables. In some old ECMAScript implementations arguments.caller was an object whose properties aliased variables in that function. This is a security hazard 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, arguments.caller for a strict mode function is also a non-deletable property which throws when set or retrieved:

+ +
'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)
+
+ +

Paving the way for future ECMAScript versions

+ +

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.

+ +

First, in strict mode, a short list of identifiers become reserved keywords. These words are implements, interface, let, package, private, protected, public, static, and yield. In strict mode, then, you can't name or use variables or arguments with these names.

+ +
function package(protected) { // !!!
+  'use strict';
+  var implements; // !!!
+
+  interface: // !!!
+  while (true) {
+    break interface; // !!!
+  }
+
+  function private() { } // !!!
+}
+function fun(static) { 'use strict'; } // !!!
+
+
+ +

Two Mozilla-specific caveats: First, if your code is JavaScript 1.7 or greater (for example in chrome code or when using the right <script type="">) and is strict mode code, let and yield have the functionality they've had since those keywords were first introduced. But strict mode code on the web, loaded with <script src=""> or <script>...</script>, won't be able to use let/yield as identifiers. Second, while ES5 unconditionally reserves the words class, enum, export, extends, import, and super, before Firefox 5 Mozilla reserved them only in strict mode.

+ +

Second, strict mode prohibits function statements, not at the top level of a script or function. In normal mode in browsers, function statements are permitted "everywhere". This is not part of ES5 (or even ES3)! It's an extension with incompatible semantics in different browsers. Note that function statements outside top level are permitted in ES2015.

+ +
'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
+}
+
+ +

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.

+ +

Strict mode in browsers

+ +

The major browsers now implement strict mode. However, don't blindly depend on it since there still are numerous Browser versions used in the wild that only have partial support for strict mode or do not support it at all (e.g. Internet Explorer below version 10!). Strict mode changes semantics. 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 test your code in browsers that do and don't support strict mode. 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.

+ +

Specifications

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-strict-mode-code', 'Strict Mode Code')}}
+ +

See also

+ + -- cgit v1.2.3-54-g00ecf