From da78a9e329e272dedb2400b79a3bdeebff387d47 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:17 -0500 Subject: initial commit --- .../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 ++++++++ .../global_objects/function/prototype/index.html | 143 ++++++ .../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/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/purwarupa/index.html | 221 ++++++++++ .../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 +++++ 67 files changed, 11538 insertions(+) create mode 100644 files/id/web/javascript/reference/global_objects/array/concat/index.html create mode 100644 files/id/web/javascript/reference/global_objects/array/filter/index.html create mode 100644 files/id/web/javascript/reference/global_objects/array/from/index.html create mode 100644 files/id/web/javascript/reference/global_objects/array/index.html create mode 100644 files/id/web/javascript/reference/global_objects/array/isarray/index.html create mode 100644 files/id/web/javascript/reference/global_objects/array/join/index.html create mode 100644 files/id/web/javascript/reference/global_objects/array/length/index.html create mode 100644 files/id/web/javascript/reference/global_objects/array/of/index.html create mode 100644 files/id/web/javascript/reference/global_objects/array/pop/index.html create mode 100644 files/id/web/javascript/reference/global_objects/array/reverse/index.html create mode 100644 files/id/web/javascript/reference/global_objects/array/shift/index.html create mode 100644 files/id/web/javascript/reference/global_objects/array/slice/index.html create mode 100644 files/id/web/javascript/reference/global_objects/array/splice/index.html create mode 100644 files/id/web/javascript/reference/global_objects/array/unshift/index.html create mode 100644 files/id/web/javascript/reference/global_objects/array/values/index.html create mode 100644 files/id/web/javascript/reference/global_objects/date/getfullyear/index.html create mode 100644 files/id/web/javascript/reference/global_objects/date/index.html create mode 100644 files/id/web/javascript/reference/global_objects/date/now/index.html create mode 100644 files/id/web/javascript/reference/global_objects/date/tojson/index.html create mode 100644 files/id/web/javascript/reference/global_objects/date/totimestring/index.html create mode 100644 files/id/web/javascript/reference/global_objects/error/index.html create mode 100644 files/id/web/javascript/reference/global_objects/error/name/index.html create mode 100644 files/id/web/javascript/reference/global_objects/function/displayname/index.html create mode 100644 files/id/web/javascript/reference/global_objects/function/index.html create mode 100644 files/id/web/javascript/reference/global_objects/function/length/index.html create mode 100644 files/id/web/javascript/reference/global_objects/function/name/index.html create mode 100644 files/id/web/javascript/reference/global_objects/function/prototype/index.html create mode 100644 files/id/web/javascript/reference/global_objects/index.html create mode 100644 files/id/web/javascript/reference/global_objects/isnan/index.html create mode 100644 files/id/web/javascript/reference/global_objects/json/index.html create mode 100644 files/id/web/javascript/reference/global_objects/json/parse/index.html create mode 100644 files/id/web/javascript/reference/global_objects/map/clear/index.html create mode 100644 files/id/web/javascript/reference/global_objects/map/delete/index.html create mode 100644 files/id/web/javascript/reference/global_objects/map/index.html create mode 100644 files/id/web/javascript/reference/global_objects/math/abs/index.html create mode 100644 files/id/web/javascript/reference/global_objects/math/ceil/index.html create mode 100644 files/id/web/javascript/reference/global_objects/math/e/index.html create mode 100644 files/id/web/javascript/reference/global_objects/math/floor/index.html create mode 100644 files/id/web/javascript/reference/global_objects/math/index.html create mode 100644 files/id/web/javascript/reference/global_objects/math/ln10/index.html create mode 100644 files/id/web/javascript/reference/global_objects/math/max/index.html create mode 100644 files/id/web/javascript/reference/global_objects/math/min/index.html create mode 100644 files/id/web/javascript/reference/global_objects/math/pow/index.html create mode 100644 files/id/web/javascript/reference/global_objects/object/getprototypeof/index.html create mode 100644 files/id/web/javascript/reference/global_objects/object/index.html create mode 100644 files/id/web/javascript/reference/global_objects/object/keys/index.html create mode 100644 files/id/web/javascript/reference/global_objects/object/preventextensions/index.html create mode 100644 files/id/web/javascript/reference/global_objects/promise/catch/index.html create mode 100644 files/id/web/javascript/reference/global_objects/promise/index.html create mode 100644 files/id/web/javascript/reference/global_objects/promise/reject/index.html create mode 100644 files/id/web/javascript/reference/global_objects/promise/resolve/index.html create mode 100644 files/id/web/javascript/reference/global_objects/promise/then/index.html create mode 100644 files/id/web/javascript/reference/global_objects/regexp/index.html create mode 100644 files/id/web/javascript/reference/global_objects/string/concat/index.html create mode 100644 files/id/web/javascript/reference/global_objects/string/fromcharcode/index.html create mode 100644 files/id/web/javascript/reference/global_objects/string/fromcodepoint/index.html create mode 100644 files/id/web/javascript/reference/global_objects/string/index.html create mode 100644 files/id/web/javascript/reference/global_objects/string/indexof/index.html create mode 100644 files/id/web/javascript/reference/global_objects/string/length/index.html create mode 100644 files/id/web/javascript/reference/global_objects/string/link/index.html create mode 100644 files/id/web/javascript/reference/global_objects/string/purwarupa/index.html create mode 100644 files/id/web/javascript/reference/global_objects/string/split/index.html create mode 100644 files/id/web/javascript/reference/global_objects/string/tolowercase/index.html create mode 100644 files/id/web/javascript/reference/global_objects/string/tostring/index.html create mode 100644 files/id/web/javascript/reference/global_objects/string/touppercase/index.html create mode 100644 files/id/web/javascript/reference/global_objects/typedarray/index.html create mode 100644 files/id/web/javascript/reference/global_objects/typedarray/join/index.html (limited to 'files/id/web/javascript/reference/global_objects') 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 new file mode 100644 index 0000000000..c6a25609db --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/array/concat/index.html @@ -0,0 +1,169 @@ +--- +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 new file mode 100644 index 0000000000..5c23313268 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/array/filter/index.html @@ -0,0 +1,244 @@ +--- +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 new file mode 100644 index 0000000000..7845da9755 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/array/from/index.html @@ -0,0 +1,248 @@ +--- +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 new file mode 100644 index 0000000000..2b052487c4 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/array/index.html @@ -0,0 +1,484 @@ +--- +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 new file mode 100644 index 0000000000..152b6cdfd0 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/array/isarray/index.html @@ -0,0 +1,144 @@ +--- +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 new file mode 100644 index 0000000000..8ddd3bb8ed --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/array/join/index.html @@ -0,0 +1,132 @@ +--- +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 new file mode 100644 index 0000000000..6e8e9e3ae8 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/array/length/index.html @@ -0,0 +1,145 @@ +--- +title: Array.length +slug: Web/JavaScript/Reference/Global_Objects/Array/length +tags: + - 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 new file mode 100644 index 0000000000..49ca553133 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/array/of/index.html @@ -0,0 +1,129 @@ +--- +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 new file mode 100644 index 0000000000..f8dc9f0523 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/array/pop/index.html @@ -0,0 +1,134 @@ +--- +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 new file mode 100644 index 0000000000..dca16b463e --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/array/reverse/index.html @@ -0,0 +1,127 @@ +--- +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 new file mode 100644 index 0000000000..ac20d5cd60 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/array/shift/index.html @@ -0,0 +1,129 @@ +--- +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 new file mode 100644 index 0000000000..44f018ba65 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/array/slice/index.html @@ -0,0 +1,152 @@ +--- +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 new file mode 100644 index 0000000000..a0c7c1cb86 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/array/splice/index.html @@ -0,0 +1,146 @@ +--- +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 new file mode 100644 index 0000000000..4df2069f54 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/array/unshift/index.html @@ -0,0 +1,135 @@ +--- +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 new file mode 100644 index 0000000000..dd77cc65a5 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/array/values/index.html @@ -0,0 +1,120 @@ +--- +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 new file mode 100644 index 0000000000..08e657aeec --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/date/getfullyear/index.html @@ -0,0 +1,88 @@ +--- +title: Date.prototype.getFullYear() +slug: Web/JavaScript/Reference/Global_Objects/Date/getFullYear +tags: + - Date + - JavaScript + - 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 new file mode 100644 index 0000000000..1fc6272dcf --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/date/index.html @@ -0,0 +1,261 @@ +--- +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 new file mode 100644 index 0000000000..43760a275b --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/date/now/index.html @@ -0,0 +1,124 @@ +--- +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 new file mode 100644 index 0000000000..cb951d5fa0 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/date/tojson/index.html @@ -0,0 +1,119 @@ +--- +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 new file mode 100644 index 0000000000..90ebd23e68 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/date/totimestring/index.html @@ -0,0 +1,125 @@ +--- +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 new file mode 100644 index 0000000000..c0fc3cec6f --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/error/index.html @@ -0,0 +1,231 @@ +--- +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 new file mode 100644 index 0000000000..6644fff80a --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/error/name/index.html @@ -0,0 +1,119 @@ +--- +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 new file mode 100644 index 0000000000..952014983b --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/function/displayname/index.html @@ -0,0 +1,123 @@ +--- +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 new file mode 100644 index 0000000000..49d1c1a114 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/function/index.html @@ -0,0 +1,241 @@ +--- +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 new file mode 100644 index 0000000000..901c11b336 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/function/length/index.html @@ -0,0 +1,148 @@ +--- +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 new file mode 100644 index 0000000000..1a35d62020 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/function/name/index.html @@ -0,0 +1,191 @@ +--- +title: Function.name +slug: Web/JavaScript/Reference/Global_Objects/Function/name +tags: + - ECMAScript6 + - Function + - JavaScript + - Property +translation_of: Web/JavaScript/Reference/Global_Objects/Function/name +--- +
{{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/function/prototype/index.html b/files/id/web/javascript/reference/global_objects/function/prototype/index.html new file mode 100644 index 0000000000..d522a363e0 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/function/prototype/index.html @@ -0,0 +1,143 @@ +--- +title: Function.prototype +slug: Web/JavaScript/Reference/Global_Objects/Function/prototype +tags: + - Function + - JavaScript + - Property + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Function +--- +
{{JSRef}}
+ +

Properti Function.prototype mewakili objek properti {{jsxref("Function")}} .

+ +

Deskripsi

+ +

Objek {{jsxref("Function")}} turunan dari Function.prototypeFunction.prototype tidak dapat di ubah.

+ +

Properti

+ +
+
{{jsxref("Function.arguments")}} {{deprecated_inline}}
+
Sebuah array berdasakan argumen yang diberikan ke sebuah fungsi. Ini telah diabaikan sebagai properti dari {{jsxref("Function")}}, gunakan objek {{jsxref("Functions/arguments", "arguments")}} yang tersedia di dalam fungsi saja.
+
{{jsxref("Function.arity")}} {{obsolete_inline}}
+
Digunakan untuk menentukan jumlah argumen yang diperlukan fungsi, tapi telah dihapus. Gunakan properti {{jsxref("Function.length", "length")}}.
+
{{jsxref("Function.caller")}} {{non-standard_inline}}
+
Menentukan fungsi yang dipanggil oleh fungsi yang sedang dijalankan saat ini.
+
{{jsxref("Function.length")}}
+
Menentukan jumlah argumen yang diperlukan oleh fungsi.
+
{{jsxref("Function.name")}}
+
Nama dari fungsi.
+
{{jsxref("Function.displayName")}} {{non-standard_inline}}
+
Tampilan nama fungsi.
+
Function.prototype.constructor
+
Menentukan fungsi yang membuat objek prototype. Lihat {{jsxref("Object.prototype.constructor")}} untuk lebih detailnya.
+
+ +

Method

+ +
+
{{jsxref("Function.prototype.apply()")}}
+
Memanggil fungsi dan menentukan nilai this berdasar nilai yang diberikan, argument bisa ditambahkan sebagai objek {{jsxref("Array")}}.
+
{{jsxref("Function.prototype.bind()")}}
+
Membuat fungsi baru dimana, ketika dipanggil, memiliki this yang diberi nilai yang tersedia, dengan urutan tertentu sesudah nilai yang tersedia ketika fungsi di jalankan.
+
{{jsxref("Function.prototype.call()")}}
+
Memanggil (menjalankan) sebuah fungsi dan memberi nilai this dari nilai yang tersedia, argumen bisa ditambahkan sebagaimana mestinya.
+
{{jsxref("Function.prototype.isGenerator()")}} {{non-standard_inline}}
+
Mengembalikan true jika fungsi adalah sebuah generator; selain itu akan mengembalikan  nilai false.
+
{{jsxref("Function.prototype.toSource()")}} {{non-standard_inline}}
+
Mengembalikan string berdasarkan kode sumber dari fungsi. Mengesampingkan method {{jsxref("Object.prototype.toSource")}}.
+
{{jsxref("Function.prototype.toString()")}}
+
Mengembalikan string berdasarkan kode sumber dari fungsi, mengesampingkan method {{jsxref("Object.prototype.toString")}}.
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1
{{SpecName('ES5.1', '#sec-15.3.5.2', 'Function.prototype')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-instances-prototype', 'Function.prototype')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-function-instances-prototype', 'Function.prototype')}}{{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/index.html b/files/id/web/javascript/reference/global_objects/index.html new file mode 100644 index 0000000000..5259bde5b8 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/index.html @@ -0,0 +1,189 @@ +--- +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 new file mode 100644 index 0000000000..b7a6774528 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/isnan/index.html @@ -0,0 +1,186 @@ +--- +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 new file mode 100644 index 0000000000..4f07030358 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/json/index.html @@ -0,0 +1,243 @@ +--- +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 new file mode 100644 index 0000000000..5eb3f60424 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/json/parse/index.html @@ -0,0 +1,171 @@ +--- +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 new file mode 100644 index 0000000000..2869835e02 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/map/clear/index.html @@ -0,0 +1,109 @@ +--- +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 new file mode 100644 index 0000000000..ad9d1922b9 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/map/delete/index.html @@ -0,0 +1,114 @@ +--- +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 new file mode 100644 index 0000000000..9e4a93cfa0 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/map/index.html @@ -0,0 +1,443 @@ +--- +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 new file mode 100644 index 0000000000..c15b00b315 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/math/abs/index.html @@ -0,0 +1,145 @@ +--- +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 new file mode 100644 index 0000000000..cba010ffdb --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/math/ceil/index.html @@ -0,0 +1,174 @@ +--- +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 new file mode 100644 index 0000000000..79e9f21f4a --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/math/e/index.html @@ -0,0 +1,81 @@ +--- +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 new file mode 100644 index 0000000000..ecd6e89cdd --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/math/floor/index.html @@ -0,0 +1,210 @@ +--- +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 new file mode 100644 index 0000000000..4d9bb6a9bb --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/math/index.html @@ -0,0 +1,213 @@ +--- +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 new file mode 100644 index 0000000000..04e4fe5468 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/math/ln10/index.html @@ -0,0 +1,81 @@ +--- +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 new file mode 100644 index 0000000000..aeb1b207ce --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/math/max/index.html @@ -0,0 +1,144 @@ +--- +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 new file mode 100644 index 0000000000..eb557f36bf --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/math/min/index.html @@ -0,0 +1,150 @@ +--- +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 new file mode 100644 index 0000000000..878fde0e04 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/math/pow/index.html @@ -0,0 +1,53 @@ +--- +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 new file mode 100644 index 0000000000..6ac06ec718 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/object/getprototypeof/index.html @@ -0,0 +1,133 @@ +--- +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 new file mode 100644 index 0000000000..cc79ab6890 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/object/index.html @@ -0,0 +1,221 @@ +--- +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 new file mode 100644 index 0000000000..cc1c7dc1a9 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/object/keys/index.html @@ -0,0 +1,197 @@ +--- +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 new file mode 100644 index 0000000000..3899fef48f --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/object/preventextensions/index.html @@ -0,0 +1,185 @@ +--- +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 new file mode 100644 index 0000000000..f2d5e38e8f --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/promise/catch/index.html @@ -0,0 +1,127 @@ +--- +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 new file mode 100644 index 0000000000..240915ba23 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/promise/index.html @@ -0,0 +1,317 @@ +--- +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 new file mode 100644 index 0000000000..180fcc5571 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/promise/reject/index.html @@ -0,0 +1,81 @@ +--- +title: Promise.reject() +slug: Web/JavaScript/Reference/Global_Objects/Promise/reject +tags: + - ECMAScript6 + - 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 new file mode 100644 index 0000000000..d958ab4d52 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/promise/resolve/index.html @@ -0,0 +1,140 @@ +--- +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 new file mode 100644 index 0000000000..5a1e275c8c --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/promise/then/index.html @@ -0,0 +1,132 @@ +--- +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 new file mode 100644 index 0000000000..8bd6dce4b9 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/regexp/index.html @@ -0,0 +1,231 @@ +--- +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/concat/index.html b/files/id/web/javascript/reference/global_objects/string/concat/index.html new file mode 100644 index 0000000000..0ba2b2a156 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/string/concat/index.html @@ -0,0 +1,134 @@ +--- +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 new file mode 100644 index 0000000000..786e32883e --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/string/fromcharcode/index.html @@ -0,0 +1,143 @@ +--- +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 new file mode 100644 index 0000000000..dc4024f941 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/string/fromcodepoint/index.html @@ -0,0 +1,149 @@ +--- +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 new file mode 100644 index 0000000000..35f78502d5 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/string/index.html @@ -0,0 +1,371 @@ +--- +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 new file mode 100644 index 0000000000..3b7f7d0965 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/string/indexof/index.html @@ -0,0 +1,190 @@ +--- +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 new file mode 100644 index 0000000000..6975d8b7d3 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/string/length/index.html @@ -0,0 +1,126 @@ +--- +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 new file mode 100644 index 0000000000..914eff9955 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/string/link/index.html @@ -0,0 +1,130 @@ +--- +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/purwarupa/index.html b/files/id/web/javascript/reference/global_objects/string/purwarupa/index.html new file mode 100644 index 0000000000..3570a3627a --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/string/purwarupa/index.html @@ -0,0 +1,221 @@ +--- +title: String.prototype +slug: Web/JavaScript/Reference/Global_Objects/String/purwarupa +tags: + - JavaScript + - Property + - Prototype + - Reference + - Referensi + - String + - purwarupa +translation_of: Web/JavaScript/Reference/Global_Objects/String +--- +
{{JSRef}}
+ +

Properti String.prototype mewakili objek prototype {{jsxref("Global_Objects/String", "String")}}.

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

Deskripsi

+ +

Semua benda {{jsxref("Global_Objects/String", "String")}} diwariskan dari String.prototype. Perubahan ke objek purwarupa String disebarkan ke semua benda {{jsxref("Global_Objects/String", "String")}}.

+ +

Properti

+ +
+
String.prototype.constructor
+
Menentukan fungsi yang membuat sebuah purwarupa dari objek.
+
{{jsxref("String.prototype.length")}}
+
Menggambarkan panjang dari string.
+
N
+
Digunakan untuk mengakses karakter pada posisi ke-N di mana N adalah sebuah bilangan bulat positif antara 0 dan nilai dari {{jsxref("String.length", "panjang")}} dikurangi satu. Nilai ini baca-saja.
+
+ +

Metode

+ +

Metode yang tidak terkait dengan HTML

+ +
+
{{jsxref("String.prototype.charAt()")}}
+
Mengembalikan karakter pada indeks yang diberikan.
+
{{jsxref("String.prototype.charCodeAt()")}}
+
Mengembalikan sebuah angka yang menggambarkan nilai Unicode dari karakter pada indeks yang diberikan.
+
{{jsxref("String.prototype.codePointAt()")}} {{experimental_inline}}
+
Mengembalikan sebuah bilangan bulat non negatif yang merupakan nilai penyandian code point UTF-16 pada posisi yang diberikan.
+
{{jsxref("String.prototype.concat()")}}
+
Menggabungkan teks dari dua string dan mengembalikan sebuah string baru.
+
{{jsxref("String.prototype.includes()")}} {{experimental_inline}}
+
Menentukan apakah satu string mungkin terdapat pada string lain.
+
{{jsxref("String.prototype.endsWith()")}} {{experimental_inline}}
+
Menentukan apakah sebuah string berakhir dengan karakter dari string lain.
+
{{jsxref("String.prototype.indexOf()")}}
+
Mengembalikan indeks pada objek {{jsxref("Global_Objects/String", "String")}} terpanggil dari pertemuan pertama dari nilai yang diberikan, atau -1 jika tidak ditemukan.
+
{{jsxref("String.prototype.lastIndexOf()")}}
+
Mengembalikan indeks pada objek {{jsxref("Global_Objects/String", "String")}} terpanggil dari pertemuan terakhir dari nilai yang diberikan, atau -1 jika tidak ditemukan.
+
{{jsxref("String.prototype.localeCompare()")}}
+
Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.
+
{{jsxref("String.prototype.match()")}}
+
Digunakan untuk mencocokkan sebuah regular expression pada string.
+
{{jsxref("String.prototype.normalize()")}} {{experimental_inline}}
+
Mengembalikan Unicode Normalization Form dari string terpanggil.
+
{{jsxref("String.prototype.quote()")}} {{obsolete_inline}}
+
Membungkus string dalam petik ganda (""").
+
{{jsxref("String.prototype.repeat()")}} {{experimental_inline}}
+
Mengembalikan sebuah string yang tersiri dari elemen-elemen dari objek yang diulangi sebanyak yang diberikan.
+
{{jsxref("String.prototype.replace()")}}
+
Digunakan untuk mencari kecocokkan antara sebuah regular expression dan sebuah string, dan untuk menggantikan substring yang cocok dengan substring yang baru.
+
{{jsxref("String.prototype.search()")}}
+
Menjalankan pencarian untuk sebuah kecocokan antara sebuah regular expression dan sebuah string yang diberikan.
+
{{jsxref("String.prototype.slice()")}}
+
Menghasilkan sebuah bagian dari string dan mengembalikan sebuah string baru.
+
{{jsxref("String.prototype.split()")}}
+
Memisahkan sebuah objek {{jsxref("Global_Objects/String", "String")}} ke dalam sebuah susunan dari string dengan memisahkan string ke dalam substring.
+
{{jsxref("String.prototype.startsWith()")}} {{experimental_inline}}
+
Menentukan apakah sebuah string dimulai dengan karakter dari string lain.
+
{{jsxref("String.prototype.substr()")}}
+
Mengembalikan karakter-karakter dalam sebuah string yang dimulai dari indeks yang diberikan sebanyak jumlah karakter yang diberikan.
+
{{jsxref("String.prototype.substring()")}}
+
Mengembalikan karakter-karakter dalam sebuah string antara dua indeks ke dalam string.
+
{{jsxref("String.prototype.toLocaleLowerCase()")}}
+
Karakter-karakter di dalam string diubah menjadi huruf kecil dengan menjunjung tempat sekarang. Kebanyakan bahasa akan mengembalikan hasil yang sama seperti {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}}.
+
{{jsxref("String.prototype.toLocaleUpperCase()")}}
+
Karakter-karakter di dalam string diubah menjadi huruf kapital dengan menjunjung tempat sekarang. Kebanyakan bahasa akan mengembalikan hasil yang sama seperti {{jsxref("String.prototype.toUpperCase()", "toUpperCase()")}}.
+
{{jsxref("String.prototype.toLowerCase()")}}
+
Mengembalikan nilai string terpanggil yang diubah menjadi huruf kecil.
+
{{jsxref("String.prototype.toSource()")}} {{non-standard_inline}}
+
Mengembalikan sebuah objek harfiah yang menggambarkan objek yang diberikan; Anda dapat menggunakan nilai ini untuk membuat sebuah objek baru. Mengesampingkan metode {{jsxref("Object.prototype.toSource()")}}.
+
{{jsxref("String.prototype.toString()")}}
+
Mengembalikan sebuah string menggambarkan objek yang diberikan. Mengesampingkan metode {{jsxref("Object.prototype.toString()")}}.
+
{{jsxref("String.prototype.toUpperCase()")}}
+
Mengembalikan nilai string terpanggil yang diubah menjadi huruf kapital.
+
{{jsxref("String.prototype.trim()")}}
+
Memotong whitespace dari permulaan dan akhir string. Bagian dari standar ECMAScript 5.
+
{{jsxref("String.prototype.trimLeft()")}} {{non-standard_inline}}
+
Memotong whitespace dari sisi kiri dari string.
+
{{jsxref("String.prototype.trimRight()")}} {{non-standard_inline}}
+
Memotong whitespace dari sisi kanan dari string.
+
{{jsxref("String.prototype.valueOf()")}}
+
Mengembalikan nilai primitif dari objek yang diberikan. Mengesampingkan metode {{jsxref("Object.prototype.valueOf()")}}.
+
{{jsxref("String.prototype.@@iterator()", "String.prototype[@@iterator]()")}} {{experimental_inline}}
+
Mengembalikan sebuah objek Iterator baru yang mengulangi melewati code points dari nilai String, mengembalikan setiap code point sebagai sebuah nilai String.
+
+ +

Metode pembungkus HTML

+ +

Metode-metode ini merupakan penggunaan terbatas, karena mereka hanya memberikan sebuah subset dari tag dan atribut HTML yang tersedia.

+ +
+
{{jsxref("String.prototype.anchor()")}}
+
{{htmlattrxref("name", "a", "<a name=\"name\">")}} (menarget hiperteks)
+
{{jsxref("String.prototype.big()")}} {{deprecated_inline}}
+
{{HTMLElement("big")}}
+
{{jsxref("String.prototype.blink()")}} {{deprecated_inline}}
+
{{HTMLElement("blink")}}
+
{{jsxref("String.prototype.bold()")}} {{deprecated_inline}}
+
{{HTMLElement("b")}}
+
{{jsxref("String.prototype.fixed()")}} {{deprecated_inline}}
+
{{HTMLElement("tt")}}
+
{{jsxref("String.prototype.fontcolor()")}} {{deprecated_inline}}
+
{{htmlattrxref("color", "font", "<font color=\"color\">")}}
+
{{jsxref("String.prototype.fontsize()")}} {{deprecated_inline}}
+
{{htmlattrxref("size", "font", "<font size=\"size\">")}}
+
{{jsxref("String.prototype.italics()")}} {{deprecated_inline}}
+
{{HTMLElement("i")}}
+
{{jsxref("String.prototype.link()")}}
+
{{htmlattrxref("href", "a", "<a href=\"url\">")}} (tautan ke URL)
+
{{jsxref("String.prototype.small()")}} {{deprecated_inline}}
+
{{HTMLElement("small")}}
+
{{jsxref("String.prototype.strike()")}} {{deprecated_inline}}
+
{{HTMLElement("strike")}}
+
{{jsxref("String.prototype.sub()")}} {{deprecated_inline}}
+
{{HTMLElement("sub")}}
+
{{jsxref("String.prototype.sup()")}} {{deprecated_inline}}
+
{{HTMLElement("sup")}}
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusKomentar
ECMAScript 1st Edition.StandardDefinisi awal.
{{SpecName('ES5.1', '#sec-15.5.3.1', 'String.prototype')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype', 'String.prototype')}}{{Spec2('ES6')}} 
+ +

Kompatibilitas 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/split/index.html b/files/id/web/javascript/reference/global_objects/string/split/index.html new file mode 100644 index 0000000000..21f19d353f --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/string/split/index.html @@ -0,0 +1,241 @@ +--- +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 new file mode 100644 index 0000000000..69fdfd1bec --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/string/tolowercase/index.html @@ -0,0 +1,121 @@ +--- +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 new file mode 100644 index 0000000000..dba9c9f792 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/string/tostring/index.html @@ -0,0 +1,118 @@ +--- +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 new file mode 100644 index 0000000000..bf8182a590 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/string/touppercase/index.html @@ -0,0 +1,115 @@ +--- +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 new file mode 100644 index 0000000000..e0b8d942c1 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/typedarray/index.html @@ -0,0 +1,344 @@ +--- +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 new file mode 100644 index 0000000000..84f328ae1b --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/typedarray/join/index.html @@ -0,0 +1,114 @@ +--- +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

+ + -- cgit v1.2.3-54-g00ecf