diff options
Diffstat (limited to 'files/ru/conflicting/web/javascript/guide')
3 files changed, 1224 insertions, 0 deletions
diff --git a/files/ru/conflicting/web/javascript/guide/index.html b/files/ru/conflicting/web/javascript/guide/index.html new file mode 100644 index 0000000000..a0f5770315 --- /dev/null +++ b/files/ru/conflicting/web/javascript/guide/index.html @@ -0,0 +1,923 @@ +--- +title: Predefined Core Objects +slug: Web/JavaScript/Guide/Predefined_Core_Objects +translation_of: Web/JavaScript/Guide +translation_of_original: Web/JavaScript/Guide/Predefined_Core_Objects +--- +<p>Эта глава описывает предопределённые объекты в стандартном JavaScript: <code>Array</code>, <code>Boolean</code>, <code>Date</code>, <code>Function</code>, <code>Math</code>, <code>Number</code>, <code>RegExp</code>, и <code>String</code>.</p> + +<h2 id="Объект_Array">Объект Array</h2> + +<p>В JavaScript массив как тип данных отсутствует. Тем не менее, вы можете использовать предопределённый объект <code>Array</code> и его методы, чтобы работать с массивами в ваших приложениях. Объект <code>Array</code> содержит различные методы для манипуляций с массивами, такими как объединение, обращение и сортировка. У него есть свойство для определения длины массива и другие свойства для работы с регулярными выражениями.</p> + +<p><em>Массив</em> - это упорядоченный набор значений, обращаться к которым можно с помощью имени и индекса. Например, можно создать массив <code>emp</code>, который содержит имена сотрудников фирмы, проиндексированные номерами. Тогда <code>emp[1]</code> будет соответствовать сотруднику номер один, <code>emp[2]</code> сотруднику номер два и так далее.</p> + +<h3 id="Создание_объекта_Array">Создание объекта Array</h3> + +<p>Следующие инструкции создают эквивалентные массивы:</p> + +<div style="margin-right: 270px;"> +<pre class="brush: js">var arr = new Array(element0, element1, ..., elementN); +var arr = Array(element0, element1, ..., elementN); +var arr = [element0, element1, ..., elementN]; +</pre> +</div> + +<p><code>element0, element1, ..., elementN</code> это список значений во вновь создаваемом массиве. Когда эти значения заданы, массив инициализирует ими свои эелементы. Длина массива определяется по числу аргументов и сохраняется в свойстве <code>length </code>(длина).</p> + +<p>Синтаксис с квадратными скобками называется "литералом массива" (array literal) или "инициализатором массива" (array initializer). Такая запись короче других и используется чаще. Подробности смотрите в <a href="/en-US/docs/JavaScript/Guide/Values,_Variables,_and_Literals#Array_Literals" title="en-US/docs/JavaScript/Guide/Values, Variables, and Literals#Array Literals">Array Literals</a>.</p> + +<p>Создать массив ненулевой длины, но без элементов, можно одним из следующих способов:</p> + +<pre class="brush: js">var arr = new Array(arrayLength); +var arr = Array(arrayLength); + +// This has exactly the same effect +var arr = []; +arr.length = arrayLength; +</pre> + +<p>Обратите внимание: в приведённом выше коде <code>arrayLength</code> должен быть значением типа <code>Number</code>, то есть числом, иначе будет создан массив с одним элементом (переданным конструктору значением). Вызов <code>arr.length</code> возвратит <code>arrayLength</code>, хотя на самом деле элемент содержит пустые (неопределённые, undefined) элементы. Итерация по массиву циклом for...in не возвратит никаких элементов.</p> + +<p>Массивы можно не только определить как и переменные, но и присвоить существующему объекту как свойство:</p> + +<pre class="brush: js">var obj = {}; +// ... +obj.prop = [element0, element1, ..., elementN]; + +// OR +var obj = {prop: [element0, element1, ...., elementN]} +</pre> + +<p>Если же вы хотите создать одноэлементный массив, содержащий число, придётся использовать запись с квадратными скобками, так как когда конструктору Array() передаётся одно-единственное число, оно трактуется как длина массива, а не как хранимвый элемент.</p> + +<pre><code>var arr = [42]; +var arr = Array(42); // Creates an array with no element, but with arr.length set to 42 + +// The above code is equivalent to +var arr = []; +arr.length = 42; +</code> +</pre> + +<p>Вызов <code>Array(N)</code> приводит к <code>RangeError</code>, если <code>N</code> не является целым числом, чья дробная часть не равна нулю. Следующий пример иллюстрирует это поведение.</p> + +<pre>var arr = Array(9.3); // RangeError: Invalid array length +</pre> + +<p>Если ваш код должен создавать массивы с отдельными элементами произвольного типа, безопаснее использовать литералы массива. Или, создайте пустой массив, прежде чем добавлять элементы к нему.</p> + +<h3 id="Заполнение_массива">Заполнение массива</h3> + +<p>You can populate an array by assigning values to its elements. For example,</p> + +<pre class="brush: js">var emp = []; +emp[0] = "Casey Jones"; +emp[1] = "Phil Lesh"; +emp[2] = "August West"; +</pre> + +<p><strong>Note:</strong> if you supply a non-integer value to the array operator in the code above, a property will be created in the object representing the array, instead of an array element.</p> + +<pre> var arr = []; +arr[3.4] = "Oranges"; +console.log(arr.length); // 0 +console.log(arr.hasOwnProperty(3.4)); // true +</pre> + +<p>You can also populate an array when you create it:</p> + +<pre class="brush: js">var myArray = new Array("Hello", myVar, 3.14159); +var myArray = ["Mango", "Apple", "Orange"] +</pre> + +<h3 id="Referring_to_Array_Elements">Referring to Array Elements</h3> + +<p>You refer to an array's elements by using the element's ordinal number. For example, suppose you define the following array:</p> + +<pre class="brush: js">var myArray = ["Wind", "Rain", "Fire"]; +</pre> + +<p>You then refer to the first element of the array as <code>myArray[0]</code> and the second element of the array as <code>myArray[1]</code>. The index of the elements begins with zero.</p> + +<p><strong>Note:</strong> the array operator (square brackets) is also used for accessing the array's properties (arrays are also objects in JavaScript). For example,</p> + +<pre> var arr = ["one", "two", "three"]; +arr[2]; // three +arr["length"]; // 3 +</pre> + +<h3 id="Understanding_length">Understanding length</h3> + +<p>At the implementation level, JavaScript's arrays actually store their elements as standard object properties, using the array index as the property name. The <code>length</code> property is special; it always returns the index of the last element plus one (in following example Dusty is indexed at 30 so cats.length returns 30 + 1). Remember, Javascript Array indexes are 0-based: they start at 0, not 1. This means that the <code><code>length</code></code> property will be one more than the highest index stored in the array:</p> + +<pre class="brush: js">var cats = []; +cats[30] = ['Dusty']; +print(cats.length); // 31 +</pre> + +<p>You can also assign to the <code>length</code> property. Writing a value that is shorter than the number of stored items truncates the array; writing 0 empties it entirely:</p> + +<pre class="brush: js">var cats = ['Dusty', 'Misty', 'Twiggy']; +console.log(cats.length); // 3 + +cats.length = 2; +console.log(cats); // prints "Dusty,Misty" - Twiggy has been removed + +cats.length = 0; +console.log(cats); // prints nothing; the cats array is empty + +cats.length = 3; +console.log(cats); // [undefined, undefined, undefined] +</pre> + +<h3 id="Iterating_over_arrays">Iterating over arrays</h3> + +<p>A common operation is to iterate over the values of an array, processing each one in some way. The simplest way to do this is as follows:</p> + +<pre class="brush: js">var colors = ['red', 'green', 'blue']; +for (var i = 0; i < colors.length; i++) { + console.log(colors[i]); +} +</pre> + +<p>If you know that none of the elements in your array evaluate to <code>false</code> in a boolean context — if your array consists only of <a href="/en-US/docs/DOM" title="en-US/docs/DOM">DOM</a> nodes, for example, you can use a more efficient idiom:</p> + +<pre class="brush: js">var divs = document.getElementsByTagName('div'); +for (var i = 0, div; div = divs[i]; i++) { + /* Process div in some way */ +} +</pre> + +<p>This avoids the overhead of checking the length of the array, and ensures that the <code>div</code> variable is reassigned to the current item each time around the loop for added convenience.</p> + +<p>The <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach" title="en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach"><code>forEach()</code></a> method, introduced in JavaScript 1.6, provides another way of iterating over an array:</p> + +<pre class="brush: js">var colors = ['red', 'green', 'blue']; +colors.forEach(function(color) { + console.log(color); +}); +</pre> + +<p>The function passed to <code>forEach</code> is executed once for every item in the array, with the array item passed as the argument to the function. Unassigned values are not iterated in a <code>forEach</code> loop.</p> + +<p>Note that the elements of array omitted when the array is defined are not listed when iterating by <code>forEach, </code>but are listed when <code>undefined</code> has been manually assigned to the element:</p> + +<pre class="brush: js">var array = ['first', 'second', , 'fourth']; + +// returns ['first', 'second', 'fourth']; +array.forEach(function(element) { + console.log(element); +}) + +if(array[2] === undefined) { console.log('array[2] is undefined'); } // true + +var array = ['first', 'second', undefined, 'fourth']; + +// returns ['first', 'second', undefined, 'fourth']; +array.forEach(function(element) { + console.log(element); +})</pre> + +<p>Since JavaScript elements are saved as standard object properties, it is not advisable to iterate through JavaScript arrays using for...in loops because normal elements and all enumerable properties will be listed.</p> + +<h3 id="Array_Methods">Array Methods</h3> + +<p>The <code>Array</code> object has the following methods:</p> + +<ul> + <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/concat" title="en-US/docs/JavaScript/Reference/Global + Objects/Array/concat"><code>concat()</code></a> joins two arrays and returns a new array. + + <pre class="brush: js">var myArray = new Array("1", "2", "3"); +myArray = myArray.concat("a", "b", "c"); // myArray is now ["1", "2", "3", "a", "b", "c"] +</pre> + </li> + <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/join" title="en-US/docs/JavaScript/Reference/Global + Objects/Array/join"><code>join(deliminator = ",")</code></a> joins all elements of an array into a string. + <pre class="brush: js">var myArray = new Array("Wind", "Rain", "Fire"); +var list = myArray.join(" - "); // list is "Wind - Rain - Fire" +</pre> + </li> + <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/push" title="en-US/docs/JavaScript/Reference/Global + Objects/Array/push"><code>push()</code></a> adds one or more elements to the end of an array and returns the resulting length of the array. + <pre class="brush: js">var myArray = new Array("1", "2"); +myArray.push("3"); // myArray is now ["1", "2", "3"] +</pre> + </li> + <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/pop" title="en-US/docs/JavaScript/Reference/Global + Objects/Array/pop"><code>pop()</code></a> removes the last element from an array and returns that element. + <pre class="brush: js">var myArray = new Array("1", "2", "3"); +var last = myArray.pop(); // myArray is now ["1", "2"], last = "3" +</pre> + </li> + <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/shift" title="en-US/docs/JavaScript/Reference/Global + Objects/Array/shift"><code>shift()</code></a> removes the first element from an array and returns that element. + <pre class="brush: js">var myArray = new Array ("1", "2", "3"); +var first = myArray.shift(); // myArray is now ["2", "3"], first is "1" +</pre> + </li> + <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/unshift" title="en-US/docs/JavaScript/Reference/Global + Objects/Array/unshift"><code>unshift()</code></a> adds one or more elements to the front of an array and returns the new length of the array. + <pre class="brush: js">var myArray = new Array ("1", "2", "3"); +myArray.unshift("4", "5"); // myArray becomes ["4", "5", "1", "2", "3"]</pre> + </li> + <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/slice" title="en-US/docs/JavaScript/Reference/Global + Objects/Array/slice"><code>slice(start_index, upto_index)</code></a> extracts a section of an array and returns a new array. + <pre class="brush: js">var myArray = new Array ("a", "b", "c", "d", "e"); +myArray = myArray.slice(1, 4); /* starts at index 1 and extracts all elements + until index 3, returning [ "b", "c", "d"] */ +</pre> + </li> + <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/splice" title="en-US/docs/JavaScript/Reference/Global + Objects/Array/splice"><code>splice(index, count_to_remove, addelement1, addelement2, ...)</code></a> removes elements from an array and (optionally) replaces them. + <pre class="brush: js">var myArray = new Array ("1", "2", "3", "4", "5"); +myArray.splice(1, 3, "a", "b", "c", "d"); // myArray is now ["1", "a", "b", "c", "d", "5"] + // This code started at index one (or where the "2" was), removed 3 elements there, + // and then inserted all consecutive elements in its place. +</pre> + </li> + <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/reverse" title="en-US/docs/JavaScript/Reference/Global + Objects/Array/reverse"><code>reverse()</code></a> transposes the elements of an array: the first array element becomes the last and the last becomes the first. + <pre class="brush: js">var myArray = new Array ("1", "2", "3"); +myArray.reverse(); // transposes the array so that myArray = [ "3", "2", "1" ] +</pre> + </li> + <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/sort" title="en-US/docs/JavaScript/Reference/Global + Objects/Array/sort"><code>sort()</code></a> sorts the elements of an array. + <pre class="brush: js">var myArray = new Array("Wind", "Rain", "Fire"); +myArray.sort(); // sorts the array so that myArrray = [ "Fire", "Rain", "Wind" ] +</pre> + + <p><code>sort()</code> can also take a callback function to determine how array elements are compared. The function compares two values and returns one of three values:</p> + + <ul> + <li>if <code>a</code> is less than <code>b</code> by the sorting system, return -1 (or any negative number)</li> + <li>if <code>a</code> is greater than <code>b</code> by the sorting system, return 1 (or any positive number)</li> + <li>if <code>a</code> and <code>b</code> are considered equivalent, return 0.</li> + </ul> + + <p>For instance, the following will sort by the last letter of an array:</p> + + <pre class="brush: js">var sortFn = function(a, b){ + if (a[a.length - 1] < b[b.length - 1]) return -1; + if (a[a.length - 1] > b[b.length - 1]) return 1; + if (a[a.length - 1] == b[b.length - 1]) return 0; +} +myArray.sort(sortFn); // sorts the array so that myArray = ["Wind","Fire","Rain"]</pre> + </li> +</ul> + +<p>Compatibility code for older browsers can be found for each of these functions on the individual pages. Native browser support for these features in various browsers can be found<a class="external" href="http://www.robertnyman.com/javascript/" title="http://www.robertnyman.com/javascript/"> here.</a></p> + +<ul> + <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf" title="en-US/docs/JavaScript/Reference/Global + Objects/Array/indexOf"><code>indexOf(searchElement[, fromIndex])</code></a> searches the array for <code>searchElement</code> and returns the index of the first match. + + <pre class="brush: js">var a = ['a', 'b', 'a', 'b', 'a']; +alert(a.indexOf('b')); // Alerts 1 +// Now try again, starting from after the last match +alert(a.indexOf('b', 2)); // Alerts 3 +alert(a.indexOf('z')); // Alerts -1, because 'z' was not found +</pre> + </li> + <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/lastIndexOf" title="en-US/docs/JavaScript/Reference/Global + Objects/Array/lastIndexOf"><code>lastIndexOf(searchElement[, fromIndex])</code></a> works like <code>indexOf</code>, but starts at the end and searches backwards. + <pre class="brush: js">var a = ['a', 'b', 'c', 'd', 'a', 'b']; +alert(a.lastIndexOf('b')); // Alerts 5 +// Now try again, starting from before the last match +alert(a.lastIndexOf('b', 4)); // Alerts 1 +alert(a.lastIndexOf('z')); // Alerts -1 +</pre> + </li> + <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach" title="en-US/docs/JavaScript/Reference/Global + Objects/Array/forEach"><code>forEach(callback[, thisObject])</code></a> executes <code>callback</code> on every array item. + <pre class="brush: js">var a = ['a', 'b', 'c']; +a.forEach(alert); // Alerts each item in turn +</pre> + </li> + <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/map" title="en-US/docs/JavaScript/Reference/Global + Objects/Array/map"><code>map(callback[, thisObject])</code></a> returns a new array of the return value from executing <code>callback</code> on every array item. + <pre class="brush: js">var a1 = ['a', 'b', 'c']; +var a2 = a1.map(function(item) { return item.toUpperCase(); }); +alert(a2); // Alerts A,B,C +</pre> + </li> + <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter" title="en-US/docs/JavaScript/Reference/Global + Objects/Array/filter"><code>filter(callback[, thisObject])</code></a> returns a new array containing the items for which callback returned true. + <pre class="brush: js">var a1 = ['a', 10, 'b', 20, 'c', 30]; +var a2 = a1.filter(function(item) { return typeof item == 'number'; }); +alert(a2); // Alerts 10,20,30 +</pre> + </li> + <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/every" title="en-US/docs/JavaScript/Reference/Global + Objects/Array/every"><code>every(callback[, thisObject])</code></a> returns true if <code>callback</code> returns true for every item in the array. + <pre class="brush: js">function isNumber(value){ + return typeof value == 'number'; +} +var a1 = [1, 2, 3]; +alert(a1.every(isNumber)); // Alerts true +var a2 = [1, '2', 3]; +alert(a2.every(isNumber)); // Alerts false +</pre> + </li> + <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/some" title="en-US/docs/JavaScript/Reference/Global + Objects/Array/some"><code>some(callback[, thisObject])</code></a> returns true if <code>callback</code> returns true for at least one item in the array. + <pre class="brush: js">function isNumber(value){ + return typeof value == 'number'; +} +var a1 = [1, 2, 3]; +alert(a1.some(isNumber)); // Alerts true +var a2 = [1, '2', 3]; +alert(a2.some(isNumber)); // Alerts true +var a3 = ['1', '2', '3']; +alert(a3.some(isNumber)); // Alerts false +</pre> + </li> +</ul> + +<p>The methods above that take a callback are known as <em>iterative methods</em>, because they iterate over the entire array in some fashion. Each one takes an optional second argument called <code>thisObject</code>. If provided, <code>thisObject</code> becomes the value of the <code>this</code> keyword inside the body of the callback function. If not provided, as with other cases where a function is invoked outside of an explicit object context, <code>this</code> will refer to the global object (<a href="/en-US/docs/DOM/window" title="en-US/docs/DOM/window"><code>window</code></a>).</p> + +<p>The callback function is actually called with three arguments. The first is the value of the current item, the second is its array index, and the third is a reference to the array itself. JavaScript functions ignore any arguments that are not named in the parameter list so it is safe to provide a callback function that only takes a single argument, such as <code>alert</code>.</p> + +<ul> + <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/Reduce" title="en-US/docs/JavaScript/Reference/Global + Objects/Array/reduce"><code>reduce(callback[, initialValue])</code></a> applies <code>callback(firstValue, secondValue)</code> to reduce the list of items down to a single value. + + <pre class="brush: js">var a = [10, 20, 30]; +var total = a.reduce(function(first, second) { return first + second; }, 0); +alert(total) // Alerts 60 +</pre> + </li> + <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/ReduceRight" title="en-US/docs/JavaScript/Reference/Global + Objects/Array/reduceRight"><code>reduceRight(callback[, initialValue])</code></a> works like <code>reduce()</code>, but starts with the last element.</li> +</ul> + +<p><code>reduce</code> and <code>reduceRight</code> are the least obvious of the iterative array methods. They should be used for algorithms that combine two values recursively in order to reduce a sequence down to a single value.</p> + +<h3 id="Multi-Dimensional_Arrays">Multi-Dimensional Arrays</h3> + +<p>Arrays can be nested, meaning that an array can contain another array as an element. Using this characteristic of JavaScript arrays, multi-dimensional arrays can be created.</p> + +<p>The following code creates a two-dimensional array.</p> + +<pre class="brush: js">var a = new Array(4); +for (i = 0; i < 4; i++) { + a[i] = new Array(4); + for (j = 0; j < 4; j++) { + a[i][j] = "[" + i + "," + j + "]"; + } +} +</pre> + +<p>This example creates an array with the following rows:</p> + +<pre>Row 0: [0,0] [0,1] [0,2] [0,3] +Row 1: [1,0] [1,1] [1,2] [1,3] +Row 2: [2,0] [2,1] [2,2] [2,3] +Row 3: [3,0] [3,1] [3,2] [3,3] +</pre> + +<h3 id="Arrays_and_Regular_Expressions">Arrays and Regular Expressions</h3> + +<p>When an array is the result of a match between a regular expression and a string, the array returns properties and elements that provide information about the match. An array is the return value of <a href="/en-US/docs/JavaScript/Reference/Global_Objects/RegExp/exec" title="en-US/docs/JavaScript/Reference/Global Objects/RegExp/exec"><code>RegExp.exec()</code></a>, <a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/match" title="en-US/docs/JavaScript/Reference/Global Objects/String/match"><code>String.match()</code></a>, and <a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/split" title="en-US/docs/JavaScript/Reference/Global +Objects/String/split"><code>String.split()</code></a>. For information on using arrays with regular expressions, see <a href="/en-US/docs/JavaScript/Guide/Regular_Expressions" title="en-US/docs/JavaScript/Guide/Regular Expressions">Regular Expressions</a>.</p> + +<h3 id="Working_with_Array-like_objects">Working with Array-like objects</h3> + +<p>Some JavaScript objects, such as the <a href="/en-US/docs/DOM/NodeList" title="en-US/docs/DOM/NodeList"><code>NodeList</code></a> returned by <a href="/en-US/docs/DOM/document.getElementsByTagName" title="en-US/docs/DOM/document.getElementsByTagName"><code>document.getElementsByTagName()</code></a> or the <a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments" title="en-US/docs/JavaScript/Reference/Functions and +function +scope/arguments"><code>arguments</code></a> object made available within the body of a function, look and behave like arrays on the surface but do not share all of their methods. The <code>arguments</code> object provides a <a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/length" title="en-US/docs/JavaScript/Reference/Functions +and function +scope/arguments/length"><code>length</code></a> attribute but does not implement the <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach" title="en-US/docs/JavaScript/Reference/Global Objects/Array/forEach"><code>forEach()</code></a> method, for example.</p> + +<p>Array generics, introduced in JavaScript 1.6, provide a way of running <code>Array</code> methods against other array-like objects. Each standard array method has a corresponding method on the <code>Array</code> object itself; for example:</p> + +<pre class="brush: js"> function alertArguments() { + Array.forEach(arguments, function(item) { + alert(item); + }); + } +</pre> + +<p>These generic methods can be emulated more verbosely in older versions of JavaScript using the call method provided by JavaScript function objects:</p> + +<pre class="brush: js"> Array.prototype.forEach.call(arguments, function(item) { + alert(item); + }); +</pre> + +<p>Array generic methods can be used on strings as well, since they provide sequential access to their characters in a similar way to arrays:</p> + +<pre class="brush: js">Array.forEach("a string", function(chr) { + alert(chr); +});</pre> + +<p>Here are some further examples of applying array methods to strings, also taking advantage of <a href="/en-US/docs/JavaScript/New_in_JavaScript/1.8#Expression_closures" title="en-US/docs/New_in_JavaScript_1.8#Expression_closures">JavaScript 1.8 expression closures</a>:</p> + +<pre class="brush: js">var str = 'abcdef'; +var consonantsOnlyStr = Array.filter(str, function (c) !(/[aeiou]/i).test(c)).join(''); // 'bcdf' +var vowelsPresent = Array.some(str, function (c) (/[aeiou]/i).test(c)); // true +var allVowels = Array.every(str, function (c) (/[aeiou]/i).test(c)); // false +var interpolatedZeros = Array.map(str, function (c) c+'0').join(''); // 'a0b0c0d0e0f0' +var numerologicalValue = Array.reduce(str, function (c, c2) c+c2.toLowerCase().charCodeAt()-96, 0); +// 21 (reduce() since JS v1.8) +</pre> + +<p>Note that <code>filter</code> and <code>map</code> do not automatically return the characters back into being members of a string in the return result; an array is returned, so we must use <code>join</code> to return back to a string.</p> + +<h3 id="Array_comprehensions">Array comprehensions</h3> + +<p>Introduced in JavaScript 1.7, array comprehensions provide a useful shortcut for constructing a new array based on the contents of another. Comprehensions can often be used in place of calls to <code>map()</code> and <code>filter()</code>, or as a way of combining the two.</p> + +<p>The following comprehension takes an array of numbers and creates a new array of the double of each of those numbers.</p> + +<pre class="brush: js">var numbers = [1, 2, 3, 4]; +var doubled = [i * 2 for (i of numbers)]; +alert(doubled); // Alerts 2,4,6,8 +</pre> + +<p>This is equivalent to the following <code>map()</code> operation:</p> + +<pre class="brush: js">var doubled = numbers.map(function(i){return i * 2;}); +</pre> + +<p>Comprehensions can also be used to select items that match a particular expression. Here is a comprehension which selects only even numbers:</p> + +<pre class="brush: js">var numbers = [1, 2, 3, 21, 22, 30]; +var evens = [i for (i of numbers) if (i % 2 === 0)]; +alert(evens); // Alerts 2,22,30 +</pre> + +<p><code>filter()</code> can be used for the same purpose:</p> + +<pre class="brush: js">var evens = numbers.filter(function(i){return i % 2 === 0;}); +</pre> + +<p><code>map()</code> and <code>filter()</code> style operations can be combined into a single array comprehension. Here is one that filters just the even numbers, then creates an array containing their doubles:</p> + +<pre class="brush: js">var numbers = [1, 2, 3, 21, 22, 30]; +var doubledEvens = [i * 2 for (i of numbers) if (i % 2 === 0)]; +alert(doubledEvens); // Alerts 4,44,60 +</pre> + +<p>The square brackets of an array comprehension introduce an implicit block for scoping purposes. New variables (such as i in the example) are treated as if they had been declared using <a href="/en-US/docs/JavaScript/Reference/Statements/let" title="/en-US/docs/JavaScript/Reference/Statements/let"><code>let</code></a>. This means that they will not be available outside of the comprehension.</p> + +<p>The input to an array comprehension does not itself need to be an array; <a href="/en-US/docs/JavaScript/Guide/Iterators_and_Generators" title="en-US/docs/JavaScript/Guide/Iterators and Generators">iterators and generators</a> can also be used.</p> + +<p>Even strings may be used as input; to achieve the filter and map actions (under Array-like objects) above:</p> + +<pre class="brush: js">var str = 'abcdef'; +var consonantsOnlyStr = [c for (c of str) if (!(/[aeiouAEIOU]/).test(c)) ].join(''); // 'bcdf' +var interpolatedZeros = [c+'0' for (c of str) ].join(''); // 'a0b0c0d0e0f0' +</pre> + +<p>Again, the input form is not preserved, so we have to use <code>join()</code> to revert back to a string.</p> + +<h2 id="Boolean_Object">Boolean Object</h2> + +<p>The <code>Boolean</code> object is a wrapper around the primitive Boolean data type. Use the following syntax to create a <code>Boolean</code> object:</p> + +<pre class="brush: js">var booleanObjectName = new Boolean(value); +</pre> + +<p>Do not confuse the primitive Boolean values <code>true</code> and <code>false</code> with the true and false values of the <code>Boolean</code> object. Any object whose value is not <code>undefined</code> , <code>null</code>, <code>0</code>, <code>NaN</code>, or the empty string, including a <code>Boolean</code> object whose value is false, evaluates to true when passed to a conditional statement. See <a href="/en-US/docs/JavaScript/Guide/Statements#if...else_Statement" title="en-US/docs/JavaScript/Guide/Statements#if...else Statement">if...else Statement</a> for more information.</p> + +<h2 id="Date_Object">Date Object</h2> + +<p>JavaScript does not have a date data type. However, you can use the <code>Date</code> object and its methods to work with dates and times in your applications. The <code>Date</code> object has a large number of methods for setting, getting, and manipulating dates. It does not have any properties.</p> + +<p>JavaScript handles dates similarly to Java. The two languages have many of the same date methods, and both languages store dates as the number of milliseconds since January 1, 1970, 00:00:00.</p> + +<p>The <code>Date</code> object range is -100,000,000 days to 100,000,000 days relative to 01 January, 1970 UTC.</p> + +<p>To create a <code>Date</code> object:</p> + +<pre class="brush: js">var dateObjectName = new Date([parameters]); +</pre> + +<p>where <code>dateObjectName</code> is the name of the <code>Date</code> object being created; it can be a new object or a property of an existing object.</p> + +<p>Calling <code>Date</code> without the <code>new</code> keyword simply converts the provided date to a string representation.</p> + +<p>The <code>parameters</code> in the preceding syntax can be any of the following:</p> + +<ul> + <li>Nothing: creates today's date and time. For example, <code>today = new Date();</code>.</li> + <li>A string representing a date in the following form: "Month day, year hours:minutes:seconds." For example, <code>var Xmas95 = new Date("December 25, 1995 13:30:00")</code>. If you omit hours, minutes, or seconds, the value will be set to zero.</li> + <li>A set of integer values for year, month, and day. For example, <code>var Xmas95 = new Date(1995, 11, 25)</code>.</li> + <li>A set of integer values for year, month, day, hour, minute, and seconds. For example, <code>var Xmas95 = new Date(1995, 11, 25, 9, 30, 0);</code>.</li> +</ul> + +<p><strong>JavaScript 1.2 and earlier</strong><br> + The <code>Date</code> object behaves as follows:</p> + +<ul> + <li>Dates prior to 1970 are not allowed.</li> + <li>JavaScript depends on platform-specific date facilities and behavior; the behavior of the <code>Date</code> object varies from platform to platform.</li> +</ul> + +<h3 id="Methods_of_the_Date_Object">Methods of the Date Object</h3> + +<p>The <code>Date</code> object methods for handling dates and times fall into these broad categories:</p> + +<ul> + <li>"set" methods, for setting date and time values in <code>Date</code> objects.</li> + <li>"get" methods, for getting date and time values from <code>Date</code> objects.</li> + <li>"to" methods, for returning string values from <code>Date</code> objects.</li> + <li>parse and UTC methods, for parsing <code>Date</code> strings.</li> +</ul> + +<p>With the "get" and "set" methods you can get and set seconds, minutes, hours, day of the month, day of the week, months, and years separately. There is a <code>getDay</code> method that returns the day of the week, but no corresponding <code>setDay</code> method, because the day of the week is set automatically. These methods use integers to represent these values as follows:</p> + +<ul> + <li>Seconds and minutes: 0 to 59</li> + <li>Hours: 0 to 23</li> + <li>Day: 0 (Sunday) to 6 (Saturday)</li> + <li>Date: 1 to 31 (day of the month)</li> + <li>Months: 0 (January) to 11 (December)</li> + <li>Year: years since 1900</li> +</ul> + +<p>For example, suppose you define the following date:</p> + +<pre class="brush: js">var Xmas95 = new Date("December 25, 1995"); +</pre> + +<p>Then <code>Xmas95.getMonth()</code> returns 11, and <code>Xmas95.getFullYear()</code> returns 1995.</p> + +<p>The <code>getTime</code> and <code>setTime</code> methods are useful for comparing dates. The <code>getTime</code> method returns the number of milliseconds since January 1, 1970, 00:00:00 for a <code>Date</code> object.</p> + +<p>For example, the following code displays the number of days left in the current year:</p> + +<pre class="brush: js">var today = new Date(); +var endYear = new Date(1995, 11, 31, 23, 59, 59, 999); // Set day and month +endYear.setFullYear(today.getFullYear()); // Set year to this year +var msPerDay = 24 * 60 * 60 * 1000; // Number of milliseconds per day +var daysLeft = (endYear.getTime() - today.getTime()) / msPerDay; +var daysLeft = Math.round(daysLeft); //returns days left in the year +</pre> + +<p>This example creates a <code>Date</code> object named <code>today</code> that contains today's date. It then creates a <code>Date</code> object named <code>endYear</code> and sets the year to the current year. Then, using the number of milliseconds per day, it computes the number of days between <code>today</code> and <code>endYear</code>, using <code>getTime</code> and rounding to a whole number of days.</p> + +<p>The <code>parse</code> method is useful for assigning values from date strings to existing <code>Date</code> objects. For example, the following code uses <code>parse</code> and <code>setTime</code> to assign a date value to the <code>IPOdate</code> object:</p> + +<pre class="brush: js">var IPOdate = new Date(); +IPOdate.setTime(Date.parse("Aug 9, 1995")); +</pre> + +<h3 id="Using_the_Date_Object_an_Example">Using the Date Object: an Example</h3> + +<p>In the following example, the function <code>JSClock()</code> returns the time in the format of a digital clock.</p> + +<pre class="brush: js">function JSClock() { + var time = new Date(); + var hour = time.getHours(); + var minute = time.getMinutes(); + var second = time.getSeconds(); + var temp = "" + ((hour > 12) ? hour - 12 : hour); + if (hour == 0) + temp = "12"; + temp += ((minute < 10) ? ":0" : ":") + minute; + temp += ((second < 10) ? ":0" : ":") + second; + temp += (hour >= 12) ? " P.M." : " A.M."; + return temp; +} +</pre> + +<p>The <code>JSClock</code> function first creates a new <code>Date</code> object called <code>time</code>; since no arguments are given, time is created with the current date and time. Then calls to the <code>getHours</code>, <code>getMinutes</code>, and <code>getSeconds</code> methods assign the value of the current hour, minute, and second to <code>hour</code>, <code>minute</code>, and <code>second</code>.</p> + +<p>The next four statements build a string value based on the time. The first statement creates a variable <code>temp</code>, assigning it a value using a conditional expression; if <code>hour</code> is greater than 12, (<code>hour - 12</code>), otherwise simply hour, unless hour is 0, in which case it becomes 12.</p> + +<p>The next statement appends a <code>minute</code> value to <code>temp</code>. If the value of <code>minute</code> is less than 10, the conditional expression adds a string with a preceding zero; otherwise it adds a string with a demarcating colon. Then a statement appends a seconds value to <code>temp</code> in the same way.</p> + +<p>Finally, a conditional expression appends "P.M." to <code>temp</code> if <code>hour</code> is 12 or greater; otherwise, it appends "A.M." to <code>temp</code>.</p> + +<h2 id="Function_Object">Function Object</h2> + +<p>The predefined <code>Function</code> object specifies a string of JavaScript code to be compiled as a function.</p> + +<p>To create a <code>Function</code> object:</p> + +<pre class="brush: js">var functionObjectName = new Function ([arg1, arg2, ... argn], functionBody); +</pre> + +<p><code>functionObjectName</code> is the name of a variable or a property of an existing object. It can also be an object followed by a lowercase event handler name, such as <code>window.onerror</code>.</p> + +<p><code>arg1</code>, <code>arg2</code>, ... <code>argn</code> are arguments to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier; for example "x" or "theForm".</p> + +<p><code>functionBody</code> is a string specifying the JavaScript code to be compiled as the function body.</p> + +<p><code>Function</code> objects are evaluated each time they are used. This is less efficient than declaring a function and calling it within your code, because declared functions are compiled.</p> + +<p>In addition to defining functions as described here, you can also use the <a href="/en-US/docs/JavaScript/Reference/Statements/function" title="en-US/docs/JavaScript/Reference/Statements/function"><code>function</code> statement</a> and the function expression. See the <a href="/en-US/docs/JavaScript/Reference" title="en-US/docs/JavaScript/Reference">JavaScript Reference</a> for more information.</p> + +<p>The following code assigns a function to the variable <code>setBGColor</code>. This function sets the current document's background color.</p> + +<pre class="brush: js">var setBGColor = new Function("document.bgColor = 'antiquewhite'"); +</pre> + +<p>To call the <code>Function</code> object, you can specify the variable name as if it were a function. The following code executes the function specified by the <code>setBGColor</code> variable:</p> + +<pre class="brush: js">var colorChoice="antiquewhite"; +if (colorChoice=="antiquewhite") {setBGColor()} +</pre> + +<p>You can assign the function to an event handler in either of the following ways:</p> + +<ol> + <li> + <pre class="brush: js">document.form1.colorButton.onclick = setBGColor; +</pre> + </li> + <li> + <pre class="brush: html"><INPUT NAME="colorButton" TYPE="button" + VALUE="Change background color" + onClick="setBGColor()"> +</pre> + </li> +</ol> + +<p>Creating the variable <code>setBGColor</code> shown above is similar to declaring the following function:</p> + +<pre class="brush: js">function setBGColor() { + document.bgColor = 'antiquewhite'; +} +</pre> + +<p>Assigning a function to a variable is similar to declaring a function, but there are differences:</p> + +<ul> + <li>When you assign a function to a variable using <code>var setBGColor = new Function("...")</code>, <code>setBGColor</code> is a variable for which the current value is a reference to the function created with <code>new Function()</code>.</li> + <li>When you create a function using <code>function setBGColor() {...}</code>, <code>setBGColor</code> is not a variable, it is the name of a function.</li> +</ul> + +<p>You can nest a function within a function. The nested (inner) function is private to its containing (outer) function:</p> + +<ul> + <li>The inner function can be accessed only from statements in the outer function.</li> + <li>The inner function can use the arguments and variables of the outer function. The outer function cannot use the arguments and variables of the inner function.</li> +</ul> + +<h2 id="Math_Object">Math Object</h2> + +<p>The predefined <code>Math</code> object has properties and methods for mathematical constants and functions. For example, the <code>Math</code> object's <code>PI</code> property has the value of pi (3.141...), which you would use in an application as</p> + +<pre class="brush: js">Math.PI +</pre> + +<p>Similarly, standard mathematical functions are methods of <code>Math</code>. These include trigonometric, logarithmic, exponential, and other functions. For example, if you want to use the trigonometric function sine, you would write</p> + +<pre class="brush: js">Math.sin(1.56) +</pre> + +<p>Note that all trigonometric methods of <code>Math</code> take arguments in radians.</p> + +<p>The following table summarizes the <code>Math</code> object's methods.</p> + +<table class="standard-table"> + <caption>Table 7.1 Methods of Math</caption> + <thead> + <tr> + <th scope="col">Method</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>abs</code></td> + <td>Absolute value</td> + </tr> + <tr> + <td><code>sin</code>, <code>cos</code>, <code>tan</code></td> + <td>Standard trigonometric functions; argument in radians</td> + </tr> + <tr> + <td><code>acos</code>, <code>asin</code>, <code>atan</code>, <code>atan2</code></td> + <td>Inverse trigonometric functions; return values in radians</td> + </tr> + <tr> + <td><code>exp</code>, <code>log</code></td> + <td>Exponential and natural logarithm, base <code>e</code></td> + </tr> + <tr> + <td><code>ceil</code></td> + <td>Returns least integer greater than or equal to argument</td> + </tr> + <tr> + <td><code>floor</code></td> + <td>Returns greatest integer less than or equal to argument</td> + </tr> + <tr> + <td><code>min</code>, <code>max</code></td> + <td>Returns greater or lesser (respectively) of two arguments</td> + </tr> + <tr> + <td><code>pow</code></td> + <td>Exponential; first argument is base, second is exponent</td> + </tr> + <tr> + <td><code>random</code></td> + <td>Returns a random number between 0 and 1.</td> + </tr> + <tr> + <td><code>round</code></td> + <td>Rounds argument to nearest integer</td> + </tr> + <tr> + <td><code>sqrt</code></td> + <td>Square root</td> + </tr> + </tbody> +</table> + +<p>Unlike many other objects, you never create a <code>Math</code> object of your own. You always use the predefined <code>Math</code> object.</p> + +<h2 id="Number_Object">Number Object</h2> + +<p>The <code>Number</code> object has properties for numerical constants, such as maximum value, not-a-number, and infinity. You cannot change the values of these properties and you use them as follows:</p> + +<pre class="brush: js">var biggestNum = Number.MAX_VALUE; +var smallestNum = Number.MIN_VALUE; +var infiniteNum = Number.POSITIVE_INFINITY; +var negInfiniteNum = Number.NEGATIVE_INFINITY; +var notANum = Number.NaN; +</pre> + +<p>You always refer to a property of the predefined <code>Number</code> object as shown above, and not as a property of a <code>Number</code> object you create yourself.</p> + +<p>The following table summarizes the <code>Number</code> object's properties.</p> + +<table class="standard-table"> + <caption>Table 7.2 Properties of Number</caption> + <thead> + <tr> + <th scope="col">Property</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>MAX_VALUE</code></td> + <td>The largest representable number</td> + </tr> + <tr> + <td><code>MIN_VALUE</code></td> + <td>The smallest representable number</td> + </tr> + <tr> + <td><code>NaN</code></td> + <td>Special "not a number" value</td> + </tr> + <tr> + <td><code>NEGATIVE_INFINITY</code></td> + <td>Special negative infinite value; returned on overflow</td> + </tr> + <tr> + <td><code>POSITIVE_INFINITY</code></td> + <td>Special positive infinite value; returned on overflow</td> + </tr> + </tbody> +</table> + +<p>The Number prototype provides methods for retrieving information from Number objects in various formats. The following table summarizes the methods of <code>Number.prototype</code>.</p> + +<table class="fullwidth-table"> + <caption>Table 7.3 Methods of Number.prototype</caption> + <thead> + <tr> + <th scope="col">Method</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>toExponential</code></td> + <td>Returns a string representing the number in exponential notation.</td> + </tr> + <tr> + <td><code>toFixed</code></td> + <td>Returns a string representing the number in fixed-point notation.</td> + </tr> + <tr> + <td><code>toPrecision</code></td> + <td>Returns a string representing the number to a specified precision in fixed-point notation.</td> + </tr> + <tr> + <td><code>toSource</code></td> + <td>Returns an object literal representing the specified <code>Number</code> object; you can use this value to create a new object. Overrides the <code>Object.toSource</code> method.</td> + </tr> + <tr> + <td><code>toString</code></td> + <td>Returns a string representing the specified object. Overrides the <code>Object.toString </code>method.</td> + </tr> + <tr> + <td><code>valueOf</code></td> + <td>Returns the primitive value of the specified object. Overrides the <code>Object.valueOf </code>method.</td> + </tr> + </tbody> +</table> + +<h2 id="RegExp_Object">RegExp Object</h2> + +<p>The <code>RegExp</code> object lets you work with regular expressions. It is described in <a href="/en-US/docs/JavaScript/Guide/Regular_Expressions" title="en-US/docs/JavaScript/Guide/Regular Expressions">Regular Expressions</a>.</p> + +<h2 id="String_Object">String Object</h2> + +<p>The <code>String</code> object is a wrapper around the string primitive data type. Do not confuse a string literal with the <code>String</code> object. For example, the following code creates the string literal <code>s1</code> and also the <code>String</code> object <code>s2</code>:</p> + +<pre class="brush: js">var s1 = "foo"; //creates a string literal value +var s2 = new String("foo"); //creates a String object +</pre> + +<p>You can call any of the methods of the <code>String</code> object on a string literal value—JavaScript automatically converts the string literal to a temporary <code>String</code> object, calls the method, then discards the temporary <code>String</code> object. You can also use the <code>String.length</code> property with a string literal.</p> + +<p>You should use string literals unless you specifically need to use a <code>String</code> object, because <code>String</code> objects can have counterintuitive behavior. For example:</p> + +<pre class="brush: js">var s1 = "2 + 2"; //creates a string literal value +var s2 = new String("2 + 2"); //creates a String object +eval(s1); //returns the number 4 +eval(s2); //returns the string "2 + 2"</pre> + +<p>A <code>String</code> object has one property, <code>length</code>, that indicates the number of characters in the string. For example, the following code assigns <code>x</code> the value 13, because "Hello, World!" has 13 characters:</p> + +<pre class="brush: js">var mystring = "Hello, World!"; +var x = mystring.length; +</pre> + +<p>A <code>String</code> object has two types of methods: those that return a variation on the string itself, such as <code>substring</code> and <code>toUpperCase</code>, and those that return an HTML-formatted version of the string, such as <code>bold</code> and <code>link</code>.</p> + +<p>For example, using the previous example, both <code>mystring.toUpperCase()</code> and <code>"hello, world!".toUpperCase()</code> return the string "HELLO, WORLD!"</p> + +<p>The <code>substring</code> method takes two arguments and returns a subset of the string between the two arguments. Using the previous example, <code>mystring.substring(4, 9)</code> returns the string "o, Wo". See the <a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/substring" title="en-US/docs/JavaScript/Reference/Global Objects/String/substring"><code>substring</code></a> method of the <code>String</code> object in the JavaScript Reference for more information.</p> + +<p>The <code>String</code> object also has a number of methods for automatic HTML formatting, such as <code>bold</code> to create boldface text and <code>link</code> to create a hyperlink. For example, you could create a hyperlink to a hypothetical URL with the <code>link</code> method as follows:</p> + +<pre class="brush: js">mystring.link("http://www.helloworld.com") +</pre> + +<p>The following table summarizes the methods of <code>String</code> objects.</p> + +<table class="fullwidth-table"> + <caption>Table 7.4 Methods of String Instances</caption> + <thead> + <tr> + <th scope="col">Method</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/anchor" title="en-US/docs/JavaScript/Reference/Global_Objects/String/anchor">anchor</a></code></td> + <td>Creates HTML named anchor.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/big" title="en-US/docs/JavaScript/Reference/Global_Objects/String/big">big</a></code>, <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/blink" title="en-US/docs/JavaScript/Reference/Global_Objects/String/blink">blink</a></code>, <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/bold" title="en-US/docs/JavaScript/Reference/Global_Objects/String/bold">bold</a></code>, <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/fixed" title="en-US/docs/JavaScript/Reference/Global_Objects/String/fixed">fixed</a></code>, <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/italics" title="en-US/docs/JavaScript/Reference/Global_Objects/String/italics">italics</a></code>, <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/small" title="en-US/docs/JavaScript/Reference/Global_Objects/String/small">small</a></code>, <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/strike" title="en-US/docs/JavaScript/Reference/Global_Objects/String/strike">strike</a></code>, <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/sub" title="en-US/docs/JavaScript/Reference/Global_Objects/String/sub">sub</a></code>, <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/sup" title="en-US/docs/JavaScript/Reference/Global_Objects/String/sup">sup</a></code></td> + <td>Create HTML formatted string.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/charAt" title="en-US/docs/JavaScript/Reference/Global_Objects/String/charAt">charAt</a></code>, <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/charCodeAt" title="en-US/docs/JavaScript/Reference/Global_Objects/String/charCodeAt">charCodeAt</a></code></td> + <td>Return the character or character code at the specified position in string.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/indexOf" title="en-US/docs/JavaScript/Reference/Global_Objects/String/indexOf">indexOf</a></code>, <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/lastIndexOf" title="en-US/docs/JavaScript/Reference/Global_Objects/String/lastIndexOf">lastIndexOf</a></code></td> + <td>Return the position of specified substring in the string or last position of specified substring, respectively.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/link" title="en-US/docs/JavaScript/Reference/Global_Objects/String/link">link</a></code></td> + <td>Creates HTML hyperlink.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/concat" title="en-US/docs/JavaScript/Reference/Global_Objects/String/concat">concat</a></code></td> + <td>Combines the text of two strings and returns a new string.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/fromCharCode" title="en-US/docs/JavaScript/Reference/Global_Objects/String/fromCharCode">fromCharCode</a></code></td> + <td>Constructs a string from the specified sequence of Unicode values. This is a method of the String class, not a String instance.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/split" title="en-US/docs/JavaScript/Reference/Global_Objects/String/split">split</a></code></td> + <td>Splits a <code>String</code> object into an array of strings by separating the string into substrings.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/slice" title="en-US/docs/JavaScript/Reference/Global_Objects/String/slice">slice</a></code></td> + <td>Extracts a section of an string and returns a new string.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/substring" title="en-US/docs/JavaScript/Reference/Global_Objects/String/substring">substring</a></code>, <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/substr" title="en-US/docs/JavaScript/Reference/Global_Objects/String/substr">substr</a></code></td> + <td>Return the specified subset of the string, either by specifying the start and end indexes or the start index and a length.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/match" title="en-US/docs/JavaScript/Reference/Global_Objects/String/match">match</a></code>, <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/replace" title="en-US/docs/JavaScript/Reference/Global_Objects/String/replace">replace</a></code>, <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/search" title="en-US/docs/JavaScript/Reference/Global_Objects/String/search">search</a></code></td> + <td>Work with regular expressions.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/toLowerCase" title="en-US/docs/JavaScript/Reference/Global_Objects/String/toLowerCase">toLowerCase</a></code>, <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/toUpperCase" title="en-US/docs/JavaScript/Reference/Global_Objects/String/toUpperCase">toUpperCase</a></code></td> + <td> + <p>Return the string in all lowercase or all uppercase, respectively.</p> + </td> + </tr> + </tbody> +</table> + +<p>autoPreviousNext("JSGChapters")</p> diff --git a/files/ru/conflicting/web/javascript/guide/introduction/index.html b/files/ru/conflicting/web/javascript/guide/introduction/index.html new file mode 100644 index 0000000000..6d58fafb80 --- /dev/null +++ b/files/ru/conflicting/web/javascript/guide/introduction/index.html @@ -0,0 +1,159 @@ +--- +title: Об этом учебнике +slug: Web/JavaScript/Guide/About +translation_of: Web/JavaScript/Guide/Introduction +translation_of_original: Web/JavaScript/Guide/About +--- +<p>JavaScript это кросс-платформенный, объектно-ориентированный интерпретируемый язык программирования. В этом учебнике описано все, что вам нужно знать для того, чтобы начать ипользовать JavaScript.</p> + +<h2 id="Особенности_разных_версий_JavaScript">Особенности разных версий JavaScript</h2> + +<p> </p> + +<ul> + <li><a class="new" href="/ru/docs/Web/JavaScript/New_in_JavaScript/1.2" rel="nofollow">/ru/docs/Web/JavaScript/New_in_JavaScript/1.2</a></li> + <li><a class="new" href="/ru/docs/Web/JavaScript/New_in_JavaScript/1.3" rel="nofollow">/ru/docs/Web/JavaScript/New_in_JavaScript/1.3</a></li> + <li><a class="new" href="/ru/docs/Web/JavaScript/New_in_JavaScript/1.4" rel="nofollow">/ru/docs/Web/JavaScript/New_in_JavaScript/1.4</a></li> + <li><a href="/ru/docs/Web/JavaScript/New_in_JavaScript/1.5">Новое в JavaScript 1.5</a></li> + <li><a href="/ru/docs/Web/JavaScript/New_in_JavaScript/1.6">Новое в JavaScript 1.6</a></li> + <li><a href="/ru/docs/Web/JavaScript/New_in_JavaScript/1.7">Новое в JavaScript 1.7</a></li> + <li><a href="/ru/docs/Web/JavaScript/New_in_JavaScript/1.8">New in JavaScript 1.8</a></li> + <li><a href="/ru/docs/Web/JavaScript/New_in_JavaScript/1.8.1">Новое в JavaScript 1.8.1</a></li> + <li><a href="/ru/docs/Web/JavaScript/New_in_JavaScript/1.8.5">Новое в JavaScript 1.8.5</a></li> +</ul> + +<p> </p> + +<h2 id="Что_вы_уже_должны_знать">Что вы уже должны знать</h2> + +<p>Этот учебник предполагает, что у вас уже имеются некоторые знания и опыт:</p> + +<p>Общее понимание, что такое Интернет и всемирная сеть WWW. Знание языка разметки гипертекста (<a href="/en/HTML" title="en/HTML">HTML</a>) также привествуется.</p> + +<p>Некоторый опыт программирования на C или Visual Basic будет полезен, но не является обязательным.</p> + +<h2 id="Версии_JavaScript">Версии JavaScript</h2> + +<table class="standard-table"> + <caption>Таблица 1. Версии JavaScript и Navigator</caption> + <thead> + <tr> + <th scope="col">Версия JavaScript</th> + <th scope="col">Версия Navigator</th> + </tr> + </thead> + <tbody> + <tr> + <td>JavaScript 1.0</td> + <td>Navigator 2.0</td> + </tr> + <tr> + <td>JavaScript 1.1</td> + <td>Navigator 3.0</td> + </tr> + <tr> + <td>JavaScript 1.2</td> + <td>Navigator 4.0-4.05</td> + </tr> + <tr> + <td>JavaScript 1.3</td> + <td>Navigator 4.06-4.7x</td> + </tr> + <tr> + <td>JavaScript 1.4</td> + <td> </td> + </tr> + <tr> + <td>JavaScript 1.5</td> + <td>Navigator 6.0<br> + Mozilla (браузер с открытым исходным кодом)</td> + </tr> + <tr> + <td>JavaScript 1.6</td> + <td><a href="/en/Firefox_1.5_for_developers" title="en/Firefox_1.5_for_developers">Firefox 1.5</a>, другие, основанные на Mozilla 1.8 продукты</td> + </tr> + <tr> + <td>JavaScript 1.7</td> + <td><a href="/en/Firefox_2_for_developers" title="en/Firefox_2_for_developers">Firefox 2</a>, другие, основанные на Mozilla 1.8.1 продукты</td> + </tr> + <tr> + <td>JavaScript 1.8</td> + <td><a href="/en/Firefox_3_for_developers" title="en/Firefox_3_for_developers">Firefox 3</a>, другие, основанные на Mozilla 1.9 продукты</td> + </tr> + </tbody> +</table> + +<p>Каждая версия Netscape Enterprise Server также поддерживает разные версии JavaScript. Чтобы помочь вам писать скрипты совместимые с разными версиями Enterprise Server, это руководство пользуется аббревиатурой, которая однозначно идентифицирует версию сервера, в которой реализована каждая функциональность.</p> + +<p><br> + <strong style="font-style: inherit; font-weight: 700; line-height: 1.5;"> Таблица 2. Аббревиатуры версий Netscape Enterprise Server</strong></p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Abbreviation</th> + <th scope="col">Enterprise Server version</th> + </tr> + </thead> + <tbody> + <tr> + <td>NES 2.0</td> + <td>Netscape Enterprise Server 2.0</td> + </tr> + <tr> + <td>NES 3.0</td> + <td>Netscape Enterprise Server 3.0</td> + </tr> + </tbody> +</table> + +<h2 id="Где_найти_информацию_по_JavaScript">Где найти информацию по JavaScript</h2> + +<p>Документация JavaScript включает в себя следующие материалы:</p> + +<ul> + <li><a href="/ru/JavaScript/Guide" title="en/Core_JavaScript_1.5_Guide">Учебник JavaScript</a> (тот учебник, который вы сейчас читаете) содержит информацию о языке JavaScript и его объектах.</li> + <li><a href="/en/JavaScript/Reference" title="en/JavaScript/Reference">JavaScript Reference</a> содержит справочный материал по языку JavaScript.</li> +</ul> + +<p>Если вы новичок в JavaScript, то начните с <a href="/en/JavaScript/Guide" title="en/Core_JavaScript_1.5_Guide">Учебника </a><a href="/en/JavaScript/Guide" title="en/Core_JavaScript_1.5_Guide">JavaScript</a>. Как только вы усвоили фундаментальные основы, вы можете начать пользоваться <a href="/en/JavaScript/Reference" title="en/JavaScript/Reference">Справочником JavaScript</a>, чтобы получить больше информации об определенных объектах, выражениях и операторах.</p> + +<h2 id="Советы_изучающим_JavaScript">Советы изучающим JavaScript</h2> + +<p>Начать изучать JavaScript очень легко: все что вам нужно - это современный веб браузер. Этот учебник включает описание некоторых особенностей JavaScript, которые доступны только в самых последних версиях Firefox (и других браузерах основанных на движке Gecko), так что лучше всего воспользоваться самой последней версией Firefox.</p> + +<h3 id="Интерактивный_интерпретатор.">Интерактивный интерпретатор.</h3> + +<p>Интерактивная строка ввода JavaScript окажет бесценную услугу в изучении языка, так как позволит пробовать все вещи сразу же, вам не потребуется сохранять изменения в файле и обновлять страницу каждый раз. Консоль ошибок Firefox, доступна через меню Инструменты, предлагает простой способ попробовать выполнить JavaScript выражения: просто введите строку с кодом и нажмите кнопку "Evaluate".</p> + +<p><img alt="Image:ErrorConsole.png" class="internal" src="/@api/deki/files/192/=ErrorConsole.png"></p> + +<h3 id="Firebug">Firebug</h3> + +<p>Более продвинутое средство доступно в <a class="external" href="http://www.getfirebug.com/">Firebug</a>. Firebug это расширение Firefox. Хотя в последних версиях Firefox средства отладки становятся более совершенными и такой нужды Firebug уже нет. Выражения которые вы вводите интерпретируются как объекты и связываются c другими частями в Firebug. Например, вы можете сложить 5 плюс 5, заменить буквы в строке со строчных на прописные, получить кликабельную ссылку на документ, или получить ссылку на элемент в документе:</p> + +<p><img alt="" class="internal" src="/@api/deki/files/5188/=FirebugCommandLine.PNG" style="height: 281px; width: 728px;"></p> + +<p>Нажав на кнопке со стрелкой в нижнем правом углу вы можете открыть многострочный редактор скриптов.</p> + +<p>Firebug также имеет в составе продвинутый инспектор DOM, дебаггер JavaScript, инструменты профилирования и многие другие полезные утилиты. JavaScript код выполняемый на веб странице может вызвать функцию <code>console.log()</code>, которая выведет свой аргумент на консоль Firebug.</p> + +<p>Множество примеров в этом учебнике используют функцию <code>alert()</code>, чтобы вывести сообщение во время выполнения скрипта.</p> + +<h2 id="Принятые_соглашения_в_документе">Принятые соглашения в документе</h2> + +<p>JavaScript приложения выполняются на разных операционных системах; информация в этом учебнике актуальна в любом случае. Пути к директориям или файлам даны в формате Windows (обратный слеш как разделитель). Для версии Юникс, пути точно такие же, за исключением того, что используеся обычный слеш вместо обратного, а также соотвественно корневая директория начинается с '/' а не 'c:/' как это в Windows.</p> + +<p>Этот учебник использует единый локатор ресурсов (URL-ы) следующей формы:</p> + +<p><code>http://<em>server</em>.<em>domain</em>/<em>path</em>/<em>file</em>.html</code></p> + +<p>В этих URL-ах, <em>server</em> - это имя сервера на котором запущено ваше приложение, например <code>research1</code> или <code>www</code>; <em>domain</em> - это имя Internet домена, например <code>netscape.com</code> или <code>uiuc.edu</code>; <em>path</em> - структура директорий на сервере; и <em>file</em><code>.html</code> - имя файла, который расположен на вашем сервере. В общем, элементы выделенные курсивом в URL-ах это метки-заполнители, а элементы выделенные нормальным моноширинным шрифтом точные неизменные значения (например, конфиругацию сервера вы можете изменить, как и сменить доменное имя, структура каталогов может поменяться, а вот протокол всегда один, и расширение файла для вебстраниц тоже постоянно). Если ваш вебсервер поддерживает Secure Sockets Layer (SSL), то вы можете пользоваться <code>https</code> вместо <code>http</code> в URL.</p> + +<p>Этот учебник пользуется следующим соглашением об использовании шрифтов:</p> + +<ul> + <li><code>Моноширинный шрифт </code>используется для примеров кода и их вывода, API и элементов языка (например, имена методов или имена свойств), имена файлов, имена директорий, путей, тегов HTML, и любого другого текста, который должен быть выведен на экран. (<code><em>Моноширинный курсивный шрифт</em></code> использован для меток-заменителей встроенных в код.)</li> + <li><em>Курсивное начертание </em>использовано для оглавлений, особого выделения, переменных и меток-заменителей, и слов использованых в буквальном смысле.</li> + <li><strong>Жирное начертание </strong>использовано для терминов из глоссария.</li> +</ul> diff --git a/files/ru/conflicting/web/javascript/guide/introduction_6f341ba6db4b060ccbd8dce4a0d5214b/index.html b/files/ru/conflicting/web/javascript/guide/introduction_6f341ba6db4b060ccbd8dce4a0d5214b/index.html new file mode 100644 index 0000000000..5db1f95ca4 --- /dev/null +++ b/files/ru/conflicting/web/javascript/guide/introduction_6f341ba6db4b060ccbd8dce4a0d5214b/index.html @@ -0,0 +1,142 @@ +--- +title: Обзор JavaScript +slug: Web/JavaScript/Guide/JavaScript_Overview +translation_of: Web/JavaScript/Guide/Introduction +translation_of_original: Web/JavaScript/Guide/JavaScript_Overview +--- +<p>Эта глава является введением в JavaScript и описывает некоторые из базовых понятий.</p> + +<h3 id="What_is_JavaScript.3F" name="What_is_JavaScript.3F">Что такое JavaScript?</h3> + +<p>JavaScript это кросс-платформенный, объектно-ориентированный, скриптовый язык. JavaScript - это маленький и легковесный язык; он спроектирован не для создания законченных, полноценных приложений, а для легкого встраивания в другие продукты и приложения, например, в веб браузеры. Внутри основного приложения, JavaScript может соединяться с объектами этого приложения и осуществлять программный контроль над ними.</p> + +<p>Ядро JavaScript содержит набор базовых объектов, например Array, Date и Math, и набор элементов языка: операторов, управляющих структур, и выражений. Ядро JavaScript может быть расширено для различных целей с помощью дополнений, например:</p> + +<ul> + <li><em>Client-side JavaScript</em> расширяет ядро языка предоставляя объекты управления браузером (Navigator или другой веб-браузер) и его Document Object Model (DOM). Например, клиентские расширения позволяют приложению размещать элементы в HTML-форме и реагировать на пользовательские события, такие как щелчок мыши, ввод данных в форму и навигация по страницам.</li> + <li><em>Server-side JavaScript</em> расширяет ядро языка предоставляя объекты для запуска JavaScript на сервере. Например, server-side расширения позволяют приложению соединяться с реляционной базой данных, обеспечивать непрерывность информации между вызовами приложения, или выполнять операции над файлами на сервере.</li> +</ul> + +<p>Используя функции JavaScript LiveConnect, Вы можете позволить коду на Java и JavaScript общаться между собой. Вы можете создать экземпляр объекта Java из JavaScript и получить доступ к его публичным методам и свойствам. Из Java, Вы можете получить доступ к объектам, свойствам и методам JavaScript.</p> + +<p>Впервые JavaScript был использован в браузерах Netscape.</p> + +<h3 id="JavaScript_and_Java" name="JavaScript_and_Java">JavaScript и Java</h3> + +<p>JavaScript и Java схожи в некоторых отношениях, но принципиально отличаются в других. Язык JavaScript напоминает Java, но не имеет статической типизации и строгой проверки типов. В основном, JavaScript следует большей части синтакса Java в выражениях, именованиях и основного потока управления конструкциями, что стало причиной, почему он был переименован из LiveScript в JavaScript.</p> + +<p>В отличии от системы компилированных классов в Java, построенной на объявлениях, JavaScript поддерживает систему исполнения, основанную на небольшом количестве типов данных, представляющих числовые, логические и строковые значения. JavaScript обладает моделью объектов на базе прототипов вместо более общей модели объектов на базе классов. Модель объектов на базе прототипов делает возможным динамическое наследование; то есть, то, что унаследовано, может различаться для отдельных объектов. JavaScript также поддерживает функции без каких-либо специальных декларативных требований. Функции могут быть свойствами объектов, выполняться как слабо типизированные методы.</p> + +<p>По сравнению с Java, JavaScript - это язык с очень свободной формой языка. Вам не надо объявлять переменные, классы или методы. Вы не должны беспокоиться, является ли метод public, private или protected, Вам не надо реализовывать интерфейсы. Переменные, параметры и возвращаемые функциями типы не являются явно типизированными.</p> + +<p>Java - язык программирования на основе классов, предназначенный для быстрого выполнения и безопасности типов. Безопасность типов означает, например, что Вы не можете взять тип Java integer и привести его к типу object reference или получить доступ к закрытой памяти изменяя байт-код Java. Ориентированная на классы модель Java означает, что программы состоят исключительно из классов и их методов. Наследование классов и строгая типизация в Java обычно тербуют тесно связанную иерархию объектов. Эти требования делают программирование на Java более сложным чем на JavaScript.</p> + +<p>По духу JavaScript происходит от нескольких небольших, динамически типизированных языков программирования, таких как HyperTalk и dBASE. Эти скриптовые языки предлагают инструменты программирования для гораздо более широкой аудитории благодаря более простому синтаксису, специальной встроенной функциональности и минимальным требованиям для создания объектов.</p> + +<table class="standard-table"> + <caption>Таблица 1.1 Сравнение JavaScript и Java</caption> + <thead> + <tr> + <th scope="col">JavaScript</th> + <th scope="col">Java</th> + </tr> + </thead> + <tbody> + <tr> + <td>Объектно-ориентированный. Нет различий между типами объектов. Наследование реализовано через механизм прототипов, свойства и методы могут быть динамически добавлены к любому объекту.</td> + <td>На базе классов. Объекты делятся на классы и экземпляры с наследованием через иерархию классов. Классы и экземпляры не могут иметь динамически добавленные свойства и методы.</td> + </tr> + <tr> + <td>Типы данных переменных не объявлены (динамическая типизация).</td> + <td>Типы данных переменных должны быть объявлены (статическая типизация).</td> + </tr> + <tr> + <td>Не может автоматически записывать на жесткий диск.</td> + <td>Может автоматически записывать на жесткий диск.</td> + </tr> + </tbody> +</table> + +<p>Для получения дополнительной информации о различиях между JavaScript и Java, см. раздел <a href="/en/JavaScript/Guide/Details_of_the_Object_Model" title="en/JavaScript/Guide/Details of the Object Model">Details of the Object Model</a>.</p> + +<h3 id="JavaScript_and_the_ECMAScript_Specification" name="JavaScript_and_the_ECMAScript_Specification">JavaScript and the ECMAScript Specification</h3> + +<p>Netscape invented JavaScript, and JavaScript was first used in Netscape browsers. However, Netscape is working with <a class="external" href="http://www.ecma-international.org/">Ecma International</a> — the European association for standardizing information and communication systems (ECMA was formerly an acronym for the European Computer Manufacturers Association) to deliver a standardized, international programming language based on core JavaScript. This standardized version of JavaScript, called ECMAScript, behaves the same way in all applications that support the standard. Companies can use the open standard language to develop their implementation of JavaScript. The ECMAScript standard is documented in the ECMA-262 specification.</p> + +<p>The ECMA-262 standard is also approved by the <a class="external" href="http://www.iso.ch/">ISO</a> (International Organization for Standardization) as ISO-16262. You can find a <a class="external" href="http://www-archive.mozilla.org/js/language/E262-3.pdf" title="http://www-archive.mozilla.org/js/language/E262-3.pdf">PDF version of ECMA-262</a> (outdated version) at the Mozilla website. You can also find the specification on <a class="external" href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">the Ecma International website</a>. The ECMAScript specification does not describe the Document Object Model (DOM), which is standardized by the <a class="external" href="http://www.w3.org/">World Wide Web Consortium (W3C)</a>. The DOM defines the way in which HTML document objects are exposed to your script.</p> + +<h4 id="Relationship_between_JavaScript_Versions_and_ECMAScript_Editions" name="Relationship_between_JavaScript_Versions_and_ECMAScript_Editions">Relationship between JavaScript Versions and ECMAScript Editions</h4> + +<p>Netscape worked closely with Ecma International to produce the ECMAScript Specification (ECMA-262). The following table describes the relationship between JavaScript versions and ECMAScript editions.</p> + +<table class="standard-table"> + <caption>Table 1.2 JavaScript versions and ECMAScript editions</caption> + <thead> + <tr> + <th scope="row">JavaScript version</th> + <th scope="col">Relationship to ECMAScript edition</th> + </tr> + </thead> + <tbody> + <tr> + <td>JavaScript 1.1</td> + <td>ECMA-262, Edition 1 is based on JavaScript 1.1.</td> + </tr> + <tr> + <td>JavaScript 1.2</td> + <td>ECMA-262 was not complete when JavaScript 1.2 was released. JavaScript 1.2 is not fully compatible with ECMA-262, Edition 1, for the following reasons: + <ul> + <li>Netscape developed additional features in JavaScript 1.2 that were not considered for ECMA-262.</li> + <li>ECMA-262 adds two new features: internationalization using Unicode, and uniform behavior across all platforms. Several features of JavaScript 1.2, such as the <code>Date</code> object, were platform-dependent and used platform-specific behavior.</li> + </ul> + </td> + </tr> + <tr> + <td> + <p>JavaScript 1.3</p> + </td> + <td> + <p>JavaScript 1.3 is fully compatible with ECMA-262, Edition 1.</p> + + <p>JavaScript 1.3 resolved the inconsistencies that JavaScript 1.2 had with ECMA-262, while keeping all the additional features of JavaScript 1.2 except == and !=, which were changed to conform with ECMA-262.</p> + </td> + </tr> + <tr> + <td> + <p>JavaScript 1.4</p> + </td> + <td> + <p>JavaScript 1.4 is fully compatible with ECMA-262, Edition 1.</p> + + <p>The third version of the ECMAScript specification was not finalized when JavaScript 1.4 was released.</p> + </td> + </tr> + <tr> + <td>JavaScript 1.5</td> + <td>JavaScript 1.5 is fully compatible with ECMA-262, Edition 3.</td> + </tr> + </tbody> +</table> + +<div class="note"><strong>Note</strong>: ECMA-262, Edition 2 consisted of minor editorial changes and bug fixes to the Edition 1 specification. The current release by the TC39 working group of Ecma International is ECMAScript Edition 5.1</div> + +<p>The <a href="/en/JavaScript/Reference" title="en/JavaScript/Reference">JavaScript Reference</a> indicates which features of the language are ECMAScript-compliant.</p> + +<p>JavaScript will always include features that are not part of the ECMAScript Specification; JavaScript is compatible with ECMAScript, while providing additional features.</p> + +<h4 id="JavaScript_Documentation_versus_the_ECMAScript_Specification" name="JavaScript_Documentation_versus_the_ECMAScript_Specification">JavaScript Documentation versus the ECMAScript Specification</h4> + +<p>The ECMAScript specification is a set of requirements for implementing ECMAScript; it is useful if you want to determine whether a JavaScript feature is supported in other ECMAScript implementations. If you plan to write JavaScript code that uses only features supported by ECMAScript, then you may need to review the ECMAScript specification.</p> + +<p>The ECMAScript document is not intended to help script programmers; use the JavaScript documentation for information on writing scripts.</p> + +<h4 id="JavaScript_and_ECMAScript_Terminology">JavaScript and ECMAScript Terminology</h4> + +<p>The ECMAScript specification uses terminology and syntax that may be unfamiliar to a JavaScript programmer. Although the description of the language may differ in ECMAScript, the language itself remains the same. JavaScript supports all functionality outlined in the ECMAScript specification.</p> + +<p>The JavaScript documentation describes aspects of the language that are appropriate for a JavaScript programmer. For example:</p> + +<ul> + <li>The Global Object is not discussed in the JavaScript documentation because you do not use it directly. The methods and properties of the Global Object, which you do use, are discussed in the JavaScript documentation but are called top-level functions and properties.</li> + <li>The no parameter (zero-argument) constructor with the <code>Number</code> and <code>String</code> objects is not discussed in the JavaScript documentation, because what is generated is of little use. A <code>Number</code> constructor without an argument returns +0, and a <code>String</code> constructor without an argument returns "" (an empty string).</li> +</ul> |