aboutsummaryrefslogtreecommitdiff
path: root/files/tr/web/javascript/reference/global_objects/array/map/index.html
blob: 0c8d66f4de7228455b9c3d209672af24adb09fdf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
---
title: Array.prototype.map()
slug: Web/JavaScript/Reference/Global_Objects/Array/map
translation_of: Web/JavaScript/Reference/Global_Objects/Array/map
---
<div>{{JSRef}}</div>

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

<div>{{EmbedInteractiveExample("pages/js/array-map.html")}}</div>



<h2 id="Sözdizimi">Sözdizimi</h2>

<pre class="syntaxbox"><var>var new_array = arr</var>.map(function <var>callback(currentValue[, index[, array]]) {
    // Return element for new_array
}</var>[, <var>thisArg</var>])</pre>

<h3 id="Parameters">Parameters</h3>

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

<h3 id="Return_value">Return value</h3>

<p>Elemanları, <code>callback</code> fonksiyonunun sonuçları olan yeni bir dizi.</p>

<h2 id="Açıklama">Açıklama</h2>

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

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

<pre class="syntaxbox">dizi.map( (deger, index) =&gt; /* yapılacak işlem */ ) </pre>

<p>If a <code>thisArg</code> parameter is provided to <code>map</code>, it will be used as callback's <code>this</code> value. Otherwise, the value {{jsxref("undefined")}} will be used as its <code>this</code> value. The <code>this</code> value ultimately observable by <code>callback</code> is determined according to <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">the usual rules for determining the <code>this</code> seen by a function</a>.</p>

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

<p>The range of elements processed by <code>map</code> is set before the first invocation of <code>callback</code>. Elements which are appended to the array after the call to <code>map</code> begins will not be visited by <code>callback</code>. If existing elements of the array are changed, their value as passed to <code>callback</code> will be the value at the time <code>map</code> visits them. Elements that are deleted after the call to <code>map</code> begins and before being visited are not visited.<br>
 <br>
 Due to the algorithm defined in the specification if the array which map was called upon is sparse, resulting array will also be sparse keeping same indices blank.</p>

<h2 id="Examples">Examples</h2>

<h3 id="Mapping_an_array_of_numbers_to_an_array_of_square_roots">Mapping an array of numbers to an array of square roots</h3>

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

<pre class="brush: js">var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
// roots is now [1, 2, 3]
// numbers is still [1, 4, 9]
</pre>

<h3 id="Using_map_to_reformat_objects_in_an_array">Using map to reformat objects in an array</h3>

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

<pre class="brush: js">var kvArray = [{key: 1, value: 10},
               {key: 2, value: 20},
               {key: 3, value: 30}];

var reformattedArray = kvArray.map(obj =&gt;{
   var rObj = {};
   rObj[obj.key] = obj.value;
   return rObj;
})
// reformattedArray is now [{1: 10}, {2: 20}, {3: 30}],

// kvArray is still:
// [{key: 1, value: 10},
//  {key: 2, value: 20},
//  {key: 3, value: 30}]
</pre>

<h3 id="Mapping_an_array_of_numbers_using_a_function_containing_an_argument">Mapping an array of numbers using a function containing an argument</h3>

<p>The following code shows how map works when a function requiring one argument is used with it. The argument will automatically be assigned from each element of the array as map loops through the original array.</p>

<pre class="brush: js">var numbers = [1, 4, 9];
var doubles = numbers.map(function(num) {
  return num * 2;
});

// doubles is now [2, 8, 18]
// numbers is still [1, 4, 9]
</pre>

<h3 id="Using_map_generically">Using <code>map</code> generically</h3>

<p>This example shows how to use map on a {{jsxref("String")}} to get an array of bytes in the ASCII encoding representing the character values:</p>

<pre class="brush: js">var map = Array.prototype.map;
var a = map.call('Hello World', function(x) {
  return x.charCodeAt(0);
});
// a now equals [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
</pre>

<h3 id="Using_map_generically_querySelectorAll">Using <code>map</code> generically <code>querySelectorAll</code></h3>

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

<pre class="brush: js">var elems = document.querySelectorAll('select option:checked');
var values = Array.prototype.map.call(elems, function(obj) {
  return obj.value;
});
</pre>

<p>Easier way would be using {{jsxref("Array.from()")}} method.</p>

<h3 id="Tricky_use_case">Tricky use case</h3>

<p><a href="http://www.wirfs-brock.com/allen/posts/166">(inspired by this blog post)</a></p>

<p>It is common to use the callback with one argument (the element being traversed). Certain functions are also commonly used with one argument, even though they take additional optional arguments. These habits may lead to confusing behaviors.</p>

<pre class="brush: js">// Consider:
['1', '2', '3'].map(parseInt);
// While one could expect [1, 2, 3]
// The actual result is [1, NaN, NaN]

// parseInt is often used with one argument, but takes two.
// The first is an expression and the second is the radix.
// To the callback function, Array.prototype.map passes 3 arguments:
// the element, the index, the array
// The third argument is ignored by parseInt, but not the second one,
// hence the possible confusion. See the blog post for more details

function returnInt(element) {
  return parseInt(element, 10);
}

['1', '2', '3'].map(returnInt); // [1, 2, 3]
// Actual result is an array of numbers (as expected)

// Same as above, but using the concise arrow function syntax
['1', '2', '3'].map( str =&gt; parseInt(str) );

// A simpler way to achieve the above, while avoiding the "gotcha":
['1', '2', '3'].map(Number); // [1, 2, 3]
// but unlike `parseInt` will also return a float or (resolved) exponential notation:
['1.1', '2.2e2', '3e300'].map(Number); // [1.1, 220, 3e+300]
</pre>

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

<pre class="brush: js">var xs = ['10', '10', '10'];

xs = xs.map(parseInt);

console.log(xs);
// Actual result of 10,NaN,2 may be unexpected based on the above description.</pre>

<h2 id="Polyfill">Polyfill</h2>

<p><code>map</code> was added to the ECMA-262 standard in the 5th edition; as such it may not be present in all implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of <code>map</code> in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming {{jsxref("Object")}}, {{jsxref("TypeError")}}, and {{jsxref("Array")}} have their original values and that <code>callback.call</code> evaluates to the original value of <code>{{jsxref("Function.prototype.call")}}</code>.</p>

<pre class="brush: js">// Production steps of ECMA-262, Edition 5, 15.4.4.19
// Reference: http://es5.github.io/#x15.4.4.19
if (!Array.prototype.map) {

  Array.prototype.map = function(callback/*, thisArg*/) {

    var T, A, k;

    if (this == null) {
      throw new TypeError('this is null or not defined');
    }

    // 1. Let O be the result of calling ToObject passing the |this|
    //    value as the argument.
    var O = Object(this);

    // 2. Let lenValue be the result of calling the Get internal
    //    method of O with the argument "length".
    // 3. Let len be ToUint32(lenValue).
    var len = O.length &gt;&gt;&gt; 0;

    // 4. If IsCallable(callback) is false, throw a TypeError exception.
    // See: http://es5.github.com/#x9.11
    if (typeof callback !== 'function') {
      throw new TypeError(callback + ' is not a function');
    }

    // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
    if (arguments.length &gt; 1) {
      T = arguments[1];
    }

    // 6. Let A be a new array created as if by the expression new Array(len)
    //    where Array is the standard built-in constructor with that name and
    //    len is the value of len.
    A = new Array(len);

    // 7. Let k be 0
    k = 0;

    // 8. Repeat, while k &lt; len
    while (k &lt; len) {

      var kValue, mappedValue;

      // a. Let Pk be ToString(k).
      //   This is implicit for LHS operands of the in operator
      // b. Let kPresent be the result of calling the HasProperty internal
      //    method of O with argument Pk.
      //   This step can be combined with c
      // c. If kPresent is true, then
      if (k in O) {

        // i. Let kValue be the result of calling the Get internal
        //    method of O with argument Pk.
        kValue = O[k];

        // ii. Let mappedValue be the result of calling the Call internal
        //     method of callback with T as the this value and argument
        //     list containing kValue, k, and O.
        mappedValue = callback.call(T, kValue, k, O);

        // iii. Call the DefineOwnProperty internal method of A with arguments
        // Pk, Property Descriptor
        // { Value: mappedValue,
        //   Writable: true,
        //   Enumerable: true,
        //   Configurable: true },
        // and false.

        // In browsers that support Object.defineProperty, use the following:
        // Object.defineProperty(A, k, {
        //   value: mappedValue,
        //   writable: true,
        //   enumerable: true,
        //   configurable: true
        // });

        // For best browser support, use the following:
        A[k] = mappedValue;
      }
      // d. Increase k by 1.
      k++;
    }

    // 9. return A
    return A;
  };
}
</pre>

<h2 id="Specifications">Specifications</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>{{SpecName('ES5.1', '#sec-15.4.4.19', 'Array.prototype.map')}}</td>
   <td>{{Spec2('ES5.1')}}</td>
   <td>Initial definition. Implemented in JavaScript 1.6.</td>
  </tr>
  <tr>
   <td>{{SpecName('ES6', '#sec-array.prototype.map', 'Array.prototype.map')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td> </td>
  </tr>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-array.prototype.map', 'Array.prototype.map')}}</td>
   <td>{{Spec2('ESDraft')}}</td>
   <td> </td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>

<div>


<p>{{Compat("javascript.builtins.Array.map")}}</p>
</div>

<h2 id="See_also">See also</h2>

<ul>
 <li>{{jsxref("Array.prototype.forEach()")}}</li>
 <li>{{jsxref("Map")}} object</li>
 <li>{{jsxref("Array.from()")}}</li>
</ul>