From 95aca4b4d8fa62815d4bd412fff1a364f842814a Mon Sep 17 00:00:00 2001 From: Ryan Johnson Date: Thu, 29 Apr 2021 16:16:42 -0700 Subject: remove retired locales (#699) --- files/id/web/javascript/reference/about/index.html | 86 --- .../reference/classes/constructor/index.html | 162 ----- .../reference/classes/extends/index.html | 112 ---- .../id/web/javascript/reference/classes/index.html | 383 ------------ .../errors/called_on_incompatible_type/index.html | 69 --- .../id/web/javascript/reference/errors/index.html | 12 - .../errors/invalid_array_length/index.html | 78 --- .../missing_semicolon_before_statement/index.html | 78 --- .../errors/negative_repetition_count/index.html | 45 -- .../reference/errors/not_a_codepoint/index.html | 56 -- .../reference/errors/not_defined/index.html | 66 -- .../errors/property_access_denied/index.html | 47 -- .../reference/errors/too_much_recursion/index.html | 70 --- .../web/javascript/reference/functions/index.html | 596 ------------------ .../global_objects/array/concat/index.html | 169 ------ .../global_objects/array/filter/index.html | 244 -------- .../reference/global_objects/array/from/index.html | 248 -------- .../reference/global_objects/array/index.html | 484 --------------- .../global_objects/array/isarray/index.html | 144 ----- .../reference/global_objects/array/join/index.html | 132 ---- .../global_objects/array/length/index.html | 145 ----- .../reference/global_objects/array/of/index.html | 129 ---- .../reference/global_objects/array/pop/index.html | 134 ----- .../global_objects/array/reverse/index.html | 127 ---- .../global_objects/array/shift/index.html | 129 ---- .../global_objects/array/slice/index.html | 152 ----- .../global_objects/array/splice/index.html | 146 ----- .../global_objects/array/unshift/index.html | 135 ----- .../global_objects/array/values/index.html | 120 ---- .../global_objects/date/getfullyear/index.html | 88 --- .../reference/global_objects/date/index.html | 261 -------- .../reference/global_objects/date/now/index.html | 124 ---- .../global_objects/date/tojson/index.html | 119 ---- .../global_objects/date/totimestring/index.html | 125 ---- .../reference/global_objects/error/index.html | 231 ------- .../reference/global_objects/error/name/index.html | 119 ---- .../global_objects/function/displayname/index.html | 123 ---- .../reference/global_objects/function/index.html | 241 -------- .../global_objects/function/length/index.html | 148 ----- .../global_objects/function/name/index.html | 191 ------ .../javascript/reference/global_objects/index.html | 189 ------ .../reference/global_objects/isnan/index.html | 186 ------ .../reference/global_objects/json/index.html | 243 -------- .../reference/global_objects/json/parse/index.html | 171 ------ .../reference/global_objects/map/clear/index.html | 109 ---- .../reference/global_objects/map/delete/index.html | 114 ---- .../reference/global_objects/map/index.html | 443 -------------- .../reference/global_objects/math/abs/index.html | 145 ----- .../reference/global_objects/math/ceil/index.html | 174 ------ .../reference/global_objects/math/e/index.html | 81 --- .../reference/global_objects/math/floor/index.html | 210 ------- .../reference/global_objects/math/index.html | 213 ------- .../reference/global_objects/math/ln10/index.html | 81 --- .../reference/global_objects/math/max/index.html | 144 ----- .../reference/global_objects/math/min/index.html | 150 ----- .../reference/global_objects/math/pow/index.html | 53 -- .../object/getprototypeof/index.html | 133 ---- .../reference/global_objects/object/index.html | 221 ------- .../global_objects/object/keys/index.html | 197 ------ .../object/preventextensions/index.html | 185 ------ .../global_objects/promise/catch/index.html | 127 ---- .../reference/global_objects/promise/index.html | 317 ---------- .../global_objects/promise/reject/index.html | 81 --- .../global_objects/promise/resolve/index.html | 140 ----- .../global_objects/promise/then/index.html | 132 ---- .../reference/global_objects/regexp/index.html | 231 ------- .../global_objects/string/charat/index.html | 238 -------- .../global_objects/string/concat/index.html | 134 ----- .../global_objects/string/fromcharcode/index.html | 143 ----- .../global_objects/string/fromcodepoint/index.html | 149 ----- .../reference/global_objects/string/index.html | 371 ------------ .../global_objects/string/indexof/index.html | 190 ------ .../global_objects/string/length/index.html | 126 ---- .../global_objects/string/link/index.html | 130 ---- .../global_objects/string/split/index.html | 241 -------- .../global_objects/string/tolowercase/index.html | 121 ---- .../global_objects/string/tostring/index.html | 118 ---- .../global_objects/string/touppercase/index.html | 115 ---- .../reference/global_objects/typedarray/index.html | 344 ----------- .../global_objects/typedarray/join/index.html | 114 ---- files/id/web/javascript/reference/index.html | 48 -- .../reference/lexical_grammar/index.html | 670 --------------------- .../operators/conditional_operator/index.html | 167 ----- .../reference/operators/function/index.html | 154 ----- .../web/javascript/reference/operators/index.html | 269 --------- .../reference/operators/yield/index.html | 109 ---- .../reference/statements/class/index.html | 171 ------ .../reference/statements/do...while/index.html | 101 ---- .../reference/statements/empty/index.html | 147 ----- .../reference/statements/export/index.html | 171 ------ .../reference/statements/for...in/index.html | 201 ------- .../reference/statements/function/index.html | 233 ------- .../web/javascript/reference/statements/index.html | 139 ----- 93 files changed, 15852 deletions(-) delete mode 100644 files/id/web/javascript/reference/about/index.html delete mode 100644 files/id/web/javascript/reference/classes/constructor/index.html delete mode 100644 files/id/web/javascript/reference/classes/extends/index.html delete mode 100644 files/id/web/javascript/reference/classes/index.html delete mode 100644 files/id/web/javascript/reference/errors/called_on_incompatible_type/index.html delete mode 100644 files/id/web/javascript/reference/errors/index.html delete mode 100644 files/id/web/javascript/reference/errors/invalid_array_length/index.html delete mode 100644 files/id/web/javascript/reference/errors/missing_semicolon_before_statement/index.html delete mode 100644 files/id/web/javascript/reference/errors/negative_repetition_count/index.html delete mode 100644 files/id/web/javascript/reference/errors/not_a_codepoint/index.html delete mode 100644 files/id/web/javascript/reference/errors/not_defined/index.html delete mode 100644 files/id/web/javascript/reference/errors/property_access_denied/index.html delete mode 100644 files/id/web/javascript/reference/errors/too_much_recursion/index.html delete mode 100644 files/id/web/javascript/reference/functions/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/concat/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/filter/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/from/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/isarray/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/join/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/length/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/of/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/pop/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/reverse/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/shift/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/slice/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/splice/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/unshift/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/values/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/date/getfullyear/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/date/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/date/now/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/date/tojson/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/date/totimestring/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/error/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/error/name/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/function/displayname/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/function/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/function/length/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/function/name/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/isnan/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/json/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/json/parse/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/map/clear/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/map/delete/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/map/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/math/abs/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/math/ceil/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/math/e/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/math/floor/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/math/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/math/ln10/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/math/max/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/math/min/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/math/pow/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/object/getprototypeof/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/object/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/object/keys/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/object/preventextensions/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/promise/catch/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/promise/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/promise/reject/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/promise/resolve/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/promise/then/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/regexp/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/charat/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/concat/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/fromcharcode/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/fromcodepoint/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/indexof/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/length/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/link/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/split/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/tolowercase/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/tostring/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/touppercase/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/typedarray/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/typedarray/join/index.html delete mode 100644 files/id/web/javascript/reference/index.html delete mode 100644 files/id/web/javascript/reference/lexical_grammar/index.html delete mode 100644 files/id/web/javascript/reference/operators/conditional_operator/index.html delete mode 100644 files/id/web/javascript/reference/operators/function/index.html delete mode 100644 files/id/web/javascript/reference/operators/index.html delete mode 100644 files/id/web/javascript/reference/operators/yield/index.html delete mode 100644 files/id/web/javascript/reference/statements/class/index.html delete mode 100644 files/id/web/javascript/reference/statements/do...while/index.html delete mode 100644 files/id/web/javascript/reference/statements/empty/index.html delete mode 100644 files/id/web/javascript/reference/statements/export/index.html delete mode 100644 files/id/web/javascript/reference/statements/for...in/index.html delete mode 100644 files/id/web/javascript/reference/statements/function/index.html delete mode 100644 files/id/web/javascript/reference/statements/index.html (limited to 'files/id/web/javascript/reference') diff --git a/files/id/web/javascript/reference/about/index.html b/files/id/web/javascript/reference/about/index.html deleted file mode 100644 index 02c6ef967c..0000000000 --- a/files/id/web/javascript/reference/about/index.html +++ /dev/null @@ -1,86 +0,0 @@ ---- -title: Mengenai Pustaka Ini -slug: Web/JavaScript/Reference/About -tags: - - JavaScript -translation_of: Web/JavaScript/Reference/About ---- -

Apa yang perlu diketahui sebelumnya

- -

Pengalaman menggunakan bahasa pemrograman lainnya dapat menjadi manfaat, meskipun tidak menjadi prasyarat.

- -

JavaScript ditujukan untuk digunakan pada lingkup yang lebih besar, seperti peramban, script server-side, atau sejenisnya. Secara umum, pustaka ini tergantung pada platform tertentu, dan tidak ditujukan hanya untuk peramban.

- -

Untuk tujuan demo, pustakan ini menggunakan fungsi, println. Fungsi tersebut bukanlah bagian dari JavaScript. Namun ia dapat dipetakan terhadap implementasi spesifik pada platform tertentu.

- -

Misal, bila berjalan di peramban, maka fungsi di atas dapat implementasikan sebagai:

- -
-
function println(string) {
-  window.alert(string);
-}
-
- -

 

-
- -

Sejarah JavaScript

- -

Versi terbaru dari peramban berbasis Mozilla mendukung versi terbaru dari JavaScript. Tabel berikut menampilkan daftar dari versi JavaScript yang didukung oleh versi yang berbeda dari peramban berbasis Mozilla.

- -

Peramban yang tidak mendukung versi JavaScript setidaknya versi 1.5 adalah hal yang sangat langka untuk saat ini. JavaScript versi 1.5 sudah dipublikasikan sejak tahun 1999. Bila Anda tertarik untuk mempelajari sejarahnya, silahkan mengunjungi referensi yang terdapat di Wikipedia, ECMAScript.

- -

JavaScript/Browser support history

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
JavaScript (SpiderMonkey) versionMozilla releaseGecko version
JavaScript 1.5Navigator 6.0, Mozilla Application Suite, Firefox 1.0Gecko 0.6x-1.7
JavaScript 1.6Firefox 1.5Gecko 1.8
JavaScript 1.7Firefox 2Gecko 1.8.1
JavaScript 1.8Firefox 3Gecko 1.9
JavaScript 1.8.5Firefox 4Gecko 2.0
JavaScript 1.8.6Firefox 17Gecko 17
- -

Sumber informasi JavaScript

- -

Dokumentasi JavaScript dari fitur bahasa inti (murni ECMAScript, untuk sebagian besar) mencakup:

- - - -

Bila Anda masih baru terhadap JavaScript, mulailah dari pedoman. Bila kemudian Anda sudah merasa memiliki pemahaman yang lebih mendalam, Anda dapat memanfaatkan referensi.

diff --git a/files/id/web/javascript/reference/classes/constructor/index.html b/files/id/web/javascript/reference/classes/constructor/index.html deleted file mode 100644 index 8da1df9428..0000000000 --- a/files/id/web/javascript/reference/classes/constructor/index.html +++ /dev/null @@ -1,162 +0,0 @@ ---- -title: constructor -slug: Web/JavaScript/Reference/Classes/constructor -translation_of: Web/JavaScript/Reference/Classes/constructor ---- -
{{jsSidebar("Classes")}}
- -

Metode dengan nama "constructor" adalah metode spesial untuk pembuatan dan penginisialisasian objek yang dibuat dengan kelas.

- -

sintaks

- -
constructor([arguments]) { ... }
- -

Deskripsi

- -

Hanya boleh ada satu metode spesial dengan nama "constructor" dalam sebuah kelas. {{jsxref("SyntaxError")}}  akan dilemparkan jika suatu kelas memiliki lebih dari satu metode konstruktor.

- -

Konstruktor dapat menggunakan kata kunci {{jsxref("Operators/super", "super")}} untuk memanggil konstruktor orang-tua.

- -

Jika metode konstruktor tidak didefinisikan dalam sebuah kelas, maka  kontruktor asali yang akan digunakan.

- -

Contoh

- -

Menggunakan metode constructor

- -

Potongan kode ini diambil dari contoh kelas (demostrasi langsung).

- -
class Square extends Polygon {
-  constructor(length) {
-    // Di sini, akan memanggil konstruktor orang-tua dengan panjang
-    // diberikan untuk panjang dan tinggi Polygon
-    super(length, length);
-    // Catatan: di kelas turunan, super() harus dipanggil sebelum
-    // bisa menggunakan kata kunci 'this'. Meninggalkan pemanggilan ini di awal
-    // akan menyebabkan kesalahan referensi.
-    this.name = 'Square';
-  }
-
-  get area() {
-    return this.height * this.width;
-  }
-
-  set area(value) {
-    this.area = value;
-  }
-}
- -

Konstruktor asali

- -

Jika metode konstruktor tidak didefinisikan dalam sebuah kelas, maka kontruktor asali yang akan digunakan. Untuk konstruktor asali untuk kelas dasar adalah:

- -
constructor() {}
-
- -

Konstruktor asali untuk kelas turunan adalah:

- -
constructor(...args) {
-  super(...args);
-}
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-static-semantics-constructormethod', 'Constructor Method')}}{{Spec2('ES6')}}Definisi awal
{{SpecName('ESDraft', '#sec-static-semantics-constructormethod', 'Constructor Method')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas Peramban

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(42.0)}}{{CompatGeckoDesktop(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Default constructors{{CompatUnknown}}{{CompatGeckoDesktop(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(42.0)}}{{CompatGeckoMobile(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(42.0)}}
Default constructors{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

Lihat Pula

- - diff --git a/files/id/web/javascript/reference/classes/extends/index.html b/files/id/web/javascript/reference/classes/extends/index.html deleted file mode 100644 index c6def454fe..0000000000 --- a/files/id/web/javascript/reference/classes/extends/index.html +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: extends -slug: Web/JavaScript/Reference/Classes/extends -tags: - - ECMAScript 2015 - - JavaScript - - Kelas -translation_of: Web/JavaScript/Reference/Classes/extends ---- -
{{jsSidebar("Classes")}}
- -

Kata kunci extends digunakan pada class declarations atau class expressions untuk membuat sebuah class yang merupakan turunan dari class lain.

- -
{{EmbedInteractiveExample("pages/js/classes-extends.html", "taller")}}
- - - -

Sintaks

- -
class ChildClass extends ParentClass { ... }
- -

Deskripsi

- -

Kata kunci extends dapat digunakan untuk subclass custom classes dan built-in objects.

- -

.prototype dari suatu ekstensi harus berupa sebuah {{jsxref("Object")}} atau {{jsxref("null")}}.

- -

Contoh

- -

Menggunakan extends

- -

Contoh pertama membuat sebuah class bernama Square dari kelas bernama Polygon. Contoh ini diambil dari live demo (source).

- -
class Square extends Polygon {
-  constructor(length) {
-    // Disini, obyek dari Square memanggil konstruktor dari parent class dengan argumen lengths yang tersedia
-    // untuk width dan height pada Polygon
-    super(length, length);
-    // Catatan: Pada kelas turunan, super() harus dipanggil sebelum Anda
-    // dapat menggunakan 'this'. Pengabaian terhadap hal tersebut akan menyebabkan reference error.
-    this.name = 'Square';
-  }
-
-  get area() {
-    return this.height * this.width;
-  }
-}
- -

Menggunakan extends dengan built-in objects

- -

Contoh berikut mewarisi built-in {{jsxref("Date")}} object. Contoh ini diambil dari live demo (source).

- -
class myDate extends Date {
-  constructor() {
-    super();
-  }
-
-  getFormattedDate() {
-    var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
-    return this.getDate() + '-' + months[this.getMonth()] + '-' + this.getFullYear();
-  }
-}
- -

Extending (Pewarisan) null

- -

Extending/pewarisan dari {{jsxref("null")}} bekerja layaknya seperti normal class, dengan pengecualian prototype object tidak mewarisi dari {{jsxref("Object.prototype")}}.

- -
class nullExtends extends null {
-  constructor() {}
-}
-
-Object.getPrototypeOf(nullExtends); // Function.prototype
-Object.getPrototypeOf(nullExtends.prototype) // null
-
-new nullExtends(); //ReferenceError: this is not defined
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ES2015', '#sec-class-definitions', 'extends')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-class-definitions', 'extends')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas peramban

- - - -

{{Compat("javascript.classes.extends")}}

- -

Cek juga

- - diff --git a/files/id/web/javascript/reference/classes/index.html b/files/id/web/javascript/reference/classes/index.html deleted file mode 100644 index 3a8a71f562..0000000000 --- a/files/id/web/javascript/reference/classes/index.html +++ /dev/null @@ -1,383 +0,0 @@ ---- -title: Classes -slug: Web/JavaScript/Reference/Classes -tags: - - Classes - - Constructors - - ECMAScript6 - - Inheritance - - Intermediate - - JavaScript - - NeedsTranslation - - TopicStub -translation_of: Web/JavaScript/Reference/Classes ---- -
{{JsSidebar("Classes")}}
- -

Kelas di JavaScript diperkenalkan pada ECMAScript 6 seperti pemanis dari prototype-based JavaScript yang sudah ada. Syntax dari kelas tidak menggunakan model object-oriented inheritance yang baru. JavaScript kelas menyediakan syntax yang lebih sederhana dan rapi untuk membuat object-object dan mengatasi / dealing dengan turunan / inheritance.

- -

Definisi kelas

- -

Kelas seperti "fungsi istimewa", dan seperti kamu bisa mendeklarasikan ekspresi fungsi (function expressions) dan deklarasi fungsi (function declarations), syntax kelas sendiri mempunyai dua komponen: ekspresi kelas (class expressions) dan deklarasi kelas (class declarations).

- -

Deklarasi Kelas

- -

Salah satu cara untuk mendefinisikan kelas adalah dengan menggunakan class declaration / deklarasi kelas. Untuk mendeklarasikan kelas, kamu bisa menggunakan kata kunci class sebagai contoh class "Polygon" di bawah ini.

- -
class Polygon {
-  constructor(height, width) {
-    this.height = height;
-    this.width = width;
-  }
-}
- -

Hoisting

- -

Perbedaan penting antara deklarasi fungsi (function declarations) dan deklarasi kelas (class declarations) adalah deklarasi fungsi  {{Glossary("Hoisting", "hoisted")}} dan  deklarasi class tidak. Pertama-tama kamu harus mendeklarasikan kelas dan mengaksesnya, jika tidak maka kode seperti berikut akan menampilkan {{jsxref("ReferenceError")}}:

- -
var p = new Polygon(); // ReferenceError
-
-class Polygon {}
-
- -

Ekspresi Kelas

- -

Ekspresi kelas (class expression) adalah cara lain untuk mendefinisikan sebuah class. Class expression bisa bernama ataupun tidak. Nama yang diberikan berbentuk lokal berada di body class.

- -
// unnamed
-var Polygon = class {
-  constructor(height, width) {
-    this.height = height;
-    this.width = width;
-  }
-};
-
-// named
-var Polygon = class Polygon {
-  constructor(height, width) {
-    this.height = height;
-    this.width = width;
-  }
-};
-
- -

Catatan: Ekspresi kelas (Class expressions) juga mempunyai masalah yang sama terkait hoisting seperti pada Deklarasi kelas (Class declarations).

- -

Tubuh Kelas (class body) and definisi metode

- -

Tubuh atau body sebuah kelas berada didalam kurung {}. Disitu kamu dapat mendefinisikan isi kelas seperti method atau konstruktor.

- -

Strict mode

- -

Body atau bagian badan dari kelas deklarasi dan kelas ekspresi di eksekusi pada strict mode.

- -

Konstruktor

- -

konstruktor adalah metode (method) khusus untuk membuat dan inisialisasi sebuah objek yang dibuat dengan  class. Hanya ada satu metode khusus dengan nama "konstruktor" di kelas. Sebuah {{jsxref("SyntaxError")}} akan tampil jika kelas berisi lebih dari satu method constructor.

- -

Sebuah konstruktor dapat digunakan keyword super untuk memanggil kostruktor dari kelas parent nya.

- -

Prototipe method

- -

Lihat juga definisi method

- -
class Polygon {
-  constructor(height, width) {
-    this.height = height;
-    this.width = width;
-  }
-
-  get area() {
-    return this.calcArea();
-  }
-
-  calcArea() {
-    return this.height * this.width;
-  }
-}
-
-const square = new Polygon(10, 10);
-
-console.log(square.area);
- -

Metode Statis

- -

Kata kunci statis mendefinisikan metode statis untuk suatu kelas. Metode statis dipanggil tanpa membuat instance kelasnya dan tidak bisa dipanggil ketika kelas tersebut dipakai. Metode statis sering digunakan untuk membuat fungsi utilitas untuk suatu aplikasi.

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

Mem-binding this dengan prototipe dan metode statis

- -

Ketika metode statis atau prototipe dipanggil tanpa objek yang bernilai "this" (atau "this" sebagai boolean, string, angka, tidak terdefinisi atau null), maka nilai "this" akan ditentukan dalam fungsi yang digunakan. Autoboxing tidak akan berjalan. Hal tersebut juga berlaku ketika kita menulis kode dalam mode non-strict.laku akan sama bahkan jika kita menulis kode dalam mode tidak ketat.

- -
class Animal {
-  speak() {
-    return this;
-  }
-  static eat() {
-    return this;
-  }
-}
-
-let obj = new Animal();
-let speak = obj.speak;
-speak(); // undefined
-
-let eat = Animal.eat;
-eat(); // undefined
- -

Jika kita menulis kode diatas menggunakan fungsi tradisional berdasarkan kelas, maka autoboxing akan berjalan sesuai dengan nilai "this" pada fungsi yang dipanggil.

- -
function Animal() { }
-
-Animal.prototype.speak = function(){
-  return this;
-}
-
-Animal.eat = function() {
-  return this;
-}
-
-let obj = new Animal();
-let speak = obj.speak;
-speak(); // global object
-
-let eat = Animal.eat;
-eat(); // global object
-
- -

Sub kelas dengan extends

- -

extends digunakan pada deklarasi kelas atau kelas expresi untuk membuat suatu kelas sebagai turunan dari kelas lain.

- -
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.');
-  }
-}
-
-var d = new Dog('Mitzie');
-d.speak();
-
- -

Jika terdapat constructor pada sub kelas saat ini, maka pertama dibutuhkan untuk memanggil super() sebelum menggunakan "this".

- -
Seseorang juga dapat mengextend "kelas" berbasis fungsi tradisional:
- -
function Animal (name) {
-  this.name = name;
-}
-
-Animal.prototype.speak = function () {
-  console.log(this.name + ' makes a noise.');
-}
-
-class Dog extends Animal {
-  speak() {
-    console.log(this.name + ' barks.');
-  }
-}
-
-var d = new Dog('Mitzie');
-d.speak();
-
- -

Perhatikan bahwa kelas tidak dapat di extend pada objek reguler atau biasa (non-constructible) . Jika ingin mewarisi regurel object,  maka dapat menggunakan {{jsxref("Object.setPrototypeOf()")}}:

- -
var Animal = {
-  speak() {
-    console.log(this.name + ' makes a noise.');
-  }
-};
-
-class Dog {
-  constructor(name) {
-    this.name = name;
-  }
-  speak() {
-    console.log(this.name + ' barks.');
-  }
-}
-
-Object.setPrototypeOf(Dog.prototype, Animal);
-
-var d = new Dog('Mitzie');
-d.speak();
-
- -

Species

- -

Kamu dapat mengembalikan objek {{jsxref("Array")}}  di kelas array yang diturunkan MyArray. Pola spesies memungkinkan Kamu overide konstruktor default.

- -

Contohnya, ketika menggunakan method seperti {{jsxref("Array.map", "map()")}} yang mana mengembalikan konstruktor default, kamu butuh method yang dapat mengembalikan objek parent Array, bukan dari objek MyArray. Simbol {{jsxref("Symbol.species")}} memungkinkan untuk melakukan:

- -
class MyArray extends Array {
-  // Overwrite species to the parent Array constructor
-  static get [Symbol.species]() { return Array; }
-}
-
-var a = new MyArray(1,2,3);
-var mapped = a.map(x => x * x);
-
-console.log(mapped instanceof MyArray); // false
-console.log(mapped instanceof Array);   // true
-
- -

Memanggil Kelas Super dengan keyword super

- -

Keyword super digunakan untuk memanggil fungsi pada objek parent nya.

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

- -

Subkelas Abstrak or mix-ins adalah template untuk kelas. Kelas berbasis  ECMAScript hanya dapat memiliki satu superclass (Kelas super), jadi inheritence berganda dari kelas tool sebagai contohnya, itu tidak memungkinkan. Fungsionalitas harus disediakan oleh superclass.

- -

Sebuah fungsi dengan superclass sebagai inputanya dan sukelas as input and a subclass extend superclass sebagai output dapat mengimplemtasikan pada  ECMAScript sebagai berikut:

- -
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)) { }
- -

Spesifikasi

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

Kompatibilitas Browser

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)EdgeInternet ExplorerOperaSafari
Basic support{{CompatChrome(42.0)}}[1]
- {{CompatChrome(49.0)}}
{{CompatGeckoDesktop(45)}}13{{CompatNo}}{{CompatNo}}{{CompatSafari(9.0)}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatGeckoMobile(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.

- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/errors/called_on_incompatible_type/index.html b/files/id/web/javascript/reference/errors/called_on_incompatible_type/index.html deleted file mode 100644 index 4fab8e8ca2..0000000000 --- a/files/id/web/javascript/reference/errors/called_on_incompatible_type/index.html +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: X.prototype.y called on incompatible type -slug: Web/JavaScript/Reference/Errors/Called_on_incompatible_type -tags: - - Error - - JavaScript - - TypeError -translation_of: Web/JavaScript/Reference/Errors/Called_on_incompatible_type ---- -
{{jsSidebar("Errors")}}
- -

Message

- -
TypeError: 'this' is not a Set object (EdgE)
-TypeError: Function.prototype.toString called on incompatible object (Firefox)
-TypeError: Function.prototype.bind called on incompatible target (Firefox)
-TypeError: Method Set.prototype.add called on incompatible receiver undefined (Chrome)
-TypeError: Bind must be called on a function (Chrome)
-
- -

Tipe error

- -

{{jsxref("TypeError")}}

- -

Apa yang salah?

- -

Ketika error ini dilempar, suatu fungsi (dari objek yang diberikan), dipanggil dengan this tidak berkorespondensi ke tipe yang diharapkan fungsi tersebut.

- -

Isu ini bisa terbit ketika menggunakan metode {{jsxref("Function.prototype.call()")}} atau {{jsxref("Function.prototype.apply()")}}, dan menyediakan argumen this yang tak punya tipe yang diharapkan.

- -

Isu ini juga bisa terjadi ketika menyediakan fungsi yang disimpan sebagai properti suatu objek sebagai argumen fungsi lain. Dalam hal ini, objek yang menyimpan fungsi tersebut takkan menjadi target this target dari fungsi itu ketika dipanggil oleh fungsi lain. Untuk mengatasi isu ini, kamu harus menyediakan lambda yang membuat panggilan, ataupun menggunakan fungsi {{jsxref("Function.prototype.bind()")}} untuk memaksa argumen this ke objek yang diharapkan.

- -

Contoh

- -

Kasus tak valid

- -
var mySet = new Set;
-['bar', 'baz'].forEach(mySet.add);
-// mySet.add adalah fungsi, tapi "mySet" tidak dikaptur sebagai this.
-
-var myFun = function () {
-  console.log(this);
-};
-['bar', 'baz'].forEach(myFun.bind);
-// myFun.bind adalah fungsi, tapi "myFun" tidak dikaptur sebagai this.
-
-
- -

Kasus valid

- -
var mySet = new Set;
-['bar', 'baz'].forEach(mySet.add.bind(mySet));
-// Ini berjalan karena mengikat "mySet" sebagai this.
-
-var myFun = function () {
-  console.log(this);
-};
-['bar', 'baz'].forEach(x => myFun.bind(x));
-// Ini berjalan menggunakan fungsi "bind". Ia membuat lambda yang meneruskan argumen.
-
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/errors/index.html b/files/id/web/javascript/reference/errors/index.html deleted file mode 100644 index 68e7cce3df..0000000000 --- a/files/id/web/javascript/reference/errors/index.html +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Referensi error JavaScript -slug: Web/JavaScript/Reference/Errors -tags: - - JavaScript -translation_of: Web/JavaScript/Reference/Errors ---- -

{{jsSidebar("Errors")}}

- -

Error, error dimana - mana.

- -

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

diff --git a/files/id/web/javascript/reference/errors/invalid_array_length/index.html b/files/id/web/javascript/reference/errors/invalid_array_length/index.html deleted file mode 100644 index 3b7fd4e78e..0000000000 --- a/files/id/web/javascript/reference/errors/invalid_array_length/index.html +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: 'RangeError: invalid array length' -slug: Web/JavaScript/Reference/Errors/Invalid_array_length -tags: - - Errors - - JavaScript - - RangeError -translation_of: Web/JavaScript/Reference/Errors/Invalid_array_length ---- -
{{jsSidebar("Errors")}}
- -

Message

- -
RangeError: Array length must be a finite positive integer (Edge)
-RangeError: invalid array length (Firefox)
-RangeError: Invalid array length (Chrome)
-RangeError: Invalid array buffer length (Chrome)
-
- -

Tipe error

- -

{{jsxref("RangeError")}}

- -

Apa yang salah?

- -

Panjang array tak valid bisa muncul di situasi berikut:

- - - -

Kenapa panjang Array dan ArrayBuffer dibatasi? Properti length dari Array atau ArrayBuffer diwakili dengan satu unsigned 32-bit integer, yang hanya menyimpan nilai dalam kisaran dari 0 hingga 232-1.

- -

Jika kamu membuat satu Array, menggunakan constructor, kamu mungkin mau memakai notasi literal saja, karena argumen pertama diinterpretasi sebagai panjang Array.

- -

Sebaliknya, kamu mungkin mau mengelam panjangnya sebelum mengeset properti panjangnya, atau memakainya sebagai argumen konstructor.

- -

Contoh

- -

Kasus tak valid

- -
new Array(Math.pow(2, 40))
-new Array(-1)
-new ArrayBuffer(Math.pow(2, 32))
-new ArrayBuffer(-1)
-
-let a = [];
-a.length = a.length - 1;         // set -1 to the length property
-
-let b = new Array(Math.pow(2, 32) - 1);
-b.length = b.length + 1;         // set 2^32 to the length property
-
- -

Kasus valid

- -
[ Math.pow(2, 40) ]                     // [ 1099511627776 ]
-[ -1 ]                                  // [ -1 ]
-new ArrayBuffer(Math.pow(2, 32) - 1)
-new ArrayBuffer(0)
-
-let a = [];
-a.length = Math.max(0, a.length - 1);
-
-let b = new Array(Math.pow(2, 32) - 1);
-b.length = Math.min(0xffffffff, b.length + 1);
-
-// 0xffffffff is the hexadecimal notation for 2^32 - 1
-// which can also be written as (-1 >>> 0)
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/errors/missing_semicolon_before_statement/index.html b/files/id/web/javascript/reference/errors/missing_semicolon_before_statement/index.html deleted file mode 100644 index 32be54e5ce..0000000000 --- a/files/id/web/javascript/reference/errors/missing_semicolon_before_statement/index.html +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: 'SyntaxError: missing ; before statement' -slug: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement -translation_of: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement ---- -
{{jsSidebar("Errors")}}
- -

Pesan

- -
SyntaxError: Expected ';' (Edge)
-SyntaxError: missing ; before statement (Firefox)
-
- -

Tipe error

- -

{{jsxref("SyntaxError")}}.

- -

Apa yang Salah?

- -

Ada titik koma (;) yang hilang di suatu tempat. JavaScript statements harus diakhiri dengan semicolon. Beberapa dari mereka dipengaruhi oleh automatic semicolon insertion (ASI), tetapi dalam hal ini anda perlu memberikan titik koma, sehingga JavaScript dapat mem-parse kode sumber dengan benar.

- -

Namun, seringkali, kesalahan ini hanya merupakan konsekuensi dari kesalahan lain, seperti tidak menempatkan string dengan benar, atau menggunakan var secara salah. Ada mungkin juga memiliki terlalu banyak tanda kurung di suatu tempat. Hati-hati memeriksa sintaks ketika kesalahan ini dilemparkan.

- -

Contoh

- -

Unescaped strings

- -

Kesalahan ini dapat terjadi dengan mudah ketika tidak melepaskan string dengan benar dan engine JavaScript is expecting the end of your string already. Sebagai contoh:

- -
var foo = 'Tom's bar';
-// SyntaxError: missing ; before statement
- -

Anda dapat menggunakan double quotes, atau menggunakan tanda kutip dengan menambahkan backslash

- -
var foo = "Tom's bar";
-var foo = 'Tom\'s bar';
-
- -

Declaring properties with var

- -

Anda tidak dapat mendeklarasikan property dari sebuah objek atau larik(array) dengan deklarasi var.

- -
var obj = {};
-var obj.foo = 'hi'; // SyntaxError missing ; before statement
-
-var array = [];
-var array[0] = 'there'; // SyntaxError missing ; before statement
-
- -

Sebagai gantinya, hapus kata kunci var:

- -
var obj = {};
-obj.foo = 'hi';
-
-var array = [];
-array[0] = 'there';
-
- -

Kata kunci yang buruk

- -

Jika ada berasal dari bahasa pemrograman yang lain, itu juga umum untuk menggunakan kata kunci yang tidak berarti sama atau tidak memiliki arti sama sekali di JavaScript:

- -
def print(info){
-  console.log(info);
-}; // SyntaxError missing ; before statement
- -

Sebagai gantinya, gunakan function daripada menggunakan kata kunci def:

- -
function print(info){
-  console.log(info);
-};
- -

See also

- - diff --git a/files/id/web/javascript/reference/errors/negative_repetition_count/index.html b/files/id/web/javascript/reference/errors/negative_repetition_count/index.html deleted file mode 100644 index 0ea4bec83a..0000000000 --- a/files/id/web/javascript/reference/errors/negative_repetition_count/index.html +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: 'RangeError: repeat count must be non-negative' -slug: Web/JavaScript/Reference/Errors/Negative_repetition_count -tags: - - Errors - - JavaScript - - RangeError -translation_of: Web/JavaScript/Reference/Errors/Negative_repetition_count ---- -
{{jsSidebar("Errors")}}
- -

Pesan

- -
RangeError: argument out of range
-RangeError: repeat count must be non-negative (Firefox)
-RangeError: Invalid count value (Chrome)
-
- -

Tipe error

- -

{{jsxref("RangeError")}}

- -

Apa yang salah?

- -

Metode {{jsxref("String.prototype.repeat()")}} telah digunakan. Ia punya parameter count mengindikasikan jumlah pengulangan string. Ia harus bernilai antara 0 dan kurang dari positif {{jsxref("Infinity")}} dan tidak boleh angka negatif. Kisarannya nilai yang diperbolehkan bisa dijelaskan seperti ini: [0, +∞).

- -

Contoh

- -

Kasus tak valid

- -
'abc'.repeat(-1); // RangeError 
- -

Kasus valid

- -
'abc'.repeat(0);    // ''
-'abc'.repeat(1);    // 'abc'
-'abc'.repeat(2);    // 'abcabc'
-'abc'.repeat(3.5);  // 'abcabcabc' (count will be converted to integer)
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/errors/not_a_codepoint/index.html b/files/id/web/javascript/reference/errors/not_a_codepoint/index.html deleted file mode 100644 index d3d8b2f934..0000000000 --- a/files/id/web/javascript/reference/errors/not_a_codepoint/index.html +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: 'RangeError: argument is not a valid code point' -slug: Web/JavaScript/Reference/Errors/Not_a_codepoint -tags: - - Errors - - JavaScript - - RangeError -translation_of: Web/JavaScript/Reference/Errors/Not_a_codepoint ---- -
{{jsSidebar("Errors")}}
- -

Pesan

- -
RangeError: Invalid code point {0} (Edge)
-RangeError: {0} is not a valid code point (Firefox)
-RangeError: Invalid code point {0} (Chrome)
-
- -

 

- -

Tipe error

- -

{{jsxref("RangeError")}}

- -

Apa yang salah?

- -

{{jsxref("String.fromCodePoint()")}} throws this error when passed {{jsxref("NaN")}} values, negative Integers (-1), non-Integers (5.4), or values larger than 0x10FFFF (1114111).

- -

Satu poin kode ialah satu nilai dalam codespace Unicode; yaitu, kisaran integer dari 0 hingga 0x10FFFF.

- -

Contoh

- -

Kasus tak nvalid

- -
String.fromCodePoint('_');      // RangeError
-String.fromCodePoint(Infinity); // RangeError
-String.fromCodePoint(-1);       // RangeError
-String.fromCodePoint(3.14);     // RangeError
-String.fromCodePoint(3e-2);     // RangeError
-String.fromCodePoint(NaN);      // RangeError
- -

Kasus valid

- -
String.fromCodePoint(42);       // "*"
-String.fromCodePoint(65, 90);   // "AZ"
-String.fromCodePoint(0x404);    // "\u0404"
-String.fromCodePoint(0x2F804);  // "\uD87E\uDC04"
-String.fromCodePoint(194564);   // "\uD87E\uDC04"
-String.fromCodePoint(0x1D306, 0x61, 0x1D307) // "\uD834\uDF06a\uD834\uDF07"
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/errors/not_defined/index.html b/files/id/web/javascript/reference/errors/not_defined/index.html deleted file mode 100644 index d0dc93a0c6..0000000000 --- a/files/id/web/javascript/reference/errors/not_defined/index.html +++ /dev/null @@ -1,66 +0,0 @@ ---- -title: 'ReferenceError: "x" is not defined' -slug: Web/JavaScript/Reference/Errors/Not_defined -translation_of: Web/JavaScript/Reference/Errors/Not_defined ---- -
{{jsSidebar("Errors")}}
- -

Pesan

- -
ReferenceError: "x" is not defined
-
- -

Type Error

- -

{{jsxref("ReferenceError")}}.

- -

Mengapa salah?

- -

Tidak ditemukannya referensi variabel dimanapun. Variabel ini perlu dideklarasikan, atau anda pastikan lagi bahwa ada di dalam script atau {{Glossary("scope")}} anda.

- -
-

Note: Ketika memanggil sebuah library (seperti jQuery), pastikan memanggilnya terlebih dahulu tanda "$" sebelum mengakses variabel library. Gunakan tag {{HTMLElement("script")}} untuk memanggil library sebelum menggunakannya pada kode anda.

-
- -

Contoh

- -

Variable tidak dideklarasikan

- -
foo.substring(1); // ReferenceError: foo is not defined
-
- -

Variabel "foo" tidak ditemukan dimanapun. Variabel tersebut diperlukan oleh beberapa string, agar metode {{jsxref("String.prototype.substring()")}} dapat bekerja.

- -
var foo = 'bar';
-foo.substring(1); // "ar"
- -

Ruang lingkup salah

- -

Sebuah variabel harus tersedia dalam kontek eksekusi saat ini . Variabel yang berada di dalam sebuah fungsi tidak dapat diakses dari luar fungsi, sebab sebuah variabel mepunyai batasan pada cakupan wilayah sebuah fungsi

- -
function numbers() {
-  var num1 = 2,
-      num2 = 3;
-  return num1 + num2;
-}
-
-console.log(num1); // ReferenceError num1 is not defined.
- -

Dengan demikian sebuah fungsi dapat mengakses semua variabel dan fungsi lainnya yang didefinisikan di dalam cakupan dimana ia didefinisikan. Dengan kata lain, sebiah fungsi yang didefinisikan di cakupan global dapat mengakses semua variabel yang didefinisian secara global pula.

- -
var num1 = 2,
-    num2 = 3;
-
-function numbers() {
-  return num1 + num2;
-}
-
-console.log(numbers()); // 5
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/errors/property_access_denied/index.html b/files/id/web/javascript/reference/errors/property_access_denied/index.html deleted file mode 100644 index 6cbece3868..0000000000 --- a/files/id/web/javascript/reference/errors/property_access_denied/index.html +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: 'Error: Permission denied to access property "x"' -slug: Web/JavaScript/Reference/Errors/Property_access_denied -tags: - - Error - - Errors - - JavaScript - - Keamanan -translation_of: Web/JavaScript/Reference/Errors/Property_access_denied ---- -
{{jsSidebar("Errors")}}
- -

Pesan

- -
Error: Permission denied to access property "x"
-
- -

Tipe error

- -

{{jsxref("Error")}}.

- -

Apa kesalahannya?

- -

Ada usaha pengaksesan objeck yang kamu belum punya ijinnya. Sepertinya elemen {{HTMLElement("iframe")}} diload dari domain berbeda yang kebijakan same-origin policynya kamu langgar.

- -

Contoh

- -
<!DOCTYPE html>
-<html>
-  <head>
-    <iframe id="myframe" src="http://www1.w3c-test.org/common/blank.html"></iframe>
-    <script>
-      onload = function() {
-        console.log(frames[0].document);
-        // Error: Permission denied to access property "document"
-      }
-    </script>
-  </head>
-  <body></body>
-</html>
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/errors/too_much_recursion/index.html b/files/id/web/javascript/reference/errors/too_much_recursion/index.html deleted file mode 100644 index 4c35bcfc83..0000000000 --- a/files/id/web/javascript/reference/errors/too_much_recursion/index.html +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: 'InternalError: too much recursion' -slug: Web/JavaScript/Reference/Errors/Too_much_recursion -tags: - - Errors - - InternalError - - JavaScript -translation_of: Web/JavaScript/Reference/Errors/Too_much_recursion ---- -
{{jsSidebar("Errors")}}
- -

Pesan

- -
Error: Out of stack space (Edge)
-InternalError: too much recursion (Firefox)
-RangeError: Maximum call stack size exceeded (Chrome)
-
- -

Tipe error

- -

{{jsxref("InternalError")}}.

- -

Apa yang salah?

- -

Fungsi yang memanggil dirinya sendiri disebut fungsi rekursif. Sekali satu kondisi telah ketemu, fungsi itu berhenti memanggil dirinya. Ini disebut base case.

- -

Dalam beberapa cara, rekursi analog dengan loop. Keduanya mengeksekusi kode yang sama berulang kali, dan keduanya membutuhkan satu kondisi (untuk mencegah loop tak-terbatas, atau lebih tepatnya, rekursi tak-terbatas dalam hal ini). Ketika panggilan fungsi terlalu banyak, atau tak ada base case dalam fungsi, JavaScript akan melempar error ini.

- -

Contoh

- -

Fungsi rekursif ini berjalan 10 kali, per kondisi exit.

- -
function loop(x) {
-  if (x >= 10) // "x >= 10" is the exit condition
-    return;
-  // do stuff
-  loop(x + 1); // the recursive call
-}
-loop(0);
- -

Mengeset kondisi ini ke nilai extrem sangat tinggi, tak akan jalan:

- -
function loop(x) {
-  if (x >= 1000000000000)
-    return;
-  // do stuff
-  loop(x + 1);
-}
-loop(0);
-
-// InternalError: too much recursion
- -

Fungsi rekursif ini tak punya base case. Jika tak kondisi exit, function akan memanggil dirinya sendiri terus-terusan.

- -
function loop(x) {
- // The base case is missing
-
-loop(x + 1); // Recursive call
-}
-
-loop(0);
-
-// InternalError: too much recursion
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/functions/index.html b/files/id/web/javascript/reference/functions/index.html deleted file mode 100644 index adb0d13f05..0000000000 --- a/files/id/web/javascript/reference/functions/index.html +++ /dev/null @@ -1,596 +0,0 @@ ---- -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.
-
- -
-
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.
-
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 benefits of creating a named function expression is that in case we encountered an error, the stack trace will contain the name of the function, making it easier to find the origin of the error.

- -

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.
-
- -
-
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.
-
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 representing 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/id/web/javascript/reference/global_objects/array/concat/index.html b/files/id/web/javascript/reference/global_objects/array/concat/index.html deleted file mode 100644 index c6a25609db..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/concat/index.html +++ /dev/null @@ -1,169 +0,0 @@ ---- -title: Array.prototype.concat() -slug: Web/JavaScript/Reference/Global_Objects/Array/concat -tags: - - Array -translation_of: Web/JavaScript/Reference/Global_Objects/Array/concat ---- -
{{JSRef}}
- -

Method concat() mengembalikan sebuah array baru yang terdiri dari array yang dipanggil kemudian digabung dengan array dan/atau nilai yang ditambahkan pada argumen.

- -

Syntax

- -
var array_baru = array_lama.concat(value1[, value2[, ...[, valueN]]])
- -

Parameter

- -
-
valueN
-
Array dan/atau nilai untuk digabung menjadi array baru. Untuk detailnya lihat deskripsi dibawah.
-
- -

Deskripsi

- -

concat menciptakan array baru yang terdiri dari unsur - unsur dalam object yang disebut, berdasarkan urutannya, setiap argumen, elemen dari argumen tersebut(Jika argumen adalah array) atau argumennya sendiri (jika argumennya bukan array).

- -

concat tidak mengubah this atau beberapa array yang tersedia sebagai argumen melainkan mengembalikan shallow copy yang berisi salinan dari elemen yang sama digabung dengan array yang asli. Elemen dari array asli disalin ke array baru sebagai berikut:

- - - -
-

Catatan: Concatenating array/nilai akan membiarkan aslinya tidak tersentuh. Selanjutnya, setiap operasi pada array baru tidak akan mempengaruhi array yang asli, begitupun sebaliknya.

-
- -

Contoh

- -

Menggabungkan dua Array

- -

Berikut kode untuk menggabunggkan dua array:

- -
var huruf = ['a', 'b', 'c'],
-    angka = [1, 2, 3];
-
-var hurufAngka = huruf.concat(angka);
-
-console.log(hurufAngka); // Hasil: ['a', 'b', 'c', 1, 2, 3]
-
- -

Menggabungkan tiga array

- -

Berikut kode untuk mengabungkan tiga array:

- -
var angka1 = [1, 2, 3],
-    angka2 = [4, 5, 6],
-    angka3 = [7, 8, 9];
-
-var angkaBaru = angka1.concat(angka2, angka3);
-
-console.log(angkaBaru); // Hasil: [1, 2, 3, 4, 5, 6, 7, 8, 9]
-
- -

Menggabungkan nilai ke sebuah array

- -

Berikut kode untuk menggabungkan tiga nilai ke sebuah array :

- -
var huruf = ['a', 'b', 'c'];
-
-var hurufAngka = huruf.concat(1, [2, 3]);
-
-console.log(hurufAngka);
-// Hasil: ['a', 'b', 'c', 1, 2, 3]
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial 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')}} 
{{SpecName('ESDraft', '#sec-array.prototype.concat', 'Array.prototype.concat')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/filter/index.html b/files/id/web/javascript/reference/global_objects/array/filter/index.html deleted file mode 100644 index 5c23313268..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/filter/index.html +++ /dev/null @@ -1,244 +0,0 @@ ---- -title: Array.prototype.filter() -slug: Web/JavaScript/Reference/Global_Objects/Array/filter -tags: - - Array - - ECMAScript 5 - - JavaScript - - Metode - - Referensi - - polyfill - - purwarupa -translation_of: Web/JavaScript/Reference/Global_Objects/Array/filter ---- -
{{JSRef}}
- -

Fungsi filter() membuat array baru berisi elemen yang lolos pengecekan di dalam fungsi anonim yang dikirim sebagai parameter.

- -
var words = ["spray", "limit", "elite", "exuberant", "destruction", "present"];
-
-var longWords = words.filter(function(word){
-  return word.length > 6;
-});
-
-// Filtered array longWords is ["exuberant", "destruction", "present"]
-
- -

Versi ES6

- -
const words = ["spray", "limit", "elite", "exuberant", "destruction", "present"];
-
-let longWords = words.filter(word => word.length > 6);
-
-// Filtered array longWords is ["exuberant", "destruction", "present"]
-
- -

Sintaksis

- -
var newArray = arr.filter(callback[, thisArg])
- -

Parameter-parameter

- -
-
callback
-
Fungsi berupa tes untuk mengecek elemen yang ada di dalam array. Kembalikan nilai true untuk meloloskan element, false untuk tidak lolos, dan dapat memiliki tiga argumen:
-
-
-
element
-
Elemen saat ini yang sedang diproses.
-
index
-
Nilai indeks (posisi) dari elemen yang sedang diproses.
-
array
-
Array yang memanggil fungsi filter.
-
-
-
thisArg {{Optional_inline}}
-
Opsional. Objek yang akan digunakan sebagai this saat mengeksekusi callback.
-
- -

Nilai balikan

- -

Array baru yang berisi elemen lolos pengecekan.

- -

Deskripsi

- -

filter() akan memanggil fungsi callback sekali untuk tiap elemen di dalam array, dan membuat array baru dari semua nilai yang dianggap true dari hasil yang dikembalikan callbackcallback hanya dipanggil untuk indeks dari array yang berisi sebuah nilai; fungsi tidak akan dipanggil untuk indeks yang telah dihapus atau belum diisi nilai tertentu. Elemen array yang tidak lolos tes callback akan dilewati dan tidak dimasukkan ke dalam array baru.

- -

callback dapat dipanggil dengan tiga argumen:

- -
    -
  1. nilai dari elemen
  2. -
  3. indeks dari elemen
  4. -
  5. objek array yang diproses
  6. -
- -

Jika parameter thisArg tersedia juga saat memanggil filter, itu akan digunakan sebagai nilai this di dalam callback.  Jika tidak disediakan, maka undefined yang digunakan sebagai nilai this. Nilai this yang dapat digunakan dalam callback ditentukan dari aturan umum penentuan this dalam fungsi.

- -

filter() tidak mengubah array yang memanggil fungsi ini.

- -

Kumpulan elemen yang akan diproses oleh filter() ditentukan sebelum pemanggilan pertama callback. Elemen yang ditambahkan ke array setelah pemanggilanfilter() dimulai tidak akan diproses oleh callback. Jika elemen yang sudah ada dalam array berubah, atau dihapus, nilai yang digunakan dalam callback adalah nilai pada saat filter() menggunakannya; elemen yang dihapus tidak akan diproses.

- -

Contoh

- -

Menyaring semua nilai kecil

- -

Contoh berikut ini menggunakan filter() untuk membuat array yang menyaring semua nilai di bawah 10.

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

Menyaring entri invalid dari JSON

- -

Contoh berikut ini menggunakan filter() untuk membuat json tersaring berisi semua elemen id berupa angka bukan nol.

- -
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)) {
-    return true;
-  }
-  invalidEntries++;
-  return false;
-}
-
-var arrByID = arr.filter(filterByID);
-
-console.log('Filtered Array\n', arrByID);
-// Filtered Array
-// [{ id: 15 }, { id: -1 }, { id: 0 }, { id: 3 }, { id: 12.2 }]
-
-console.log('Number of Invalid Entries = ', invalidEntries);
-// Number of Invalid Entries = 4
-
- -

Pencarian dalam array

- -

Contoh berikut menggunakan filter() untuk menyaring isi array berdasarkan kriteria pencarian

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

Implementasi ES2015

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

- -

filter() ditambahkan ke standar ECMA-262 baru pada edisi ke-5; sehingga fungsi ini mungkin tidak terdapat pada semua implementasi standar. Anda dapat mengatasi hal ini dengan menambahkan kode berikut pada awalan skrip Anda, memungkinkan penggunaan filter() di implementasi ECMA-262 yang belum mendukung. Algoritma ini persis sepadan dengan yang dispesifikasikan dalam ECMA-262, edisi ke-5, dengan asumsi fn.call dievaluasi ke nilai asli dari {{jsxref("Function.prototype.bind()")}}, dan {{jsxref("Array.prototype.push()")}} memiliki nilai aslinya.

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

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ES5.1', '#sec-15.4.4.20', 'Array.prototype.filter')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.6.
{{SpecName('ES2015', '#sec-array.prototype.filter', 'Array.prototype.filter')}}{{Spec2('ES2015')}} 
{{SpecName('ESDraft', '#sec-array.prototype.filter', 'Array.prototype.filter')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas browser

- -
- - -

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

-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/from/index.html b/files/id/web/javascript/reference/global_objects/array/from/index.html deleted file mode 100644 index 7845da9755..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/from/index.html +++ /dev/null @@ -1,248 +0,0 @@ ---- -title: Array.from() -slug: Web/JavaScript/Reference/Global_Objects/Array/from -translation_of: Web/JavaScript/Reference/Global_Objects/Array/from ---- -
{{JSRef}}
- -

Method Array.from() membuat sebuah instansi Array dari sebuah array-like atau objek iterable.

- -

Di ES6, sintaks class memungkinkan untuk subclassing diantaranya built-in dan user defined classes; hasilnya , method statik class-side seperti Array.from  "diwariskan" oleh subclasses dari Array dan membuat instansi baru dari subclass, bukan Array.

- -

Sintaks

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

Parameter

- -
-
arrayLike
-
 Array-like atau objek iterable untuk diubah menjadi array.
-
mapFn
-
Opsional. Fungsi Map untuk memanggil setiap elemen array.
-
thisArg
-
Opsional. Nilai untuk digunakan this ketika mengeksekusi mapFn.
-
- -

Deskripsi

- -

Array.from() memungkinkan anda membuat Arrays dari:

- - - -

Array.from() memiliki parameter opsional mapFn, yang memungkinkan anda untuk mengeksekusi fungsi {{jsxref("Array.prototype.map", "map")}} pada setiap elemen array (atau objek subclass) yang akan dibuat. Jelasnya, Array.from(obj, mapFn, thisArg) sama dengan Array.from(obj).map(mapFn, thisArg), kecuali dengan tidak membuat array menengah. Ini sangat penting untuk setiap subclass array, seperti typed arrays, selama array menengah akan memiliki nilai yang terpisah agar bisa masuk ke tipe yang sesuai.

- -

Properti length dari method from() adalah 1.

- -

Contoh

- -
// Array-like object (arguments) to Array
-function f() {
-  return Array.from(arguments);
-}
-
-f(1, 2, 3);
-// [1, 2, 3]
-
-
-// Any iterable object...
-// Set
-var s = new Set(["foo", window]);
-Array.from(s);
-// ["foo", window]
-
-
-// Map
-var m = new Map([[1, 2], [2, 4], [4, 8]]);
-Array.from(m);
-// [[1, 2], [2, 4], [4, 8]]
-
-
-// String
-Array.from("foo");
-// ["f", "o", "o"]
-
-
-// Using an arrow function as the map function to
-// manipulate the elements
-Array.from([1, 2, 3], x => x + x);
-// [2, 4, 6]
-
-
-// Generate a sequence of numbers
-Array.from({length: 5}, (v, k) => k);
-// [0, 1, 2, 3, 4]
-
-
- -

Polyfill

- -

Array.from telah di masukkan di standar ECMA-262 pada edisi ke-6; karena itu mungkin tidak bisa digunakan pada implementasi standar lain. Anda bisa menyiasatinya dengan menambahkan kode berikut ke awal script, memungkinkan penggunaan Array.from pada implementasi yang aslinya tidak mendukung.  Algoritma ini sama dengan yang di spesifikasikan di ECMA-262, edisi ke-6, dengan saumsi Object dan TypeError memiliki nilai tersendiri dan callback.call mengevaluasi nilai valur dari {{jsxref("Function.prototype.call")}}. Selain itu, sejak iterable tidak dapat di polyfill, implementasi ini tidak mendukung generik iterable seperti yang didefinisikan di edisi ke-6 di ECMA-262.

- -
// Production steps of ECMA-262, Edition 6, 22.1.2.1
-// Reference: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.from
-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;
-    };
-  }());
-}
-
- -

Spesifikasi

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

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)EdgeInternet ExplorerOperaSafari
Dukungan dasar{{CompatChrome("45")}}{{CompatGeckoDesktop("32")}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}9.0
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("32")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/index.html b/files/id/web/javascript/reference/global_objects/array/index.html deleted file mode 100644 index 2b052487c4..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/index.html +++ /dev/null @@ -1,484 +0,0 @@ ---- -title: Array -slug: Web/JavaScript/Reference/Global_Objects/Array -tags: - - Array - - Global Objects - - JavaScript - - NeedsTranslation - - Reference - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Array ---- -
{{JSRef}}
- -

Objek JavaScript Array merupakan objek global yang berguna membangun himpunan; dimana merupakan objek level tinggi dan (seperti) daftar.

- -

Membuat sebuah Array

- -
var fruits = ["Apple", "Banana"];
-
-console.log(fruits.length);
-// 2
-
- -

Akses (index) kedalam sebuah item Array

- -
var first = fruits[0];
-// Apple
-
-var last = fruits[fruits.length - 1];
-// Banana
-
- -

Perulangan pada Array

- -
fruits.forEach(function (item, index, array) {
-  console.log(item, index);
-});
-// Apple 0
-// Banana 1
-
- -

Menambahkan elemen pada bagian akhir sebuah Array

- -
var newLength = fruits.push("Orange");
-// ["Apple", "Banana", "Orange"]
-
- -

Menghapus elemen di akhir sebuah Array

- -
var last = fruits.pop(); // remove Orange (from the end)
-// ["Apple", "Banana"];
-
- -

Menghapus elemen di awal sebuah Array

- -
var first = fruits.shift(); // remove Apple from the front
-// ["Banana"];
-
- -

Menambahkan elemen di bagian awal sebuah Array

- -
var newLength = fruits.unshift("Strawberry") // add to the front
-// ["Strawberry", "Banana"];
-
- -

Mencari (nomor) index elemen pada sebuah Array

- -
fruits.push("Mango");
-// ["Strawberry", "Banana", "Mango"]
-
-var pos = fruits.indexOf("Banana");
-// 1
-
- -

Menghapus elemen berdasar posisi index

- -
var removedItem = fruits.splice(pos, 1); // this is how to remove an item
-// ["Strawberry", "Mango"]
-
- -

Menduplikat sebuah Array

- -
var shallowCopy = fruits.slice(); // this is how to make a copy
-// ["Strawberry", "Mango"]
-
- -

Syntax

- -
[element0, element1, ..., elementN]
-new Array(element0, element1[, ...[, elementN]])
-new Array(arrayLength)
- -
-
elementN
-
A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the Array constructor and that argument is a number (see the arrayLength parameter below).Note that this special case only applies to JavaScript arrays created with the Array constructor, not array literals created with the bracket syntax.
-
arrayLength
-
If the only argument passed to the Array constructor is an integer between 0 and 232-1 (inclusive), this returns a new JavaScript array with length set to that number. If the argument is any other number, a {{jsxref("RangeError")}} exception is thrown.
-
- -

Description

- -

Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. Neither the length of a JavaScript array nor the types of its elements are fixed. Since an array's length can change at any time, and data can be stored at non-contiguous locations in the array, JavaScript arrays are not guaranteed to be dense; this depends on how the programmer chooses to use them. In general, these are convenient characteristics; but if these features are not desirable for your particular use, you might consider using typed arrays.

- -

Some people think that you shouldn't use an array as an associative array. In any case, 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.

- -

Accessing array elements

- -

JavaScript arrays are zero-indexed: the first element of an array is at index 0, and the last element is at the index equal to the value of the array's {{jsxref("Array.length", "length")}} property minus 1.

- -
var arr = ['this is the first element', 'this is the second element'];
-console.log(arr[0]);              // logs 'this is the first element'
-console.log(arr[1]);              // logs 'this is the second element'
-console.log(arr[arr.length - 1]); // logs 'this is the second element'
-
- -

Array elements are object properties in the same way that toString is a property, but trying to access an element of an array as follows throws a syntax error, because the property name is not valid:

- -
console.log(arr.0); // a syntax error
-
- -

There is nothing special about JavaScript arrays and the properties that cause this. JavaScript properties that begin with a digit cannot be referenced with dot notation; and must be accessed using bracket notation. For example, if you had an object with a property named '3d', it can only be referenced using bracket notation. E.g.:

- -
var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010];
-console.log(years.0);   // a syntax error
-console.log(years[0]);  // works properly
-
- -
renderer.3d.setTexture(model, 'character.png');     // a syntax error
-renderer['3d'].setTexture(model, 'character.png');  // works properly
-
- -

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] is coerced into a string by the JavaScript engine 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 could be 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(but it can be accessed by dot notation in firefox 40.0a2 at least):

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

Relationship between length and numerical properties

- -

A JavaScript array's {{jsxref("Array.length", "length")}} property and numerical properties are connected. Several of the built-in array methods (e.g., {{jsxref("Array.join", "join")}}, {{jsxref("Array.slice", "slice")}}, {{jsxref("Array.indexOf", "indexOf")}}, etc.) take into account the value of an array's {{jsxref("Array.length", "length")}} property when they're called. Other methods (e.g., {{jsxref("Array.push", "push")}}, {{jsxref("Array.splice", "splice")}}, etc.) also result in updates to an array's {{jsxref("Array.length", "length")}} property.

- -
var fruits = [];
-fruits.push('banana', 'apple', 'peach');
-
-console.log(fruits.length); // 3
-
- -

When setting a property on a JavaScript array when the property is a valid array index and that index is outside the current bounds of the array, the engine will update the array's {{jsxref("Array.length", "length")}} property accordingly:

- -
fruits[5] = 'mango';
-console.log(fruits[5]); // 'mango'
-console.log(Object.keys(fruits));  // ['0', '1', '2', '5']
-console.log(fruits.length); // 6
-
- -

Increasing the {{jsxref("Array.length", "length")}}.

- -
fruits.length = 10;
-console.log(Object.keys(fruits)); // ['0', '1', '2', '5']
-console.log(fruits.length); // 10
-
- -

Decreasing the {{jsxref("Array.length", "length")}} property does, however, delete elements.

- -
fruits.length = 2;
-console.log(Object.keys(fruits)); // ['0', '1']
-console.log(fruits.length); // 2
-
- -

This is explained further on the {{jsxref("Array.length")}} page.

- -

Creating an array using the result of a match

- -

The result of a match between a regular expression and a string can create a JavaScript array. This array has properties and elements which provide information about the match. Such an array is returned by {{jsxref("RegExp.exec")}}, {{jsxref("String.match")}}, and {{jsxref("String.replace")}}. To help explain these properties and elements, look at the following example and then refer to the table below:

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

The properties and elements returned from this match are as follows:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Property/ElementDescriptionExample
inputA read-only property that reflects the original string against which the regular expression was matched.cdbBdbsbz
indexA read-only property that is the zero-based index of the match in the string.1
[0]A read-only element that specifies the last matched characters.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
- -

Properties

- -
-
Array.length
-
The Array constructor's length property whose value is 1.
-
{{jsxref("Array.@@species", "get Array[@@species]")}}
-
The constructor function that is used to create derived objects.
-
{{jsxref("Array.prototype")}}
-
Allows the addition of properties to all array objects.
-
- -

Methods

- -
-
{{jsxref("Array.from()")}}
-
Creates a new Array instance from an array-like or iterable object.
-
{{jsxref("Array.isArray()")}}
-
Returns true if a variable is an array, if not false.
-
{{jsxref("Array.of()")}}
-
Creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments.
-
- -

Array instances

- -

All Array instances inherit from {{jsxref("Array.prototype")}}. The prototype object of the Array constructor can be modified to affect all Array instances.

- -

Properties

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

Methods

- -

Mutator methods

- -
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Mutator_methods')}}
- -

Accessor methods

- -
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Accessor_methods')}}
- -

Iteration methods

- -
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Iteration_methods')}}
- -

Array generic methods

- -
-

Array generics are non-standard, deprecated and will get removed near future. Note that you can not rely on them cross-browser. However, there is a shim available on GitHub.

-
- -

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)) {
-  console.log("The string '" + str + "' contains only letters!");
-}
-
- -

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

- -
if (Array.every(str, isLetter)) {
-  console.log("The string '" + str + "' contains only letters!");
-}
-
- -

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

- -

These are 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', 'find', 'findIndex', 'entries', 'keys',
-      'values', 'copyWithin', 'includes'
-    ],
-    methodCount = methods.length,
-    assignArrayGeneric = function(methodName) {
-      if (!Array[methodName]) {
-        var method = Array.prototype[methodName];
-        if (typeof method === 'function') {
-          Array[methodName] = function() {
-            return method.call.apply(method, arguments);
-          };
-        }
-      }
-    };
-
-  for (i = 0; i < methodCount; i++) {
-    assignArrayGeneric(methods[i]);
-  }
-}());
-
- -

Examples

- -

Creating an array

- -

The following example creates an array, msgArray, with a length of 0, then assigns values to msgArray[0] and msgArray[99], changing the length of the array to 100.

- -
var msgArray = [];
-msgArray[0] = 'Hello';
-msgArray[99] = 'world';
-
-if (msgArray.length === 100) {
-  console.log('The length is 100.');
-}
-
- -

Creating a two-dimensional array

- -

The following creates a chess board as a two dimensional array of strings. The first move is made by copying the 'p' in (6,4) to (4,4). The old position (6,4) is made blank.

- -
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'] ];
-
-console.log(board.join('\n') + '\n\n');
-
-// Move King's Pawn forward 2
-board[4][4] = board[6][4];
-board[6][4] = ' ';
-console.log(board.join('\n'));
-
- -

Here is the output:

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

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.4', 'Array')}}{{Spec2('ES5.1')}}New methods added: {{jsxref("Array.isArray")}}, {{jsxref("Array.prototype.indexOf", "indexOf")}}, {{jsxref("Array.prototype.lastIndexOf", "lastIndexOf")}}, {{jsxref("Array.prototype.every", "every")}}, {{jsxref("Array.prototype.some", "some")}}, {{jsxref("Array.prototype.forEach", "forEach")}}, {{jsxref("Array.prototype.map", "map")}}, {{jsxref("Array.prototype.filter", "filter")}}, {{jsxref("Array.prototype.reduce", "reduce")}}, {{jsxref("Array.prototype.reduceRight", "reduceRight")}}
{{SpecName('ES6', '#sec-array-objects', 'Array')}}{{Spec2('ES6')}}New methods added: {{jsxref("Array.from")}}, {{jsxref("Array.of")}}, {{jsxref("Array.prototype.find", "find")}}, {{jsxref("Array.prototype.findIndex", "findIndex")}}, {{jsxref("Array.prototype.fill", "fill")}}, {{jsxref("Array.prototype.copyWithin", "copyWithin")}}
{{SpecName('ESDraft', '#sec-array-objects', 'Array')}}{{Spec2('ESDraft')}}New method added: {{jsxref("Array.prototype.includes()")}}
- -

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/id/web/javascript/reference/global_objects/array/isarray/index.html b/files/id/web/javascript/reference/global_objects/array/isarray/index.html deleted file mode 100644 index 152b6cdfd0..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/isarray/index.html +++ /dev/null @@ -1,144 +0,0 @@ ---- -title: Array.isArray() -slug: Web/JavaScript/Reference/Global_Objects/Array/isArray -tags: - - Array - - ECMAScript5 - - polyfill -translation_of: Web/JavaScript/Reference/Global_Objects/Array/isArray ---- -
{{JSRef}}
- -

Method Array.isArray() mengembalikan nilai true jika objek adalah array, false jika bukan.

- -

Sintaks

- -
Array.isArray(obj)
- -

Parameter

- -
-
obj
-
Objek yang di cek.
-
- -

Deskripsi

- -

Baca artikel “Determining with absolute accuracy whether or not a JavaScript object is an array” untuk detailnya.

- -

Contoh

- -
// semuanya mengembalikan nilai true
-Array.isArray([]);
-Array.isArray([1]);
-Array.isArray(new Array());
-// Sekedar fakta : Array.prototype sendiri adalah array:
-Array.isArray(Array.prototype);
-
-// semua mengembalikan nilai false
-Array.isArray();
-Array.isArray({});
-Array.isArray(null);
-Array.isArray(undefined);
-Array.isArray(17);
-Array.isArray('Array');
-Array.isArray(true);
-Array.isArray(false);
-Array.isArray({ __proto__: Array.prototype });
-
- -

Polyfill

- -

Jalankan kode berikut sebelum kode lain untuk membuat method Array.isArray() jika secara native tidak tersedia.

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

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES5.1', '#sec-15.4.3.2', 'Array.isArray')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("5")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("9")}}{{CompatOpera("10.5")}}{{CompatSafari("5")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/join/index.html b/files/id/web/javascript/reference/global_objects/array/join/index.html deleted file mode 100644 index 8ddd3bb8ed..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/join/index.html +++ /dev/null @@ -1,132 +0,0 @@ ---- -title: Array.prototype.join() -slug: Web/JavaScript/Reference/Global_Objects/Array/join -tags: - - Array - - Method - - Referensi -translation_of: Web/JavaScript/Reference/Global_Objects/Array/join ---- -
{{JSRef}}
- -

Method join() menggabungkan semua elemen dari sebuah array menjadi sebuah string.

- -

Syntax

- -
str = arr.join([separator = ','])
- -

Parameter

- -
-
separator
-
Opsional. Menentukan string untuk memisahkan setiap elemen array. separator dapat di konersi ke string jika diperlukan. Jika dihilangkan, elemen array akan dipisahkan dengan koma, jika separator adalah string kosong, semua elemen digabungkan tanpa karakter pemisah.
-
- -

Deskripsi

- -

mengonversi string dari semua elemen array dengan menggabungkannya menjadi sebuah string. Jika elemen bernilai undefined atau null, akan dikonversi menjadi string kosong.

- -

Contoh

- -

Penggabungan array menggunakan empat cara yang berbeda

- -

Berikut merupakan contoh membuat array, dengan tiga elemen, kemudian menggabungkan array dengan empa cara berbeda : menggunakan separator default, koma dan spasi, plus dan string kosong.

- -
var a = ['Angin', 'Air', 'Api'];
-var variabel1 = a.join();      // Memberikan nilai 'Angin,Air,Api' pada variabel1
-var variabel2 = a.join(', ');  // Memberikan nilai 'Angin, Air, Api' pada variabel2
-var variabel3 = a.join(' + '); // Memberikan nilai 'Angin + Air + Api' pada variabel3
-var variabel4 = a.join('');    // Memberikan nilai 'AnginAirApi' pada variabel4
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{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')}} 
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan Dasar{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan Dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/length/index.html b/files/id/web/javascript/reference/global_objects/array/length/index.html deleted file mode 100644 index 6e8e9e3ae8..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/length/index.html +++ /dev/null @@ -1,145 +0,0 @@ ---- -title: Array.length -slug: Web/JavaScript/Reference/Global_Objects/Array/length -tags: - - Array - - JavaScript - - Property - - Reference -translation_of: Web/JavaScript/Reference/Global_Objects/Array/length ---- -
{{JSRef}}
- -

Properti array length merangkai atau mengembalikan angka dari sejumlah elemen pada array. berupa unsigned, 32-bit integer yang selalu lebih besar dari indeks array terbesar atau index array terakhir.

- -
var items = ["sepatu", "kaos", "baju", "sweater"];
-items.length;
-
-// index terakhir "sweater" 3
-// returns 4
- -

Deskripsi

- -

Nilai properti length berupa integer positif dan nilainya lebih kecil dari 2 sampai 2 pangkat 32 (232).

- -

Anda bisa merangkai properti length untuk memotong array kapanpun. Ketika anda memperpanjang array dengan mengubah properti length, nomor dari elemen sebenarnya tidak bertambah; contoh, jika anda merangkai length ke 3 ketika saat ini adalah 2, array tetap berisi 2 element. Dengan begitu, properti length tidak selalu menunjukkan jumlah angka dari nilai yang didefinisikan pada array. Lihat juga Hubungan antara length dan properti numerik.

- -

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

- -

Contoh

- -

Iterasi pada array

- -

Pada contoh, numbers array diiterasikan melalui nilai properti array length. Nilai setiap elemen kemudian dikalikan.

- -
var numbers = [1, 2, 3, 4, 5];
-var length = numbers.length;
-for (var i = 0; i < length; i++) {
-  numbers[i] *= 2;
-}
-// numbers is now [2, 4, 6, 8, 10]
-
- -

Memendekan array

- -

Pada contoh memendekkan array numbers ke panjang array 3 jika panjang array sebenarnya lebih besar dari 3.

- -
var numbers = [1,2,3,4,5];
-
-if (numbers.length > 3) {
-  numbers.length = 3;
-}
-
-console.log(numbers); // [1, 2, 3]
-console.log(numbers.length); // 3
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{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')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/of/index.html b/files/id/web/javascript/reference/global_objects/array/of/index.html deleted file mode 100644 index 49ca553133..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/of/index.html +++ /dev/null @@ -1,129 +0,0 @@ ---- -title: Array.of() -slug: Web/JavaScript/Reference/Global_Objects/Array/of -tags: - - Array - - JavaScript - - Method -translation_of: Web/JavaScript/Reference/Global_Objects/Array/of ---- -
{{JSRef}}
- -

Method Array.of() membuat instansi Array baru denganjumlah variabel argumen.

- -

Perbedaan antara Array.of() dan konstruktor Array pada penanganan argumen integer: Array.of(42) membuat sebuah array dengan sebuah elemen, 42, sedang Array(42) membuat array dengan 42 element, yang masing - masing undefined.

- -

Sintaks

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

Parameter

- -
-
elementN
-
Element yang digunakan untuk membuat array.
-
- -

Deskripsi

- -

Fungsi ini merupakan bagian dari ECMAScript 6 standard. Untuk informasi lengkap lihat Array.of and Array.from proposal dan Array.of polyfill.

- -

Contoh

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

Polyfill

- -

Menjalankan kode berikut sebelum kode lain membuat Array.of() jika secara native tidak tersedia.

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

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-array.of', 'Array.of')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.of', 'Array.of')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(45)}}{{CompatGeckoDesktop("25")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome(39)}}{{CompatGeckoMobile("25")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/pop/index.html b/files/id/web/javascript/reference/global_objects/array/pop/index.html deleted file mode 100644 index f8dc9f0523..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/pop/index.html +++ /dev/null @@ -1,134 +0,0 @@ ---- -title: Array.prototype.pop() -slug: Web/JavaScript/Reference/Global_Objects/Array/pop -tags: - - Array - - JavaScript - - Method - - Prototype -translation_of: Web/JavaScript/Reference/Global_Objects/Array/pop ---- -
{{JSRef}}
- -

Method pop() menghapus elemen terakhir dari array dan mengembalikan elemen tersebut.

- -

Syntaks

- -
arr.pop()
- -

Deskripsi

- -

Method pop menghapus elemen terakhir pada array dan mengembalikan nilai ke pemanggil.

- -

pop adalah desain generic; method ini dapat berupa {{jsxref("Function.call", "called", "", 1)}} atau {{jsxref("Function.apply", "applied", "", 1)}} ke objek yang menyerupai array. Objek yang tidak memiliki properti length mencerminkan akhir dari urutan, properti numerik yang berbasis zero mungkin tidak memiliki makna yang berarti.

- -

jika anda menggunakan pop() pada array yang kosong, akan mengembalikan nilai {{jsxref("undefined")}}.

- -

Contoh

- -

Menghapus elemen terakhir pada array

- -

Kode berikut membuat array myFish yang memiliki empat elemen, kemudian menghapus elemen teakhirnya.

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

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{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')}} 
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/reverse/index.html b/files/id/web/javascript/reference/global_objects/array/reverse/index.html deleted file mode 100644 index dca16b463e..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/reverse/index.html +++ /dev/null @@ -1,127 +0,0 @@ ---- -title: Array.prototype.reverse() -slug: Web/JavaScript/Reference/Global_Objects/Array/reverse -tags: - - Array - - Method -translation_of: Web/JavaScript/Reference/Global_Objects/Array/reverse ---- -
{{JSRef}}
- -

Method reverse() membalikkan urutan array elemen. Elemen array pertama menjadi terakhir dan sebaliknya.

- -

Sintaks

- -
arr.reverse()
- -

Parameter

- -

None.

- -

Deskripsi

- -

Method reverse mengubah urutan elemen objek array, memutasi array, dan mengembalikan referensi ke array.

- -

Contoh

- -

Membalikan elemen di dalam array

- -

Pada contoh membuat array myArray dengan tiga elemen,  kemudian membalikkan array.

- -
var myArray = ['one', 'two', 'three'];
-myArray.reverse();
-
-console.log(myArray) // ['three', 'two', 'one']
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{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')}} 
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/shift/index.html b/files/id/web/javascript/reference/global_objects/array/shift/index.html deleted file mode 100644 index ac20d5cd60..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/shift/index.html +++ /dev/null @@ -1,129 +0,0 @@ ---- -title: Array.prototype.shift() -slug: Web/JavaScript/Reference/Global_Objects/Array/shift -translation_of: Web/JavaScript/Reference/Global_Objects/Array/shift ---- -
{{JSRef}}
- -

method shift() menghapus elemen pertama pada array dan mengembalikan elemen tersebut. Method ini mengubah panjang (jumlah elemen) array.

- -

Sintaks

- -
arr.shift()
- -

Deskripsi

- -

Method shift menghapus elemen pada index 0 dan menggeser nilai index setelahnya, kemudian mengembalikan nilai yang dihapus. Jika properti {{jsxref("Array.length", "length")}} bernilai 0, maka akan mengembalikan nilai {{jsxref("undefined")}}.

- -

shift adalah desain generic; method ini dapat berupa {{jsxref("Function.call", "called", "", 1)}} atau {{jsxref("Function.apply", "applied", "", 1)}} pada objek yag menyerupai array. Objek yang tidak memiliki properti length akan dianggap terakhir dalam urutan, properti numerik berbasis zero mungkin tidak memiliki makna yang berarti.

- -

Contoh

- -

Menghapus Elemen dari sebuah Array

- -

Kode berikut menampilkan array myFish sebelum dan sesudah menghapus elemen pertama. Juga menampilkan elemen yang dihapus:

- -
var myFish = ['angel', 'clown', 'mandarin', 'surgeon'];
-
-console.log('myFish sebelum: ' + myFish);
-// myFish sebelum: angel,clown,mandarin,surgeon
-
-var shifted = myFish.shift();
-
-console.log('myFish sesudah: ' + myFish);
-// myFish sesudah: clown,mandarin,surgeon
-
-console.log('Elemen yang dihapus: ' + shifted);
-// Elemen yang dihapus: angel
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{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')}} 
- -

Kompabiltas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/slice/index.html b/files/id/web/javascript/reference/global_objects/array/slice/index.html deleted file mode 100644 index 44f018ba65..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/slice/index.html +++ /dev/null @@ -1,152 +0,0 @@ ---- -title: Array.prototype.slice() -slug: Web/JavaScript/Reference/Global_Objects/Array/slice -translation_of: Web/JavaScript/Reference/Global_Objects/Array/slice ---- -
{{JSRef}}
- -

Method slice() mengembalikan sebuah salinan dangkal dari sebagian array menjadi sebuah objek array baru yang dimulai dari start sampai end (end tidak termasuk) dimana start dan end merupakan index dari  item yang ada di  array tersebut. Tidak merubah array asli.

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

Sintaks

- -
arr.slice([start[, end]])
-
- -

Parameter

- -
-
start {{optional_inline}}
-
Indeks berbasis nol untuk memulai ekstraksi.
-

- Indeks negatif dapat digunakan, menunjukkan offset dari akhir urutan.. slice(-2) mengekstrak dua elemen terakhir dari urutan.
-
Jika start tidak terdefinisi, slice memulai dari indeks ke 0.
-
Jika start lebih besar dari indeks urutan, array kosong akan dikembalikan.
-
end {{optional_inline}}
-
Indeks berbasis nol untuk mengakhiri ekstraksi. slice mengekstrak hingga tapi tidak termasuk end. Sebagai contoh, slice(1,4) mengekstrak elemen kedua menuju elemen ke-empat (indeks elemen 1, 2, dan 3).
-
-

Indeks negatif bisa digunakan,
- menunjukkan offset dari akhir urutan. slice(2,-1) mengekstrak elemen ketiga menuju elemen kedua-ke-terakhir dalam urutan.

-
-
Jika end dihillangkan, slice mengekstrak melalui akhir dari urutan (arr.length).
-
Jika end lebih besar dari panjang urutan, slice mengkstrak melalui akhir urutan (arr.length).
-
- -

Return value

- -

Array baru berisi elemen yang diekstrak.

- -

Deskripsi

- -

slice does not alter the original array. It returns a shallow copy of elements from the original array. Elements of the original array are copied into the returned array as follows:

- - - -

If a new element is added to either array, the other array is not affected.

- -

Contoh

- -

Return a portion of an existing array

- -
let fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
-let citrus = fruits.slice(1, 3)
-
-// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
-// citrus contains ['Orange','Lemon']
-
- -

Using slice

- -

In the following example, slice creates a new array, newCar, from myCar. Both include a reference to the object myHonda. When the color of myHonda is changed to purple, both arrays reflect the change.

- -
// Using slice, create newCar from myCar.
-let myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } }
-let myCar = [myHonda, 2, 'cherry condition', 'purchased 1997']
-let newCar = myCar.slice(0, 2)
-
-// Display the values of myCar, newCar, and the color of myHonda
-//  referenced from both arrays.
-console.log('myCar = ' + JSON.stringify(myCar))
-console.log('newCar = ' + JSON.stringify(newCar))
-console.log('myCar[0].color = ' + myCar[0].color)
-console.log('newCar[0].color = ' + newCar[0].color)
-
-// Change the color of myHonda.
-myHonda.color = 'purple'
-console.log('The new color of my Honda is ' + myHonda.color)
-
-// Display the color of myHonda referenced from both arrays.
-console.log('myCar[0].color = ' + myCar[0].color)
-console.log('newCar[0].color = ' + newCar[0].color)
-
- -

This script writes:

- -
myCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2,
-         'cherry condition', 'purchased 1997']
-newCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2]
-myCar[0].color = red
-newCar[0].color = red
-The new color of my Honda is purple
-myCar[0].color = purple
-newCar[0].color = purple
-
- -

Array-like objects

- -

slice method can also be called to convert Array-like objects/collections to a new Array. You just {{jsxref("Function.prototype.bind", "bind")}} the method to the object. The {{jsxref("Functions/arguments", "arguments")}} inside a function is an example of an 'array-like object'.

- -
function list() {
-  return Array.prototype.slice.call(arguments)
-}
-
-let list1 = list(1, 2, 3) // [1, 2, 3]
-
- -

Binding can be done with the {{jsxref("Function.prototype.call", "call()")}} method of {{jsxref("Function.prototype")}} and it can also be reduced using [].slice.call(arguments) instead of Array.prototype.slice.call.

- -

Anyway, it can be simplified using {{jsxref("Function.prototype.bind", "bind")}}.

- -
let unboundSlice = Array.prototype.slice
-let slice = Function.prototype.call.bind(unboundSlice)
-
-function list() {
-  return slice(arguments)
-}
-
-let list1 = list(1, 2, 3) // [1, 2, 3]
- -

Spesifikasi

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

Kompatibilitas Peramban

- - - -

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

- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/splice/index.html b/files/id/web/javascript/reference/global_objects/array/splice/index.html deleted file mode 100644 index a0c7c1cb86..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/splice/index.html +++ /dev/null @@ -1,146 +0,0 @@ ---- -title: Array.prototype.splice() -slug: Web/JavaScript/Reference/Global_Objects/Array/splice -tags: - - Indonesia -translation_of: Web/JavaScript/Reference/Global_Objects/Array/splice ---- -
{{JSRef}}
- -

Metode splice() mengubah konten dari array dengan menghapus elemen yang ada dan/atau menambah elemen baru.

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

Syntax

- -
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
-
- -

Parameters

- -
-
start
-
Indeks di mana untuk mulai mengubah array (dengan asal 0). Jika lebih besar dari panjang array, indeks awal sebenarnya akan diatur ke panjang array. Jika negatif, akan mulai banyak elemen dari akhir array (dengan asal -1) dan akan diset ke 0 jika nilai absolut lebih besar dari panjang array.
-
deleteCount {{optional_inline}}
-
Sebuah integer yang menunjukkan jumlah elemen array lama yang akan dihapus.
-
Jika deleteCount dihilangkan, atau jika nilainya lebih besar dari array.length - start (yaitu, jika lebih besar dari jumlah elemen yang tersisa dalam array, mulai dari start), maka semua elemen dari start sampai akhir dari array akan dihapus.
-
Jika deleteCount adalah 0 atau negatif, tidak ada elemen yang dihapus. Dalam kasus ini, Anda harus menentukan setidaknya satu elemen baru (lihat di bawah).
-
item1, item2, ... {{optional_inline}}
-
Elemen yang ditambahkan ke array, dimulai pada indeks awal. Jika kamu tidak menentukan elemen apapun, splice() hanya akan menghapus elemen-elemen dari array.
-
- -

Return value

- -

Array berisi elemen yang dihapus. Jika hanya satu elemen yang dihapus, array dari satu elemen dikembalikan. Jika tidak ada elemen yang dihapus, sebuah array kosong akan dikembalikan.

- -

Deskripsi

- -

Jika anda menentukan elemen yang berbeda untuk disisipkan daripada nomor yang anda hapus, array akan memiliki panjang yang berbeda ketika kamu memanggilnya nanti.

- -

Contoh

- -

Remove 0 elements from index 2, and insert "drum"

- -
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
-var removed = myFish.splice(2, 0, 'drum');
-
-// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]
-// removed is [], no elements removed
-
- -

Remove 1 element from index 3

- -
var myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon'];
-var removed = myFish.splice(3, 1);
-
-// removed is ["mandarin"]
-// myFish is ["angel", "clown", "drum", "sturgeon"]
-
- -

Remove 1 element from index 2, and insert "trumpet"

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

Remove 2 elements from index 0, and insert "parrot", "anemone" and "blue"

- -
var myFish = ['angel', 'clown', 'trumpet', 'sturgeon'];
-var removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue');
-
-// myFish is ["parrot", "anemone", "blue", "trumpet", "sturgeon"]
-// removed is ["angel", "clown"]
- -

Remove 2 elements from index 2

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

Remove 1 element from index -2

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

Remove all elements after index 2 (incl.)

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

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{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')}} 
- -

Browser compatibility

- -
- - -

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

-
- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/array/unshift/index.html b/files/id/web/javascript/reference/global_objects/array/unshift/index.html deleted file mode 100644 index 4df2069f54..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/unshift/index.html +++ /dev/null @@ -1,135 +0,0 @@ ---- -title: Array.prototype.unshift() -slug: Web/JavaScript/Reference/Global_Objects/Array/unshift -translation_of: Web/JavaScript/Reference/Global_Objects/Array/unshift ---- -
{{JSRef}}
- -

Method unshift() menambahkan satu atau lebih elemen ke indek awal array dan mengembalikan jumlah index array yang baru.

- -

Sintaks

- -
arr.unshift([element1[, ...[, elementN]]])
- -

Parameter

- -
-
elementN
-
Elemen yang akan di tambahkan di awal array.
-
- -

Returns

- -

Properti {{jsxref("Array.length", "length")}} baru dari objek teratas dimana method di panggil.

- -

Deskripsi

- -

Method unshift menambahkan nilai yang diberikan ke awal objek array.

- -

unshift biasanya generic; method ini bisa berupa {{jsxref("Function.call", "called", "", 1)}} atau {{jsxref("Function.apply", "applied", "", 1)}} ke objek menyerupai array. Objek yang tidak memiliki properti length mencerminkan dari serangkaian urutan, properti numerik berbasis zero kemungkinan tidak berperilaku dengan cara yang berarti.

- -

Contoh

- -
var arr = [1, 2];
-
-arr.unshift(0); // result of call is 3, the new array length
-// arr is [0, 1, 2]
-
-arr.unshift(-2, -1); // = 5
-// arr is [-2, -1, 0, 1, 2]
-
-arr.unshift([-3]);
-// arr is [[-3], -2, -1, 0, 1, 2]
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{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')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/values/index.html b/files/id/web/javascript/reference/global_objects/array/values/index.html deleted file mode 100644 index dd77cc65a5..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/values/index.html +++ /dev/null @@ -1,120 +0,0 @@ ---- -title: Array.prototype.values() -slug: Web/JavaScript/Reference/Global_Objects/Array/values -translation_of: Web/JavaScript/Reference/Global_Objects/Array/values ---- -
{{JSRef}}
- -

Method values() mengembalikan objek Array Iterator baru yang berisi nilai setiap index pada array.

- -

Sintaks

- -
arr.values()
- -

Contoh

- -

Iterasi menggunakan for...of loop

- -
var arr = ['w', 'y', 'k', 'o', 'p'];
-var eArr = arr.values();
-// your browser must support for..of loop
-// and let-scoped variables in for loops
-for (let letter of eArr) {
-  console.log(letter);
-}
-
- -

Iterasi alternatif

- -
var arr = ['w', 'y', 'k', 'o', 'p'];
-var eArr = arr.values();
-console.log(eArr.next().value); // w
-console.log(eArr.next().value); // y
-console.log(eArr.next().value); // k
-console.log(eArr.next().value); // o
-console.log(eArr.next().value); // p
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-array.prototype.values', 'Array.prototype.values')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.values', 'Array.prototype.values')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("51")}}{{CompatGeckoDesktop(48)}}{{CompatNo}}{{CompatNo}}9
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome("51")}}{{CompatGeckoMobile(48)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/date/getfullyear/index.html b/files/id/web/javascript/reference/global_objects/date/getfullyear/index.html deleted file mode 100644 index 08e657aeec..0000000000 --- a/files/id/web/javascript/reference/global_objects/date/getfullyear/index.html +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: Date.prototype.getFullYear() -slug: Web/JavaScript/Reference/Global_Objects/Date/getFullYear -tags: - - Date - - JavaScript - - Metode - - Prototype - - Referensi -translation_of: Web/JavaScript/Reference/Global_Objects/Date/getFullYear ---- -
{{JSRef}}
- -

Metode getFullYear() mengembanlikan tahun dari tanggal yang dispesifikasi, mengikuti waktu lokal.

- -

Gunakan metode ini ketimbang metode {{jsxref("Date.prototype.getYear()", "getYear()")}}.

- -
{{EmbedInteractiveExample("pages/js/date-getfullyear.html")}}
- - - -

Syntax

- -
dateObj.getFullYear()
- -

Nilai kembali

- -

Angka yang berkorespondensi ke tahuny dari tanggal yang diberikan, mengikuti waktu lokal.

- -

Deskripsi

- -

Nilai yang dikembalikan oleh getFullYear() is an absolute number. For dates between the years 1000 and 9999, getFullYear() returns a four-digit number, for example, 1995. Use this function to make sure a year is compliant with years after 2000.

- -

Contoh

- -

Menggunakan getFullYear()

- -

Contoh ini menggassign nilai empat-digit dari tahun saat ini ke variabel year.

- -
var today = new Date();
-var year = today.getFullYear();
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomen
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi inisial. Diimplementasi di JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.10', 'Date.prototype.getFullYear')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.getfullyear', 'Date.prototype.getFullYear')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.getfullyear', 'Date.prototype.getFullYear')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas peramban

- - - -

{{Compat("javascript.builtins.Date.getFullYear")}}

- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/date/index.html b/files/id/web/javascript/reference/global_objects/date/index.html deleted file mode 100644 index 1fc6272dcf..0000000000 --- a/files/id/web/javascript/reference/global_objects/date/index.html +++ /dev/null @@ -1,261 +0,0 @@ ---- -title: Date -slug: Web/JavaScript/Reference/Global_Objects/Date -tags: - - Date - - JavaScript - - NeedsTranslation - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Date ---- -
{{JSRef}}
- -

Creates a JavaScript Date instance that represents a single moment in time. Date objects are based on a time value that is the number of milliseconds since 1 January, 1970 UTC.

- -

Syntax

- -
new Date();
-new Date(value);
-new Date(dateString);
-new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);
-
- -
-

Note: JavaScript Date objects can only be instantiated by calling JavaScript Date as a constructor: calling it as a regular function (i.e. without the {{jsxref("Operators/new", "new")}} operator) will return a string rather than a Date object; unlike other JavaScript object types, JavaScript Date objects have no literal syntax.

-
- -

Parameters

- -
-

Note: Where Date is called as a constructor with more than one argument, if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013, 13, 1) is equivalent to new Date(2014, 1, 1), both create a date for 2014-02-01 (note that the month is 0-based). Similarly for other values: new Date(2013, 2, 1, 0, 70) is equivalent to new Date(2013, 2, 1, 1, 10) which both create a date for 2013-03-01T01:10:00.

-
- -
-

Note: Where Date is called as a constructor with more than one argument, the specifed arguments represent local time. If UTC is desired, use new Date({{jsxref("Date.UTC()", "Date.UTC(...)")}}) with the same arguments.

-
- -
-
value
-
Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC (Unix Epoch).
-
dateString
-
String value representing a date. The string should be in a format recognized by the {{jsxref("Date.parse()")}} method (IETF-compliant RFC 2822 timestamps and also a version of ISO8601). -
-

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.

-
-
-
year
-
Integer value representing the year. Values from 0 to 99 map to the years 1900 to 1999. See the {{anch("Example:_Two_digit_years_map_to_1900_-_1999", "example below")}}.
-
month
-
Integer value representing the month, beginning with 0 for January to 11 for December.
-
day
-
Optional. Integer value representing the day of the month.
-
hour
-
Optional. Integer value representing the hour of the day.
-
minute
-
Optional. Integer value representing the minute segment of a time.
-
second
-
Optional. Integer value representing the second segment of a time.
-
millisecond
-
Optional. Integer value representing the millisecond segment of a time.
-
- -

Description

- - - -

Properties

- -
-
{{jsxref("Date.prototype")}}
-
Allows the addition of properties to a JavaScript Date object.
-
Date.length
-
The value of Date.length is 7. This is the number of arguments handled by the constructor.
-
- -

Methods

- -
-
{{jsxref("Date.now()")}}
-
Returns the numeric value corresponding to the current time - the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.
-
{{jsxref("Date.parse()")}}
-
Parses a string representation of a date and returns the number of milliseconds since 1 January, 1970, 00:00:00, UTC. -
-

Note: Parsing of strings with Date.parse is strongly discouraged due to browser differences and inconsistencies.

-
-
-
{{jsxref("Date.UTC()")}}
-
Accepts the same parameters as the longest form of the constructor (i.e. 2 to 7) and returns the number of milliseconds since 1 January, 1970, 00:00:00 UTC.
-
- -

JavaScript Date instances

- -

All Date instances inherit from {{jsxref("Date.prototype")}}. The prototype object of the Date constructor can be modified to affect all Date instances.

- -

Date.prototype Methods

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

Examples

- -

Several ways to create a Date object

- -

The following examples show several ways to create JavaScript dates:

- -
-

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.

-
- -
var today = new Date();
-var birthday = new Date('December 17, 1995 03:24:00');
-var birthday = new Date('1995-12-17T03:24:00');
-var birthday = new Date(1995, 11, 17);
-var birthday = new Date(1995, 11, 17, 3, 24, 0);
-
- -

Two digit years map to 1900 - 1999

- -

In order to create and get dates between the years 0 and 99 the {{jsxref("Date.prototype.setFullYear()")}} and {{jsxref("Date.prototype.getFullYear()")}} methods should be used.

- -
var date = new Date(98, 1); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)
-
-// Deprecated method, 98 maps to 1998 here as well
-date.setYear(98);           // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)
-
-date.setFullYear(98);       // Sat Feb 01 0098 00:00:00 GMT+0000 (BST)
-
- -

Calculating elapsed time

- -

The following examples show how to determine the elapsed time between two JavaScript dates in millisconds.

- -

Due to the differing lengths of days (due to daylight saving changeover), months and years, expressing elapsed time in units greater than hours, minutes and seconds requires addressing a number of issues and should be thoroughly researched before being attempted.

- -
// using Date objects
-var start = Date.now();
-
-// the event to time goes here:
-doSomethingForALongTime();
-var end = Date.now();
-var elapsed = end - start; // elapsed time in milliseconds
-
- -
// using built-in methods
-var start = new Date();
-
-// the event to time goes here:
-doSomethingForALongTime();
-var end = new Date();
-var elapsed = end.getTime() - start.getTime(); // elapsed time in milliseconds
-
- -
// to test a function and get back its return
-function printElapsedTime(fTest) {
-  var nStartTime = Date.now(),
-      vReturn = fTest(),
-      nEndTime = Date.now();
-
-  console.log('Elapsed time: ' + String(nEndTime - nStartTime) + ' milliseconds');
-  return vReturn;
-}
-
-yourFunctionReturn = printElapsedTime(yourFunction);
-
- -
-

Note: In browsers that support the {{domxref("window.performance", "Web Performance API", "", 1)}}'s high-resolution time feature, {{domxref("Performance.now()")}} can provide more reliable and precise measurements of elapsed time than {{jsxref("Date.now()")}}.

-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-date-objects', 'Date')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-date-objects', 'Date')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-15.9', 'Date')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [2]{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [1]
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

[1] Some browsers can have issues when parsing dates: 3/14/2012 blog from danvk Comparing FF/IE/Chrome on Parsing Date Strings

- -

[2] ISO8601 Date Format is not supported in Internet Explorer 8, and other version can have issues when parsing dates

diff --git a/files/id/web/javascript/reference/global_objects/date/now/index.html b/files/id/web/javascript/reference/global_objects/date/now/index.html deleted file mode 100644 index 43760a275b..0000000000 --- a/files/id/web/javascript/reference/global_objects/date/now/index.html +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: Date.now() -slug: Web/JavaScript/Reference/Global_Objects/Date/now -tags: - - Date - - JavaScript - - Method - - Referensi -translation_of: Web/JavaScript/Reference/Global_Objects/Date/now ---- -
{{JSRef}}
- -

Method Date.now() mengembalikan jumlah milisekon sejak 1 Januari 1970 00:00:00 UTC.

- -

Sintaks

- -
var timeInMs = Date.now();
- -

Parameter

- -

None.

- -

Deskripsi

- -

Method now() mengembalikan nilaimillisekon sejak 1 January 1970 00:00:00 UTC hingga sekarang sebagai {{jsxref("Number")}}.

- -

Karena now() adalah method static dari {{jsxref("Date")}}, anda bisa menggunakannya sebagai Date.now().

- -

Polyfill

- -

Method ini di bakukan pada ECMA-262 5th edition. Mesin yang belum diupdate untuk mendukung method ini bisa menggunkan shim berikut:

- -
if (!Date.now) {
-  Date.now = function now() {
-    return new Date().getTime();
-  };
-}
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES5.1', '#sec-15.9.4.4', 'Date.now')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.5.
{{SpecName('ES6', '#sec-date.now', 'Date.now')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.now', 'Date.now')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatChrome("5")}}{{CompatGeckoDesktop("1.9")}}{{CompatIE("9")}}{{CompatOpera("10.50")}}{{CompatSafari("4")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/date/tojson/index.html b/files/id/web/javascript/reference/global_objects/date/tojson/index.html deleted file mode 100644 index cb951d5fa0..0000000000 --- a/files/id/web/javascript/reference/global_objects/date/tojson/index.html +++ /dev/null @@ -1,119 +0,0 @@ ---- -title: Date.prototype.toJSON() -slug: Web/JavaScript/Reference/Global_Objects/Date/toJSON -tags: - - Date - - Method - - Referensi -translation_of: Web/JavaScript/Reference/Global_Objects/Date/toJSON ---- -
{{JSRef}}
- -

Method toJSON() mengembalikan string berdasarkan pada object {{jsxref("Date")}}.

- -

Syntax

- -
dateObj.toJSON()
- -

Deskripsi

- -

{{jsxref("Date")}} mengacu pada titik waktu tertentu. Memanggil toJSON() mengembalikan nilai ke string (menggunakan {{jsxref("Date.prototype.toISOString()", "toISOString()")}}) berdasarkan nilai pada object {{jsxref("Date")}}. Method ini biasanya ditujukan, secara default, guna menserialisasi object {{jsxref("Date")}} saat serialisasi {{Glossary("JSON")}}.

- -

Contoh

- -

Penggunaan toJSON()

- -
var jsonDate = (new Date()).toJSON();
-var backToDate = new Date(jsonDate);
-
-console.log(jsonDate); //2015-10-26T07:46:36.611Z
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES5.1', '#sec-15.9.5.44', 'Date.prototype.toJSON')}}{{Spec2('ES5.1')}}Definisi Inisial. Diimplementasikan dalam JavaScript 1.8.5.
{{SpecName('ES6', '#sec-date.prototype.tojson', 'Date.prototype.toJSON')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.tojson', 'Date.prototype.toJSON')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

 

- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/date/totimestring/index.html b/files/id/web/javascript/reference/global_objects/date/totimestring/index.html deleted file mode 100644 index 90ebd23e68..0000000000 --- a/files/id/web/javascript/reference/global_objects/date/totimestring/index.html +++ /dev/null @@ -1,125 +0,0 @@ ---- -title: Date.prototype.toTimeString() -slug: Web/JavaScript/Reference/Global_Objects/Date/toTimeString -tags: - - Date - - JavaScript - - Prototype - - Referensi -translation_of: Web/JavaScript/Reference/Global_Objects/Date/toTimeString ---- -
{{JSRef}}
- -

Method toTimeString() mengembalikan satuan waktu dari objek {{jsxref("Date")}} object dalam format yang dapat dibaca manusia.

- -

Sintaks

- -
dateObj.toTimeString()
- -

Deskripsi

- -

Instansi {{jsxref("Date")}} menunjuk pada titik waktu spesifik. Dengan memanggil {{jsxref("Date.prototype.toString()", "toString()")}} akan mengembalikan format tanggal dalam bentuk yang mudah dibaca manuasia dengan format tanggal English (Amerika). Di SpiderMonkey, Bagian tanggal terdiri dari (hari, bulan, dan tahun) di ikuti dengan waktu (Jam, menit, detik, dan waktu bagian). Terkadang kita hanya membutuhan bagian waktu dalam bentuk string; hal tersebut bisa di capai dengan menggunakan metod toTimeString().

- -

Method toTimeString() sangatlah berguna karena berdasarkan engine (compiliant engine) yang di implementasikan ECMA-262 mungkin string yang diperoleh akan berbeda dari {{jsxref("Date.prototype.toString()", "toString()")}} untuk objek {{jsxref("Date")}}, dengan format tergantung dari implementasi; pendekatan bagian string sederhana kemungkinan tidak sama untuk engine yang berbeda.

- -

Contoh

- -

Dasar penggunaan of toTimeString()

- -
var d = new Date(1993, 6, 28, 14, 39, 7);
-
-console.log(d.toString());     // logs Wed Jul 28 1993 14:39:07 GMT-0600 (PDT)
-console.log(d.toTimeString()); // logs 14:39:07 GMT-0600 (PDT)
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.9.5.4', 'Date.prototype.toTimeString')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.totimestring', 'Date.prototype.toTimeString')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.totimestring', 'Date.prototype.toTimeString')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/error/index.html b/files/id/web/javascript/reference/global_objects/error/index.html deleted file mode 100644 index c0fc3cec6f..0000000000 --- a/files/id/web/javascript/reference/global_objects/error/index.html +++ /dev/null @@ -1,231 +0,0 @@ ---- -title: Error -slug: Web/JavaScript/Reference/Global_Objects/Error -tags: - - Error - - JavaScript - - Reference -translation_of: Web/JavaScript/Reference/Global_Objects/Error ---- -
{{JSRef}}
- -

Konstruktor Error membuat sebuah objek error. Misal objek Error di lontarkan ketika terjadi runtime error. Objek Error juga dapat digunakan sebagai objek dasar dengan pengecualian yang ditentukan pengguna. Berikut untuk standard jenis built-in error.

- -

Sintaks

- -
new Error([message[, fileName[, lineNumber]]])
- -

Parameter

- -
-
message
-
Optional. Human-readable description of the error.
-
fileName {{non-standard_inline}}
-
Optional. The value for the fileName property on the created Error object. Defaults to the name of the file containing the code that called the Error() constructor.
-
lineNumber {{non-standard_inline}}
-
Optional. The value for the lineNumber property on the created Error object. Defaults to the line number containing the Error() constructor invocation.
-
- -

Description

- -

Runtime errors result in new Error objects being created and thrown.

- -

This page documents the use of the Error object itself and its use as a constructor function. For a list of properties and methods inherited by Error instances, see {{jsxref("Error.prototype")}}.

- -

Error types

- -

Besides the generic Error constructor, there are six other core error constructors in JavaScript. For client-side exceptions, see Exception Handling Statements.

- -
-
{{jsxref("EvalError")}}
-
Creates an instance representing an error that occurs regarding the global function {{jsxref("Global_Objects/eval", "eval()")}}.
-
{{jsxref("InternalError")}} {{non-standard_inline}}
-
Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g. "too much recursion".
-
{{jsxref("RangeError")}}
-
Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range.
-
{{jsxref("ReferenceError")}}
-
Creates an instance representing an error that occurs when de-referencing an invalid reference.
-
{{jsxref("SyntaxError")}}
-
Creates an instance representing a syntax error that occurs while parsing code in {{jsxref("Global_Objects/eval", "eval()")}}.
-
{{jsxref("TypeError")}}
-
Creates an instance representing an error that occurs when a variable or parameter is not of a valid type.
-
{{jsxref("URIError")}}
-
Creates an instance representing an error that occurs when {{jsxref("Global_Objects/encodeURI", "encodeURI()")}} or {{jsxref("Global_Objects/decodeURI", "decodeURI()")}} are passed invalid parameters.
-
- -

Properties

- -
-
{{jsxref("Error.prototype")}}
-
Allows the addition of properties to Error instances.
-
- -

Methods

- -

The global Error object contains no methods of its own, however, it does inherit some methods through the prototype chain.

- -

Error instances

- -
{{page('en-US/docs/JavaScript/Reference/Global_Objects/Error/prototype', 'Description')}}
- -

Properties

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

Methods

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

Examples

- -

Throwing a generic error

- -

Usually you create an Error object with the intention of raising it using the {{jsxref("Statements/throw", "throw")}} keyword. You can handle the error using the {{jsxref("Statements/try...catch", "try...catch")}} construct:

- -
try {
-  throw new Error('Whoops!');
-} catch (e) {
-  console.log(e.name + ': ' + e.message);
-}
-
- -

Handling a specific error

- -

You can choose to handle only specific error types by testing the error type with the error's {{jsxref("Object.prototype.constructor", "constructor")}} property or, if you're writing for modern JavaScript engines, {{jsxref("Operators/instanceof", "instanceof")}} keyword:

- -
try {
-  foo.bar();
-} catch (e) {
-  if (e instanceof EvalError) {
-    console.log(e.name + ': ' + e.message);
-  } else if (e instanceof RangeError) {
-    console.log(e.name + ': ' + e.message);
-  }
-  // ... etc
-}
-
- -

Custom Error Types

- -

You might want to define your own error types deriving from Error to be able to throw new MyError() and use instanceof MyError to check the kind of error in the exception handler. The common way to do this is demonstrated below.

- -
-

Note that the thrown MyError will report incorrect lineNumber and fileName at least in Firefox.

-
- -

See also the "What's a good way to extend Error in JavaScript?" discussion on Stackoverflow.

- -
// Create a new object, that prototypically inherits from the Error constructor
-function MyError(message) {
-  this.name = 'MyError';
-  this.message = message || 'Default Message';
-  this.stack = (new Error()).stack;
-}
-MyError.prototype = Object.create(Error.prototype);
-MyError.prototype.constructor = MyError;
-
-try {
-  throw new MyError();
-} catch (e) {
-  console.log(e.name);     // 'MyError'
-  console.log(e.message);  // 'Default Message'
-}
-
-try {
-  throw new MyError('custom message');
-} catch (e) {
-  console.log(e.name);     // 'MyError'
-  console.log(e.message);  // 'custom message'
-}
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.11', 'Error')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-error-objects', 'Error')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-error-objects', 'Error')}}{{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/id/web/javascript/reference/global_objects/error/name/index.html b/files/id/web/javascript/reference/global_objects/error/name/index.html deleted file mode 100644 index 6644fff80a..0000000000 --- a/files/id/web/javascript/reference/global_objects/error/name/index.html +++ /dev/null @@ -1,119 +0,0 @@ ---- -title: Error.prototype.name -slug: Web/JavaScript/Reference/Global_Objects/Error/name -tags: - - Error - - JavaScript - - Property - - Prototype -translation_of: Web/JavaScript/Reference/Global_Objects/Error/name ---- -
{{JSRef}}
- -

Properti name menyatakan nama dari jenis error. Nilai awalnya adalah "Error".

- -

Deskripsi

- -

Secara default, misalnya {{jsxref("Error")}} diberi nama "Error". Properti name, sebagai tambahan utuk properti {{jsxref("Error.prototype.message", "message")}}, digunakan oleh method {{jsxref("Error.prototype.toString()")}} untuk membuat sebuah pernyataan dalam bentuk string yang menyatakan error.

- -

Contoh

- -

Menggunakan custom error

- -
var e = new Error('Inputan tidak lengkap'); // e.name nilainya 'Error'
-
-e.name = 'ParseError';
-throw e;
-// e.toString() akan mengembalikan 'ParseError: Inputan tidak lengkap'
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.11.4.2', 'Error.prototype.name')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-error.prototype.name', 'Error.prototype.name')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-error.prototype.name', 'Error.prototype.name')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

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

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/function/displayname/index.html b/files/id/web/javascript/reference/global_objects/function/displayname/index.html deleted file mode 100644 index 952014983b..0000000000 --- a/files/id/web/javascript/reference/global_objects/function/displayname/index.html +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: Function.displayName -slug: Web/JavaScript/Reference/Global_Objects/Function/displayName -tags: - - Function - - JavaScript - - Property -translation_of: Web/JavaScript/Reference/Global_Objects/Function/displayName ---- -
{{JSRef}} {{non-standard_header}}
- -

Properti function.displayName mengembalikan nama fungsi.

- -

Deskripsi

- -

Ketika didefinisikan, properti displayName mengembalikan nama dari sebuah fungsi:

- -
function doSomething() {}
-
-console.log(doSomething.displayName); // "undefined"
-
-var popup = function(content) { console.log(content); };
-
-popup.displayName = 'Show Popup';
-
-console.log(popup.displayName); // "Show Popup"
-
- -

Anda bisa mendefinisikan sebuah fungsi dengan sebuah display nama di {{jsxref("Functions", "function expression", "", 1)}}:

- -
var object = {
-  someMethod: function() {}
-};
-
-object.someMethod.displayName = 'someMethod';
-
-console.log(object.someMethod.displayName); // logs "someMethod"
-
-try { someMethod } catch(e) { console.log(e); }
-// ReferenceError: someMethod is not defined
-
- -

Anda bisa merubah  displayName dari sebuah fungsi secara dinamis:

- -
var object = {
-  // anonymous
-  someMethod: function(value) {
-    this.displayName = 'someMethod (' + value + ')';
-  }
-};
-
-console.log(object.someMethod.displayName); // "undefined"
-
-object.someMethod('123')
-console.log(object.someMethod.displayName); // "someMethod (123)"
-
- -

Contoh

- -

Biasanya lebih banyak digunakan dengan console dan profiler melalui {{jsxref("Function.name", "func.name")}} untuk menampilkan nama function.

- -

Dengan menuliskan kode berikut, maka seharusnya akan menampilkan "function My Function()":

- -
var a = function() {};
-a.displayName = 'My Function';
-
-a; // "function My Function()"
- -

Spesifikasi

- -

Bukan bagian dari spesifikasi.

- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatUnknown}}{{CompatGeckoDesktop(13)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
diff --git a/files/id/web/javascript/reference/global_objects/function/index.html b/files/id/web/javascript/reference/global_objects/function/index.html deleted file mode 100644 index 49d1c1a114..0000000000 --- a/files/id/web/javascript/reference/global_objects/function/index.html +++ /dev/null @@ -1,241 +0,0 @@ ---- -title: Function -slug: Web/JavaScript/Reference/Global_Objects/Function -tags: - - Constructor - - Function - - JavaScript - - NeedsTranslation - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Function ---- -
{{JSRef}}
- -

Konstruktor Function membuat sebuah objek Function baru. Di Javascript setiap fungsi adalah sebuah objek Function.

- -

Sintaks

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

Parameter

- -
-
arg1, arg2, ... argN
-
Nama yang akan digunakan oleh fungsi sebagai nama formal argumen. Masing-masing harus berupa string yang sesuai dengan identifier JavaScript yang valid atau daftar string dipisahkan dengan koma; contohnya "x", "theValue", atau "a,b".
-
functionBody
-
String berisi sintaks JavaScript yang terdiri dari definisi fungsi.
-
- -

Deskripsi

- -

Objek  Function yang dibuat dengan konstruktor Function diuraikan ketika fungsi dibuat. Hal tersebut kurang efisien dibandingkan dengan mendeklarasikan fungsi dengan function expression atau function statement dan memanggilnya dengan kode Anda, karena fungsi-fungsi tersebut diuraikan dengan sisa kode.

- -

Semua argumen yang diteruskan ke fungsi diperlakukan sebagai nama identifier parameter dalam fungsi yang akan dibuat, dalam urutan yang dilewatkan.

- -
-

Catatan: Fungsi dibuat dengan konstruktor Function  jangan membuat penutup pada konteks kreasi mereka; Mereka selalu dibuat dalam ruang lingkup global. Saat menjalankannya, mereka hanya bisa mengakses variabel lokal mereka sendiri dan variabel global, bukan variabel dari ruang lingkup dimana konstruktor Function dipanggil. Berbeda dari menggunakan {{jsxref("eval")}} dengan kode untuk fungsi ekspresi.

-
- -

memanggil konstruktor Function sebagai sebuah fungsi (tanpa menggunakan operatur baru) mempunyai efek yang sama seperti memanggilnya sebagai konstruktor

- -

Properti dan Method Function

- -

Objek Function global tidak memiliki method atau properti sendiri. Namun, fungsi itu sendiri mewarisi beberapa method dan properti melalui prototipe dari {{jsxref("Function.prototype")}}.

- -

Objek prototipe Function

- -

Properti

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

Method

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

Function instances

- -

Function instances mewarisi method dan properti dari {{jsxref("Function.prototype")}}. Seperti halnya semua konstruktor, Anda dapat mengubah objek prototipe konstruktor untuk membuat perubahan pada semua Function instances.

- -

Contoh

- -

Menentukan arguman dengan konstruktor Function

- -

Dibawah ini kode untuk membuat sebuah objek Function yang menggunakan dua argumen.

- -
// Contoh dapat dijalankan langsung di konsol JavaScript Anda
-
-// Buat fungsi yang mengambil dua argumen dan mengembalikan jumlah argumen tersebut
-var adder = new Function('a', 'b', 'return a + b');
-
-// Memanggil fungsi
-adder(2, 6);
-// > 8
-
- -

Argumen "a" dan "b" adalah nama argumen formal yang digunakan pada function body "return a + b".

- -

Pintasan rekursif untuk memofikasi DOM secara masif

- -

Membuat fungsi dengan konstruktor Function adalah salah satu cara dinamis untuk membuat objek baru dengan beberapa kode yang dapat dieksekusi ke dalam lingkup global dari suatu fungsi. Contoh berikut (pintasan rekursif untuk memodifikasi DOM secara masif) tidak dimungkinkan tanpa permintaan konstruktor Function untuk setiap kueri baru jika Anda ingin menghindari penutup tiap fungsi.

- -
<!doctype html>
-<html>
-<head>
-<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
-<title>MDN Example - a recursive shortcut to massively modify the DOM</title>
-<script type="text/javascript">
-var domQuery = (function() {
-  var aDOMFunc = [
-    Element.prototype.removeAttribute,
-    Element.prototype.setAttribute,
-    CSSStyleDeclaration.prototype.removeProperty,
-    CSSStyleDeclaration.prototype.setProperty
-  ];
-
-  function setSomething(bStyle, sProp, sVal) {
-    var bSet = Boolean(sVal), fAction = aDOMFunc[bSet | bStyle << 1],
-        aArgs = Array.prototype.slice.call(arguments, 1, bSet ? 3 : 2),
-        aNodeList = bStyle ? this.cssNodes : this.nodes;
-
-    if (bSet && bStyle) { aArgs.push(''); }
-    for (
-      var nItem = 0, nLen = this.nodes.length;
-      nItem < nLen;
-      fAction.apply(aNodeList[nItem++], aArgs)
-    );
-    this.follow = setSomething.caller;
-    return this;
-  }
-
-  function setStyles(sProp, sVal) { return setSomething.call(this, true, sProp, sVal); }
-  function setAttribs(sProp, sVal) { return setSomething.call(this, false, sProp, sVal); }
-  function getSelectors() { return this.selectors; };
-  function getNodes() { return this.nodes; };
-
-  return (function(sSelectors) {
-    var oQuery = new Function('return arguments.callee.follow.apply(arguments.callee, arguments);');
-    oQuery.selectors = sSelectors;
-    oQuery.nodes = document.querySelectorAll(sSelectors);
-    oQuery.cssNodes = Array.prototype.map.call(oQuery.nodes, function(oInlineCSS) { return oInlineCSS.style; });
-    oQuery.attributes = setAttribs;
-    oQuery.inlineStyle = setStyles;
-    oQuery.follow = getNodes;
-    oQuery.toString = getSelectors;
-    oQuery.valueOf = getNodes;
-    return oQuery;
-  });
-})();
-</script>
-</head>
-
-<body>
-
-<div class="testClass">Lorem ipsum</div>
-<p>Some text</p>
-<div class="testClass">dolor sit amet</div>
-
-<script type="text/javascript">
-domQuery('.testClass')
-  .attributes('lang', 'en')('title', 'Risus abundat in ore stultorum')
-  .inlineStyle('background-color', 'black')('color', 'white')('width', '100px')('height', '50px');
-</script>
-</body>
-
-</html>
-
- -

Spesifikasi

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

Kesesuaian Browser

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

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/function/length/index.html b/files/id/web/javascript/reference/global_objects/function/length/index.html deleted file mode 100644 index 901c11b336..0000000000 --- a/files/id/web/javascript/reference/global_objects/function/length/index.html +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: Function.length -slug: Web/JavaScript/Reference/Global_Objects/Function/length -tags: - - Function - - JavaScript - - Property -translation_of: Web/JavaScript/Reference/Global_Objects/Function/length ---- -
{{JSRef}}
- -

Properti length menentukan jumlah argumen yang diharapkan oleh fungsi.

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

Deskripsi

- -

length merupakan properti dari objek fungsi, dan mengindikasikan berapa banyak argumen yang diharapkan fungsi, mis. jumlah parameter formal. Jumlah ini mengesampingkan {{jsxref("rest_parameters", "rest parameter", "", 1)}}. Sebaliknya, {{jsxref("Functions_and_function_scope/arguments/length", "arguments.length")}} adalah lokal untuk fungsi dan memberikan jumlah argumen sebenarnya ke fungsi.

- -

Properti data dari constructor Function

- -

Construktor {{jsxref("Function")}} sendiri adalah objek {{jsxref("Function")}}. data properti length bernilai 1. Properti atribut: Writable: false, Enumerable: false, Configurable: true.

- -

Properti dari Function prototype object

- -

Panjang properti dari prototype objek {{jsxref("Function")}} bernilai 0.

- -

Contoh

- -
console.log(Function.length); /* 1 */
-
-console.log((function()        {}).length); /* 0 */
-console.log((function(a)       {}).length); /* 1 */
-console.log((function(a, b)    {}).length); /* 2 etc. */
-
-console.log((function(...args) {}).length);
-// 0, rest parameter is not counted
-
-console.log((function(a, b = 1, c) {}).length);
-// 1, only parameters before the first one with
-// a default value is counted
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.3.5.1', 'Function.length')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-instances-length', 'Function.length')}}{{Spec2('ES6')}}The configurable attribute of this property is now true.
{{SpecName('ESDraft', '#sec-function-instances-length', 'Function.length')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Configurable: true{{CompatUnknown}}{{CompatGeckoDesktop(37)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Configurable: true{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(37)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/function/name/index.html b/files/id/web/javascript/reference/global_objects/function/name/index.html deleted file mode 100644 index 1a35d62020..0000000000 --- a/files/id/web/javascript/reference/global_objects/function/name/index.html +++ /dev/null @@ -1,191 +0,0 @@ ---- -title: Function.name -slug: Web/JavaScript/Reference/Global_Objects/Function/name -tags: - - ECMAScript6 - - Function - - JavaScript - - Property -translation_of: Web/JavaScript/Reference/Global_Objects/Function/name ---- -
{{JSRef}}
- -

Properti function.name mengembalikan nama fungsi.

- -
{{js_property_attributes(0,0,1)}}
- -
Perlu di ingat bahwa ini di dalam non-standard, implementasi pre-ES6 atribut configurable juga false.
- -

Deskripsi

- -

Properti name property mengembalikan nama sebuah fungsi , atau (sebelum implementasi ES6) string kosong untuk anonymous functions:

- -
function doSomething() {}
-
-console.log(doSomething.name); // logs "doSomething"
-
- -

Fungsi di buat menggunakan sintaks new Function(...) atau hanya Function(...) memiliki properti name di set empty string. Pada contoh anonymous functions dibuat, sehingga name mengembalikan empty string:

- -
var f = function() {};
-var object = {
-  someMethod: function() {}
-};
-
-console.log(f.name == ''); // true
-console.log(object.someMethod.name == ''); // also true
-
- -

Browser yang mengimplementasikan fungsi ES6 mengambil nama dari anonymous function dari posisi syntactic-nya. Contoh:

- -
var f = function() {};
-console.log(f.name); // "f"
- -

Anda bisa mendefinisikan sebuah fungsi dengan nama di {{jsxref("Operators/Function", "function expression", "", 1)}}:

- -
var object = {
-  someMethod: function object_someMethod() {}
-};
-console.log(object.someMethod.name); // logs "object_someMethod"
-
-try { object_someMethod } catch(e) { console.log(e); }
-// ReferenceError: object_someMethod is not defined
-
- -

Anda tidak bisa mengubah nama fungsi, Properti ini hanya bisa dibaca:

- -
var object = {
-  // anonymous
-  someMethod: function() {}
-};
-
-object.someMethod.name = 'someMethod';
-console.log(object.someMethod.name); // empty string, someMethod is anonymous
-
- -

Untuk mengubah, anda perlu menggunakan {{jsxref("Object.defineProperty()")}}.

- -

Contoh

- -

Anda bisa menggunakan obj.constructor.name untuk memeriksa "class" dari sebuah objek:

- -
function a() {}
-
-var b = new a();
-
-console.log(b.constructor.name); // logs "a"
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-name', 'name')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-name', 'name')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(33.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Configurable: true{{CompatChrome(43.0)}}{{CompatGeckoDesktop(38)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Inferred names on anonymous functions{{CompatChrome(51.0)}}{{CompatNo}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Configurable: true{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(38)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Inferred names on anonymous functions{{CompatNo}}{{CompatChrome(51.0)}}{{CompatNo}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(51.0)}}
-
- -

[1] See {{bug(883377)}}.

diff --git a/files/id/web/javascript/reference/global_objects/index.html b/files/id/web/javascript/reference/global_objects/index.html deleted file mode 100644 index 5259bde5b8..0000000000 --- a/files/id/web/javascript/reference/global_objects/index.html +++ /dev/null @@ -1,189 +0,0 @@ ---- -title: Global Objek -slug: Web/JavaScript/Reference/Global_Objects -tags: - - JavaScript - - Reference -translation_of: Web/JavaScript/Reference/Global_Objects ---- -
{{jsSidebar("Objects")}}
- -

Pada bagian ini membahas standar javascript, objek built-in, Termasuk didalamnya method dan properti.

- -
-

Istilah "Global Objek" (atau standar objek built-in)disini bukan berarti Global Objek. Disini global objek di artikan sebagai objek pada scope global (tapi hanya jika ECMAScript 5 mode strict tidak digunakan; pada kasus ini mengembalikan {{jsxref("undefined")}}).  Global objek sendiri bisa di akses menggunakan operator {{jsxref("Operators/this", "this")}} pada lingkup global. Bahkan, lingkup global terdiri dari properti pada global objek, termasuk peoperti yang diwariskan, jika ada.

- -

Objek lain di lingkup global salah satunya dibuat oleh user script atau disediakan oleh aplikasi host. Objek host tersedia di konteks browser, didokumentasi di Referensi API. Untuk informasi lengkap tentang perbedaan antara DOM dan inti JavaScript, lihat Gambaran teknologi javaScript.

- -

Objek standar berdasarkan kategori

- -

Properti nilai

- -

Properti global ini mengembalikan nilai simple; tidak memiliki properti ataupun method.

- - - -

Properti fungsi

- -

Fungsi global—fungsi yang di panggil secara global bukan pada objek — langsung mengembalikan nilai ke pemenggil.

- - - -

Fundamental objek

- -

Ini merupakan fundamental, objek dasar berdasarkan pada semua objek lain yang didasarkan. Ini termasuk objek yang mewakili objek umum, fungsi dan error.

- - - -

Nomor dan tanggal

- -

Objek dasar yang mewakili angka, tanggal dan kalkulasi matematik.

- - - -

Pengolah teks

- -

Objek yang mewakili string dan dukungan untuk memanipulasinya.

- - - -

Koleksi Index

- -

Objek ini mewakili koleksi data berdasarkan nilai index. Ini termasuk (jenis) array dan konstruksi mirip array (array-like).

- - - -

Koleksi keyed

- -

Objek ini merupakan koleksi yang menggunakan key; mengandung unsur yang iterable di urutan penyisipan.

- - - -

Koleksi vektor

- -

{{Glossary("SIMD")}} tipe data vector adalah objek dimana data diatur arahnya.

- - - -

Data terstruktur

- -

Objek ini mewakili dan berinteraksi dengan buffer data terstruktur dan data yang dikodekan menggunakan JavaScript Object Notation (JSON).

- - - -

Kontrol objek abstraksi 

- - - -

Refleksi (Pantulan)

- - - -

Internasionalisasi

- -

Penambahan inti ECMAScript untuk fungsi bahasa-sensitif.

- - - -

Objek Non-standar

- - - -

Lainnya

- - -
- -

 

diff --git a/files/id/web/javascript/reference/global_objects/isnan/index.html b/files/id/web/javascript/reference/global_objects/isnan/index.html deleted file mode 100644 index b7a6774528..0000000000 --- a/files/id/web/javascript/reference/global_objects/isnan/index.html +++ /dev/null @@ -1,186 +0,0 @@ ---- -title: isNaN() -slug: Web/JavaScript/Reference/Global_Objects/isNaN -translation_of: Web/JavaScript/Reference/Global_Objects/isNaN ---- -
{{jsSidebar("Objects")}}
- -

Fungsi isNaN() menentukan apakah nilai adalah sebuah {{jsxref("NaN")}} atau bukan. Catatan: pemaksaan pada fungsi isNaN memiliki aturan yang menarik. Anda mungkin ingin menggunakan {{jsxref("Number.isNaN()")}}, seperti yang didefinisikan dalam ECMAScript 2015.

- -

Syntax

- -
isNaN(value)
- -

Parameters

- -
-
value
-
Nilai yang akan di uji.
-
- -

Return value

- -

true Jika nilai yang di uji adalah {{jsxref("NaN")}}; jika tidak, false.

- -

Deskripsi

- -

Kebutuhan akan fungsi isNaN

- -

Mungkin tidak seperti nilai lainnya dalam javascript, Ini tidak memungkinkan untuk mengandalkan operator persamaan (== dan ===) untuk menentukan bahwa nilai adalah {{jsxref("NaN")}} atau bukan, karena NaN == NaN dan NaN === NaN mengevaluasi ke false. Oleh karena itu, diperlukan adanya fungsi isNaN.

- -

Asal Mula Nilai NaN

- -

NilaiNaN dihasilkan saat operasi aritmatika menghasilkan nilai undefined atau unrepresentable. Nilai tersebut tidak harus mewakili kondisi overflowNaN juga dihasilkan dari percobaan pemaksaan ke nilai numerik dari nilai non-numerik yang tidak memiliki nilai numerik primitif yang tersedia.

- -

Misalnya, membagi nol dengan nol menghasilkan sebuah NaN — namun membagi angka lain dengan nol tidak menghasilkan sebuah NaN.

- -

Perilaku Khusus yang membingungkan

- -

Karena versi paling awal dari spesifikasi fungsi isNaN , perilaku untuk argumen non-numerik menjadi membingungkan. Ketika argumen ke fungsi isNaN bukan bertipe Number, Nilainya akan dipaksakan terlebih dahulu ke tipe Number. Nilai yang dihasilkan kemudian diuji untuk menentukan apakah itu {{jsxref("NaN")}}. Jadi untuk non-angka yang jika dipaksakan pada hasil numerik menghasilkan nilai numerik non-NaN (terutama string kosong dan primitif boolean, yang jika dipaksakan memberi nilai numerik nol atau satu), nilai pengembalian "false" mungkin tidak terduga; String kosong, misalnya, pastinya "not a number". Kebingungan itu berawal dari kenyataan bahwa istilah "not a number", memiliki arti khusus untuk angka yang diwakili sebagai nilai floating-point IEEE-754. Fungsi harus diinterpretasikan sebagai penjawab pertanyaan, "apakah nilai ini, jika dipaksakan pada nilai numerik, nilai IEEE-754 'Not A Number'?"

- -

Versi terbaru dari ECMAScript (ES2015) berisi fungsi {{jsxref("Number.isNaN()")}}. Number.isNaN(x) akan menjadi cara yang andal untuk menguji apakah x adalah NaN atau bukan. Bahkan dengan Number.isNaN, namun arti NaN tetap merupakan makna numerik yang tepat, dan bukan sekadar, "not a number". Sebagai alternatif, untuk ketidakhadiran Number.isNaN, ekspresi (x != x) adalah cara yang lebih dapat diandalkan untuk menguji apakah variabel x adalah NaN atau bukan, karena hasilnya tidak sesuai dengan false positive yang membuat isNaN tidak dapat diandalkan.

- -

Anda bisa memikirkan isNaN sebagai:

- -
var isNaN = function(value) {
-    return Number.isNaN(Number(value));
-}
- -

Contoh

- -
isNaN(NaN);       // true
-isNaN(undefined); // true
-isNaN({});        // true
-
-isNaN(true);      // false
-isNaN(null);      // false
-isNaN(37);        // false
-
-// strings
-isNaN('37');      // false: "37" dikonversi ke nomor 37 yang mana bukan NaN
-isNaN('37.37');   // false: "37.37" dikonversi ke nomor 37.37 yang mana bukan NaN
-isNaN('123ABC');  // true:  parseInt("123ABC") adalah 123 namun Number("123ABC") adalah NaN
-isNaN('');        // false: string kosing dikonversi ke 0 yang mana bukan NaN
-isNaN(' ');       // false: string dengan spasi dikonversi ke 0 yang mana bukan NaN
-
-// dates
-isNaN(new Date());                // false
-isNaN(new Date().toString());     // true
-
-// Ini adalah false positif dan alasan mengapa NaN tidak sepenuhnya dapat diandalkan
-isNaN('blabla');   // true: "blabla" dikonversi ke nomor.
-                   // Parsing ini sebagai nomor gagal dan mengembalikan NaN
-
- -

Berguna dalam perilaku khusus

- -

Ada cara penggunaan yang lebih berorientasi untuk memikirkan isNaN isNaN(): Jika isNaN(x) mengembalikan false, anda bisa menggunakan x dalam ekspresi aritmatika tidak membuat ekspresi mengembalikan NaN. Jika itu mengembalikantrue, x akan membuat setiap ekspresi aritmatika mengembalikan NaN. Ini berarti bahwa dalam JavaScript, isNaN(x) == true setara dengan x - 0 mengembalikan NaN (meskipun di JavaScript x - 0 == NaN selalu mengembalikan false, jadi anda tidak bisa mengujinya). Sebenarnya, isNaN(x), isNaN(x - 0), isNaN(Number(x)), Number.isNaN(x - 0), dan Number.isNaN(Number(x)) selalu kembali sama dan di JavaScriptisNaN(x) hanya bentuk sesingkat mungkin untuk mengungkapkan masing-masing istilah ini.

- -

Anda dapat menggunakan ini, misalnya, untuk menguji apakah sebuah argumen terhadap suatu fungsi secara aritmatika dapat diolah (dapat digunakan "seperti" angka), atau jika tidak dan Anda harus memberikan nilai default atau yang lainnya. Dengan cara ini Anda dapat memiliki fungsi yang memanfaatkan fleksibilitas penuh JavaScript yang disediakan oleh nilai konversi secara implisit bergantung pada konteks.

- -

Contoh

- -
function increment(x) {
-  if (isNaN(x)) x = 0;
-  return x + 1;
-}
-
-// Efek yang sama dengan Number.isNaN():
-function increment(x) {
-  if (Number.isNaN(Number(x))) x = 0;
-  return x + 1;
-}
-
-// Dalam kasus berikut untuk argumen fungsi x,
-// isNaN(x)selalu salah, meski x memang bukan sebuah
-// nomor, namun bisa digunakan seperti itu dalam ekspresi
-// aritmatika
-increment('');            // 1: "" dikonversi ke 0
-increment(new String());  // 1: Objek String yang mewakili string kosong dikonversi menjadi 0
-increment([]);            // 1: [] dikonversi ke 0
-increment(new Array());   // 1: Objek array yang mewakili sebuah array kosong dikonversi menjadi 0
-increment('0');           // 1: "0" dikonversi ke 0
-increment('1');           // 2: "1" dikonversi ke 1
-increment('0.1');         // 1.1: "0.1" dikonversi ke 0.1
-increment('Infinity');    // Infinity: "Infinity" dikonversi ke Infinity
-increment(null);          // 1: null dikonversi ke 0
-increment(false);         // 1: false dikonversi ke 0
-increment(true);          // 2: true dikonversi ke 1
-increment(new Date());    // mengembalikan tanggal/waktu sekarang dalam milidetik ditambah 1
-
-// Dalam kasus berikut untuk argumen fungsi x,
-// isNaN(x) selalu false dan x memang angka
-increment(-1);            // 0
-increment(-0.1);          // 0.9
-increment(0);             // 1
-increment(1);             // 2
-increment(2);             // 3
-// ... dan seterusnya ...
-increment(Infinity);      // Infinity
-
-// Dalam kasus berikut untuk argumen fungsi x,
-// isNaN(x) selalu true dan x benar-benar bukan angka,
-// sehingga fungsi tersebut menggantikannya dengan 0 dan mengembalikan 1
-increment(String);            // 1
-increment(Array);             // 1
-increment('blabla');          // 1
-increment('-blabla');         // 1
-increment(0 / 0);               // 1
-increment('0 / 0');             // 1
-increment(Infinity / Infinity); // 1
-increment(NaN);               // 1
-increment(undefined);         // 1
-increment();                  // 1
-
-// isNaN(x) selalu sama dengan isNaN(Number(x)),
-// namun kehadirannya x adalah wajib disini!
-isNaN(x) == isNaN(Number(x)); // true untuk setiap nilai x, termasuk x == undefined,
-                              // karena isNaN(undefined) == true dan Number(undefined) mengembalikan NaN,
-                              // namun ...
-isNaN() == isNaN(Number());   // false, karena isNaN() == true dan Number() == 0
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.1.2.4', 'isNaN')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-isnan-number', 'isNaN')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-isnan-number', 'isNaN')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- - - -

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

- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/json/index.html b/files/id/web/javascript/reference/global_objects/json/index.html deleted file mode 100644 index 4f07030358..0000000000 --- a/files/id/web/javascript/reference/global_objects/json/index.html +++ /dev/null @@ -1,243 +0,0 @@ ---- -title: JSON -slug: Web/JavaScript/Reference/Global_Objects/JSON -translation_of: Web/JavaScript/Reference/Global_Objects/JSON ---- -
{{JSRef}}
- -

Didalam object JSON terdapat banyak method untuk memparse JavaScript Object Notation ({{glossary("JSON")}}) dan mengkonversi nilai ke JSON. Hal ini tidak dapat di gunakan atau dibangun, dan selain dari kedua sifat method tersebut tidak memiliki fungsi tersendiri.

- -

Deskripsi

- -

JavaScript Object Notation

- -

JSON merupakan sebuah syntax untuk menserialisasi objects, array, angka, string, boolean, dan {{jsxref("null")}}. Hal ini dilihat berdasarkan pada syntax  javascript. Akan tetapi terpisah dari dari hal tersebut: beberapa javascript bukanlah JSON, dan beberapa JSON juga tidak dapat dikatakan sebagai Javascript. Lihat juga JSON: The JavaScript subset that isn't.

- - - - - - - - - - - - - - - - - - - - - - - -
Perbedaan JavaScript dan JSON
Type pada JavaScriptPerbedaan dengan JSON
Object dan ArrayNama properti harus menggunakan string double quotes; tidak diakhiri dengan koma.
AngkaTidak diawali dengan nol; desimal harus di ikuti setidaknya satu digit.
String -

Hanya beberapa karakter tertentu yang menggunakan escape; Kontrol karakter tertentu tidak diperbolehkan; Pemisah baris Unicode (U+2028) dan pemisah paragraf (U+2029) dapat digunakan; string harus menggunakan double-quoted. Lihat contoh dimana {{jsxref("JSON.parse()")}} bisa digunakan dan {{jsxref("SyntaxError")}} dilemparkan ketika mengevaluasi kode sebagai javascript:

- -
-var kode = '"\u2028\u2029"';
-JSON.parse(kode); // bisa digunakan.
-eval(kode); // gagal!
-
-
- -

Syntax JSON lengkapnya sebagai berikut:

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

Whitespace yang tidak signifikan dapat digunakan dimanasaja kecuali didalam JSONNumber (angka tidak dipisahkan dengan whitespace) atau JSONString (dimana ditafsirkan sebagai karakter yang sesuai dalam string; atau akan menyebabkan kesalahan). Karakter Tab (U+0009), carriage return (U+000D), line feed (U+000A), dan karakter spasi (U+0020) merupakan karakter whitespace yang valid.

- -

Method

- -
-
{{jsxref("JSON.parse()")}}
-
Memparse string sebagai JSON, biasanya mengubah nilai yang diberikan beserta sifatnya, dan mengembalikan nilai.
-
{{jsxref("JSON.stringify()")}}
-
Mengembalikan string JSON berdasarkan nilai spesifik, biasanya termasuk beberapa properti tertentu saja atau mengganti nilai properti secara user-defined.
-
- -

Polyfill

- -

Object JSON tidak didukung oleh browser lawas. Anda bisa menyiasatinya dengan memasukkan kode berikut di awal skrip Anda, memungkinkan penggunaan JSON objek dalam implementasi yang secara native tidak mendukung Object JSON (seperti Internet Explorer 6).

- -

Algoritma berikut adalah tiruan dari objek JSON asli:

- -
if (!window.JSON) {
-  window.JSON = {
-    parse: function(sJSON) { return eval('(' + sJSON + ')'); },
-    stringify: (function () {
-      var toString = Object.prototype.toString;
-      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) {
-              if (value.hasOwnProperty(k))
-                tmp.push(stringify(k) + ': ' + stringify(value[k]));
-            }
-            return '{' + tmp.join(', ') + '}';
-          }
-        }
-        return '"' + value.toString().replace(escRE, escFunc) + '"';
-      };
-    })()
-  };
-}
-
- -

Lebih kompleks dari polyfills yang banyak dikenal untuk object JSON adalah JSON2 dan JSON3.

- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES5.1', '#sec-15.12', 'JSON')}}{{Spec2('ES5.1')}}Initial definition.
{{SpecName('ES6', '#sec-json-object', 'JSON')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-json-object', 'JSON')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("8.0")}}{{CompatOpera("10.5")}}{{CompatSafari("4.0")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

 

- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/json/parse/index.html b/files/id/web/javascript/reference/global_objects/json/parse/index.html deleted file mode 100644 index 5eb3f60424..0000000000 --- a/files/id/web/javascript/reference/global_objects/json/parse/index.html +++ /dev/null @@ -1,171 +0,0 @@ ---- -title: JSON.parse() -slug: Web/JavaScript/Reference/Global_Objects/JSON/parse -tags: - - ECMAScript5 - - JSON - - Method - - Referensi -translation_of: Web/JavaScript/Reference/Global_Objects/JSON/parse ---- -
{{JSRef}}
- -

Method JSON.parse() memparse string ke JSON, biasanya mengubah nilai yang dihasilkan oleh parsing.

- -

Sintaks

- -
JSON.parse(text[, reviver])
- -

Parameters

- -
-
text
-
String yang akan di parse ke JSON. Lihat objek {{jsxref("JSON")}} untuk deskripsi lengkap sintaks JSON.
-
reviver {{optional_inline}}
-
Jika sebuah fungsi, mendeskripsikan bagaimana nilai asli dihasilkan oleh parsing berubah, sebelum dikembalikan.
-
- -

Pemulangan

- -

Mengembalikan {{jsxref("Object")}} sesuai dengan teks JSON yang diberikan.

- -

Lontaran

- -

Melontarkan pengecualian {{jsxref("SyntaxError")}} jika string yang di parse tidak sesuai JSON.

- -

Contoh

- -

Menggunakan JSON.parse()

- -
JSON.parse('{}');              // {}
-JSON.parse('true');            // true
-JSON.parse('"foo"');           // "foo"
-JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
-JSON.parse('null');            // null
-
- -

Menggunakan parameter reviver

- -

Jika reviver telah ditentukan, nilai dihitung dengan parsing transformed sebelum dikembalikan. Khususnya, nilai yang terhitung, dan semua propertinya (dimulai dari properti yang paling bersarang dan berlanjut ke nilai asli), secara individu dijalankan melalui reviver, yang di panggil dengan objek yang berada di dalam properti yang akan diproses sebagai this dan dengan nama properti sebagai string dan nilai properti sebagai argumen. jika fungsi reviver mengembalikan {{jsxref("undefined")}} (tidak mengembalikan nilai, contoh, jika eksekusi gagal di akhir fungsi), properti akan dihapus dari objek. Jika tidak, properti akan didefinisikan ulang sebagai sebuah nilai kembali.

- -

reviver dipanggil dengan string kosong dan nilai paling atas mengizinkan tranformsi dari nilai paling atas. Jadi untuk menangani kasus ini dengan baik, biasanya dengan mengembalikan nilai yang diberikan, atau JSON.parse() akan mengembalikan {{jsxref("undefined")}}.

- -
JSON.parse('{"p": 5}', function(k, v) {
-  if (k === '') { return v; } // if topmost value, return it,
-  return v * 2;               // else return v * 2.
-});                           // { p: 10 }
-
-JSON.parse('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}', function(k, v) {
-  console.log(k); // log the current property name, the last is "".
-  return v;       // return the unchanged property value.
-});
-
-// 1
-// 2
-// 4
-// 6
-// 5
-// 3
-// ""
-
- -

JSON.parse() tidak mengizinkan trailing koma

- -
// both will throw a SyntaxError
-JSON.parse('[1, 2, 3, 4, ]');
-JSON.parse('{"foo" : 1, }');
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES5.1', '#sec-15.12.2', 'JSON.parse')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.7.
{{SpecName('ES6', '#sec-json.parse', 'JSON.parse')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-json.parse', 'JSON.parse')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("8.0")}}{{CompatOpera("10.5")}}{{CompatSafari("4.0")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Gecko-specific notes

- -

Pada Gecko 29 {{geckoRelease("29")}}, string JSON yang gagal akan menampilkan pesan kesalahan yang lebih rinci tentang error dalam memparse. Hal ini sangat berguna ketika mendebug data JSON yang besar.

- -
JSON.parse('[1, 2, 3, 4,]');
-// SyntaxError: JSON.parse: unexpected character at
-// line 1 column 13 of the JSON data
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/map/clear/index.html b/files/id/web/javascript/reference/global_objects/map/clear/index.html deleted file mode 100644 index 2869835e02..0000000000 --- a/files/id/web/javascript/reference/global_objects/map/clear/index.html +++ /dev/null @@ -1,109 +0,0 @@ ---- -title: Map.prototype.clear() -slug: Web/JavaScript/Reference/Global_Objects/Map/clear -translation_of: Web/JavaScript/Reference/Global_Objects/Map/clear ---- -
{{JSRef}}
- -

Method clear() menghapus semua elemen yang ada pada objek Map.

- -

Sintaks

- -
myMap.clear();
- -

Contoh

- -

Menggunakan method clear

- -
var myMap = new Map();
-myMap.set("bar", "baz");
-myMap.set(1, "foo");
-
-myMap.size;       // 2
-myMap.has("bar"); // true
-
-myMap.clear();
-
-myMap.size;       // 0
-myMap.has("bar")  // false
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-map.prototype.clear', 'Map.prototype.clear')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-map.prototype.clear', 'Map.prototype.clear')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar38{{CompatGeckoDesktop("19.0")}}11257.1
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasart{{CompatNo}}38{{CompatGeckoMobile("19.0")}}{{CompatNo}}{{CompatNo}}8
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/map/delete/index.html b/files/id/web/javascript/reference/global_objects/map/delete/index.html deleted file mode 100644 index ad9d1922b9..0000000000 --- a/files/id/web/javascript/reference/global_objects/map/delete/index.html +++ /dev/null @@ -1,114 +0,0 @@ ---- -title: Map.prototype.delete() -slug: Web/JavaScript/Reference/Global_Objects/Map/delete -translation_of: Web/JavaScript/Reference/Global_Objects/Map/delete ---- -
{{JSRef}}
- -

Method  delete() menghapus elemen yang ditentukan dari objek Map.

- -

Sintaks

- -
myMap.delete(key);
- -

Parameter

- -
-
key
-
Diperlukan. Kunci dari elemen untuk menghapusnya dari objek Map.
-
- -

Return value

- -

Mengembalikan nilai true jika elemen yang ada di dalam objek Map ada dan telah dihapus, atau false jika elemen tidak ada.

- -

Contoh

- -

Menggunakan method delete

- -
var myMap = new Map();
-myMap.set("bar", "foo");
-
-myMap.delete("bar"); // Returns true. Berhasil dihapus.
-myMap.has("bar");    // Returns false. Elemen "bar" sudah tidak tersedia.
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-map.prototype.delete', 'Map.prototype.delete')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-map.prototype.delete', 'Map.prototype.delete')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar38{{CompatGeckoDesktop("13.0")}}11257.1
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatNo}}38{{CompatGeckoMobile("13.0")}}{{CompatNo}}{{CompatNo}}8
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/map/index.html b/files/id/web/javascript/reference/global_objects/map/index.html deleted file mode 100644 index 9e4a93cfa0..0000000000 --- a/files/id/web/javascript/reference/global_objects/map/index.html +++ /dev/null @@ -1,443 +0,0 @@ ---- -title: Map -slug: Web/JavaScript/Reference/Global_Objects/Map -tags: - - ECMAScript6 - - JavaScript - - Map - - NeedsTranslation - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Map ---- -
{{JSRef}}
- -

The Map object is a simple key/value map. 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
-
Iterable is an Array or other iterable object whose elements are key-value pairs (2-element Arrays). Each key-value pair is added to the new Map. null is 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.

- -

Key equality

- -

Key equality is based on the "same-value" 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 earlier versions of the ECMAScript 6 draft -0 and +0 were considered distinct (even though -0 === +0), this has been changed in later versions and has been adapted in Gecko 29 {{geckoRelease("29")}} ({{bug("952870")}}) and a recent nightly Chrome.

- -

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 between Objects and Maps that make using a Map better:

- - - -

This does not mean you should use Maps everywhere, objects still are used in most cases. Map instances are only useful for collections, and you should consider adapting your code where you have previously used objects for such. Objects shall be used as records, with fields and methods.
- If you're still not sure which one to use, ask yourself the following questions:

- - - -

Those all are signs that you want a Map for a collection. If in contrast you have a fixed amount of keys, operate on them individually, and distinguish between their usage, then you want an object.

- -

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);
-}
-// Will show 2 logs; first with "0 = zero" and second with "1 = one"
-
-for (var key of myMap.keys()) {
-  console.log(key);
-}
-// Will show 2 logs; first with "0" and second with "1"
-
-for (var value of myMap.values()) {
-  console.log(value);
-}
-// Will show 2 logs; first with "zero" and second with "one"
-
-for (var [key, value] of myMap.entries()) {
-  console.log(key + " = " + value);
-}
-// Will show 2 logs; first with "0 = zero" and second with "1 = one"
-
- -

Iterating Maps with forEach()

- -

Maps can be iterated using the forEach() method:

- -
myMap.forEach(function(value, key) {
-  console.log(key + " = " + value);
-}, myMap)
-// 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 spread operator to transform a map into a 2D key-value Array.
-console.log(uneval([...myMap])); // Will show you exactly the same Array as kvArray
-
-// Or use the spread operator on the keys or values iterator to get
-// an array of only the keys or values
-console.log(uneval([...myMap.keys()])); // Will show ["key1", "key2"]
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-map-objects', 'Map')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-map-objects', 'Map')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support -

{{ CompatChrome(38) }} [1]

-
{{ CompatGeckoDesktop("13") }}11257.1
Constructor argument: new Map(iterable){{ CompatChrome(38) }}{{ CompatGeckoDesktop("13") }}{{CompatNo}}25{{CompatNo}}
iterable{{ CompatChrome(38) }}{{ CompatGeckoDesktop("17") }}{{CompatNo}}257.1
Map.clear(){{ CompatChrome(31) }}
- {{ CompatChrome(38) }}
{{CompatGeckoDesktop("19")}}11257.1
Map.keys(), Map.values(), Map.entries(){{ CompatChrome(37) }}
- {{ CompatChrome(38) }}
{{CompatGeckoDesktop("20")}}{{CompatNo}}257.1
Map.forEach(){{ CompatChrome(36) }}
- {{ CompatChrome(38) }}
{{CompatGeckoDesktop("25")}}11257.1
Key equality for -0 and 0{{ CompatChrome(34) }}
- {{ CompatChrome(38) }}
{{CompatGeckoDesktop("29")}}{{CompatNo}}25{{CompatNo}}
Constructor argument: new Map(null){{CompatVersionUnknown}}{{CompatGeckoDesktop("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Monkey-patched set() in Constructor{{CompatVersionUnknown}}{{CompatGeckoDesktop("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Map[@@species]{{CompatUnknown}}{{CompatGeckoDesktop("41")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Map() without new throws{{CompatUnknown}}{{ CompatGeckoDesktop("42") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{ CompatChrome(38) }} [1]{{ CompatGeckoMobile("13") }}{{CompatNo}}{{CompatNo}}8
Constructor argument: new Map(iterable){{CompatNo}}{{ CompatChrome(38) }}{{ CompatGeckoMobile("13") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
iterable{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile("17") }}{{CompatNo}}{{CompatNo}}8
Map.clear(){{CompatNo}}{{ CompatChrome(31) }}
- {{ CompatChrome(38) }}
{{CompatGeckoMobile("19")}}{{CompatNo}}{{CompatNo}}8
Map.keys(), Map.values(), Map.entries(){{CompatNo}}{{ CompatChrome(37) }}
- {{ CompatChrome(38) }}
{{CompatGeckoMobile("20")}}{{CompatNo}}{{CompatNo}}8
Map.forEach(){{CompatNo}}{{ CompatChrome(36) }}
- {{ CompatChrome(38) }}
{{CompatGeckoMobile("25")}}{{CompatNo}}{{CompatNo}}8
Key equality for -0 and 0{{CompatNo}}{{ CompatChrome(34) }}
- {{ CompatChrome(38) }}
{{CompatGeckoMobile("29")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Constructor argument: new Map(null){{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Monkey-patched set() in Constructor{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Map[@@species]{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("41")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Map() without new throws{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("42")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

[1] Starting with Chrome 31, the feature was available behind a preference. In chrome://flags, activate the entry “Enable Experimental JavaScript”.

- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/math/abs/index.html b/files/id/web/javascript/reference/global_objects/math/abs/index.html deleted file mode 100644 index c15b00b315..0000000000 --- a/files/id/web/javascript/reference/global_objects/math/abs/index.html +++ /dev/null @@ -1,145 +0,0 @@ ---- -title: Math.abs() -slug: Web/JavaScript/Reference/Global_Objects/Math/abs -tags: - - Math - - abs - - math abs -translation_of: Web/JavaScript/Reference/Global_Objects/Math/abs ---- -
{{JSRef}}
- -

Fungsi Math.abs() mengembalikan nilai mutlak dari sebuah bilangan, yakni

- -

Math.abs(x)=|x|={xifx>00ifx=0-xifx<0{\mathtt{\operatorname{Math.abs}(x)}} = {|x|} = \begin{cases} x & \text{if} \quad x \geq 0 \\ -x & \text{if} \quad x < 0 \end{cases}

- -

Sintak

- -
Math.abs(x)
- -

Parameter

- -
-
x
-
Sebuah bilangan.
-
- -

Nilai kembali

- -

Nilai mutlak dari bilangan yang diberikan.

- -

Deskripsi

- -

Karena abs() merupakan sebuah metode statis dari Math, anda harus menggunakannya/menulisnya sebagai berikut Math.abs(), Bukan sebagai metode dari sebuah object Math yang anda buat (Math bukanlah sebuah konstruktor).

- -

Contoh

- -

Prilaku dari Math.abs()

- -

Mengabaikan objek kosong, sebuah array dengan lebih dari satu anggota, sebuah string non-numerik atau {{jsxref("undefined")}}/variabel kosong dikembalikan{{jsxref("NaN")}}. Mengabaikan {{jsxref("null")}}, sebuah string kosong atau sebuah array kosong akan menghasilkan 0.

- -
Math.abs('-1');     // 1
-Math.abs(-2);       // 2
-Math.abs(null);     // 0
-Math.abs('');       // 0
-Math.abs([]);       // 0
-Math.abs([2]);      // 2
-Math.abs([1,2]);    // NaN
-Math.abs({});       // NaN
-Math.abs('string'); // NaN
-Math.abs();         // NaN
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi awal. Diimplementasikan pada JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.1', 'Math.abs')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.abs', 'Math.abs')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.abs', 'Math.abs')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome untuk AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/math/ceil/index.html b/files/id/web/javascript/reference/global_objects/math/ceil/index.html deleted file mode 100644 index cba010ffdb..0000000000 --- a/files/id/web/javascript/reference/global_objects/math/ceil/index.html +++ /dev/null @@ -1,174 +0,0 @@ ---- -title: Math.ceil() -slug: Web/JavaScript/Reference/Global_Objects/Math/ceil -tags: - - JavaScript - - Math - - Metode - - Referensi -translation_of: Web/JavaScript/Reference/Global_Objects/Math/ceil ---- -
{{JSRef}}
- -

Fungsi Math.ceil() adalah memberikan nilai integer lebih-besar-dari terkecil atau sama-dengan (pembulatan ke atas) nilai yang ditentukan.

- -

Catatan: Nilai kembalian Math.ceil(null) adalah integer 0 dan tidak memberikan kesalahan NaN.

- -
{{EmbedInteractiveExample("pages/js/math-ceil.html")}}
- - - -

Sintaks

- -
Math.ceil(x)
- -

Parameter

- -
-
x
-
Sebuah angka.
-
- -

Nilai kembali

- -

Nilai integer lebih-besar-dari terkecil atau sama-dengan (pembulatan ke atas) nilai yang ditentukan.

- -

Deskripsi

- -

Karena ceil() adalah sebuah metode statis dari Math, Anda harus selalu menggunakan sebagai Math.ceil(), bukan sebagai metode dari object  Math yang Anda buat (Math bukanlah sebuah konstruktor).

- -

Contoh

- -

Menggunakan Math.ceil()

- -

Berikut adalah contoh penggunaan dari Math.ceil().

- -
Math.ceil(.95);    // 1
-Math.ceil(4);      // 4
-Math.ceil(7.004);  // 8
-Math.ceil(-0.95);  // -0
-Math.ceil(-4);     // -4
-Math.ceil(-7.004); // -7
-
- -

Penyesuaian desimal

- -
// Closure
-(function() {
-  /**
-   * Penyesuaian desimal dari sebuah angka.
-   *
-   * @param {String}  type  Tipe dari penyesuaian.
-   * @param {Number}  value Angka.
-   * @param {Integer} exp   Eksponen (10 logaritma basis penyesuaian).
-   * @returns {Number} Nilai yang di sesuaikan.
-   */
-  function decimalAdjust(type, value, exp) {
-    // jika exp adalah undefined atau nol...
-    if (typeof exp === 'undefined' || +exp === 0) {
-      return Math[type](value);
-    }
-    value = +value;
-    exp = +exp;
-    // Jika nilai adalah bukan sebuah angka atau bilangan integer...
-    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
-      return NaN;
-    }
-    // Shift
-    value = value.toString().split('e');
-    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
-    // Shift back
-    value = value.toString().split('e');
-    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
-  }
-
-  // Decimal round
-  if (!Math.round10) {
-    Math.round10 = function(value, exp) {
-      return decimalAdjust('round', value, exp);
-    };
-  }
-  // Decimal floor
-  if (!Math.floor10) {
-    Math.floor10 = function(value, exp) {
-      return decimalAdjust('floor', value, exp);
-    };
-  }
-  // Decimal ceil
-  if (!Math.ceil10) {
-    Math.ceil10 = function(value, exp) {
-      return decimalAdjust('ceil', value, exp);
-    };
-  }
-})();
-
-// Round
-Math.round10(55.55, -1);   // 55.6
-Math.round10(55.549, -1);  // 55.5
-Math.round10(55, 1);       // 60
-Math.round10(54.9, 1);     // 50
-Math.round10(-55.55, -1);  // -55.5
-Math.round10(-55.551, -1); // -55.6
-Math.round10(-55, 1);      // -50
-Math.round10(-55.1, 1);    // -60
-// Floor
-Math.floor10(55.59, -1);   // 55.5
-Math.floor10(59, 1);       // 50
-Math.floor10(-55.51, -1);  // -55.6
-Math.floor10(-51, 1);      // -60
-// Ceil
-Math.ceil10(55.51, -1);    // 55.6
-Math.ceil10(51, 1);        // 60
-Math.ceil10(-55.59, -1);   // -55.5
-Math.ceil10(-59, 1);       // -50
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomen
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi awal. Diimplementasikan dalam JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.6', 'Math.ceil')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.ceil', 'Math.ceil')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.ceil', 'Math.ceil')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas peramban

- -
- -
- -

{{Compat("javascript.builtins.Math.ceil")}}

- -

Lihat pula

- - diff --git a/files/id/web/javascript/reference/global_objects/math/e/index.html b/files/id/web/javascript/reference/global_objects/math/e/index.html deleted file mode 100644 index 79e9f21f4a..0000000000 --- a/files/id/web/javascript/reference/global_objects/math/e/index.html +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: Math.E -slug: Web/JavaScript/Reference/Global_Objects/Math/E -translation_of: Web/JavaScript/Reference/Global_Objects/Math/E ---- -
{{JSRef}}
- -

Properti Math.E mewakili dasar logaritma alami, e,  mendekati 2.718.

- -

Math.E=e2.718\mathtt{\mi{Math.E}} = e \approx 2.718

- -
{{EmbedInteractiveExample("pages/js/math-e.html")}}
- - - -
{{js_property_attributes(0, 0, 0)}}
- -

Deskripsi

- -

Karena E adalah sebuah properti matematika statis, saudara selalu menggunakannya sebagai Math.E, daripada sebagai sebuah properti dari objek matematika yang saudara buat. (Math bukan sebuah konstruktor).

- -

Contoh

- -

Menggunakan Math.E

- -

Fungsi berikut menampilkan nilai e:

- -
function getNapier() {
-  return Math.E;
-}
-
-getNapier(); // 2.718281828459045
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ES1')}}{{Spec2('ES1')}} -

definisi inisial. Diimplementasikan dalam  JavaScript 1.0.

-
{{SpecName('ES5.1', '#sec-15.8.1.1', 'Math.E')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.e', 'Math.E')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.e', 'Math.E')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas browser

- - - -

{{Compat("javascript.builtins.Math.E")}}

- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/math/floor/index.html b/files/id/web/javascript/reference/global_objects/math/floor/index.html deleted file mode 100644 index ecd6e89cdd..0000000000 --- a/files/id/web/javascript/reference/global_objects/math/floor/index.html +++ /dev/null @@ -1,210 +0,0 @@ ---- -title: Math.floor() -slug: Web/JavaScript/Reference/Global_Objects/Math/floor -tags: - - Math - - math floor - - pembulatan - - pembulatan bilangan - - pembulatan kebawah javascript -translation_of: Web/JavaScript/Reference/Global_Objects/Math/floor ---- -
{{JSRef}}
- -

Fungsi Math.floor() mengembalikan bilangan bulat terbesar yang kurang dari atau sama dengan bilangan yang diberikan.

- -

Sintaks

- -
Math.floor(x)
- -

Parameter

- -
-
x
-
Sebuah bilangan.
-
- -

Nilai kembali

- -

Sebuah bilangan yang merepresentasikan bilangan bulat terbesar yang kurang dari atau sama dengan nilai yang diberikan

- -

Deskripsi

- -

Karena floor() adalah sebuah metode statis dari Math, sintaks yang harus anda gunakan adalah Math.floor(), bukan sebagai metode dari obyek Math yang anda buat (Math bukanlah sebuah konstruktor).

- -

Contoh

- -

Penggunaan Math.floor()

- -
Math.floor( 45.95); //  45
-Math.floor( 45.05); //  45
-Math.floor(  4   ); //   4
-Math.floor(-45.05); // -46
-Math.floor(-45.95); // -46
-
- -

Penyesuaian desimal

- -
// Closure
-(function() {
-  /**
-   * Penyesuaian desimal dari sebuah bilangan.
-   *
-   * @param {String}  type  Jenis penyesuaian.
-   * @param {Number}  value Nomor.
-   * @param {Integer} exp   Eksponen (10 logaritma dari penyesuaian dasar).
-   * @returns {Number} Nilai yang disesuaikan.
-   */
-  function decimalAdjust(jenis, nilai, eks) {
-    // Jika eks adalah undefined(belum didefinisikan) atau kosong...
-    if (typeof eks === 'undefined' || +eks === 0) {
-      return Math[jenis](nilai);
-    }
-    nilai = +nilai;
-    eks= +eks;
-    // Jika nilai bukan sebuah angka atau eks bukan sebuah bilangan integer...
-    if (isNaN(nilai) || !(typeof eks === 'number' && eks % 1 === 0)) {
-      return NaN;
-    }
-    // Pengalihan
-    nilai = nilai.toString().split('e');
-    nilai = Math[jenis](+(nilai[0] + 'e' + (nilai[1] ? (+nilai[1] - eks) : -eks)));
-    // pengalihan kembali
-    nilai = nilai.toString().split('e');
-    return +(nilai[0] + 'e' + (nilai[1] ? (+nilai[1] + eks) : eks));
-  }
-
-  // Desimal bulat
-  if (!Math.round10) {
-    Math.round10 = function(nilai, eks) {
-      return decimalAdjust('round', nilai, eks);
-    };
-  }
-  // Desimal floor
-  if (!Math.floor10) {
-    Math.floor10 = function(nilai, eks) {
-      return decimalAdjust('floor', nilai, eks);
-    };
-  }
-  // Desimal ceil
-  if (!Math.ceil10) {
-    Math.ceil10 = function(nilai, eks) {
-      return decimalAdjust('ceil', nilai, eks);
-    };
-  }
-})();
-
-// Round
-Math.round10(55.55, -1);   // 55.6
-Math.round10(55.549, -1);  // 55.5
-Math.round10(55, 1);       // 60
-Math.round10(54.9, 1);     // 50
-Math.round10(-55.55, -1);  // -55.5
-Math.round10(-55.551, -1); // -55.6
-Math.round10(-55, 1);      // -50
-Math.round10(-55.1, 1);    // -60
-// Floor
-Math.floor10(55.59, -1);   // 55.5
-Math.floor10(59, 1);       // 50
-Math.floor10(-55.51, -1);  // -55.6
-Math.floor10(-51, 1);      // -60
-// Ceil
-Math.ceil10(55.51, -1);    // 55.6
-Math.ceil10(51, 1);        // 60
-Math.ceil10(-55.59, -1);   // -55.5
-Math.ceil10(-59, 1);       // -50
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi awal. Diimplementasikan pada JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.9', 'Math.floor')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.floor', 'Math.floor')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.floor', 'Math.floor')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas browser

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

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/math/index.html b/files/id/web/javascript/reference/global_objects/math/index.html deleted file mode 100644 index 4d9bb6a9bb..0000000000 --- a/files/id/web/javascript/reference/global_objects/math/index.html +++ /dev/null @@ -1,213 +0,0 @@ ---- -title: Math -slug: Web/JavaScript/Reference/Global_Objects/Math -tags: - - JavaScript - - Math - - NeedsTranslation - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Math ---- -
{{JSRef}}
- -

Math merupakan objek built-in yang memiliki properti dan method untuk perhitungan konstan dan fungsi. bukan Fungsi Objek.

- -

Description

- -

Tidak seperti global objects lain, Math bukanlah constructor. Semua properti dan method dari Math adalah 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.

- -

Properties

- -
-
{{jsxref("Math.E")}}
-
Euler's constant and the base of natural logarithms, approximately 2.718.
-
{{jsxref("Math.LN2")}}
-
Natural logarithm 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 circumference of a circle to its diameter, approximately 3.14159.
-
{{jsxref("Math.SQRT1_2")}}
-
Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707.
-
{{jsxref("Math.SQRT2")}}
-
Square root of 2, approximately 1.414.
-
- -

Method

- -
-

Note that the trigonometric functions (sin(), cos(), tan(), asin(), acos(), atan(), atan2()) expect or return angles in radians. To convert radians to degrees, divide by (Math.PI / 180), and multiply by this to convert the other way.

-
- -
-

Note that a lot of the math functions have a precision that's implementation-dependent. This means that different browsers can give a different result, and even the same JS engine on a different OS or architecture can give different results.

-
- -
-
{{jsxref("Global_Objects/Math/abs", "Math.abs(x)")}}
-
Returns the absolute value of a number.
-
{{jsxref("Global_Objects/Math/acos", "Math.acos(x)")}}
-
Returns the arccosine of a number.
-
{{jsxref("Global_Objects/Math/acosh", "Math.acosh(x)")}}
-
Returns the hyperbolic arccosine of a number.
-
{{jsxref("Global_Objects/Math/asin", "Math.asin(x)")}}
-
Returns the arcsine of a number.
-
{{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 a number.
-
{{jsxref("Global_Objects/Math/atanh", "Math.atanh(x)")}}
-
Returns the hyperbolic arctangent of a number.
-
{{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 a number.
-
{{jsxref("Global_Objects/Math/ceil", "Math.ceil(x)")}}
-
Returns the smallest integer greater than or equal to a number.
-
{{jsxref("Global_Objects/Math/clz32", "Math.clz32(x)")}}
-
Returns the number of leading zeroes of a 32-bit integer.
-
{{jsxref("Global_Objects/Math/cos", "Math.cos(x)")}}
-
Returns the cosine of a number.
-
{{jsxref("Global_Objects/Math/cosh", "Math.cosh(x)")}}
-
Returns the hyperbolic cosine of a number.
-
{{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 a number.
-
{{jsxref("Global_Objects/Math/fround", "Math.fround(x)")}}
-
Returns the nearest single precision float representation of a number.
-
{{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 a 32-bit integer multiplication.
-
{{jsxref("Global_Objects/Math/log", "Math.log(x)")}}
-
Returns the natural logarithm (loge, also ln) of a number.
-
{{jsxref("Global_Objects/Math/log1p", "Math.log1p(x)")}}
-
Returns the natural logarithm of 1 + x (loge, also ln) of a number.
-
{{jsxref("Global_Objects/Math/log10", "Math.log10(x)")}}
-
Returns the base 10 logarithm of a number.
-
{{jsxref("Global_Objects/Math/log2", "Math.log2(x)")}}
-
Returns the base 2 logarithm of a number.
-
{{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 to the exponent power, that is, baseexponent.
-
{{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 a number 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 a number.
-
{{jsxref("Global_Objects/Math/sinh", "Math.sinh(x)")}}
-
Returns the hyperbolic sine of a number.
-
{{jsxref("Global_Objects/Math/sqrt", "Math.sqrt(x)")}}
-
Returns the positive square root of a number.
-
{{jsxref("Global_Objects/Math/tan", "Math.tan(x)")}}
-
Returns the tangent of a number.
-
{{jsxref("Global_Objects/Math/tanh", "Math.tanh(x)")}}
-
Returns the hyperbolic tangent of a number.
-
Math.toSource() {{non-standard_inline}}
-
Returns the string "Math".
-
{{jsxref("Global_Objects/Math/trunc", "Math.trunc(x)")}}
-
Returns the integral part of the number x, removing any fractional digits.
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.8', 'Math')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math-object', 'Math')}}{{Spec2('ES6')}}New methods {{jsxref("Math.log10()", "log10()")}}, {{jsxref("Math.log2()", "log2()")}}, {{jsxref("Math.log1p()", "log1p()")}}, {{jsxref("Math.expm1()", "expm1()")}}, {{jsxref("Math.cosh()", "cosh()")}}, {{jsxref("Math.sinh()", "sinh()")}}, {{jsxref("Math.tanh()", "tanh()")}}, {{jsxref("Math.acosh()", "acosh()")}}, {{jsxref("Math.asinh()", "asinh()")}}, {{jsxref("Math.atanh()", "atanh()")}}, {{jsxref("Math.hypot()", "hypot()")}}, {{jsxref("Math.trunc()", "trunc()")}}, {{jsxref("Math.sign()", "sign()")}}, {{jsxref("Math.imul()", "imul()")}}, {{jsxref("Math.fround()", "fround()")}}, {{jsxref("Math.cbrt()", "cbrt()")}} and {{jsxref("Math.clz32()", "clz32()")}} added.
{{SpecName('ESDraft', '#sec-math-object', 'Math')}}{{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/id/web/javascript/reference/global_objects/math/ln10/index.html b/files/id/web/javascript/reference/global_objects/math/ln10/index.html deleted file mode 100644 index 04e4fe5468..0000000000 --- a/files/id/web/javascript/reference/global_objects/math/ln10/index.html +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: Math.LN10 -slug: Web/JavaScript/Reference/Global_Objects/Math/LN10 -translation_of: Web/JavaScript/Reference/Global_Objects/Math/LN10 ---- -
{{JSRef}}
- -

Properti Math.LN10 mewakili logaritma alami dari 10, mendekati 2.302:

- -

Math.LN10=ln(10)2.302\mathtt{\mi{Math.LN10}} = \ln(10) \approx 2.302

- -
{{EmbedInteractiveExample("pages/js/math-ln10.html")}}
- - - -
{{js_property_attributes(0, 0, 0)}}
- -

Deskripsi

- -

Karena LN10 adalah sebuah properti matematika statis, saudara selalu menggunakannya sebagai Math.LN10, daripada sebagai sebuah properti objek matematika yang saudara buat (Math bukan sebuah konstruktor).

- -

Contoh

- -

-

Menggunakan Math.LN10

-

- -

Fungsi berikut menampilkan log alami dari 10:

- -
function getNatLog10() {
-  return Math.LN10;
-}
-
-getNatLog10(); // 2.302585092994046
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecisifikasiStatusKomentar
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi inisial. Diimplementasikan di JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.1.2', 'Math.LN10')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.ln10', 'Math.LN10')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.ln10', 'Math.LN10')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas browser

- - - -

{{Compat("javascript.builtins.Math.LN10")}}

- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/math/max/index.html b/files/id/web/javascript/reference/global_objects/math/max/index.html deleted file mode 100644 index aeb1b207ce..0000000000 --- a/files/id/web/javascript/reference/global_objects/math/max/index.html +++ /dev/null @@ -1,144 +0,0 @@ ---- -title: Math.max() -slug: Web/JavaScript/Reference/Global_Objects/Math/max -tags: - - JavaScript - - Math - - Method - - Reference -translation_of: Web/JavaScript/Reference/Global_Objects/Math/max ---- -
{{JSRef}}
- -

Fungsi Math.max() mengembalikan nilai terbesar dari zero atau lebih besar.

- -

Sintaks

- -
Math.max([value1[, value2[, ...]]])
- -

Parameter

- -
-
value1, value2, ...
-
Nomor.
-
- -

Deskripsi

- -

Karena max() merupakan method static dari Math, anda perlu menggunakan Math.max(), daripada sebagai method dari objek Math yang anda buat (Math bukan constructor).

- -

Jika tidak diberi argumen, hasilnya akan -{{jsxref("Infinity")}}.

- -

Jika setidaknya satu argumen tidak dapat dikonversi ke angka, maka hasilnya {{jsxref("NaN")}}.

- -

Contoh

- -

Penggunaan Math.max()

- -
Math.max(10, 20);   //  20
-Math.max(-10, -20); // -10
-Math.max(-10, 20);  //  20
-
- -

Pada contoh menggunakan fungsi {{jsxref("Function.prototype.apply()")}} untuk mencari nilai elemen maksimum pada sebuah numeric array. getMaxOfArray([1, 2, 3]) sama halnya dengan Math.max(1, 2, 3), tapi anda bisa menggunakan getMaxOfArray() pada programmatikal pembuatan array untuk semua ukuran.

- -
function getMaxOfArray(numArray) {
-  return Math.max.apply(null, numArray);
-}
-
- -

Atau dengan {{jsxref("Operators/Spread_operator", "spread operator")}} baru, mencari nilai terbesar menjadi lebih mudah.

- -
var arr = [1, 2, 3];
-var max = Math.max(...arr);
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.11', 'Math.max')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.max', 'Math.max')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.max', 'Math.max')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

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

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/math/min/index.html b/files/id/web/javascript/reference/global_objects/math/min/index.html deleted file mode 100644 index eb557f36bf..0000000000 --- a/files/id/web/javascript/reference/global_objects/math/min/index.html +++ /dev/null @@ -1,150 +0,0 @@ ---- -title: Math.min() -slug: Web/JavaScript/Reference/Global_Objects/Math/min -tags: - - JavaScript - - Math - - Method - - Reference -translation_of: Web/JavaScript/Reference/Global_Objects/Math/min ---- -
{{JSRef}}
- -

Function Math.min() mengembalikan nilai terkecil dari zero atau lebih kecil.

- -

Sintaks

- -
Math.min([value1[, value2[, ...]]])
- -

Parameter

- -
-
value1, value2, ...
-
Nomor.
-
- -

Deskripsi

- -

Karena min() merupakan static method dari Math, anda perlu menggunakan  Math.min(), daripada sebagai method dari objek Math yang anda buat (Math bukanlah konstruktor).

- -

Jika tidak diberi argumen, hasilnya adalah {{jsxref("Infinity")}}.

- -

Jika setidaknya satu argumen tidak bisa di konversi ke angka, maka hasilnya{{jsxref("NaN")}}.

- -

Contoh

- -

Menggunakan Math.min()

- -

Mencari nilai terkecil diantara x dan y dan menyimpannya di variabel z:

- -
var x = 10, y = -20;
-var z = Math.min(x, y);
-
- -

Mengambil nilai dengan Math.min()

- -

Math.min() biasa digunakan untuk mengambil nilai yang terkecil atau sama berdasarkan batasan yang ada. contoh sebagai berikut.

- -
var x = f(foo);
-
-if (x > boundary) {
-  x = boundary;
-}
-
- -

bisa ditulis sebagai berikut

- -
var x = Math.min(f(foo), boundary);
-
- -

{{jsxref("Math.max()")}} bisa digunakan sama halnya denga mengambil nilai pada setiap batasan.

- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.12', 'Math.min')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.min', 'Math.min')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.min', 'Math.min')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

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

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/math/pow/index.html b/files/id/web/javascript/reference/global_objects/math/pow/index.html deleted file mode 100644 index 878fde0e04..0000000000 --- a/files/id/web/javascript/reference/global_objects/math/pow/index.html +++ /dev/null @@ -1,53 +0,0 @@ ---- -title: Math.pow -slug: Web/JavaScript/Reference/Global_Objects/Math/pow -translation_of: Web/JavaScript/Reference/Global_Objects/Math/pow ---- -

Ringkasan

-

Mengembalikan bilangan terhadap Pangkat exponent,  yaitu, bilanganeksponen.

- - - - - - - - - - - - - - - - -
Method dari Math
Diimplementasikan padaJavaScript 1.0
Edisi ECMAScriptECMAScript 1st Edition
-

Sintaks

-
Math.pow(bilangan, eksponen) 
-

Parameter

-
-
- bilangan
-
- Bilangan pokok.
-
- eksponen
-
- Eksponen yang digunakan untuk memangkatkan bilangan pokok.
-
-

Deskripsi

-

Karena pow adalah sebuah static method dari Math, anda senantiasa menggunakannya sebagai Math.pow(), daripada sebagai sebuah method dari sebuah Objek Math yang anda buat.

-

Contoh

-

Contoh: Penggunaan Math.pow

-
function raisePower(x,y) {
-   return Math.pow(x,y)
-}
-

Jika x adalah 7 dan y adalah 2, raisePower mengembalikan 49 (7 dipangkatkan 2).

-

Lihat juga

- diff --git a/files/id/web/javascript/reference/global_objects/object/getprototypeof/index.html b/files/id/web/javascript/reference/global_objects/object/getprototypeof/index.html deleted file mode 100644 index 6ac06ec718..0000000000 --- a/files/id/web/javascript/reference/global_objects/object/getprototypeof/index.html +++ /dev/null @@ -1,133 +0,0 @@ ---- -title: Object.getPrototypeOf() -slug: Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf -translation_of: Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf ---- -
{{JSRef}}
- -

Metode Object.getPrototypeOf() mengembalikan nilai prototipe dari obyek yang disebutkan (misalnya,  nilai dari properti internal [[Prototype]]).

- -

Sintaks

- -
Object.getPrototypeOf(obj)
- -

Parameter

- -
-
obj
-
Obyek yang memiliki prototipe.
-
- -

Nilai kembali

- -

Prototipe dari obyek yang diberikan. Jika tidak ada property yang ditemukan, {{jsxref("null")}} yang akan dikembalikan.

- -

Contoh

- -
var proto = {};
-var obj = Object.create(proto);
-Object.getPrototypeOf(obj) === proto; // true
-
- -

Catatan

- -

Dalam ES5, akan melemparkan eksepsi {{jsxref("TypeError")}} jika parameter obj parameter bukanlah sebuah obyek. Dalam ES6, parameter akan dipaksa menjadi {{jsxref("Object")}}.

- -
Object.getPrototypeOf("foo");
-// TypeError: "foo" is not an object (ES5 code)
-Object.getPrototypeOf("foo");
-// String.prototype                  (ES6 code)
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ES5.1', '#sec-15.2.3.2', 'Object.getPrototypeOf')}}{{Spec2('ES5.1')}}Definisi awal.
{{SpecName('ES6', '#sec-object.getprototypeof', 'Object.getProtoypeOf')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.getprototypeof', 'Object.getProtoypeOf')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas perambah

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatChrome("5")}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("9")}}{{CompatOpera("12.10")}}{{CompatSafari("5")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

Catatan khusus Opera

- -

Meskipun Opera dengan versi yang lebih lama belum mendukung Object.getPrototypeOf(), Opera mendukung properti non-standar {{jsxref("Object.proto", "__proto__")}} sejak Opera 10.50.

- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/object/index.html b/files/id/web/javascript/reference/global_objects/object/index.html deleted file mode 100644 index cc79ab6890..0000000000 --- a/files/id/web/javascript/reference/global_objects/object/index.html +++ /dev/null @@ -1,221 +0,0 @@ ---- -title: Object -slug: Web/JavaScript/Reference/Global_Objects/Object -tags: - - Constructor - - JavaScript - - Object - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Object ---- -
{{JSRef}}
- -

Konstruktor Object membuat sebuah pembungkus objek.

- -

Sintaks

- -
// Persiapan literasi objek
-{ [ nameValuePair1[, nameValuePair2[, ...nameValuePairN] ] ] }
-
-// Panggil konstruktor
-new Object([value])
- -

Parameter

- -
-
nameValuePair1, nameValuePair2, ... nameValuePairN
-
Pasangan dari nama (strings) dan nilai dimana nama dipisahkan dari nilai menggunakan titik dua (colon).
-
value
-
Nilai bebas.
-
- -

Keterangan

- -

Konstruktor Object membuat sebuah pembungkus objek dari nilai yang diberikan. Jika nilainya {{jsxref("null")}} atau {{jsxref("undefined")}}, maka akan menghasilkan dan mengembalikan objek kosong. Sebaliknya, akan mengembalikan sebuah objek dari Type yang bergantung pada nilai yang diberikan. Jika nilai adalah objek, maka nilai akan langsung dikembalikan.

- -

Ketika memanggil konteks non-constructor, Object berperilaku seperti layaknya new Object().

- -

Lihat juga object initializer / literal syntax.

- -

Properti dari konstruktor Object

- -
-
Object.length
-
Bernilai 1.
-
{{jsxref("Object.prototype")}}
-
Memungkinkan untuk menambahkan properti ke semua objek dari type Object.
-
- -

Method dari konstruktor Object

- -
-
{{jsxref("Object.assign()")}}
-
Membuat objek baru dengan menyalin nilai dari semua properti enumerable dari satu atau lebih sumber ke sebuah objek target.
-
{{jsxref("Object.create()")}}
-
Membuat objek baru dengan prototype dan properti objek tertentu.
-
{{jsxref("Object.defineProperty()")}}
-
Menambahkan nama properti berdasarkan deskripsi yang diberikan oleh descriptor pada sebuah objek.
-
{{jsxref("Object.defineProperties()")}}
-
Menambahkan nama properti yang dideskripsikan descriptors pada sebuah object.
-
{{jsxref("Object.entries()")}} {{experimental_inline}}
-
Mengembalikan sebuah array dari enumerable objek dengan  pasangan properti [key, value].
-
{{jsxref("Object.freeze()")}}
-
Membekukan objek: kode lain tidak dapat dihapus atau diubah oleh semua properti.
-
{{jsxref("Object.getOwnPropertyDescriptor()")}}
-
Mengembalikan sebuah properti descriptor untuk nama propeti pada sebuah object.
-
{{jsxref("Object.getOwnPropertyNames()")}}
-
Mengembalikan array berisi nama dari semua objek yang diberikan own enumerable dan properti non-enumerable.
-
{{jsxref("Object.getOwnPropertySymbols()")}}
-
Mengembalikan sebuah array dari semua properti simbol yang ditemukan secara langsung atas objek yang diberikan.
-
{{jsxref("Object.getPrototypeOf()")}}
-
Mengembalikan prototype dari objek tertentu.
-
{{jsxref("Object.is()")}}
-
Membandingkan dua nilai yang berbeda (mis. the same)
-
{{jsxref("Object.isExtensible()")}}
-
Menentukan apakah memperluas objek di perbolehkan.
-
{{jsxref("Object.isFrozen()")}}
-
Menentukan apakah objek telah beku.
-
{{jsxref("Object.isSealed()")}}
-
Menentukan apakah objek adalah sealed.
-
{{jsxref("Object.keys()")}}
-
Menegembalikan array berisi nama dari semua objek properti own enumerable.
-
{{jsxref("Object.preventExtensions()")}}
-
Mencegah ekstensi dari sebuah objek.
-
{{jsxref("Object.seal()")}}
-
Mencegah kode lain dari penghapusan properti dari sebuah objek.
-
{{jsxref("Object.setPrototypeOf()")}}
-
Mengatur prototype (mis., internal properti [[Prototype]])
-
{{jsxref("Object.values()")}} {{experimental_inline}}
-
Mengembalikan array dari objek nilai own enumerable.
-
- -

Perumpamaan Object dan Object prototype objek

- -

Pada JavaScript, semua objek diturunkan dari Object; dan semua objek mewarisi method dan property dari {{jsxref("Object.prototype")}}, meskipun hal tersebut telah di-override (diganti). Sebagai contoh, prototipe konstruktor lain mengesampingkan properti konstruktor dan menyediakan metode toString() yang spesifik. Perubahan ke objek prototipe Object disebarkan ke semua objek kecuali properti dan metode yang telah diubah sebelumnya diganti di sepanjang rantai prototipe.

- -

Properti

- -
{{page('/id/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Properties') }}
- -

Method

- -
{{page('/id/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Methods') }}
- -

Contoh

- -

Using Object given undefined and null types

- -

Dibawah ini adalah contoh menyimpan objek kosong pada variabel o:

- -
var o = new Object();
-
- -
var o = new Object(undefined);
-
- -
var o = new Object(null);
-
- -

Using Object to create Boolean objects

- -

Dibawah ini adalah contoh menyimpan objek {{jsxref("Boolean")}} pada variabel o:

- -
// equivalent to o = new Boolean(true);
-var o = new Object(true);
-
- -
// equivalent to o = new Boolean(false);
-var o = new Object(Boolean());
-
- -

Rincian Teknis

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi awal. Diterapkan di JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2', 'Object')}}{{Spec2('ES5.1')}}-
{{SpecName('ES6', '#sec-object-objects', 'Object')}}{{Spec2('ES6')}} -

Penambahan Object.assign, Object.getOwnPropertySymbols, Object.setPrototypeOf, Object.is

-
{{SpecName('ESDraft', '#sec-object-objects', 'Object')}}{{Spec2('ESDraft')}}Penambahan Object.entries, Object.values, dan Object.getOwnPropertyDescriptors.
- -

Kesesuaian browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/object/keys/index.html b/files/id/web/javascript/reference/global_objects/object/keys/index.html deleted file mode 100644 index cc1c7dc1a9..0000000000 --- a/files/id/web/javascript/reference/global_objects/object/keys/index.html +++ /dev/null @@ -1,197 +0,0 @@ ---- -title: Object.keys() -slug: Web/JavaScript/Reference/Global_Objects/Object/keys -translation_of: Web/JavaScript/Reference/Global_Objects/Object/keys ---- -
{{JSRef}}
- -

Object.keys() Metode mengembalikan array dari objek yang diberikan sendiri enumerable properti, dalam urutan yang sama seperti yang disediakan oleh loop {{jsxref("Statements/for...in", "for...in")}} (perbedaan adalah bahwa sebuah loop for-in enumerates properti dalam mata rantai prototipe juga).

- -

Syntax

- -
Object.keys(obj)
- -

Parameters

- -
-
obj
-
Objek yang propertinya sendiri enumerable yang harus dikembalikan.
-
- -

Description

- -

Object.keys() mengembalikan array yang elemen string yang sesuai dengan properti enumerable yang ditemukan langsung pada objek. Urutan properti adalah sama dengan yang diberikan oleh perulangan / looping melalui properti dari objek secara manual.

- -

Examples

- -
var arr = ['a', 'b', 'c'];
-console.log(Object.keys(arr)); // console: ['0', '1', '2']
-
-// array like object
-var obj = { 0: 'a', 1: 'b', 2: 'c' };
-console.log(Object.keys(obj)); // console: ['0', '1', '2']
-
-// array like object with random key ordering
-var an_obj = { 100: 'a', 2: 'b', 7: 'c' };
-console.log(Object.keys(an_obj)); // console: ['2', '7', '100']
-
-// getFoo is property which isn't enumerable
-var my_obj = Object.create({}, { getFoo: { value: function() { return this.foo; } } });
-my_obj.foo = 1;
-
-console.log(Object.keys(my_obj)); // console: ['foo']
-
- -

Jika Anda ingin semua properti, bahkan tidak enumerables, lihat {{jsxref("Object.getOwnPropertyNames()")}}.

- -

Notes

- -

Dalam ES5, jika argumen untuk metode ini bukan merupakan objek (primitive), maka akan menyebabkan {{jsxref("TypeError")}}. Dalam ES6, argumen tidak-objek akan dipaksa untuk sebuah objek.

- -
Object.keys("foo");
-// TypeError: "foo" is not an object (ES5 code)
-
-Object.keys("foo");
-// ["0", "1", "2"]                   (ES6 code)
-
- -

Polyfill

- -

Untuk menambahkan kompatibel Object.keys dukungan dalam lingkungan yang lebih tua yang tidak native mendukung itu, copy potongan berikut:

- -
// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
-if (!Object.keys) {
-  Object.keys = (function() {
-    'use strict';
-    var hasOwnProperty = Object.prototype.hasOwnProperty,
-        hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),
-        dontEnums = [
-          'toString',
-          'toLocaleString',
-          'valueOf',
-          'hasOwnProperty',
-          'isPrototypeOf',
-          'propertyIsEnumerable',
-          'constructor'
-        ],
-        dontEnumsLength = dontEnums.length;
-
-    return function(obj) {
-      if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
-        throw new TypeError('Object.keys called on non-object');
-      }
-
-      var result = [], prop, i;
-
-      for (prop in obj) {
-        if (hasOwnProperty.call(obj, prop)) {
-          result.push(prop);
-        }
-      }
-
-      if (hasDontEnumBug) {
-        for (i = 0; i < dontEnumsLength; i++) {
-          if (hasOwnProperty.call(obj, dontEnums[i])) {
-            result.push(dontEnums[i]);
-          }
-        }
-      }
-      return result;
-    };
-  }());
-}
-
- -

Harap dicatat bahwa kode di atas termasuk kunci non-enumerable di  IE7 (dan mungkin IE8), ketika lewat di sebuah objek dari berbagai window.

- -

Untuk Browser sederhana Polyfill, lihat Javascript - Object.keys Browser Compatibility.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.2.3.14', 'Object.keys')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.keys', 'Object.keys')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.keys', 'Object.keys')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("5")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("9")}}{{CompatOpera("12")}}{{CompatSafari("5")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/object/preventextensions/index.html b/files/id/web/javascript/reference/global_objects/object/preventextensions/index.html deleted file mode 100644 index 3899fef48f..0000000000 --- a/files/id/web/javascript/reference/global_objects/object/preventextensions/index.html +++ /dev/null @@ -1,185 +0,0 @@ ---- -title: Object.preventExtensions() -slug: Web/JavaScript/Reference/Global_Objects/Object/preventExtensions -translation_of: Web/JavaScript/Reference/Global_Objects/Object/preventExtensions ---- -
{{JSRef}}
- -

Metode Object.preventExtensions() mencegah properti-properti baru untuk ditambahkan pada sebuah obyek (mencegah ekstensi di masa depan pada sebuah obyek).

- -

Sintaks

- -
Object.preventExtensions(obj)
- -

Parameter

- -
-
obj
-
Obyek yang akan dibuat menjadi non-ekstensibel.
-
- -

Pengembalian nilai

- -

Obyek yang telah dibuat non-ekstensibel.

- -

Deskripsi

- -

 

- -

Sebuah obyek disebut ekstensibel jika properti baru dapat ditambahkan ke dalamnya . Object.preventExtensions() menandai suatu obyek untuk menjadi tidak ekstensibel, sehingga tidak akan pernah memiliki properti diluar properti-properti yang dimiliki sebelum ditandai sebagai non-ekstensibel. Perhatikan bahwa properti-properti obyek non-ekstensibel, secara umum, masih dapat dihapus. Mencoba untuk menambah properti baru ke obyek non-ekstensibel akan gagal, baik secara diam-diam atau dengan melemparkan {{jsxref("TypeError")}} (paling umum, tetapi tidak secara eksklusif,  ketika berada di {{jsxref("Functions_and_function_scope/Strict_mode", "strict mode", "", 1)}}).

- -

Object.preventExtensions() hanya mencegah penambahan properti sendiri . Sifat masih bisa ditambahkan ke prototipe obyek. Namun, memanggil Object.preventExtensions() pada obyek juga akan mencegah ekstensi / penambahan properti {{jsxref("Object.proto", "__proto__")}} {{deprecated_inline}}.

- -

Jika ada cara untuk mengubah suatu obyek ekstensibel untuk satu non-ekstensibel, tidak ada cara untuk melakukan yang sebaliknya di ECMAScript 5 .

- -

Contoh

- -
// Object.preventExtensions returns the object being made non-extensible.
-var obj = {};
-var obj2 = Object.preventExtensions(obj);
-obj === obj2; // true
-
-// Objects are extensible by default.
-var empty = {};
-Object.isExtensible(empty); // === true
-
-// ...but that can be changed.
-Object.preventExtensions(empty);
-Object.isExtensible(empty); // === false
-
-// Object.defineProperty throws when adding a new property to a non-extensible object.
-var nonExtensible = { removable: true };
-Object.preventExtensions(nonExtensible);
-Object.defineProperty(nonExtensible, 'new', { value: 8675309 }); // throws a TypeError
-
-// In strict mode, attempting to add new properties to a non-extensible object throws a TypeError.
-function fail() {
-  'use strict';
-  nonExtensible.newProperty = 'FAIL'; // throws a TypeError
-}
-fail();
-
-// EXTENSION (only works in engines supporting __proto__
-// (which is deprecated. Use Object.getPrototypeOf instead)):
-// A non-extensible object's prototype is immutable.
-var fixed = Object.preventExtensions({});
-fixed.__proto__ = { oh: 'hai' }; // throws a TypeError
-
- -

Catatan

- -

Pada ES5, jika argumen pada fungsi metode ini adalah bukan sebuah obyek (sebuah tipe data primitif), maka hal itu akan menyebabkan {{jsxref("TypeError")}}. Pada ES6, sebuah argumen non-obyek akan diperlakukan seperti obyek tersebut obyek biasa yang non-ekstensibel, dan langsung mengembalikan nilai. 

- -
Object.preventExtensions(1);
-// TypeError: 1 is not an object (ES5 code)
-
-Object.preventExtensions(1);
-// 1                             (ES6 code)
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ES5.1', '#sec-15.2.3.10', 'Object.preventExtensions')}}{{Spec2('ES5.1')}}Definisi awal. Terimplementasi pada JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.preventextensions', 'Object.preventExtensions')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.preventextensions', 'Object.preventExtensions')}}{{Spec2('ESDraft')}} 
- -

Browser kompatibilitas

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("6")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("9")}}{{CompatOpera("12")}}{{CompatSafari("5.1")}}
ES6 behavior for non-object argument{{CompatChrome("44")}}{{CompatGeckoDesktop("35.0")}}{{CompatIE("11")}}{{CompatOpera("31")}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ES6 behavior for non-object argument{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("35.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/promise/catch/index.html b/files/id/web/javascript/reference/global_objects/promise/catch/index.html deleted file mode 100644 index f2d5e38e8f..0000000000 --- a/files/id/web/javascript/reference/global_objects/promise/catch/index.html +++ /dev/null @@ -1,127 +0,0 @@ ---- -title: Promise.prototype.catch() -slug: Web/JavaScript/Reference/Global_Objects/Promise/catch -tags: - - ECMAScript6 - - Method - - Promise - - Prototype - - Referensi -translation_of: Web/JavaScript/Reference/Global_Objects/Promise/catch ---- -
{{JSRef}}
- -

Method catch() mengembalikan Promise dan hanya setuju jika kasusnya gagal. Sama halnya dengan memenggil method {{jsxref("Promise.then", "Promise.prototype.then(undefined, onRejected)")}}.

- -

Sintaks

- -
p.catch(onRejected);
-
-p.catch(function(reason) {
-   // rejection
-});
-
- -

Parameter

- -
-
onRejected
-
 {{jsxref("Function")}} dipanggil ketika Promise ditolak. Fungsi ini memiliki satu argumen, alasan penolakan.
-
- -

Deskripsi

- -

Method catch sangat berguna untuk menangani error di gabungan promis anda.

- -

Contoh

- -

Penggunaan method catch

- -
var p1 = new Promise(function(resolve, reject) {
-  resolve('Success');
-});
-
-p1.then(function(value) {
-  console.log(value); // "Success!"
-  throw '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');
-});
-
-// 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');
-});
-
-
- -

Promis tidak dapat mendeteksi error pada asynchronous callback

- -
var p1 = new Promise(function(resolve, reject) {
-  throw 'Uh-oh!';
-});
-
-p1.catch(function(e) {
-  console.log(e); // "Uh-oh!"
-});
-
-
-var p2 = new Promise(function(resolve, reject) {
-  setTimeout(function() {
-    throw 'Uncaught Exception!';
-  }, 1000);
-});
-
-p2.catch(function(e) {
-  console.log(e); // This is never called
-});
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -

 

- - - -

{{Compat("javascript.builtins.Promise.catch")}}

- -

 

- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/promise/index.html b/files/id/web/javascript/reference/global_objects/promise/index.html deleted file mode 100644 index 240915ba23..0000000000 --- a/files/id/web/javascript/reference/global_objects/promise/index.html +++ /dev/null @@ -1,317 +0,0 @@ ---- -title: Promise -slug: Web/JavaScript/Reference/Global_Objects/Promise -tags: - - ECMAScript6 - - JavaScript - - NeedsTranslation - - Promise - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Promise ---- -
{{JSRef}}
- -

The Promise object is used for deferred and asynchronous computations. A Promise represents an operation that hasn't completed yet, but is expected in the future.

- -

Syntax

- -
new Promise( /* executor */ function(resolve, reject) { ... } );
- -

Parameters

- -
-
executor
-
A function that will be passed to other functions via the arguments resolve and reject. The executor function is executed immediately by the Promise implementation which provides the resolve and reject functions (the executor is called before the Promise constructor even returns the created object). The resolve and reject functions are bound to the promise and calling them fulfills or rejects the promise, respectively. The executor is expected to initiate some asynchronous work and then, once that completes, call either the resolve or reject function to resolve the promise's final value or else reject it if an error occurred.
-
- -

Description

- -

A Promise represents a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers to an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of the final value, the asynchronous method returns a promise of having a value at some point in the future.

- -

A Promise is in one of these states:

- - - -

A pending promise can become either fulfilled with a value, or rejected with a reason (error). When either of these happens, the associated handlers queued up by a promise's then method are called. (If the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached.)

- -

As the {{jsxref("Promise.then", "Promise.prototype.then()")}} and {{jsxref("Promise.catch", "Promise.prototype.catch()")}} methods return promises, they can be chained—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.

-
- -

Properties

- -
-
Promise.length
-
Length property whose value is 1 (number of constructor arguments).
-
{{jsxref("Promise.prototype")}}
-
Represents the prototype for the Promise constructor.
-
- -

Methods

- -
-
{{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)")}}
-
Returns a Promise object that is rejected with the given reason.
-
- -
-
{{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

- -

Properties

- -

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

- -

Methods

- -

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

- -

Examples

- -

Creating a Promise

- - - -

This small example shows the mechanism of a Promise. The testPromise() method is called each time the {{HTMLElement("button")}} is clicked. It creates a promise that will resolve, using {{domxref("window.setTimeout()")}}, to the promise count (number starting from 1) 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 a numeric count of this promise, starting from 1 (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/>');
-}
- - - -

This example is executed when clicking the button. You need a browser supporting Promise. By clicking several times the button in a short amount of time, you'll even see the different promises being fulfilled one after the other.

- -

{{EmbedLiveSample("Creating_a_Promise", "500", "200")}}

- -

Example using new XMLHttpRequest()

- -

Creating a Promise

- -

This example shows the implementation of a method which uses a Promise to report the success or failure of an {{domxref("XMLHttpRequest")}}.

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

Loading an image with XHR

- -

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

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-promise-objects', 'Promise')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise-objects', 'Promise')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -

 

- -
- - -

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

-
- -

 

- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/promise/reject/index.html b/files/id/web/javascript/reference/global_objects/promise/reject/index.html deleted file mode 100644 index 180fcc5571..0000000000 --- a/files/id/web/javascript/reference/global_objects/promise/reject/index.html +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: Promise.reject() -slug: Web/JavaScript/Reference/Global_Objects/Promise/reject -tags: - - ECMAScript6 - - Method - - Promise - - Referensi -translation_of: Web/JavaScript/Reference/Global_Objects/Promise/reject ---- -
{{JSRef}}
- -

Method Promise.reject(reason) mengembalikan objek Promise yang ditolak dengan alasan yang diberikan.

- -

Sintaks

- -
Promise.reject(reason);
- -

Parameter

- -
-
reason
-
Alasan kenapa Promise ditolak.
-
- -

Deskripsi

- -

Fungsi static Promise.reject mengembalikan Promise yang ditolak. Untuk keperluan debugging dan seleksi penankapan error, sangat berguna untuk membuat reason pada instanceof {{jsxref("Error")}}.

- -

Contoh

- -

Penggunaan mthod static Promise.reject()

- -
Promise.reject("Testing static reject").then(function(reason) {
-  // not called
-}, function(reason) {
-  console.log(reason); // "Testing static reject"
-});
-
-Promise.reject(new Error("fail")).then(function(error) {
-  // not called
-}, function(error) {
-  console.log(error); // Stacktrace
-});
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-promise.reject', 'Promise.reject')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.reject', 'Promise.reject')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- - - -

{{Compat("javascript.builtins.Promise.reject")}}

- -

 

- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/promise/resolve/index.html b/files/id/web/javascript/reference/global_objects/promise/resolve/index.html deleted file mode 100644 index d958ab4d52..0000000000 --- a/files/id/web/javascript/reference/global_objects/promise/resolve/index.html +++ /dev/null @@ -1,140 +0,0 @@ ---- -title: Promise.resolve() -slug: Web/JavaScript/Reference/Global_Objects/Promise/resolve -tags: - - ECMAScript6 - - JavaScript - - Method - - Promise -translation_of: Web/JavaScript/Reference/Global_Objects/Promise/resolve ---- -
{{JSRef}}
- -

Method Promise.resolve(value) mengembalikan objek {{jsxref("Promise.then")}} yang diselesaikan dengan nilai yang diberikan. jika nilainya thenable (mis. memiliki {{jsxref("Promise.then", "\"then\" method")}}), promise yang dikembalikan akan "mengikuti" thenable-nya, menggunakan keadaan ini; sebaliknya promise akan dikembalikan sesuai nilai yang terpenuhi.

- -

Sintaks

- -
Promise.resolve(value);
-Promise.resolve(promise);
-Promise.resolve(thenable);
-
- -

Parameter

- -
-
value
-
Argumen untuk diselesaikan oleh Promise. Dapat juga sebuah Promise atau thenable untuk diselesaikan.
-
- -

Deskripsi

- -

Fungsi statis Promise.resolve mengembalikan Promise yang terselesaikan.

- -

Contoh

- -

Penggunaan method static Promise.resolve

- -
Promise.resolve("Success").then(function(value) {
-  console.log(value); // "Success"
-}, function(value) {
-  // not called
-});
-
- -

Penyelesaian pada array

- -
var p = Promise.resolve([1,2,3]);
-p.then(function(v) {
-  console.log(v[0]); // 1
-});
-
- -

Penyelesaian pada Promise lain

- -
var original = Promise.resolve(true);
-var cast = Promise.resolve(original);
-cast.then(function(v) {
-  console.log(v); // true
-});
-
- -

Penyelesaian thenables dan throwing Errors

- -
// Resolving a thenable object
-var p1 = Promise.resolve({
-  then: function(onFulfill, onReject) { onFulfill("fulfilled!"); }
-});
-console.log(p1 instanceof Promise) // true, object casted to a Promise
-
-p1.then(function(v) {
-    console.log(v); // "fulfilled!"
-  }, function(e) {
-    // not called
-});
-
-// Thenable throws before callback
-// Promise rejects
-var thenable = { then: function(resolve) {
-  throw new TypeError("Throwing");
-  resolve("Resolving");
-}};
-
-var p2 = Promise.resolve(thenable);
-p2.then(function(v) {
-  // not called
-}, function(e) {
-  console.log(e); // TypeError: Throwing
-});
-
-// Thenable throws after callback
-// Promise resolves
-var thenable = { then: function(resolve) {
-  resolve("Resolving");
-  throw new TypeError("Throwing");
-}};
-
-var p3 = Promise.resolve(thenable);
-p3.then(function(v) {
-  console.log(v); // "Resolving"
-}, function(e) {
-  // not called
-});
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-promise.resolve', 'Promise.resolve')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.resolve', 'Promise.resolve')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -

 

- - - -

{{Compat("javascript.builtins.Promise.resolve")}}

- -

 

- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/promise/then/index.html b/files/id/web/javascript/reference/global_objects/promise/then/index.html deleted file mode 100644 index 5a1e275c8c..0000000000 --- a/files/id/web/javascript/reference/global_objects/promise/then/index.html +++ /dev/null @@ -1,132 +0,0 @@ ---- -title: Promise.prototype.then() -slug: Web/JavaScript/Reference/Global_Objects/Promise/then -tags: - - ECMAScript6 - - JavaScript - - Method - - Promise - - Prototype - - Referensi -translation_of: Web/JavaScript/Reference/Global_Objects/Promise/then ---- -
{{JSRef}}
- -

Method then() mengembalikan {{domxref("Promise")}}. Menggunakan dua argumen: fungsi callback untuk kasus sukses dan gagal pada Promise.

- -

Sintaks

- -
p.then(onFulfilled, onRejected);
-
-p.then(function(value) {
-   // fulfillment
-  }, function(reason) {
-  // rejection
-});
-
- -

Parameter

- -
-
onFulfilled
-
{{jsxref("Function")}} dipanggil ketika Promise dipenuhi. Fungsi ini memiliki satu argumen, value pemenuhan.
-
onRejected
-
{{jsxref("Function")}} dipangil ketika Promise ditolak. fungsi ini memiliki satau argumen, alasan penolakan.
-
- -

Deskripsi

- -

Kedua method then dan {{jsxref("Promise.prototype.catch()")}} megembalikan promis, juga dapat dirantaikan — operasi yang disebut composition.

- -

Contoh

- -

Meggunakan method then

- -
var p1 = new Promise(function(resolve, reject) {
-  resolve("Success!");
-  // or
-  // reject ("Error!");
-});
-
-p1.then(function(value) {
-  console.log(value); // Success!
-}, function(reason) {
-  console.log(reason); // Error!
-});
-
- -

Perantaian

- -

Karena method then mengembalikan Promise, anda bisa merantaikan pemanggilan then.

- -
var p2 = new Promise(function(resolve, reject) {
-  resolve(1);
-});
-
-p2.then(function(value) {
-  console.log(value); // 1
-  return value + 1;
-}).then(function(value) {
-  console.log(value); // 2
-});
-
-p2.then(function(value) {
-  console.log(value); // 1
-});
-
- -

Anda juga bisa menggunakan perantaian untuk melaksanakan satu fungsi dengan sebuah Promise berbasis API diatas fungsi lainnya.

- -
function fetch_current_data() {
-  // The fetch() API returns a Promise.  This function
-  // exposes a similar API, except the fulfillment
-  // value of this function's Promise has had more
-  // work done on it.
-  return fetch("current-data.json").then((response) => {
-    if (response.headers.get("content-type") != "application/json") {
-      throw new TypeError();
-    }
-    var j = response.json();
-    // maybe do something with j
-    return j; // fulfillment value given to user of
-              // fetch_current_data().then()
-  });
-}
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-promise.prototype.then', 'Promise.prototype.then')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.prototype.then', 'Promise.prototype.then')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- - - -

{{Compat("javascript.builtins.Promise.then")}}

- -

 

- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/regexp/index.html b/files/id/web/javascript/reference/global_objects/regexp/index.html deleted file mode 100644 index 8bd6dce4b9..0000000000 --- a/files/id/web/javascript/reference/global_objects/regexp/index.html +++ /dev/null @@ -1,231 +0,0 @@ ---- -title: RegExp -slug: Web/JavaScript/Reference/Global_Objects/RegExp -translation_of: Web/JavaScript/Reference/Global_Objects/RegExp ---- -
{{JSRef}}

The RegExpobjek digunakan untuk pencocokan teks dengan pola.

- -

Untuk pengantar ekspresi reguler, baca bab Ekspresi Reguler di Panduan JavaScript .

- -

Deskripsi

- -

Notasi dan konstruktor literal

- -

Ada dua cara untuk membuat RegExpobjek: notasi literal dan konstruktor .

- - - -

Tiga ekspresi berikut membuat ekspresi reguler yang sama:

- -
/ab+c/i
-new RegExp(/ab+c/, 'i') // literal notation
-new RegExp('ab+c', 'i') // constructor
-
- -

Notasi literal menghasilkan kompilasi dari ekspresi reguler ketika ekspresi dievaluasi. Gunakan notasi literal ketika ekspresi reguler akan tetap konstan. Misalnya, jika Anda menggunakan notasi literal untuk membuat ekspresi reguler yang digunakan dalam satu lingkaran, ekspresi reguler tidak akan dikompilasi ulang pada setiap iterasi.

- -

Konstruktor objek ekspresi reguler — misalnya, new RegExp('ab+c')—menghasilkan kompilasi runtime dari ekspresi reguler. Gunakan fungsi konstruktor ketika Anda tahu pola ekspresi reguler akan berubah, atau Anda tidak tahu pola dan mendapatkannya dari sumber lain, seperti input pengguna.

- -

Bendera dalam konstruktor

- -

Dimulai dengan ECMAScript 6, new RegExp(/ab+c/, 'i')tidak lagi melempar a TypeError"can't supply flags when constructing one RegExp from another") ketika argumen pertama adalah a RegExpdan flagsargumen kedua hadir. Sebagai RegExpgantinya, argumen baru dibuat.

- -

Saat menggunakan fungsi konstruktor, aturan pelolosan string normal (mendahului karakter khusus \ketika disertakan dalam string) diperlukan.

- -

Misalnya, yang berikut ini setara:

- -
let re = /\w+/
-let re = new RegExp('\\w+')
-
- -

Properti Reg-suka seperti Perl

- -

Perhatikan bahwa beberapa RegExpproperti memiliki nama panjang dan pendek (seperti Perl). Kedua nama selalu merujuk pada nilai yang sama. (Perl adalah bahasa pemrograman tempat JavaScript memodelkan ekspresi regulernya.). Lihat juga properti yang sudah usang RegExp.

- -

Konstruktor

- -
-
RegExp()
-
Menciptakan RegExpobjek baru .
-
- -

Sifat statis

- -
-
get RegExp[@@species]
-
The constructor function that is used to create derived objects.
-
RegExp.lastIndex
-
The index at which to start the next match.
-
- -

Instance properties

- -
-
RegExp.prototype.flags
-
A string that contains the flags of the RegExp object.
-
RegExp.prototype.dotAll
-
Whether . matches newlines or not.
-
RegExp.prototype.global
-
Whether to test the regular expression against all possible matches in a string, or only against the first.
-
RegExp.prototype.ignoreCase
-
Whether to ignore case while attempting a match in a string.
-
RegExp.prototype.multiline
-
Whether or not to search in strings across multiple lines.
-
RegExp.prototype.source
-
The text of the pattern.
-
RegExp.prototype.sticky
-
Whether or not the search is sticky.
-
RegExp.prototype.unicode
-
Whether or not Unicode features are enabled.
-
- -

Instance methods

- -
-
RegExp.prototype.compile()
-
(Re-)compiles a regular expression during execution of a script.
-
RegExp.prototype.exec()
-
Executes a search for a match in its string parameter.
-
RegExp.prototype.test()
-
Tests for a match in its string parameter.
-
RegExp.prototype.toString()
-
Returns a string representing the specified object. Overrides the Object.prototype.toString() method.
-
RegExp.prototype[@@match]()
-
Performs match to given string and returns match result.
-
RegExp.prototype[@@matchAll]()
-
Returns all matches of the regular expression against a string.
-
RegExp.prototype[@@replace]()
-
Replaces matches in given string with new substring.
-
RegExp.prototype[@@search]()
-
Searches the match in given string and returns the index the pattern found in the string.
-
RegExp.prototype[@@split]()
-
Splits given string into an array by separating the string into substring.
-
- -

Examples

- -

Using a regular expression to change data format

- -

The following script uses the replace() method of the 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.

- -
let re = /(\w+)\s(\w+)/
-let str = 'John Smith'
-let 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.

- -
let text = 'Some text\nAnd some more\r\nAnd yet\rThis is the end'
-let lines = text.split(/\r\n|\r|\n/)
-console.log(lines) // logs [ 'Some text', 'And some more', 'And yet', 'This is the end' ]
-
- -

Note that the order of the patterns in the regular expression matters.

- -

Using regular expression on multiple lines

- -
let 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 RegExp.prototype.lastIndex.

- -
let str = '#foo#'
-let regex = /foo/y
-
-regex.lastIndex = 1
-regex.test(str)      // true
-regex.lastIndex = 5
-regex.test(str)      // false (lastIndex is taken into account with sticky flag)
-regex.lastIndex      // 0 (reset after match failure)
- -

The difference between the sticky flag and the global flag

- -

With the sticky flag y, the next match has to happen at the lastIndex position, while with the global flag g, the match can happen at the lastIndex position or later:

- -
re = /\d/y;
-while (r = re.exec("123 456")) console.log(r, "AND re.lastIndex", re.lastIndex);
-
-// [ '1', index: 0, input: '123 456', groups: undefined ] AND re.lastIndex 1
-// [ '2', index: 1, input: '123 456', groups: undefined ] AND re.lastIndex 2
-// [ '3', index: 2, input: '123 456', groups: undefined ] AND re.lastIndex 3
-//   ... and no more match.
- -

With the global flag g, all 6 digits would be matched, not just 3.

- -

Regular expression and Unicode characters

- -

As mentioned above, \w or \W only matches ASCII based characters; for example, a to zA to Z0 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.

- -
let text = 'Образец text на русском языке'
-let regex = /[\u0400-\u04FF]+/g
-
-let match = regex.exec(text)
-console.log(match[0])        // logs 'Образец'
-console.log(regex.lastIndex) // logs '7'
-
-let match2 = regex.exec(text)
-console.log(match2[0])       // logs 'на' [did not log 'text']
-console.log(regex.lastIndex) // logs '15'
-
-// and so on
-
- -

The Unicode property escapes feature introduces a solution, by allowing for a statement as simple as \p{scx=Cyrl}. One can also use an external resource for getting the complete Unicode block range for different scripts, such as Regexp-Unicode-block.

- -

Extracting sub-domain name from URL

- -
let url = 'http://xxx.domain.com'
-console.log(/[^.]+/.exec(url)[0].substr(7)) // logs 'xxx'
-
- -

Instead of using regular expressions for parsing URLs, it is usually better to use the browsers built-in URL parser by using the URL API.

- -

Specifications

- - - - - - - - - - - - -
Specification
ECMAScript (ECMA-262)
- The definition of 'RegExp' in that specification.
- -

Browser compatibility

- -

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

- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/string/charat/index.html b/files/id/web/javascript/reference/global_objects/string/charat/index.html deleted file mode 100644 index e464f2bd4c..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/charat/index.html +++ /dev/null @@ -1,238 +0,0 @@ ---- -title: String.prototype.charAt() -slug: Web/JavaScript/Reference/Global_Objects/String/charAt -translation_of: Web/JavaScript/Reference/Global_Objects/String/charAt ---- -
{{JSRef}}
- -

Method charAt() pada Objek {{jsxref("String")}} mengembalikan string baru yang berisi kode lokasi single UTF-16 pada offset yang ditentukan ke dalam string.

- -
{{EmbedInteractiveExample("pages/js/string-charat.html", "shorter")}}
- - - -

Syntax

- -
let character = str.charAt(index)
- -

Parameter

- -
-
index
-
Sebuah integer antara 0 sampai str.length - 1. Bila nilai index bukan dalam bentuk integer atau index tidak ditentukan, maka nilai index akan bernilai 0, sehingga karakter pertama varibel str akan dikembalikan/ di-return.
-
- -

Nilai Return

- -

Sebuah string yang merepresentasikan sebuah karakter pada indeks tertentu. Jika index indeks berada di luar range, maka charAt()  akan me-return string kosong.

- -

Deskripsi

- -

Karakter dalam sebuah string diberi indeks dari kiri ke kanan. Indeks karakter pertama adalah 0, dan index karakter terakhir dalam string — misal nama stringnya stringName, adalah stringName.length - 1. Jika indeks yang anda berikan diluar range ini, maka JavaScript akan me-return string kosong.

- -

Jika tidak ada indeks yang tertera pada charAt(), maka nilai defaultnya adalah 0.

- -

Contoh

- -

Menampilkan karakter pada lokasi yang berbeda pada sebuah string

- -

Contoh berikut menunjukan karakter di lokasi berbeda pada string "Brave new world":

- -
var anyString = 'Brave new world';
-console.log("The character at index 0   is '" + anyString.charAt()   + "'");
-// Tidak ada angka yang tertera pada charAt(), maka digunakan nilai 0 sebagai default
-
-console.log("The character at index 0   is '" + anyString.charAt(0)   + "'");
-console.log("The character at index 1   is '" + anyString.charAt(1)   + "'");
-console.log("The character at index 2   is '" + anyString.charAt(2)   + "'");
-console.log("The character at index 3   is '" + anyString.charAt(3)   + "'");
-console.log("The character at index 4   is '" + anyString.charAt(4)   + "'");
-console.log("The character at index 999 is '" + anyString.charAt(999) + "'");
-
- -

Baris kode di atas menghasilkan output sebagai berikut:

- -
The character at index 0   is 'B'
-
-The character at index 0   is 'B'
-The character at index 1   is 'r'
-The character at index 2   is 'a'
-The character at index 3   is 'v'
-The character at index 4   is 'e'
-The character at index 999 is ''
-
- -

Mendapatkan seluruh karakter

- -

Berikut ini adalah cara untuk memastikan bahwa melalui loop string selalu memberikan karakter utuh, meskipun string berisi karakter yang tidak ada dalam Bidang Multilingual Dasar.

- -
var str = 'A \uD87E\uDC04 Z'; // Kita bisa menggunakan karakter non-BMP
-for (var i = 0, chr; i < str.length; i++) {
-  if ((chr = getWholeChar(str, i)) === false) {
-    continue;
-  }
-  // Adapt this line at the top of each loop, passing in the whole string and
-  // the current iteration and returning a variable to represent the
-  // individual character
-
-  console.log(chr);
-}
-
-function getWholeChar(str, i) {
-  var code = str.charCodeAt(i);
-
-  if (Number.isNaN(code)) {
-    return ''; // Posisi tidak ditemukan
-  }
-  if (code < 0xD800 || code > 0xDFFF) {
-    return str.charAt(i);
-  }
-
-  // High surrogate (could change last hex to 0xDB7F to treat high private
-  // surrogates as single characters)
-  if (0xD800 <= code && code <= 0xDBFF) {
-    if (str.length <= (i + 1)) {
-      throw 'High surrogate without following low surrogate';
-    }
-    var next = str.charCodeAt(i + 1);
-      if (0xDC00 > next || next > 0xDFFF) {
-        throw 'High surrogate without following low surrogate';
-      }
-      return str.charAt(i) + str.charAt(i + 1);
-  }
-  // Low surrogate (0xDC00 <= code && code <= 0xDFFF)
-  if (i === 0) {
-    throw 'Low surrogate without preceding high surrogate';
-  }
-  var prev = str.charCodeAt(i - 1);
-
-  // (could change last hex to 0xDB7F to treat high private
-  // surrogates as single characters)
-  if (0xD800 > prev || prev > 0xDBFF) {
-    throw 'Low surrogate without preceding high surrogate';
-  }
-  // We can pass over low surrogates now as the second component
-  // in a pair which we have already processed
-  return false;
-}
-
- -

Pada environment ECMAScript 2016 yang memungkinkan assignment yang rusak, Berikut ini merupakan alternatif yang lebih ringkas dan fleksibel karena perulangan dilakukan penmabahan secara otomatis pada variabel increment/ penambahannya (jika karakter menjaminnya sebagai pasangan pengganti).

- -
let str = 'A\uD87E\uDC04Z'  // Kita juga dapat menggunakan karakter non-BMP
-for (let i = 0, chr; i < str.length; i++) {
-  [chr, i] = getWholeCharAndI(str, i)
-
-  // Adapt this line at the top of each loop, passing in the whole string and
-  // the current iteration and returning an array with the individual character
-  // and 'i' value (only changed if a surrogate pair)
-
-  console.log(chr)
-}
-
-function getWholeCharAndI(str, i) {
-  let code = str.charCodeAt(i)
-
-  if (Number.isNaN(code)) {
-    return ''  // Posisi tidak ditemukan
-  }
-  if (code < 0xD800 || code > 0xDFFF) {
-    return [str.charAt(i), i]  // Karakter normal, keeping 'i' the same
-  }
-
-  // High surrogate (could change last hex to 0xDB7F to treat high private
-  // surrogates as single characters)
-  if (0xD800 <= code && code <= 0xDBFF) {
-    if (str.length <= (i + 1)) {
-      throw 'High surrogate without following low surrogate'
-    }
-    let next = str.charCodeAt(i + 1)
-      if (0xDC00 > next || next > 0xDFFF) {
-        throw 'High surrogate without following low surrogate'
-      }
-      return [str.charAt(i) + str.charAt(i + 1), i + 1]
-  }
-
-  // Low surrogate (0xDC00 <= code && code <= 0xDFFF)
-  if (i === 0) {
-    throw 'Low surrogate without preceding high surrogate'
-  }
-
-  let prev = str.charCodeAt(i - 1)
-
-  // (could change last hex to 0xDB7F to treat high private surrogates
-  // as single characters)
-  if (0xD800 > prev || prev > 0xDBFF) {
-    throw 'Low surrogate without preceding high surrogate'
-  }
-
-  // Return the next character instead (and increment)
-  return [str.charAt(i + 1), i + 1]
-}
-
- -

Memperbaiki charAt() untuk mendukung karakter non-Basic-Multilingual-Plane (BMP)

- -

Pada contoh sebelumnya mungkin lebih berguna untuk program yang mendukung karakter non-BMP (karena tidak mengharuskan pemanggil untuk mengetahui dimana karakter non-BMP mungkin muncul), jika memang diinginkan, dalam memilih karakter dengan index, untuk memperlakukan pasangan pengganti dalam string sebagai karakter tunggal yang mereka wakili, dapat menggunakan yang berikut ini:

- -
function fixedCharAt(str, idx) {
-  let ret = ''
-  str += ''
-  let end = str.length
-
-  let surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g
-  while ((surrogatePairs.exec(str)) != null) {
-    let lastIdx = surrogatePairs.lastIndex
-    if (lastIdx - 2 < idx) {
-      idx++
-    } else {
-      break
-    }
-  }
-
-  if (idx >= end || idx < 0) {
-    return ''
-  }
-
-  ret += str.charAt(idx)
-
-  if (/[\uD800-\uDBFF]/.test(ret) && /[\uDC00-\uDFFF]/.test(str.charAt(idx + 1))) {
-    // Go one further, since one of the "characters" is part of a surrogate pair
-    ret += str.charAt(idx + 1)
-  }
-  return ret
-}
-
- -

Specifications

- - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-string.prototype.charat', 'String.prototype.charAt')}}
- -

Browser compatibility

- - - -

{{Compat("javascript.builtins.String.charAt")}}

- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/string/concat/index.html b/files/id/web/javascript/reference/global_objects/string/concat/index.html deleted file mode 100644 index 0ba2b2a156..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/concat/index.html +++ /dev/null @@ -1,134 +0,0 @@ ---- -title: String.prototype.concat() -slug: Web/JavaScript/Reference/Global_Objects/String/concat -tags: - - JavaScript - - Referensi - - String -translation_of: Web/JavaScript/Reference/Global_Objects/String/concat ---- -
{{JSRef}}
- -

Method concat() menggabungkan dua teks atau lebih menjadi sebuah string baru.

- -

Syntax

- -
str.concat(string2, string3[, ..., stringN])
- -

Parameter

- -
-
string2...stringN
-
String untuk menggabungkan string.
-
- -

Deskripsi

- -

Fungsi concat() menggabungkan teks dari satu atau lebih string dan mengembalikanya menjadi sebuah string. Perubahan pada salah satu teks tidak mempengaruhi string lainnya.

- -

Contoh

- -

Penggunaan concat()

- -

Untuk menggabungkan string menjadi sebuah string baru seperti pada contoh dibawah.

- -
var halo = 'Halo, ';
-console.log(halo.concat('Didik', ' semoga hari ini menyenangkan.'));
-
-/* Halo, Didik semoga hari ini menyenangkan. */
-
- -

Performa

- -

Sangat disarankan untuk menggunakan {{jsxref("Operators/Assignment_Operators", "assignment operators", "", 1)}} (+, +=) pada method concat(). lihat test performa berikut ini.

- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.5.4.6', 'String.prototype.concat')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.concat', 'String.prototype.concat')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.concat', 'String.prototype.concat')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome untuk AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/string/fromcharcode/index.html b/files/id/web/javascript/reference/global_objects/string/fromcharcode/index.html deleted file mode 100644 index 786e32883e..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/fromcharcode/index.html +++ /dev/null @@ -1,143 +0,0 @@ ---- -title: String.fromCharCode() -slug: Web/JavaScript/Reference/Global_Objects/String/fromCharCode -tags: - - JavaScript - - Method - - Metode - - Reference - - Referensi - - String - - Unicode -translation_of: Web/JavaScript/Reference/Global_Objects/String/fromCharCode ---- -
{{JSRef}}
- -

Metode statis String.fromCharCode() mengembalikan sebuah string yang dibuat dari barisan nilai Unicode tertentu.

- -

Sintak

- -
String.fromCharCode(num1[, ...[, numN]])
- -

Parameter

- -
-
num1, ..., numN
-
Barisan dari angka-angka yang merupakan nilai Unicode.Jangkauannya antara 0 sampai dengan 65535(0xFFFF).Nomor yang lebih besar dari 0xFFFF dipotong.Tidak ada cek validasi yang dilakukan.   
-
- -

Nilai kembalian

- -

Sebuah string yang di dalamnya terdapat karakter-karakter sesuai nilai Unicode dari barisan angka yang diberikan.

- -

Deskripsi

- -

Metode ini mengembalikan sebuah string dan bukan objek {{jsxref("String")}}.

- -

Karena fromCharCode() merupakan metode statis dari {{jsxref("String")}}, Anda selalu bisa menggunakannya sebagai String.fromCharCode(), daripada sebagai metode dari objek {{jsxref("String")}} yang Anda buat.

- -

Contoh

- -

Menggunakan fromCharCode()

- -

Contoh di bawah ini mengembalikan string "ABC".

- -
String.fromCharCode(65, 66, 67);  // "ABC"
-
- -

Membuatnya bekerja dengan nilai yang lebih tinggi

- -

Meskipu nilai Unicode yang umum dapat digambarkan dengan satu angka 16-bit (seperti yang diharapkan pada awal mula standarisasi JavaScript) dan fromCharCode() dapat digunakan untuk mengembalikan sebuah karakter dari nilai yang paling umum (misal. nilai UCS-2 yang merupakan bagian dari UTF-16 dengan karakter yang paling umum digunakan). Untuk menghadapi SEMUA nilai Unicode yang sah (hingga 21 bit), fromCharCode() sendiri tidak dapat menghadapinya. Semenjak nilai code point karakter yang lebih tinggi menggunakan dua angka "pengganti"  (dengan nilai yang lebih rendah) untuk membuat sebuah karakter tunggal, {{jsxref("String.fromCodePoint()")}} (bagian dari draf ES6) dapat digunakan untuk menggunakan sepasang angka tersebut, sehingga dapat menampilkan karakter dengan nilai yang lebih tinggi.

- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi awal. Diimplementasikan dalam JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.5.3.2', 'StringfromCharCode')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-string.fromcharcodes', 'String.fromCharCode')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-string.fromcharcodes', 'String.fromCharCode')}}{{Spec2('ESDraft')}}
- -

Kompabilitas peramban

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/string/fromcodepoint/index.html b/files/id/web/javascript/reference/global_objects/string/fromcodepoint/index.html deleted file mode 100644 index dc4024f941..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/fromcodepoint/index.html +++ /dev/null @@ -1,149 +0,0 @@ ---- -title: String.fromCodePoint() -slug: Web/JavaScript/Reference/Global_Objects/String/fromCodePoint -tags: - - ECMAScript 2015 - - JavaScript - - Metode - - Referensi - - String -translation_of: Web/JavaScript/Reference/Global_Objects/String/fromCodePoint ---- -
{{JSRef}}
- -

Metode String.fromCodePoint() mengembalikan string yang dibuat dengan menggunakan urutan titik kode yang ditentukan.

- -
{{EmbedInteractiveExample("pages/js/string-fromcodepoint.html")}}
- - - -

Syntax

- -
String.fromCodePoint(num1[, ...[, numN]])
- -

Parameters

- -
-
num1, ..., numN
-
Urutan Poin Kode
-
- -

Return value

- -

String yang dibuat dengan menggunakan urutan titik kode yang ditentukan.

- -

Exceptions

- - - -

Description

- -

Metode ini mengembalikan string dan bukan sebuah objek. {{jsxref("String")}} .

- -

Karena fromCodePoint() adalah metode statik dari {{jsxref("String")}}, dan anda selalu menggunakannya sebagai String.fromCodePoint(), alih-alih sebagai sebuah metode yang anda buat {{jsxref("String")}}

- -

Examples

- -

Using fromCodePoint()

- -
String.fromCodePoint(42);       // "*"
-String.fromCodePoint(65, 90);   // "AZ"
-String.fromCodePoint(0x404);    // "\u0404"
-String.fromCodePoint(0x2F804);  // "\uD87E\uDC04"
-String.fromCodePoint(194564);   // "\uD87E\uDC04"
-String.fromCodePoint(0x1D306, 0x61, 0x1D307) // "\uD834\uDF06a\uD834\uDF07"
-
-String.fromCodePoint('_');      // RangeError
-String.fromCodePoint(Infinity); // RangeError
-String.fromCodePoint(-1);       // RangeError
-String.fromCodePoint(3.14);     // RangeError
-String.fromCodePoint(3e-2);     // RangeError
-String.fromCodePoint(NaN);      // RangeError
-
- -
// String.fromCharCode() sendiri tidak bisa mendapatkan karakter pada titik kode tinggi seperti itu
-// Disisi lain, dapat juga mengembalikan karakter 4-byte dan juga
-// yang biasa 2-byte (i.e., dapat mengembalikan satu karakter yang sebenarnya sudah dimiliki
-// string 2 daripada 1!)
-console.log(String.fromCodePoint(0x2F804)); // atau 194564 dalam bilangan desimal
-
- -

Polyfill

- -

Metode String.fromCodePoint telah ditambahkan ke ECMAScript 2015 dan mungkin belum didukung di semua browser web atau lingkungannya. Gunakan kode dibawah ini untuk polyfill:

- -
if (!String.fromCodePoint) (function(stringFromCharCode) {
-    var fromCodePoint = function(_) {
-      var codeUnits = [], codeLen = 0, result = "";
-      for (var index=0, len = arguments.length; index !== len; ++index) {
-        var codePoint = +arguments[index];
-        // correctly handles all cases including `NaN`, `-Infinity`, `+Infinity`
-        // The surrounding `!(...)` is required to correctly handle `NaN` cases
-        // The (codePoint>>>0) === codePoint clause handles decimals and negatives
-        if (!(codePoint < 0x10FFFF && (codePoint>>>0) === codePoint))
-          throw RangeError("Invalid code point: " + codePoint);
-        if (codePoint <= 0xFFFF) { // BMP code point
-          codeLen = codeUnits.push(codePoint);
-        } else { // Astral code point; split in surrogate halves
-          // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
-          codePoint -= 0x10000;
-          codeLen = codeUnits.push(
-            (codePoint >> 10) + 0xD800,  // highSurrogate
-            (codePoint % 0x400) + 0xDC00 // lowSurrogate
-          );
-        }
-        if (codeLen >= 0x3fff) {
-          result += stringFromCharCode.apply(null, codeUnits);
-          codeUnits.length = 0;
-        }
-      }
-      return result + stringFromCharCode.apply(null, codeUnits);
-    };
-    try { // IE 8 only supports `Object.defineProperty` on DOM elements
-      Object.defineProperty(String, "fromCodePoint", {
-        "value": fromCodePoint, "configurable": true, "writable": true
-      });
-    } catch(e) {
-      String.fromCodePoint = fromCodePoint;
-    }
-}(String.fromCharCode));
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-string.fromcodepoint', 'String.fromCodePoint')}}{{Spec2('ES2015')}}Definisi Awal
{{SpecName('ESDraft', '#sec-string.fromcodepoint', 'String.fromCodePoint')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- - - -

{{Compat("javascript.builtins.String.fromCodePoint")}}

- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/string/index.html b/files/id/web/javascript/reference/global_objects/string/index.html deleted file mode 100644 index 35f78502d5..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/index.html +++ /dev/null @@ -1,371 +0,0 @@ ---- -title: String -slug: Web/JavaScript/Reference/Global_Objects/String -tags: - - ECMAScript6 - - JavaScript - - Reference - - Referensi - - Referensı(2) - - Référence(2) - - String -translation_of: Web/JavaScript/Reference/Global_Objects/String ---- -
{{JSRef("Global_Objects", "String")}}
- -

Ringkasan

- -

Objek global String adalah sebuah pembangun untuk string, atau sebuah rangkaian dari karakter.

- -

Sintak

- -

String secara harfiah berbentuk:

- -
'string text'
-"string text"
-"中文 español English हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ 한국어 தமிழ்"
-
- -

Sejak ECMAScript 6 String secara harfiah dapat juga menjadi Template Strings:

- -
`hello world`
-`hello!
- world!`
-`hello ${who}`
-escape `<a>${who}</a>`
- -

Selain karakter biasa yang dapat dicetak, karakter spesial dapat disandikan dengan notasi lepas:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
KodeKeluaran
\0karakter NUL
\'petik satu
\"petik dua
\\garis miring
\nbaris baru
\rcarriage return
\vtab vertikal
\ttab
\bbackspace
\fform feed
\uXXXXunicode codepoint
\u{X} ... \u{XXXXXX}unicode codepoint {{experimental_inline}}
\xXXkarakter Latin-1
- -

Atau, menggunakan objek global String langsung:

- -
String(benda)
-new String(benda)
-
- -

Parameter

- -
-
benda
-
Apapun yang akan diubah ke string.
-
- -

Deskripsi

- -

String berguna untuk membawa data yang dapat diitampilkan dalam bentuk teks. Beberapa operasi yang paling sering digunakan dalam string adalah untuk memeriksa {{jsxref("String.length", "panjangnya")}}, untuk membuat dan menggabungkannya dengan operator string + dan +=, mengecek adanya atau lokasi dari substring dengan metode {{jsxref("String.prototype.indexOf()", "indexOf()")}}, atau mendapatkan substring dengan metode {{jsxref("String.prototype.substring()", "substring()")}}.

- -

Akses karakter

- -

Ada dua cara untuk mengakses sebuah karakter dalam string. Cara yang pertama adalah metode {{jsxref("String.prototype.charAt()", "charAt()")}}:

- -
return 'cat'.charAt(1); // mengembalikan "a"
-
- -

Cara yang lain (diperkenalkan dalam ECMAScript 5) adalah menganggap string sebagai objek mirip-susunan, di mana setiap karakter disesuaikan dengan indeks angka:

- -
return 'cat'[1]; // mengembalikan "a"
-
- -

Untuk akses karakter dengan menggunakan notasi kurung, mencoba untuk menghapus atau menetapkan nilai ke propertinya tidak akan berhasil. Properti yang terlibat tidak dapat ditulis maupun diubah. (Lihat {{jsxref("Object.defineProperty()")}} untuk informasi lebih.)

- -

Membandingkan string

- -

Pengembang C mempunyai fungsi strcmp() untuk membandingkan string. Dalam JavaScript, Anda cukup menggunakan operas kurang dari dan lebih dari:

- -
var a = 'a';
-var b = 'b';
-if (a < b) { // benar
-  print(a + ' kurang dari ' + b);
-} else if (a > b) {
-  print(a + ' lebih dari ' + b);
-} else {
-  print(a + ' sama dengan ' + b);
-}
-
- -

Hasil yang serupa dapat didapatkan dengan metode {{jsxref("String.prototype.localeCompare()", "localeCompare()")}} yang diwariskan oleh benda String.

- -

Perbedaan antara string primitif dan objek String

- -

Ingat bahwa JavaScript membedakan nilai antara objek String dan string primitif. (Serupa dengan {{jsxref("Global_Objects/Boolean", "Boolean")}} dan {{jsxref("Global_Objects/Number", "Angka")}}.)

- -

String yang harfiah (ditandai dengan petik satu atau dua) dan string yang dikembalikan dari panggilan String dalam sebuah konteks non-pembangun (misal, tanpa menggunakan kata kunci {{jsxref("Operators/new", "new")}}) adalah string primitif. JavaScript secara otomatis mengubah primitif ke objek String, jadi mungkin untuk menggunakan metode objek String untuk string primitif. Dalam konteks di mana sebuah metode dipanggil pada string primitif atau sebuah pembacaan properti terjadi, JavaScript akan secara otomatis membungkus string primitif dan memanggil metode tersebut atau melakukan pembacaan properti.

- -
var s_prim = 'foo';
-var s_obj = new String(s_prim);
-
-console.log(typeof s_prim); // "string"
-console.log(typeof s_obj);  // "object"
-
- -

String primitif dan objek String juga memberikan hasil berbeda saat menggunakan {{jsxref("Global_Objects/eval", "eval()")}}. Primitif melewati eval sebagai kode sumber; Objek String dianggap semua objek lain, dengan mengembalikan objek tersebut. Sebagai contoh:

- -
var s1 = '2 + 2';             // membuat sebuah string primitif
-var s2 = new String('2 + 2'); // membuat sebuah objek String
-console.log(eval(s1));        // mengembalikan angka 4
-console.log(eval(s2));        // mengembalikan string "2 + 2"
-
- -

Untuk itu, kode mungkin berhenti saat menemui objek String saat mengharapkan string primitif, meskipun secara umum pembuat tidak perlu khawatir tentang perbedaannya.

- -

Sebuah objek String dapat selalu diubah menjadi kawan primitifnya dengan metode {{jsxref("String.prototype.valueOf()", "valueOf()")}}.

- -
console.log(eval(s2.valueOf())); // mengembalikan angka 4
-
- -
Catatan: Untuk kemungkinan lain ke string dalam JavaScript, mohon baca artikel tentang StringView — a C-like representation of strings based on typed arrays (bahasa Inggris).
- -

Properti

- -
-
{{jsxref("String.prototype")}}
-
Membolehkan penambahan properti ke sebuahobjek String.
-
- -
{{jsOverrides("Function", "Properties", "prototype")}}
- -

Metode

- -
-
{{jsxref("String.fromCharCode()")}}
-
Mengembalikan sebuah string yang dibuat dengan menggunakan nilai urutan Unicode.
-
{{jsxref("String.fromCodePoint()")}} {{experimental_inline}}
-
Mengembalikan sebuah string dibuat dengan menggunakan urutan code points.
-
{{jsxref("String.raw()")}} {{experimental_inline}}
-
Mengembalikan sebuah string yang dibuat dari sebuah templat string mentah.
-
- -
{{jsOverrides("Function", "Methods", "fromCharCode", "fromCodePoint", "raw")}}
- -

Metode umum String

- -

Metode benda String juga terdapat dalam Firefox sejak JavaScript 1.6 (meskipun bukan bagian dari standar ECMAScript) salam objek String untuk menerapkan metode String ke objek lain:

- -
var num = 15;
-console.log(String.replace(num, /5/, '2'));
-
- -

{{jsxref("Global_Objects/Array", "Metode umum", "#Metode_umum_Array", 1)}} juga terdapat dalam metode {{jsxref("Global_Objects/Array", "Array")}}.

- -

Berikut ini sebuah pengisi untuk memberikan dukungan ke peramban yang tidak mendukung:

- -
/*globals define*/
-// Menganggap semua metode String telah ada
-(function() {
-  'use strict';
-
-  var i,
-    methods = [
-      'quote', 'substring', 'toLowerCase', 'toUpperCase', 'charAt',
-      'charCodeAt', 'indexOf', 'lastIndexOf', 'startsWith', 'endsWith',
-      'trim', 'trimLeft', 'trimRight', 'toLocaleLowerCase',
-      'toLocaleUpperCase', 'localeCompare', 'match', 'search',
-      'replace', 'split', 'substr', 'concat', 'slice'
-    ],
-    methodCount = methods.length,
-    assignStringGeneric = function(methodName) {
-      var method = String.prototype[methodName];
-      String[methodName] = function(arg1) {
-        return method.apply(arg1, Array.prototype.slice.call(arguments, 1));
-      };
-    };
-
-  for (i = 0; i < methodCount; i++) {
-    assignStringGeneric(methods[i]);
-  }
-}());
-
- -

Benda String

- -

Properti

- -
{{page('/id/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Properti')}}
- -

Metode

- -

Metode yang tidak terkait dengan HTML

- -
{{page('/id/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Metode_yang_tidak_terkait_dengan_HTML')}}
- -

Metode pembungkus HTML

- -
{{page('/id/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Metode_pembungkus_HTML')}}
- -

Contoh

- -

Contoh: Pengubahan String

- -

Ini mungkin untuk menggunakan String sebagai alternatif "lebih aman" dari {{jsxref("String.prototype.toString()", "toString()")}}, meskipun masih dapat secara normal memanggil toString(), ini juga bekerja untuk {{jsxref("Global_Objects/null", "null")}} dan {{jsxref("Global_Objects/undefined", "undefined")}}. Sebagai contoh:

- -
var outputStrings = [];
-for (var i = 0, n = inputValues.length; i < n; ++i) {
-  outputStrings.push(String(inputValues[i]));
-}
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
ECMAScript 1st Edition.StandardDefinisi pertama.
{{SpecName('ES5.1', '#sec-15.5', 'String')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string-objects', 'String')}}{{Spec2('ES6')}} 
- -

Kompatibilitas peramban

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatChrome("0.2")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
\u{XXXXXX}{{CompatUnknown()}}{{CompatGeckoDesktop("40")}}{{CompatUnknown()}}{{CompatUnknown()}}{{CompatUnknown()}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
\u{XXXXXX}{{CompatUnknown()}}{{CompatUnknown()}}{{CompatGeckoMobile("40")}}{{CompatUnknown()}}{{CompatUnknown()}}{{CompatUnknown()}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/string/indexof/index.html b/files/id/web/javascript/reference/global_objects/string/indexof/index.html deleted file mode 100644 index 3b7f7d0965..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/indexof/index.html +++ /dev/null @@ -1,190 +0,0 @@ ---- -title: String.prototype.indexOf() -slug: Web/JavaScript/Reference/Global_Objects/String/indexOf -translation_of: Web/JavaScript/Reference/Global_Objects/String/indexOf ---- -
{{JSRef}}
- -

indexOf() method mengembalikan sebuah index saat memanggil objek  {{jsxref("String")}} pertama kali dengan value yang di tentukan, bermula dari pencarian pada fromIndex. Dan pencarian ini akan mengembalikan index dari karakter pada String,  dan akan mengembalikan -1 ketika pencarian indexOf ini tak menemukan karakter yang cocok/ value yang sesuai.

- -

Syntax

- -
str.indexOf(searchValue[, fromIndex])
- -

Parameters

- -
-
searchValue
-
Sebuah string yang me-representasikan dari nilai yang ingin di cari.
-
fromIndex {{optional_inline}}
-
Index bermulai dari awal hingga bergerak ke depan sepanjang string. Index bisa berupa bilangan bulat atau apa pun. Nilai standarnya adalah 0, jadi seluruh index dari array akan dicari. Jika fromIndex < 0 seluruh string dicari. Jika fromIndex >= str.length, string tidak dicari dan -1 sebagai kembaliannya. Kecuali kalau searchValue adalah string kosong, maka str.length sebagai kembaliannya.
-
- -

Deskripsi

- -

Karakter dalam sebuah string di indeks berurutan dari kiri ke kanan. Index pada karakter pertama yaitu 0, dan index pada karakter terakhir dalam sebuah String di sebut stringName is stringName.length - 1.

- -
'Blue Whale'.indexOf('Blue');     // mengembalikan  0
-'Blue Whale'.indexOf('Blute');    // mengembalikan -1
-'Blue Whale'.indexOf('Whale', 0); // mengembalikan  5
-'Blue Whale'.indexOf('Whale', 5); // mengembalikan  5
-'Blue Whale'.indexOf('', 9);      // mengembalikan  9
-'Blue Whale'.indexOf('', 10);     // mengembalikan 10
-'Blue Whale'.indexOf('', 11);     // mengembalikan 10
-
- -

Case-sensitivity

- -

The indexOf() method sangat case sensitive. Sebagai contoh, expression berikut ini mengembalikan -1:

- -
'Blue Whale'.indexOf('blue'); // mengembalikan -1
-
- -

Checking occurrences/ Memeriksa suatu kejadian

- -

Catat bahwa  '0' tak bernilai true dan '-1' bukan bernilali false. Oleh karena-nya, ketika memeriksa apakah sebuah String  Therefore, when checking if a specific string exists within another string the correct way to check would be:

- -
'Blue Whale'.indexOf('Blue') !== -1; // true
-'Blue Whale'.indexOf('Bloe') !== -1; // false
-
- -

Examples

- -

Using indexOf() and lastIndexOf()

- -

The following example uses indexOf() and {{jsxref("String.prototype.lastIndexOf()", "lastIndexOf()")}} to locate values in the string "Brave new world".

- -
var anyString = 'Brave new world';
-
-console.log('The index of the first w from the beginning is ' + anyString.indexOf('w'));
-// logs 8
-console.log('The index of the last w from the beginning is ' + anyString.lastIndexOf('w'));
-// logs 10
-
-console.log('The index of "new" from the beginning is ' + anyString.indexOf('new'));
-// logs 6
-console.log('The index of "new" from the end is ' + anyString.lastIndexOf('new'));
-// logs 6
-
- -

indexOf() and case-sensitivity

- -

The following example defines two string variables. The variables contain the same string except that the second string contains uppercase letters. The first {{domxref("console.log()")}} method displays 19. But because the indexOf() method is case sensitive, the string "cheddar" is not found in myCapString, so the second console.log() method displays -1.

- -
var myString    = 'brie, pepper jack, cheddar';
-var myCapString = 'Brie, Pepper Jack, Cheddar';
-
-console.log('myString.indexOf("cheddar") is ' + myString.indexOf('cheddar'));
-// logs 19
-console.log('myCapString.indexOf("cheddar") is ' + myCapString.indexOf('cheddar'));
-// logs -1
-
- -

Using indexOf() to count occurrences of a letter in a string

- -

The following example sets count to the number of occurrences of the letter e in the string str:

- -
var str = 'To be, or not to be, that is the question.';
-var count = 0;
-var pos = str.indexOf('e');
-
-while (pos !== -1) {
-  count++;
-  pos = str.indexOf('e', pos + 1);
-}
-
-console.log(count); // displays 4
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.5.4.7', 'String.prototype.indexOf')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}{{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/id/web/javascript/reference/global_objects/string/length/index.html b/files/id/web/javascript/reference/global_objects/string/length/index.html deleted file mode 100644 index 6975d8b7d3..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/length/index.html +++ /dev/null @@ -1,126 +0,0 @@ ---- -title: String.length -slug: Web/JavaScript/Reference/Global_Objects/String/length -translation_of: Web/JavaScript/Reference/Global_Objects/String/length ---- -
{{JSRef}}
- -

Properti length mewakili panjang string.

- -

Syntax

- -
str.length
- -

Deskripsi

- -

Properti ini mengembalikan jumlah unit kode dalam string. {{interwiki("wikipedia", "UTF-16")}}, Format string yang digunakan oleh javascript, Menggunakan 16-bit unit kode tunggal untuk mewakili karakter yang paling umum, tapi perlu menggunakan dua unit kode untuk unit karakter tertentu, sehingga dapat terjadi kemungkinan nilai yang dikembalikan oleh ​​​length tidak sesuai dengan jumlah karakter pada string.

- -

Untuk string kosong, jumlahnya 0.

- -

Properti static String.length mengembalikan nilai 1.

- -

Contoh

- -

Penggunaan Dasar

- -
var x = 'Mozilla';
-var kosong = '';
-
-console.log('Mozilla memiliki ' + x.length + ' unit kode');
-/* "Mozilla memiliki 7 unit kode" */
-
-console.log('String kosong memiliki jumlah unit kode ' + kosong.length);
-/* "String kosong memiliki jumlah unit kode 0" */
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi Inisial. Diimplementasikan dalam JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.5.1', 'String.prototype.length')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-string-instances-length', 'String.prototype.length')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-properties-of-string-instances-length', 'String.prototype.length')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

 

- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/string/link/index.html b/files/id/web/javascript/reference/global_objects/string/link/index.html deleted file mode 100644 index 914eff9955..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/link/index.html +++ /dev/null @@ -1,130 +0,0 @@ ---- -title: String.prototype.link() -slug: Web/JavaScript/Reference/Global_Objects/String/link -tags: - - JavaScript - - Method - - Prototype - - Reference - - String -translation_of: Web/JavaScript/Reference/Global_Objects/String/link ---- -
{{JSRef}}
- -

Method link() membuat sebuah string seperti halnya kode untuk sebuah elemen HTML {{HTMLElement("a")}} untuk digunakan sebagai link hypertext ke URL lain.

- -

Sintaks

- -
str.link(url)
- -

Parameters

- -
-
url
-
String yang menentukan atribut href dai tag <a>; harus merupakan URL yang valid (relative ataupun absolute), dengan setiap karakter & harus ditulis &amp;, dan setiap karakter " harus ditulis &quot;.
-
- -

Deskripsi

- -

Menggunakan method link() untuk membuat snippet HTML untuk sebuah link hypertext. Mengembalikan string  yang kemudian dapat di tambahkan ke dokumen html menggunakan {{domxref("document.write()")}} atau {{domxref("element.innerHTML")}}.

- -

Link yang dibuat menggunakan method link() akan menjadi elemen di array links dari sebuah objek document. Lihat juga {{domxref("document.links")}}.

- -

Contoh

- -

Penggunaan link()

- -

Pada contoh berikut menampilkan kata "MDN" sebagai sebuah link hypertext yang mengembalikan pengguna ke halaman Mozilla Developer Network.

- -
var hotText = 'MDN';
-var URL = 'https://developer.mozilla.org/';
-
-console.log('Klik untuk kembali ke ' + hotText.link(URL));
-// Klik untuk kembali ke <a href="https://developer.mozilla.org/">MDN</a>
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-string.prototype.link', 'String.prototype.link')}}{{Spec2('ES6')}}Initial definition. Implemented in JavaScript 1.0. Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers.
{{SpecName('ESDraft', '#sec-string.prototype.link', 'String.prototype.link')}}{{Spec2('ESDraft')}}Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers.
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Catatan Gecko-specific

- - - -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/string/split/index.html b/files/id/web/javascript/reference/global_objects/string/split/index.html deleted file mode 100644 index 21f19d353f..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/split/index.html +++ /dev/null @@ -1,241 +0,0 @@ ---- -title: String.prototype.split() -slug: Web/JavaScript/Reference/Global_Objects/String/split -tags: - - JavaScript - - Method - - Prototype - - Reference - - Regular Expressions - - String -translation_of: Web/JavaScript/Reference/Global_Objects/String/split ---- -
{{JSRef}}
- -

Method split() membagi sebuah objek {{jsxref("String")}} ke sebuah array string dengan memisahkannya menjadi substring.

- -

Sintaks

- -
str.split([separator[, limit]])
- -

Parameter

- -
-
separator
-
Opsional. Menentukan karakter yang digunakan untuk memisahkan string. separator dapat berupa string atau sebuah {{jsxref("Global_Objects/RegExp", "regular expression", "", 1)}}. Jika separator dihilangkan / tidak digunakan, array yang dikembalikan akan terdiri dari satu elemen yang berisi seluruh string. Jika separator dikosongkan atau empty string, str akan dikonversikan sebagai sebuah array dari karakter.
-
limit
-
-

Opsional. Nilai integer yang digunakan untuk menentukan jumlah batas yang dapat ditemukan. Method split() tetap membagi pada setiap kecocokan pada separator, sampai jumlah pembagi item sama dengan limit atau string jatuh lebih pendek dari separator.

-
-
- -

Deskripsi

- -

Method split() mengembalikan array baru.

- -

Saat ditemukan, separator akan dihapus dari string dan substrings akan di kembalikan ke dalam array. Jika separator tidak ditemukan atau di hilangkan, array terdiri satu elemen array yang terdiri dari keseluruhan string. Jika separator merupakan empty string, str dikonversi menjadi sebuah array karakter.

- -

Jika separator adalah ekspesi reguler yang terdapat tanda kurung , maka setiap kali separator cocok, hasilnya (termasuk hasil yang tidak didefinisikan) dari penangkap tanda kurung akan di sambungkan ke dalam output array. Namun, tidak semua browser mendukung kemampuan ini.

- -

{{Note("Ketika string kosong, method split() mengembalikan array berisi satu string kosong, dari pada array kosong. Jika string dan separator keduanya string kosong, array kosong akan dikembalikan.")}}

- -

Contoh

- -

Penggunaan split()

- -

Contoh berikut menjelaskan fungsi yang membagi string ke dalam sebuah array string menggunakan separator tertentu. Setelah memisahkan string , fungsi menampilkan pesan yang menunjukan string asli (sebelum dibagi), separator yang digunakan, jumlah elemen pada array, dan elemen array secara individual.

- -
function splitString(stringToSplit, separator) {
-  var arrayOfStrings = stringToSplit.split(separator);
-
-  console.log('The original string is: "' + stringToSplit + '"');
-  console.log('The separator is: "' + separator + '"');
-  console.log('The array has ' + arrayOfStrings.length + ' elements: ' + arrayOfStrings.join(' / '));
-}
-
-var tempestString = 'Oh brave new world that has such people in it.';
-var monthString = 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec';
-
-var space = ' ';
-var comma = ',';
-
-splitString(tempestString, space);
-splitString(tempestString);
-splitString(monthString, comma);
-
- -

Contoh ini menghasilkan output berikut:

- -
The original string is: "Oh brave new world that has such people in it."
-The separator is: " "
-The array has 10 elements: Oh / brave / new / world / that / has / such / people / in / it.
-
-The original string is: "Oh brave new world that has such people in it."
-The separator is: "undefined"
-The array has 1 elements: Oh brave new world that has such people in it.
-
-The original string is: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"
-The separator is: ","
-The array has 12 elements: Jan / Feb / Mar / Apr / May / Jun / Jul / Aug / Sep / Oct / Nov / Dec
-
- -

Menghapus spasi dari string

- -

Pada contoh berikut, split() mencari 0 atau lebih spasi diikuti semikolon, dan di ikuti 0 atau lebih spasi dan, saat ditemukan, menghapus spasi dari string. nameList merupakan array yang dikembalikan dari hasil split().

- -
var names = 'Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand ';
-
-console.log(names);
-
-var re = /\s*;\s*/;
-var nameList = names.split(re);
-
-console.log(nameList);
-
- -

Dua baris log ini; log baris pertama string asli, dan log baris kedua array yang dihasilkan.

- -
Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand
-[ "Harry Trump", "Fred Barney", "Helen Rigby", "Bill Abel", "Chris Hand " ]
-
- -

Mengembalikan batas jumlah pembagi

- -

Pada contoh berikut, split() mencari 0 atau lebih spasi didalam string dan mengembalikan 3 pembagian pertama yang ditemukan.

- -
var myString = 'Hello World. How are you doing?';
-var splits = myString.split(' ', 3);
-
-console.log(splits);
-
- -

Script ini akan menampilkan seperti berikut:

- -
Hello,World.,How
-
- -

Tanda kurung

- -

Jika separator terdapat tanda kurung, hasil yang cocok akan dikembalikan ke dalam array.

- -
var myString = 'Hello 1 word. Sentence number 2.';
-var splits = myString.split(/(\d)/);
-
-console.log(splits);
-
- -

Script tersebut menampilkan seperti berikut:

- -
[ 'Hello ', '1', ' word. Sentence number ', '2', '.' ]
-
- -

Membalikkan String menggunakan split()

- -
var str = 'asdfghjkl';
-var strReverse = str.split('').reverse().join(''); // 'lkjhgfdsa'
-// split() returns an array on which reverse() and join() can be applied
-
- -

Bonus: Gunakan operator {{jsxref("Operators/Comparison_Operators", "===", "#Identity_strict_equality_(===)")}} untuk mengetahui apakah string asli adalah palindrome.

- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.5.4.14', 'String.prototype.split')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.split', 'String.prototype.split')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.split', 'String.prototype.split')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
- - - - - - - -
Dukungan dasar 
-
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/string/tolowercase/index.html b/files/id/web/javascript/reference/global_objects/string/tolowercase/index.html deleted file mode 100644 index 69fdfd1bec..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/tolowercase/index.html +++ /dev/null @@ -1,121 +0,0 @@ ---- -title: String.prototype.toLowerCase() -slug: Web/JavaScript/Reference/Global_Objects/String/toLowerCase -tags: - - JavaScript - - Method - - Prototype - - Reference - - String -translation_of: Web/JavaScript/Reference/Global_Objects/String/toLowerCase ---- -
{{JSRef}}
- -

Method toLowerCase() mengembalikan nilai string yang dipanggil yang telah dikonversi ke lowercase (huruf kecil).

- -

Sintaks

- -
str.toLowerCase()
- -

Deskripsi

- -

Method toLowerCase() mengembaikan nilai dari string yang telah dikonversi ke lowercase. toLowerCase() tidak berdampak pada nilai string pada variabel str itu sendiri.

- -

Contoh

- -

Penggunaan toLowerCase()

- -
console.log('ALPHABET'.toLowerCase()); // 'alphabet'
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.4.16', 'String.prototype.toLowerCase')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.tolowercase', 'String.prototype.toLowerCase')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.tolowercase', 'String.prototype.toLowerCase')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/string/tostring/index.html b/files/id/web/javascript/reference/global_objects/string/tostring/index.html deleted file mode 100644 index dba9c9f792..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/tostring/index.html +++ /dev/null @@ -1,118 +0,0 @@ ---- -title: String.prototype.toString() -slug: Web/JavaScript/Reference/Global_Objects/String/toString -translation_of: Web/JavaScript/Reference/Global_Objects/String/toString ---- -
{{JSRef}}
- -

Method toString() mengembalikan sebuah string berdasarkan objek spesifik.

- -

Sintaks

- -
str.toString()
- -

Deskripsi

- -

Objek {{jsxref("String")}} akan menimpa method toString() dari objek {{jsxref("Object")}}; bukan turunan {{jsxref("Object.prototype.toString()")}}. Untuk objek {{jsxref("String")}}, method toString() mengembalikan sebuah string berdasarkan objek dan seperti halnya pada method {{jsxref("String.prototype.valueOf()")}}.

- -

Contoh

- -

Penggunaan toString()

- -

Pada contoh menampilkan nilai string dari sebuah objek {{jsxref("String")}}:

- -
var x = new String('Halo Dunia');
-
-console.log(x.toString()); // logs 'Halo Dunia'
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.5.4.2', 'String.prototype.toString')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.tostring', 'String.prototype.toString')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.tostring', 'String.prototype.toString')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan Dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan Dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/string/touppercase/index.html b/files/id/web/javascript/reference/global_objects/string/touppercase/index.html deleted file mode 100644 index bf8182a590..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/touppercase/index.html +++ /dev/null @@ -1,115 +0,0 @@ ---- -title: String.prototype.toUpperCase() -slug: Web/JavaScript/Reference/Global_Objects/String/toUpperCase -translation_of: Web/JavaScript/Reference/Global_Objects/String/toUpperCase ---- -
{{JSRef}}
- -

Method toUpperCase() mengembalikan nilai string pemanggil dikonversi ke huruf besar.

- -

Sintaks

- -
str.toUpperCase()
- -

Deskripsi

- -

Method toUpperCase() mengembalikan nilai string diconversikan ke huruf besar. toUpperCase() tidak mempengaruhi nilai string itu sendiri.

- -

Contoh

- -

Penggunaan toUpperCase()

- -
console.log('alphabet'.toUpperCase()); // 'ALPHABET'
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.4.18', 'String.prototype.toUpperCase')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.touppercase', 'String.prototype.toUpperCase')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.touppercase', 'String.prototype.toUpperCase')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

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

Lihat Pula

- - diff --git a/files/id/web/javascript/reference/global_objects/typedarray/index.html b/files/id/web/javascript/reference/global_objects/typedarray/index.html deleted file mode 100644 index e0b8d942c1..0000000000 --- a/files/id/web/javascript/reference/global_objects/typedarray/index.html +++ /dev/null @@ -1,344 +0,0 @@ ---- -title: TypedArray -slug: Web/JavaScript/Reference/Global_Objects/TypedArray -tags: - - JavaScript - - NeedsTranslation - - TopicStub - - TypedArray - - TypedArrays -translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray ---- -
{{JSRef}}
- -

A TypedArray object describes an array-like view of an underlying binary data buffer. There is no global property named TypedArray, nor is there a directly visible TypedArray constructor.  Instead, there are a number of different global properties, whose values are typed array constructors for specific element types, listed below. On the following pages you will find common properties and methods that can be used with any typed array containing elements of any type.

- -

Syntax

- -
new TypedArray(length);
-new TypedArray(typedArray);
-new TypedArray(object);
-new TypedArray(buffer [, byteOffset [, length]]);
-
-where TypedArray() is one of:
-
-Int8Array();
-Uint8Array();
-Uint8ClampedArray();
-Int16Array();
-Uint16Array();
-Int32Array();
-Uint32Array();
-Float32Array();
-Float64Array();
-
- -

Parameters

- -
-
length
-
When called with a length argument, a typed array containing length zeroes is created.
-
typedArray
-
When called with a typedArray argument, which can be an object of any of the typed array types (such as Int32Array), the typedArray gets copied into a new typed array. Each value in typedArray is converted to the corresponding type of the constructor before being copied into the new array.
-
object
-
When called with an object argument, a new typed array is created as if by the TypedArray.from() method.
-
buffer, byteOffset, length
-
When called with a buffer, and optionally a byteOffset and a length argument, a new typed array view is created that views the specified {{jsxref("ArrayBuffer")}}. The byteOffset and length parameters specify the memory range that will be exposed by the typed array view.  If both are omitted, all of buffer is viewed; if only length is omitted, the remainder of buffer is viewed.
-
- -

Description

- -

ECMAScript 6 defines a TypedArray constructor that serves as the [[Prototype]] of all TypedArray constructors.  This constructor is not directly exposed: there is no global %TypedArray% or TypedArray property.  It is only directly accessible through Object.getPrototypeOf(Int8Array.prototype) and similar.  All TypedArrays constructors inherit common properties from the %TypedArray% constructor function.  Additionally, all typed array prototypes (TypedArray.prototype) have %TypedArray%.prototype as their [[Prototype]].

- -

The %TypedArray% constructor on its own is not particularly useful.  Calling it or using it in a new expression will throw a TypeError, except when used during object creation in JS engines that support subclassing.  There are at present no such engines, so %TypedArray% is only useful to polyfill functions or properties onto all TypedArray constructors.

- -

Property access

- -

You can reference elements in the array using standard array index syntax (that is, using bracket notation). However, getting or setting indexed properties on typed arrays will not search in the prototype chain for this property, even when the indices are out of bound. Indexed properties will consult the {{jsxref("ArrayBuffer")}} and will never look at object properties. You can still use named properties, just like with all objects.

- -
// Setting and getting using standard array syntax
-var int16 = new Int16Array(2);
-int16[0] = 42;
-console.log(int16[0]); // 42
-
-// Indexed properties on prototypes are not consulted (Fx 25)
-Int8Array.prototype[20] = "foo";
-(new Int8Array(32))[20]; // 0
-// even when out of bound
-Int8Array.prototype[20] = "foo";
-(new Int8Array(8))[20]; // undefined
-// or with negative integers
-Int8Array.prototype[-1] = "foo";
-(new Int8Array(8))[-1]; // undefined
-
-// Named properties are allowed, though (Fx 30)
-Int8Array.prototype.foo = "bar";
-(new Int8Array(32)).foo; // "bar"
- -

TypedArray objects

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TypeSize in bytesDescriptionWeb IDL typeEquivalent C type
{{jsxref("Int8Array")}}18-bit two's complement signed integerbyteint8_t
{{jsxref("Uint8Array")}}18-bit unsigned integeroctetuint8_t
{{jsxref("Uint8ClampedArray")}}18-bit unsigned integer (clamped)octetuint8_t
{{jsxref("Int16Array")}}216-bit two's complement signed integershortint16_t
{{jsxref("Uint16Array")}}216-bit unsigned integerunsigned shortuint16_t
{{jsxref("Int32Array")}}432-bit two's complement signed integerlongint32_t
{{jsxref("Uint32Array")}}432-bit unsigned integerunsigned longuint32_t
{{jsxref("Float32Array")}}432-bit IEEE floating point numberunrestricted floatfloat
{{jsxref("Float64Array")}}864-bit IEEE floating point numberunrestricted doubledouble
- -

Properties

- -
-
{{jsxref("TypedArray.BYTES_PER_ELEMENT")}}
-
Returns a number value of the element size for the different typed array objects.
-
TypedArray.length
-
Length property whose value is 3.
-
{{jsxref("TypedArray.name")}}
-
Returns the string value of the constructor name. E.g "Int8Array".
-
{{jsxref("TypedArray.@@species", "get TypedArray[@@species]")}}
-
The constructor function that is used to create derived objects.
-
{{jsxref("TypedArray.prototype")}}
-
Prototype for the TypedArray objects.
-
- -

Methods

- -
-
{{jsxref("TypedArray.from()")}}
-
Creates a new typed array from an array-like or iterable object. See also {{jsxref("Array.from()")}}.
-
{{jsxref("TypedArray.of()")}}
-
Creates a new typed array with a variable number of arguments. See also {{jsxref("Array.of()")}}.
-
- -

TypedArray prototype

- -

All TypedArrays inherit from {{jsxref("TypedArray.prototype")}}.

- -

Properties

- -

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

- -

Methods

- -

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

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Typed Array')}}{{Spec2('Typed Array')}}Defined as TypedArray and ArrayBufferView interface with typed array view types. Superseded by ECMAScript 6.
{{SpecName('ES6', '#sec-typedarray-objects', 'TypedArray Objects')}}{{Spec2('ES6')}}Initial definition in an ECMA standard. Specified behaviour for indexed and named properties. Specified that new is required.
{{SpecName('ESDraft', '#sec-typedarray-objects', 'TypedArray Objects')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(7.0)}}{{CompatGeckoDesktop("2")}}1011.65.1
Indexed properties not consulting prototype{{CompatVersionUnknown}} [1]{{CompatGeckoDesktop("25")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Named properties{{CompatVersionUnknown}}{{CompatGeckoDesktop("30")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
new is required{{CompatUnknown}}{{CompatGeckoDesktop("44")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support4.0{{CompatVersionUnknown}}{{ CompatGeckoMobile("2") }}1011.64.2{{CompatVersionUnknown}}
Indexed properties not consulting prototype{{CompatUnknown}}{{CompatVersionUnknown}} [1]{{ CompatGeckoMobile("25") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}} [1]
Named properties{{CompatUnknown}}{{CompatVersionUnknown}}{{ CompatGeckoMobile("30") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
new is required{{CompatUnknown}}{{CompatUnknown}}{{ CompatGeckoMobile("44") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

[1] -1 and similar are not considered as indexed properties and therefore return the value of the prototype property.

- -

Compatibility notes

- -

Starting with ECMAScript 2015 (ES6), TypedArray constructors require to be constructed with a {{jsxref("Operators/new", "new")}} operator. Calling a TypedArray constructor as a function without new, will throw a {{jsxref("TypeError")}} from now on.

- -
var dv = Int8Array([1, 2, 3]);
-// TypeError: calling a builtin Int8Array constructor
-// without new is forbidden
- -
var dv = new Int8Array([1, 2, 3]);
- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/typedarray/join/index.html b/files/id/web/javascript/reference/global_objects/typedarray/join/index.html deleted file mode 100644 index 84f328ae1b..0000000000 --- a/files/id/web/javascript/reference/global_objects/typedarray/join/index.html +++ /dev/null @@ -1,114 +0,0 @@ ---- -title: TypedArray.prototype.join() -slug: Web/JavaScript/Reference/Global_Objects/TypedArray/join -tags: - - ECMAScript6 - - JavaScript - - Method - - Prototype - - TypedArray -translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/join ---- -
{{JSRef}}
- -

Method join() menggabungkan semua elemen dari array menjadi sebuah string. Alogaritma method ini memiliki kesamaan dengan {{jsxref("Array.prototype.join()")}}. TypedArray di sini merupakan salah datu typed array types.

- -

Sintaks

- -
typedarray.join([separator = ',']);
- -

Parameter

- -
-
separator
-
Opsional. Menentukan sebuah string untuk memisahkan setiap elemen. Separator perlu di konversi ke string jika dianggap penting. Jika dikosongkan, elemen array akan dipisahkan dengan tanda koma (",").
-
- -

Contoh

- -
var uint8 = new Uint8Array([1,2,3]);
-uint8.join();      // '1,2,3'
-uint8.join(' / '); // '1 / 2 / 3'
-uint8.join('');    // '123'
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-%typedarray%.prototype.join', 'TypedArray.prototype.join')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-%typedarray%.prototype.join', 'TypedArray.prototype.join')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatGeckoDesktop("37")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("37")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/index.html b/files/id/web/javascript/reference/index.html deleted file mode 100644 index 261b76a5b5..0000000000 --- a/files/id/web/javascript/reference/index.html +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Referensi JavaScript -slug: Web/JavaScript/Reference -tags: - - JavaScript -translation_of: Web/JavaScript/Reference ---- -
{{JsSidebar}}
- -

Laman ini merupakan bagian dari sesi JavaScript pada MDN yang berfungsi sebagai acuan mengenai bahasa pemrograman JavaScript. Pelajari lebih lanjut perihal acuan ini.

- -

Objek Global

- -

Bagian ini mendokumentasikan semua object standar built-in JavaScript, beserta method dan propertinya.

- -
{{page('/id/docs/Web/JavaScript/Reference/Global_Objects', 'Standard_objects_by_category')}}
- -

Pernyataan

- -

Bagian ini mendekumentasikan semua pernyataan dan deklarasi  JavaScript.

- -
{{page('/id/docs/Web/JavaScript/Reference/Statements', 'Statements_and_declarations_by_category')}}
- -

Ungkapan dan operator

- -

Bagian ini mendokumentasikan semua ungkapan dan operator JavaScript .

- -
{{page('/id/docs/Web/JavaScript/Reference/Operators', 'Expressions_and_operators_by_category')}}
- -

Fungsi

- -

Bagian ini mendokumentasikan tentang Fungsi JavaScrip dan penggunaanya untuk pengembangan aplikasi anda.

- - - -

Acuan tambahan

- - diff --git a/files/id/web/javascript/reference/lexical_grammar/index.html b/files/id/web/javascript/reference/lexical_grammar/index.html deleted file mode 100644 index 83e5696ccd..0000000000 --- a/files/id/web/javascript/reference/lexical_grammar/index.html +++ /dev/null @@ -1,670 +0,0 @@ ---- -title: Lexical grammar -slug: Web/JavaScript/Reference/Lexical_grammar -translation_of: Web/JavaScript/Reference/Lexical_grammar ---- -
{{JsSidebar("More")}}
- -

Halaman ini menjelaskan tata bahasa leksikal JavaScript. Teks sumber skrip JavaScript dipindai dari kiri ke kanan dan diubah menjadi urutan elemen masukan yang merupakan token, karakter kontrol, terminator baris, komentar atau whitespace. ECMAScript juga mendefinisikan kata kunci dan literal tertentu dan memiliki aturan untuk penyisipan titik koma secara otomatis untuk mengakhiri pernyataan.

- -

Karakter-karakter kontrol

- -

Karakter kontrol tidak memiliki representasi visual namun digunakan untuk mengendalikan interpretasi teks.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Karakter-karakter kontrol format unicode
KodeNamaSingkatanDeskripsi
U+200CZero width non-joiner<ZWNJ>Ditempatkan di antara karakter untuk mencegah terhubung ke ligatur dalam bahasa tertentu (Wikipedia).
U+200DZero width joiner<ZWJ>Ditempatkan di antara karakter yang biasanya tidak terhubung agar karakter dapat dirender menggunakan bentuknya yang terhubung dalam bahasa tertentu. (Wikipedia).
U+FEFFByte order mark<BOM>Digunakan pada awal skrip untuk menandainya sebagai Unicode dan urutan byte teks (Wikipedia).
- -

White space

- -

Karakter whitespace meningkatkan keterbacaan teks sumber dan memisahkan token-token. Karakter ini biasanya tidak diperlukan untuk fungsionalitas kode. Alat minifikasi sering digunakan untuk membuang whitespace agar mengurangi jumlah data yang perlu ditransfer.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Karakter-karakter whitespace
KodeNamaSingkatanDeskripsi -

Rangkaian pelolosan/Escape

-
U+0009Tabulasi karakter<HT>Tabulasi horisontal\t
U+000BTabulasi baris<VT>Tabulasi vertikal\v
U+000CForm feed<FF>Karakter kontrol pemecah halaman (Wikipedia).\f
U+0020Space<SP>Spasi normal 
U+00A0No-break space<NBSP>Spasi normal, tetapi tidak ada petunjuk dimana baris terputus. 
OthersOther Unicode space characters<USP>Spasi di Unicode on Wikipedia 
- -

Terminator baris

- -

Selain karakter whitespace, karakter terminator baris digunakan untuk meningkatkan keterbacaan teks sumber. Namun, dalam beberapa kasus, terminator baris dapat mempengaruhi eksekusi kode JavaScript karena ada beberapa tempat di mana mereka dilarang. Terminator baris juga mempengaruhi proses penyisipan titik koma otomatis. Terminator baris dicocokkan dengan kelas \s dalam regular expressions.

- -

Hanya kode Unicode berikut yang diperlakukan sebagai terminator baris di ECMAScript, karakter pemecah baris lainnya diperlakukan sebagai whitespace (misalnya, Next Line, NEL, U+0085 dianggap sebagai whitespace).

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Karakter-karakter terminator baris
KodeNamaSingkatanDeskripsiRangkaian pelolosan/escape 
U+000ALine Feed<LF>Karakter baris baru di sistem UNIX.\n
U+000DCarriage Return<CR>Karakter baris baru di Commodore dan sistem Mac awal.\r
U+2028Line Separator<LS>Wikipedia 
U+2029Paragraph Separator<PS>Wikipedia 
- -

Komentar

- -

Komentar digunakan untuk menambahkan petunjuk, catatan, saran, atau peringatan ke kode JavaScript. Hal ini dapat mempermudah membaca dan memahami. Mereka juga dapat digunakan untuk menonaktifkan kode agar tidak dieksekusi; Ini juga dapat menjadi alat debugging yang berharga.

- -

JavaScript memiliki dua cara untuk memberi komentar pada kodenya.

- -

Cara pertama adalah komentar //; Ini membuat semua teks yang mengikutinya pada baris yang sama menjadi sebuah komentar. Sebagai contoh:

- -
function komentar() {
-  // Ini adalah komentar JavaScript satu baris
-  console.log('Hello world!');
-}
-komentar();
-
- -

Cara kedua adalah komentar gaya  /* */ , yang jauh lebih fleksibel.

- -

Misalnya, Anda bisa menggunakannya dalam satu baris:

- -
function komentar() {
-  /* Ini adalah komentar JavaScript satu baris */
-  console.log('Hello world!');
-}
-komentar();
- -

Anda juga bisa membuat komentar beberapa baris, seperti ini:

- -
function komentar() {
-  /* Komentar ini merentang dalam beberapa baris. Perhatikan
-     bahwa kita tidak perlu mengakhir komentar sebelum selesai. */
-  console.log('Hello world!');
-}
-komentar();
- -

Anda juga bisa menggunakannya di tengah baris, jika Anda mau, meskipun ini bisa membuat kode Anda lebih sulit dibaca sehingga harus digunakan dengan hati-hati:

- -
function komentar(x) {
-  console.log('Hello ' + x /* menysipkan nilai dari x */ + ' !');
-}
-comment('world');
- -

Selain itu, Anda bisa menggunakannya untuk menonaktifkan kode agar tidak berjalan, dengan membungkus kode dalam komentar, seperti ini:

- -
function comment() {
-  /* console.log('Hello world!'); */
-}
-comment();
- -

Dalam hal ini, pemaggilan console.log() tidak pernah dikeluarkan, karena itu ada di dalam komentar. Sejumlah baris kode dapat dinonaktifkan dengan cara ini.

- -

Kata kunci

- -

Reserved keywords as of ECMAScript 2015

- - - -

Kata kunci akan datang yang dicadangkan

- -

Berikut ini disediakan sebagai kata kunci akan datang menurut spesifikasi ECMAScript. Mereka tidak memiliki fungsi khusus saat ini, namun mungkin pada beberapa waktu mendatang, sehingga tidak dapat digunakan sebagai pengidentifikasi.

- -

Selalu dicadangkan:

- - - -

Berikut ini hanya dicadangkan saat ditemukan dalam kode mode strict "ketat":

- - - -

Berikut ini hanya dicadangkan saat ditemukan dalam kode modul:

- - - -

Kata kunci standart lama yang masih dingunakan hingga sekarang

- -

Berikut adalah dicadankan sebagai kata kunci akan datang pada spesifikasi ECMAScript usang (ECMAScript 1 s/d 3).

- - - -

Selain itu literal-literal null, true, dan false tidak dapat digunakan sebagai pengidentifikasi didalam ECMAScript.

- -

Penggunaan kata dicadangkan

- -

Kata yang dicadangkan sebenarnya hanya berlaku untuk pengidentifikasi (vs. IdentifierNames ). Seperti yang dijelaskan di es5.github.com/#A.1, ini semua adalah IdentifierNames yang tidak mengecualikan ReservedWords .

- -
a.import
-a['import']
-a = { import: 'test' }.
-
- -

Di sisi lain, hal-hal berikut ini ilegal karena ini adalah pengidentifikasi, yaitu IdentifierName tanpa kata-kata yang dicadangkan. Pengidentifikasi digunakan untuk FunctionDeclaration dan FunctionExpression.

- -
function import() {} // Illegal.
- -

Literal

- -

Literal null

- -

Lihat juga null untuk informasi lebih lanjut.

- -
null
- -

Literal Boolean

- -

Lihat juga Boolean untuk informasi lebih lanjut.

- -
true
-false
- -

Literal numerik

- -

Decimal

- -
1234567890
-42
-
-// Waspada saat mengunakan nol dimuka:
-0888 // 888 diuraikan sebagai desimal
-0777 // diuraikan sebagai oktal, 511 dalam desimal
-
- -

Perhatikan bahwa literal desimal dapat dimulai dengan angka nol ( 0 ) diikuti oleh digit desimal lainnya, namun jika semua digit setelah angka 0 teratas lebih kecil dari 8, angka tersebut diartikan sebagai angka oktal. Ini tidak akan melempar JavaScript, lihat {{bug(957513)}}. Lihat juga halaman tentang parseInt().

- -

Biner

- -

Sintaksis bilangan biner menggunakan nol dimuka diikuti huruf kecil atau huruf besar Latin "B" ( 0b atau 0B ). Karena sintaksis ini baru di ECMAScript 2015, lihat tabel kompatibilitas browser, di bawah ini. Jika digit setelah 0b tidak 0 atau 1, SyntaxError berikut dilempar: "Missing binary digits after 0b".

- -
var FLT_SIGNBIT  = 0b10000000000000000000000000000000; // 2147483648
-var FLT_EXPONENT = 0b01111111100000000000000000000000; // 2139095040
-var FLT_MANTISSA = 0B00000000011111111111111111111111; // 8388607
- -

Oktal

- -

Sintaksis bilangan oktal menggunakan nol dimuka diikuti huruf kecil atau huruf besar Latin "O" ( 0o atau 0O). Karena sintaks ini baru di ECMAScript 2015, lihat tabel kompatibilitas browser, di bawah ini. Jika digit setelah 0o berada di luar kisaran (01234567), SyntaxError berikut dilempar: "Missing octal digits after 0o".

- -
var n = 0O755; // 493
-var m = 0o644; // 420
-
-// Juga dimungkinkan hanya menggunakan nol dimuka (lihat tentang desimal diatas)
-0755
-0644
-
- -

Heksadesimal

- -

Sintaksis bilangan heksadesimal menggunakan nol dimuka diikuti huruf kecil atau huruf besar Latin "X" ( 0x atau 0X). Jika digit setelah 0x berada di luar rentang (0123456789ABCDEF), SyntaxError berikut dilempar: "Identifier starts immediately after numeric literal".

- -
0xFFFFFFFFFFFFFFFFF // 295147905179352830000
-0x123456789ABCDEF   // 81985529216486900
-0XA                 // 10
-
- -

Literal objek

- -

Lihat juga Objek and Penginisialisasi objek untuk informasi lebih lanjut.

- -
var o = { a: 'foo', b: 'bar', c: 42 };
-
-// notasi singkat. baru di ES2015
-var a = 'foo', b = 'bar', c = 42;
-var o = {a, b, c};
-
-// bukannya
-var o = { a: a, b: b, c: c };
-
- -

Literal array

- -

Lihat juga Array untuk informasi lebih lanjut.

- -
[1954, 1974, 1990, 2014]
- -

Literal string

- -
'foo'
-"bar"
- -

Rangkaian pelolosan/escape heksadesimal

- -
'\xA9' // "©"
-
- -

Rangkaian pelolosan/escape Unicode

- -

Rangkaian pelolosan Unicode memerlukan setidaknya empat karakter diawali \u.

- -
'\u00A9' // "©"
- -

Penerapan point kode Unicode

- -

Baru di ECMAScript 2015. Dengan pelolosan kode Unicode, tiap karakter dapat diloloskan menggunakan bilangan hexadesimal jadi dimungkinkan untuk menggunkan kode Unicode sampai 0x10FFFF. Dengan pelolosan Unicode sederhana terkadang lebih dibutuhkan untuk menulis bagian pengganti secara terpisah untuk mencapai tujuan yang sama.

- -

Lihat juga String.fromCodePoint() atau String.prototype.codePointAt().

- -
'\u{2F804}'
-
-// ekuivalen dengan pelolosan Unicode sederhana
-'\uD87E\uDC04'
- -

Literal regular expression

- -

Lihat juga RegExp untuk informasi lebih lanjut.

- -
/ab+c/g
-
-// Suatu literal "kosong" regular expression
-// diperlukan grup bukan penangkap
-// untuk menghindarkan ambiguitas denga komentar satu baris
-/(?:)/
- -

Literal template

- -

Lihat juga template strings untuk informasi lebih lanjut.

- -
`string text`
-
-`string text baris 1
- string text baris 2`
-
-`string text ${expression} string text`
-
-tag `string text ${expression} string text`
- -

Penyisipan titik koma otomatis

- -

Beberapa pernyataan JavaScript harus diakhiri dengan titik koma an oleh karena itu dipengaruhi oleh penyisipan otomatis semicolon (ASI):

- - - -

Spesifikasi ECMAScript menyebutkan tiga aturan penyisipan titik koma.

- -

1.  Titik koma disisipkan sebelumnya, bila terminator baris or "}" diteramukan yang tidak diizinkan oleh tata bahasa.

- -
{ 1 2 } 3
-
-// di transformasikan ke ASI kedalam
-
-{ 1 2 ;} 3;
- -

2.  Titik koma disisipkan di bagian akhir, saat akhir aliran input token terdeteksi dan parser tidak dapat mengurai aliran input tunggal aliran sebagai program yang lengkap.

- -

Disini ++ tidak diperlakukan sebagai operator postfix yang menerapkan variabel b, karena terminator baris terjadi antara b dan ++.

- -
a = b
-++c
-
-// di transformasikan ke ASI kedalam
-
-a = b;
-++c;
-
- -

3. Titik koma disisipkan pada akhirnya, ketika sebuah pernyataan dengan produksi terbatas dalam tata bahasa diikuti oleh terminator baris. Pernyataan-pernyataan ini dengan aturan "tidak diperlukan terminator baris" adalah:

- - - -
return
-a + b
-
-// di transformasikan ke ASI kedalam
-
-return;
-a + b;
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2("ES1")}}Definisi awal.
{{SpecName('ES5.1', '#sec-7', 'Lexical Conventions')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-language-lexical-grammar', 'Lexical Grammar')}}{{Spec2('ES6')}} -

Ditambahkan: Literal Bilangan Biner dan Octal, pelolosan kode Unicode, Templates

-
{{SpecName('ESDraft', '#sec-ecmascript-language-lexical-grammar', 'Lexical Grammar')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Literal numerik biner dan oktal (0b dan 0o){{CompatChrome(41)}}12{{CompatGeckoDesktop(25)}}{{CompatUnknown}}{{CompatOpera(28)}}{{CompatSafari(9)}}
Pelolosan kode Unicode (\u{}){{CompatChrome(44)}}12{{CompatGeckoDesktop(40)}}{{CompatNo}}{{CompatOpera(31)}}{{CompatSafari(9)}}
Notasi singkat untuk literal objek{{CompatChrome(43)}}12{{CompatGeckoDesktop(33)}}{{CompatNo}}{{CompatChrome(30)}}{{CompatSafari(9)}}
Literal template{{CompatChrome(41)}}12{{CompatGeckoDesktop(34)}}{{CompatNo}}{{CompatOpera(28)}}{{CompatSafari(9)}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Literal numerik biner dan oktal (0b dan 0o){{CompatUnknown}}41{{CompatGeckomobile(33)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Pelolosan kode Unicode (\u{}){{CompatUnknown}}{{CompatUnknown}}{{CompatGeckomobile(40)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Notasi singkat untuk literal objek{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(33)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Literal template{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(34)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Firefox-specific notes

- - - -

See also

- - diff --git a/files/id/web/javascript/reference/operators/conditional_operator/index.html b/files/id/web/javascript/reference/operators/conditional_operator/index.html deleted file mode 100644 index 1a64158acb..0000000000 --- a/files/id/web/javascript/reference/operators/conditional_operator/index.html +++ /dev/null @@ -1,167 +0,0 @@ ---- -title: Operasional Kondisi (ternary) -slug: Web/JavaScript/Reference/Operators/Conditional_Operator -translation_of: Web/JavaScript/Reference/Operators/Conditional_Operator ---- -
{{jsSidebar("Operators")}}
- -

Operasianal kondisional (ternary) adalah satu-satunya operator yang hanya membutuhkan tiga operator. Operator ini sering digunakan sebagai jalan pintas untuk `if` statement.

- -

Syntax

- -
condition ? expr1 : expr2 
- -

Parameters

- -
-
condition (atau conditions)
-
Sebuah ekspresi akan menguji apakah menghasilkan true atau false.
-
- -
-
expr1, expr2
-
Ekspresi yang akan dilakukan setelah kondisi terpenuhi.
-
- -

Description

- -

Jika condition menghasilkan true, maka operator ini akan menghasilkan/mengembalikan nilai dari expr1; dan jika sebaliknya, ini akan menghasilkan/mengembalikan nilai dari expr2. Sebagai contoh, untuk menampilkan pesan yang berbeda berdasarkan nilai dari variabel isMember, anda bisa menggunakan contoh kode berikut:

- -
var isMember = true;
-'The fee is ' + (isMember ? '$2.00' : '$10.00'); //$2.00
-
- -

Anda juga dapat mendefinisikan sebuah variabel secara langsung:

- -
var elvisLives = Math.PI > 4 ? 'Yep' : 'Nope';
- -

Anda juga bisa menggunakan operator ternary secara jamak (catatan: conditional operator adalah associative yang lebih baik):

- -
var firstCheck = false, secondCheck = false, access = firstCheck ? 'Access denied' : secondCheck ? 'Access denied' : 'Access granted';
-console.log(access); // logs "Access granted"
- -

Anda juga dapat menggunakan pengondisian jamak seperti pengondisian jamak pada statement IF pada umumnya:

- -
var condition1 = true,
-    condition2 = false,
-    access = condition1 ? (condition2 ? "true true": "true false") : (condition2 ? "false true" : "false false");
-
-console.log(access); // logs "true false"
-
- -

 

- -

Note: The parentheses are not required, and do not affect the functionality. They are there to help visualize how the outcome is processed.

- -

You can also use ternary evaluations in free space in order to do different operations:

- -
var stop = false, age = 16;
-
-age > 18 ? location.assign('continue.html') : stop = true;
-
- -

You can also do more than one single operation per case, separating them with a comma, and enclosing them in parenthesis:

- -
var stop = false, age = 23;
-
-age > 18 ? (
-    alert('OK, you can go.'),
-    location.assign('continue.html')
-) : (
-    stop = true,
-    alert('Sorry, you are much too young!')
-);
-
- -

You can also do more than one operation during the assignation of a value. In this case, the last comma-separated value of the parenthesis will be the value to be assigned.

- -
var age = 16;
-
-var url = age > 18 ? (
-    alert('OK, you can go.'),
-    // alert returns "undefined", but it will be ignored because
-    // isn't the last comma-separated value of the parenthesis
-    'continue.html' // the value to be assigned if age > 18
-) : (
-    alert('You are much too young!'),
-    alert('Sorry :-('),
-    // etc. etc.
-    'stop.html' // the value to be assigned if !(age > 18)
-);
-
-location.assign(url); // "stop.html"
- -

Returning Ternary Statements

- -

The ternary operator lends itself well to function returns that would otherwise require an if/else statement.

- -
var func1 = function( .. ) {
-  if (condition1) { return value1 }
-  else { return value2 }
-}
-
-var func2 = function( .. ) {
-  return condition1 ? value1 : value2
-}
- -

A good way to spot that the ternary will be a suitable replacement for an if/else statement is when the return keyword is used multiple times and is the only expression inside of the if block.

- -

By breaking the ternary onto multiple lines and making use of extra whitespace, the ternary operator can be used to very cleanly replace a lengthy series of if/else statements. This provides a syntactically light way of expressing the same logic:

- -
var func1 = function( .. ) {
-  if (condition1) { return value1 }
-  else if (condition2) { return value2 }
-  else if (condition3) { return value3 }
-  else { return value4 }
-}
-
-var func2 = function( .. ) {
-  return condition1 ? value1
-       : condition2 ? value2
-       : condition3 ? value3
-       :              value4
-}
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-conditional-operator', 'Conditional Operator')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-conditional-operator', 'Conditional Operator')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.12', 'The conditional operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1', '#sec-11.12', 'The conditional operator')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
- -

Browser compatibility

- - - -

{{Compat("javascript.operators.conditional")}}

- -

See also

- - diff --git a/files/id/web/javascript/reference/operators/function/index.html b/files/id/web/javascript/reference/operators/function/index.html deleted file mode 100644 index 7fa9564333..0000000000 --- a/files/id/web/javascript/reference/operators/function/index.html +++ /dev/null @@ -1,154 +0,0 @@ ---- -title: ungkapan fungsi -slug: Web/JavaScript/Reference/Operators/function -tags: - - Fungsi - - JavaScript - - Operator - - Ungkapan Utama -translation_of: Web/JavaScript/Reference/Operators/function -original_slug: Web/JavaScript/Reference/Operators/fungsi ---- -
{{jsSidebar("Operators")}}
- -
Kata kunci fungsi digunakan untuk mendefinisikan fungsi dalam sebuah ungkapan.
- -
 
- -

Sintaksis

- -
function [nama]([param1[, param2[, ..., paramN]]]) {
-   pernyataan
-}
- -

Parameters

- -
-
nama
-
Bisa dihilangkan apabila fungsi merupaka fungsi anonim. Nama fungsi bersifat lokal, relatif terhadap tubuh fungsi.
-
paramN
-
Nama argumen yang akan diumpankan kepada fungsi.
-
pernyataan
-
Pernyataan yang menyusun tubuh fungsi.
-
- -

Deskripsi

- -

Sintaksis ungkapan fungsi nyaris sama apabila dibandingkan dengan sintaksis pernyataan fungsi(lihat pernyataan fungsi untuk lebih jelasnya). Perbedaan utama antara ungkapan fungsi dengan pernyataan fungsi ialah; ungkapan fungsi memperbolehkan nama fungsi untuk tidak digunakan/dihilangkan apabila ungkapan fungsi tersebut merupakan fungsi anonim. Ungkapan fungsi dapat digunakan sebagai IIFE (immediately Invoked Function Expression), sebuah fungsi yang otomatis dijalankan apabila didefinisikan. Untuk informasi lebih lanjut, lihat juga bab tentang fungsi.

- -

Contoh

- -

Dibawah ini merupakan contoh definisi sebuah fungsi tanpa nama yang kemudian ditugaskan kedalam variabel x:

- -
var x = function(y) {
-   return y * y;
-};
-
- -

Ungkapan fungsi bernama (Named function expression)

- -

Apabila sebuah fungsi hendak dipanggil dari dalam tubuh fungsi itu sendiri, pergunakanlah ungkapan fungsi bernama. Nama fungsi bersifat lokal relatif terhadap tubuh fungsi. Manfaat penggunaan ungkapan fungsi bernama ialah menghindarkan penggunaan properti non-standar arguments.callee.

- -
var math = {
-  'factorial': function factorial(n) {
-    if (n <= 1)
-      return 1;
-    return n * factorial(n - 1);
-  }
-};
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-13', 'Function definition')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-13', 'Function definition')}}{{Spec2('ES3')}}Definisi awal. Diterapkan pada JavaScript 1.5.
- -

Kesesuaian Perambah (Browser)

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan Mendasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan Mendasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/operators/index.html b/files/id/web/javascript/reference/operators/index.html deleted file mode 100644 index ef3afeb763..0000000000 --- a/files/id/web/javascript/reference/operators/index.html +++ /dev/null @@ -1,269 +0,0 @@ ---- -title: Expressions and operators -slug: Web/JavaScript/Reference/Operators -tags: - - JavaScript - - NeedsTranslation - - Operators - - TopicStub -translation_of: Web/JavaScript/Reference/Operators ---- -
{{jsSidebar("Operators")}}
- -

This chapter documents all the JavaScript language operators, expressions and keywords.

- -

Ekspresi and operator sesuai kategori

- -

Untuk daftar isi sesuai Alfabet, silahkan lihat sisi sebelah kiri artikel ini.

- -

Primary expressions

- -

Basic keywords and general expressions in JavaScript.

- -

Keyword-keyword dasar dan ekspersi-ekspresi umum di javascript

- -
-
{{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.
-
{{jsxref("Global_Objects/Array", "[]")}}
-
Array literal syntax.
-
{{jsxref("Global_Objects/Object", "{}")}}
-
Object 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.

-
-
- -

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/id/web/javascript/reference/operators/yield/index.html b/files/id/web/javascript/reference/operators/yield/index.html deleted file mode 100644 index 366f2aaa38..0000000000 --- a/files/id/web/javascript/reference/operators/yield/index.html +++ /dev/null @@ -1,109 +0,0 @@ ---- -title: yield -slug: Web/JavaScript/Reference/Operators/yield -translation_of: Web/JavaScript/Reference/Operators/yield ---- -
{{jsSidebar("Operators")}}
- -

Keyword yield digunakan untuk menghentikan sementara dan melanjutkan sebuah fungsi generator ({{jsxref("Statements/function*", "function*")}} atau legacy generator function).

- -

Sintak

- -
[rv] = yield [expression];
- -
-
expression
-
Mendefeniskan nilai yang akan dikembalikan melalui iterator protocol. Apabila diabaikan, maka undefined akan dikembalikan.
-
rv
-
-

Mengembalikan nilai opsional yang diberikan pada generator method next() untuk melanjutkan eksekusinya.

-
-
- -

Deskripsi

- -

Keyword yield menghentikan secara sementara eksekusi dari fungsi generator dan nilai setelah keyword yield dikembalikan pada pemanggil generator tersebut. yield bisa juga disebut sebagai versi generator dari keywordreturn.

- -

Keyword yield sebenarnya mengembalikan sebuah obyek IteratorResult dengan dua properti, value dan done. Propertivalue adalah hasi dari evaluasi ekspresi yield, dan done yang false, mengindikasikan bahwa fungsi generator tersebut belum selesai sepenuhnya.

- -

Sekali berhenti pada ekspresi yield , eksekusi dari code generator tersebut akan terus dihentikan sampai generator method next() dipanggil. Setiap kali method generator next() dipanggil, generator melanjutkan eksekusi dan berjalan hingga mencapai salah satu dari kondisi berikut ini :

- - - -

JIka sebuah nilai opsional diberikan pada generator method next(), nilai tersebut menjadi nilai yang dikembalikan oleh operasi yield dari generator pada saat itu.

- -

Di antara kode generator, operatoryield -nya, dan kemampuan untuk menentukan sebua nilai awal baru dengan memberikannya pada {{jsxref("Generator.prototype.next()")}}, generator menawarkan power dan kontrol yang luar biasa.

- -

Contoh

- -

Kode berikut merupakan deklarasi dari sebuah contoh fungsi generator.

- -
function* countAppleSales () {
-  var saleList = [3, 7, 5];
-  for (var i = 0; i < saleList.length; i++) {
-    yield saleList[i];
-  }
-}
- -

Setelah sebuah fungsi generator didefenisikan, maka fungsi tersebut dapat digunakan untuk menghasilkan sebuah iterator seperti berikut.

- -
var appleStore = countAppleSales(); // Generator { }
-console.log(appleStore.next()); // { value: 3, done: false }
-console.log(appleStore.next()); // { value: 7, done: false }
-console.log(appleStore.next()); // { value: 5, done: false }
-console.log(appleStore.next()); // { value: undefined, done: true }
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ES2015', '#', 'Yield')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#', 'Yield')}}{{Spec2('ESDraft')}}
- -

Kompatabilitas Browser

- - - -

{{Compat("javascript.operators.yield")}}

- -

Catatan Firefox-specific

- - - -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/statements/class/index.html b/files/id/web/javascript/reference/statements/class/index.html deleted file mode 100644 index 6ca35e9c71..0000000000 --- a/files/id/web/javascript/reference/statements/class/index.html +++ /dev/null @@ -1,171 +0,0 @@ ---- -title: class -slug: Web/JavaScript/Reference/Statements/class -tags: - - Classes - - Declaration - - ECMAScript6 - - Referensi -translation_of: Web/JavaScript/Reference/Statements/class ---- -
{{jsSidebar("Statements")}}
- -

Deklarasi class digunakan untuk membuat class baru dengan nama menggunakan turunan berbasis prototype.

- -
-

Anda juga bisa mendefinisikan kelas menggunakan{{jsxref("Operators/class", "class expression", "", 1)}}.

-
- -

Sintaks

- -
class name [extends] {
-  // class body
-}
-
- -

Deskripsi

- -

Seperti halnya dengan ekspresi class,  pembentuk (body) class dari deklarasi class di jalankan pada strict mode.

- -

Deklarasi class bukanlah {{Glossary("Hoisting", "hoisted")}} (Tidak seperti function declarations).

- -

Contoh

- -

Dasar deklarasi class

- -

Pada contoh, hal pertama yang kita lakukan adalah mendefinisikan class dengan nama Polygon, kemudian membentangkannya ( extend ) untuk membuat class bernama Square. Perlu diperhatikan bahwa super(), digunakan pada constructor, hanya dapat digunakan di konstruktor dan harus dipanggil setelah keyword 'this' dapat digunakan.

- -
class Polygon {
-  constructor(height, width) {
-    this.name = 'Polygon';
-    this.height = height;
-    this.width = width;
-  }
-}
-
-class Square extends Polygon {
-  constructor(length) {
-    super(length, length);
-    this.name = 'Square';
-  }
-}
- -

Spesifikasi

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

Kompabilitas Browser

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatChrome(42.0)}}{{CompatGeckoDesktop(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Array subclassing{{CompatChrome(43.0)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Allowed in sloppy mode{{CompatChrome(49.0)}}    
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FiturAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Dukungan dasar{{CompatNo}}{{CompatChrome(42.0)}}{{CompatGeckoMobile(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(42.0)}}
Array subclassing{{CompatNo}}{{CompatChrome(43.0)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(43.0)}}
Allowed in sloppy mode{{CompatNo}}{{CompatChrome(49.0)}}    {{CompatChrome(49.0)}}
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/statements/do...while/index.html b/files/id/web/javascript/reference/statements/do...while/index.html deleted file mode 100644 index 01c518ad84..0000000000 --- a/files/id/web/javascript/reference/statements/do...while/index.html +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: do...while -slug: Web/JavaScript/Reference/Statements/do...while -tags: - - JavaScript - - Referensi -translation_of: Web/JavaScript/Reference/Statements/do...while ---- -
{{jsSidebar("Statements")}}
- -

Pernyataan do...while digunakan untuk membuat perulangan yang mengeksekusi penyataan tertentu hingga kondisi pemeriksaan penyataan tersebut bernilai false. Kondisi akan diperiksa setelah pernyataan dieksekusi/dijalankan dengan hasil penyataan tersebut yang dijalankan sekurangnya sekali.

- -
{{EmbedInteractiveExample("pages/js/statement-dowhile.html")}}
- - - -

Sintaks

- -
do
-   penyataan
-while (kondisi);
-
- -
-
penyataan
-
Sebuah penyataan yang dieksekusi setidaknya sekali dan akan kembali dieksekusi setiap kali kondisi pemeriksaan bernial true. Untuk mengeksekusi lebih dari satu penyataan di dalam perulangan, gunakan pernyataan {{jsxref("Statements/block", "block")}}  ({ ... }) untuk mengelompokkan penyataan.
-
- -
-
kondisi
-
Sebuah ekspresi yang periksa setelah perulangan. Bila kondisi periksa bernilai true, maka pernyataan akan kembali dieksekusi. Bila kondisi periksa bernilai false, maka kendali akan melewati do...while dan meneruskan ke pernyataan selanjutnya.
-
- -

Contoh

- -

Penggunaan do...while

- -

Pada contoh berikut, perulangan do...while diiterasikan setidaknya sekali dan kembali di iterasikan sampai nilai i tidak kurang dari 5.

- -

Kode HTML

- -
<div id="example"></div>
- -

Kode JavaScript

- -
var result = '';
-var i = 0;
-do {
-   i += 1;
-   result += i + ' ';
-} while (i < 5);
-document.getElementById('example').innerHTML = result;
- -

Hasil

- -

{{ EmbedLiveSample('Examples') }}

- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2
{{SpecName('ES5.1', '#sec-12.6.1', 'do-while statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-do-while-statement', 'do-while statement')}}{{Spec2('ES6')}}Trailing ; is now optional.
{{SpecName('ESDraft', '#sec-do-while-statement', 'do-while statement')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas Peramban

- - - -

{{Compat("javascript.statements.do_while")}}

- -

Lihat pula

- - diff --git a/files/id/web/javascript/reference/statements/empty/index.html b/files/id/web/javascript/reference/statements/empty/index.html deleted file mode 100644 index 26b2bf8d20..0000000000 --- a/files/id/web/javascript/reference/statements/empty/index.html +++ /dev/null @@ -1,147 +0,0 @@ ---- -title: empty -slug: Web/JavaScript/Reference/Statements/Empty -tags: - - JavaScript - - Statement -translation_of: Web/JavaScript/Reference/Statements/Empty ---- -
{{jsSidebar("Statements")}}
- -

Pernyataan empty digunakan untuk menyediakan statement kosong, walaupun begitu sintaks JavaScript tetap menghitungnya sebagai sebuah Pernyataan.

- -

Sintak

- -
;
-
- -

Deskripsi

- -

Statemen atau penyataan kosong hanya berupa semicolon (;) menunjukkan bahawa tidak ada statement untuk dijalankan, meskipun jika sintak JavaScript membutuhkan salah satunya. Sifat kebalikan, dimana anda ingin menggunakan lebih dari satu statemen, namun javascript hanya memperbolehkan sebuah statemen kosong, anda bisa menggunakan block statement; yang merupakan gabungan dari beberapa statement menjadi satu.

- -

Contoh

- -

Statement kosong terkadang digunakan pada perulangan. Lihat pada contoh dengan body berisi sebuah statement kosong:

- -
var arr = [1, 2, 3];
-
-// Assign all array values to 0
-for (i = 0; i < arr.length; arr[i++] = 0) /* empty statement */ ;
-
-console.log(arr)
-// [0, 0, 0]
-
- -

Catatan: Ini merupakan ide yang bagus dengan menggunakan komentar pada penggunaan statement kosong, karena ini tidak benar - benar jelas seperti halnya penggunaan semicolon (;) pada umumnya. Contoh berikut bisa dikatakan merupakan penggunaan yang tidak disengaja:

- -
if (condition);       // Perhatian, "if" tidak menjalankan apapun!
-   killTheUniverse()  // Jadi ini akan selalu di jalankan!!!
-
- -

Contoh lain: Statemen if...else tanpa tanda kurung keriting ({}). Jika three bernilai true, tidak akan terjadi apapun, four tidak begitu penting, dan juga fungsi launchRocket() pada kasus else tidak akan dijalankan.

- -
if (one)
-  doOne();
-else if (two)
-  doTwo();
-else if (three)
-  ; // nothing here
-else if (four)
-  doFour();
-else
-  launchRocket();
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ESDraft', '#sec-empty-statement', 'Empty statement')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-empty-statement', 'Empty statement')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-12.3', 'Empty statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-12.3', 'Empty statement')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-12.3', 'Empty statement')}}{{Spec2('ES1')}}Initial definition.
- -

Kompabilitas Browser

- -

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

Lihat juga

- - diff --git a/files/id/web/javascript/reference/statements/export/index.html b/files/id/web/javascript/reference/statements/export/index.html deleted file mode 100644 index 1f6d26b71d..0000000000 --- a/files/id/web/javascript/reference/statements/export/index.html +++ /dev/null @@ -1,171 +0,0 @@ ---- -title: export -slug: Web/JavaScript/Reference/Statements/export -translation_of: Web/JavaScript/Reference/Statements/export ---- -
{{jsSidebar("Statements")}}
- -

export statement digunakan untuk meng-ekspor fungsi, objects atau primitives dari file yang di berikan (atau module).

- -
-

Catatan: Fitur ini tidak di implementasikan di browser secara bawaan untuk saat ini. ini hanya diimplementasikan di beberapa transpilers, seperti Traceur CompilerBabel atau Rollup.

-
- -

Syntax

- -
export { name1, name2, …, nameN };
-export { variable1 as name1, variable2 as name2, …, nameN };
-export let name1, name2, …, nameN; // also var
-export let name1 = …, name2 = …, …, nameN; // also var, const
-
-export default expression;
-export default function (…) { … } // also class, function*
-export default function name1(…) { … } // also class, function*
-export { name1 as default, … };
-
-export * from …;
-export { name1, name2, …, nameN } from …;
-export { import1 as name1, import2 as name2, …, nameN } from …;
- -
-
nameN
-
- -

Identitas yang akan diekspor ( sehingga dapat di impor via import di lain skrip).

- -

Deskripsi

- -

Ada dua jenis tipe yang berbeda-beda dari export, masing-masing sesuai dengan salah satu sintaks di atas:

- - - -

Named exports berguna untuk mengekspor beberapa nilai. Selama import, satu akan menggunakan nama yang sama untuk mengacu pada nilai yang sesuai.

- -

Mengenai default export, hanya ada satu default export per modul. default export bisa menjadi fungsi, class, objek atau yang lainya. Nilai ini dianggap sebagai  "Pokok" pengeluaran nilai karena akan menjadi sederhana untuk di import.

- -

Contoh

- -

Menggunakan named exports

- -

dalam modul, kita bisa menggunakan kode berikut:

- -
// module "my-module.js"
-export function cube(x) {
-  return x * x * x;
-}
-const foo = Math.PI + Math.SQRT2;
-export { foo };
-
- -

Cara ini, di dalam script lain  (cf. import), kita bisa memiliki:

- -
import { cube, foo } from 'my-module';
-console.log(cube(3)); // 27
-console.log(foo);    // 4.555806215962888
- -

Menggunakan default export

- -

Jika kita ingin mengekspor nilai tunggal atau memiliki nilai fallback untuk modul kita, kita bisa menggunakan default export:

- -
// module "my-module.js"
-export default function cube(x) {
-  return x * x * x;
-}
-
- -

Kemudian, di lain skrip, akan lebih mudah untuk mengimpor export default :

- -
import cube from 'my-module';
-console.log(cube(3)); // 27
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-exports', 'Exports')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-exports', 'Exports')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas browser

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/statements/for...in/index.html b/files/id/web/javascript/reference/statements/for...in/index.html deleted file mode 100644 index 0162c204ee..0000000000 --- a/files/id/web/javascript/reference/statements/for...in/index.html +++ /dev/null @@ -1,201 +0,0 @@ ---- -title: for...in -slug: Web/JavaScript/Reference/Statements/for...in -tags: - - JavaScript - - Statement -translation_of: Web/JavaScript/Reference/Statements/for...in ---- -
{{jsSidebar("Statements")}}
- -

Pernyataan for...in mengulang setiap properti enumerable dari sebuah objek, dalam urutan sembarang. Untuk setiap properti yang berbeda, pernyataan dapat dieksekusi.

- -

Sintak

- -
for (variable in object) {...
-}
- -
-
variable
-
Sebuah nama properti yang berbeda ditugaskan untuk variabel pada setiap iterasi.
-
object
-
Objek yang propertinya enumerable yang diiterasi.
-
- -

Deskripsi

- -

Perulangan for...in hanya mengiterasi pada properti enumerable. Objek yang dibuat dari built-in konstruktor seperti Array dan Object telah mewarisi properti non-enumerable dari Object.prototype dan String.prototype, seperti {{jsxref("String")}}'s {{jsxref("String.indexOf", "indexOf()")}} metode atau {{jsxref("Object")}}'s {{jsxref("Object.toString", "toString()")}} metode. Perulangan akan iterate atas semua properti enumerable dari objek itu sendiri dan mereka objek mewarisi dari prototipe konstruktor ini (properti lebih dekat ke objek di properti mata rantai prototipe menggantikan prototipe' properti).

- -

Penghapusan, penambahan atau perubahan pada properti

- -

Perulangan for...in mengiterasi properti suatu objek dalam urutan sembarang (lihat {{jsxref("Operators/delete", "delete")}} Operator untuk lebih lanjut tentang mengapa salah satu tidak dapat bergantung pada keteraturan tampak dari iterasi, setidaknya dalam pengaturan lintas-browser). Jika properti yang diubah dalam satu iterasi dan kemudian mengunjungi di lain waktu, nilainya dalam lingkaran adalah nilai pada waktu kemudian. Sebuah properti yang dihapus sebelum telah dikunjungi tidak akan dikunjungi nanti. Sifat ditambahkan ke objek dimana iterasi terjadi baik dapat dikunjungi atau dihilangkan dari iterasi. Secara umum yang terbaik adalah tidak untuk menambah, mengubah atau menghapus properti dari objek selama iterasi, selain properti saat ini sedang mengunjungi. Tidak ada jaminan apakah properti menambahkan akan dikunjungi, apakah properti dimodifikasi (selain yang saat ini) akan dikunjungi sebelum atau setelah dimodifikasi, atau apakah properti dihapus akan dikunjungi sebelum dihapus.

- -

Iterasi Array dan for...in

- -
-

Catatan: for...in tidak perlu digunakan untuk mengiterasi sebuah {{jsxref("Array")}} dimana urutan indeksnya sangat penting.

-
- -

Index array hanyalah properti enumerable dengan nama integer dan tidak sama dengan properti Objek pada umumnya. Disini tidak akan menjamin jika for...in akan mengembalikan indek pada urutan tertentu.  Pernyataan for...in akan mengembalikan semua properti enumerable, termasuk didalamnya dengan nama non–integer dan serta turunannya.

- -

Karena urutan iterasi merupakan implementation-dependent, pengiterasian pada array mungkin tidak membaca elemen pada urutan yang urut. Karena itu lebih baik menggunakan perulangan {{jsxref("Statements/for", "for")}} dengan menggunakan nomor indek (atau {{jsxref("Array.prototype.forEach()")}} atau {{jsxref("Statements/for...of", "for...of")}} loop) ketika mengiterasi array dimana urutan akses sangat penting.

- -

Iterasi hanya pada properti sendiri

- -

Jika anda hanya ingin mempertimbangkan properti yang melekat pada objek itu sendri, dan bukan prototypes-nya, gunakan {{jsxref("Object.getOwnPropertyNames", "getOwnPropertyNames()")}} atau lakukan {{jsxref("Object.prototype.hasOwnProperty", "hasOwnProperty()")}} cek ({{jsxref("Object.prototype.propertyIsEnumerable", "propertyIsEnumerable")}} juga dapat digunakan). Alternatifnya, jika anda tahu disana tidak ada campur tangan kode luar , anda dapat memperpanjang built-in prototypes dengan metode cek.

- -

Contoh

- -

Pada fungsi berikut menggunakan sebuah objek argumen. kemudian mengiterasi pada semua properti enumerable pada objek tersebut dan mengembalikan string dari nama properti dan nilainya.

- -
var obj = {a:1, b:2, c:3};
-
-for (var prop in obj) {
-  console.log("obj." + prop + " = " + obj[prop]);
-}
-
-// Output:
-// "obj.a = 1"
-// "obj.b = 2"
-// "obj.c = 3"
- -

Fungsi berikut mengiterasi menggunakan {{jsxref("Object.prototype.hasOwnProperty", "hasOwnProperty()")}}: properti turunannya tidak akan di tampilkan.

- -
var triangle = {a:1, b:2, c:3};
-
-function ColoredTriangle() {
-  this.color = "red";
-}
-
-ColoredTriangle.prototype = triangle;
-
-var obj = new ColoredTriangle();
-
-for (var prop in obj) {
-  if( obj.hasOwnProperty( prop ) ) {
-    console.log("obj." + prop + " = " + obj[prop]);
-  }
-}
-
-// Output:
-// "obj.color = red"
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ESDraft', '#sec-for-in-and-for-of-statements', 'for...in statement')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-for-in-and-for-of-statements', 'for...in statement')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-12.6.4', 'for...in statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-12.6.4', 'for...in statement')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-12.6.3', 'for...in statement')}}{{Spec2('ES1')}}Initial definition.
- -

Kompabilitas Browser

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}10{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Kompabilitas: Ekspresi Initializer

- -

Pada SpiderMonkey 40 {{geckoRelease(40)}} atau sebelumnya, bisa menggunakan ekspersi initializer (i=0) pada perulangan for...in :

- -
var obj = {a:1, b:2, c:3};
-for(var i=0 in obj) {
-  console.log(obj[i]);
-}
-// 1
-// 2
-// 3
-
- -

Perilaku non-standard ini sekarang diabaikan pada versi 40 dan selanjutnya akan disajikan dengan {{jsxref("SyntaxError")}} ("for-in loop head declarations may not have initializers") Peringatan pada konsole ({{bug(748550)}} dan {{bug(1164741)}}).

- -

Pada mesin lain seperti v8 (Chrome), Chakra (IE/Edge), dan JSC (WebKit/Safari) juga telah menyelidiki untuk menghapus perilaku non standar tersebut.

- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/statements/function/index.html b/files/id/web/javascript/reference/statements/function/index.html deleted file mode 100644 index bd6b665d2e..0000000000 --- a/files/id/web/javascript/reference/statements/function/index.html +++ /dev/null @@ -1,233 +0,0 @@ ---- -title: Deklarasi Fungsi -slug: Web/JavaScript/Reference/Statements/function -tags: - - JavaScript - - Pernyataan - - Statement -translation_of: Web/JavaScript/Reference/Statements/function -original_slug: Web/JavaScript/Reference/Statements/fungsi ---- -
{{jsSidebar("Statements")}}
- -

Deklarasi fungsi mendefinisikan sebuah fungsi dengan parameter-parameter yang ditentukan.

- -

Fungsi juga dapat didefinisikan menggukanan konstruktor {{jsxref("Function")}} dan {{jsxref("Operators/function", "function expression")}}.

- -

Sintak

- -
function name([param,[, param,[..., param]]]) {
-   [statements]
-}
-
- -
-
name
-
Nama dari fungsi.
-
- -
-
param
-
Nama dari argumen yang akan dilewatkan kepada fungsi. Jumlah maksimal dari argumen berbeda-beda di setiap mesin.
-
- -
-
statements
-
Statemen-statemen yang membentuk tubuh dari sebuah fungsi.
-
- -

Deskripsi

- -

Sebuah fungsi yang diciptakan dengan deklarasi fungsi adalah sebuah objek Function dan memiliki semua properti, method-method dan tingkah laku dari objek Function. Lihat {{jsxref("Function")}} untuk informasi mendetail tentang fungsi-fungsi.

- -

Sebuah fungsi juga dapat diciptakan menggunakan sebuah ekspresi (lihat  {{jsxref("Operators/function", "function expression")}}).

- -

Secara default, fungsi mengembalikan nilai undefined. Untuk mengembalikan nilai lain, fungsi tersebut harus memiliki sebuah {{jsxref("Statements/return", "return")}} statement yang menentukan nilai untuk dikembalikan.

- -

Fungsi yang dibuat secara kondisional

- -

Fungsi dapat dideklarasikan secara kondisional, yaitu sebuah statement fungsi dapat disarangkan di dalam sebuah statement if. Kebanyakan aplikasi perambah selain Mozilla akan memperlakukan deklarasi kondisional seperti itu sebagai sebuah deklarasi non kondisional dan menciptakan fungsi tersebut meskipun kondisi bernilai benar atau salah, lihat artikel berikut untuk ikhtisar. Untuk alasan tersebut, deklarasi kondisional seharusnya tidak digunakan -- untuk pembuatakan kondisional gunakan ekspresi fungsi sebagai gantinya.

- -

Pengangkatan deklarasi fungsi

- -

Deklarasi fungsi di javaScript mengangkat definisi fungsi. Kamu dapat menggunakan fungsi sebelum kamu mendeklarasikan fungsi tersebut.

- -
hoisted(); // logs "foo"
-
-function hoisted() {
-  console.log('foo');
-}
-
- -

Dicatat bahwa {{jsxref("Operators/function", "function expressions")}} tidak terangkat:

- -
notHoisted(); // TypeError: notHoisted is not a function
-
-var notHoisted = function() {
-   console.log('bar');
-};
-
- -

Contoh

- -

Menggunakan fungsi

- -

Kode berikut mendeklarasikan sebuah fungsi yang mengembalikan jumlah total penjualan ketika diberikan angka dari unit-unit yang terjual dari produk a, b, dan c.

- -
function calc_sales(units_a, units_b, units_c) {
-   return units_a * 79 + units_b * 129 + units_c * 699;
-}
-
- -

Spesifikasi

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

Kompabilitas Perambah

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Allowed in sloppy mode{{CompatChrome(49.0)}}{{CompatUnknown}}    
Trailing comma in parameters{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("52.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Allowed in sloppy mode{{CompatNo}} -

{{CompatChrome(49.0)}}

-
{{CompatUnknown}}     -

{{CompatChrome(49.0)}}

-
Trailing comma in parameters{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("52.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/statements/index.html b/files/id/web/javascript/reference/statements/index.html deleted file mode 100644 index 08840f4e1a..0000000000 --- a/files/id/web/javascript/reference/statements/index.html +++ /dev/null @@ -1,139 +0,0 @@ ---- -title: Statements -slug: Web/JavaScript/Reference/Statements -tags: - - JavaScript - - Referensi - - Statement -translation_of: Web/JavaScript/Reference/Statements ---- -
{{jsSidebar("Statements")}}
- -

Aplikasi JavaScript terdiri dari statemen dengan sebuah sintaks tertentu. Sebuah statement dapat terdiri lebih dari satu baris. Setiap statement dapat berupa sebaris kode jika di pisahkan dengan semikolon ( ; ). Bukan merupakan keyword, tapi sekumpulan keyword.

- -

Statemen dan deklarasi berdasarkan kategori

- -

Untuk daftar berdasarkan alfabet lihat pada sidebar sebelah kiri.

- -

Control flow

- -
-
{{jsxref("Statements/block", "Block")}}
-
Sebuah block statemen digunakan untuk mengelompokkan zero ( 0 ) atau lebih statement. Block ini dibatasi menggunakan kurung kurawal.
-
{{jsxref("Statements/break", "break")}}
-
Membatasi  loop, switch, atau label statement dan transfer kontrol program pada statement berdasakan statemen akhir.
-
{{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.
-
- -

Deklarasi

- -
-
{{jsxref("Statements/var", "var")}}
-
Mendeklarasikan variabel, biasanya menginisialisasi ke sebuah nilai.
-
{{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.
-
- -

Fungsi dan class

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

- - -- cgit v1.2.3-54-g00ecf