aboutsummaryrefslogtreecommitdiff
path: root/files/he/web/javascript/reference/operators/destructuring_assignment/index.html
blob: 07b2957fe260faa18a588125fadbb0756a422af6 (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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
---
title: השמה מפורקת
slug: Web/JavaScript/Reference/Operators/Destructuring_assignment
translation_of: Web/JavaScript/Reference/Operators/Destructuring_assignment
---
<div style="direction: rtl;">{{jsSidebar("Operators")}}</div>

<p style="direction: rtl;">תחביר <strong>השמה מפורקת </strong>הוא ביטוי JavaScript המאפשר לחלץ נתונים ממערכים או אובייקטים לערכים מפורשים, בעזרת שימוש בתחביר שמשקף את מבנה המערך או האובייקט המילולי.</p>

<h2 id="תחביר" style="direction: rtl;">תחביר</h2>

<pre class="brush:js">var a, b, rest;
[a, b] = [1, 2]
console.log(a); // 1
console.log(b); // 2

[a, b, ...rest] = [1, 2, 3, 4, 5]
console.log(a); // 1
console.log(b); // 2
console.log(rest); // [3, 4, 5]

({a, b} = {a: 1, b :2});
console.log(a); // 1 console.log(b); // 2

({a, b, ...rest} = {a: 1, b: 2, c: 3, d: 4});  //ES2016
console.log(a); // 1
console.log(b); // 2
console.log(rest); // {c: 3, d: 4}
</pre>

<div class="note">
<p style="direction: rtl;">{a, b} = {a:1, b:2} הוא לא תחביר עצמאי תקף, כי {a, b} בצד השמאלי נחשב כבלוק ולא כאובייקט מילולי.</p>

<p dir="rtl">עם זאת, ({a, b} = {a:1, b:2}) תקף, כמו גם {var {a, b} = {a:1, b:2.</p>
</div>

<h2 id="תאור" style="direction: rtl;">תאור</h2>

<div style="direction: rtl;"><span style="line-height: 1.5;">ביטויים ליטרלים של אובייקטים או מערכים מספקים דרך פשוטה ליצירה של חבילת נתונים <em>לפי דרישה</em>. לאחר יצירת חבילות נתונים אלה, ניתן להשתמש בהם בכל דרך שתרצה. ניתן אפילו להחזיר אותם מפונקציות.</span></div>

<pre class="brush: js">var x = [10, 20, 30, 40, 50];</pre>

<p style="direction: rtl;">השמה מפורקת משתמשת בתחביר דומה, אך צד שמאל של ההשמה מציין אילו ערכים לפרוק ממשתנה המקור.</p>

<pre class="brush: js" style="direction: rtl;">var x = [10, 20, 30, 40, 50];
var [y, x] = x;
console.log(y); // 10
console.log(z); // 20
</pre>

<p style="direction: rtl;">דבר אחד שימושי במיוחד שאתה יכול לעשות עם השמה מפורקת הוא לקרוא מבנה שלם בהשמה אחת, אם כי יש עוד מספר דברים מעניינים שאתה יכול לעשות איתם, כפי שמוצג בדוגמאות הבאות.</p>

<p style="direction: rtl;">יכולת זו דומה לתכונות קיימות בשפות כמו פרל ופייתון.</p>

<h2 id="פירוק_מערך" style="direction: rtl;">פירוק מערך</h2>

<h3 id="דוגמה_פשוטה" style="direction: rtl;">דוגמה פשוטה</h3>

<pre class="brush: js">var foo = ["one", "two", "three"];

// without destructuring
var one   = foo[0];
var two   = foo[1];
var three = foo[2];

// with destructuring
var [one, two, three] = foo;</pre>

<h3 id="השמה_ללא_הצהרה" style="direction: rtl;">השמה ללא הצהרה</h3>

<p style="direction: rtl;">השמה מפורקת יכולה להתבצע ללא הצהרה בעת ההשמה.</p>

<pre class="brush:js">var a, b;

[a, b] = [1, 2];</pre>

<h3 id="החלפת_משתנים" style="direction: rtl;">החלפת משתנים</h3>

<p style="direction: rtl;">לאחר ביצוע הקוד הזה, b הוא 1 וa הוא 3. ללא השמה מפורקת, החלפת שני ערכים דורשת שימוש במשתנה זמני (או, בכמה שפות נמוכות, טריק ההחלפת XOR).</p>

<pre class="brush:js">var a = 1;
var b = 3;

[a, b] = [b, a];</pre>

<h3 id="החזרה_מרובת_ערכים" style="direction: rtl;">החזרה מרובת ערכים</h3>

<p style="direction: rtl;">תודה להשמה מפורקת פונקציות יכולות להחזיר ערכים מרובים. למרות שתמיד היה ניתן להחזיר מערך מפונקציה, זה עדיין מספק מידה נוספת של גמישות.</p>

<pre class="brush:js">function f() {
  return [1, 2];
}
</pre>

<p style="direction: rtl;">כפי שניתן לראות, החזרת תוצאות נעשית באמצעות סימון כמו מערך, עם כל הערכים בתוך סוגריים. אתה יכול להחזיר מספר בלתי מוגבל של תוצאות בדרך זו. בדוגמא זו, ()f מחזירה את הערכים [1, 2] כפלט שלה.</p>

<pre class="brush:js">var a, b;
[a, b] = f();
console.log("A is " + a + " B is " + b);
</pre>

<p style="direction: rtl;">ההצהרה ()a, b] = f] מקצה את התוצאות של הפונקציה למשתנים בסוגריים, בהתאמה: a הוא 1 ו- b מוגדר 2.</p>

<p style="direction: rtl;">גם אתה יכול לקבל את ערכי החזרה כמערך:</p>

<pre class="brush:js">var a = f();
console.log("A is " + a);
</pre>

<p style="direction: rtl;">במקרה זה, a הוא מערך המכיל את הערכים 1 ו-2.</p>

<h3 id="התעלמות_ממספר_ערכי_החזר" style="direction: rtl;">התעלמות ממספר ערכי החזר</h3>

<p style="direction: rtl;">אתה יכול להתעלם מערכי החזר שאתה לא מעוניין בהם:</p>

<pre class="brush:js">function f() {
  return [1, 2, 3];
}

var [a, , b] = f();
console.log("A is " + a + " B is " + b);
</pre>

<p style="direction: rtl;">לאחר הרצת קוד זה, a הוא 1 ו- b הוא 3. הערך 2 נדחה. אתה יכול להתעלם מכל ערכי ההחזר בדרך זו. לדוגמה:</p>

<pre class="brush:js">[,,] = f();
</pre>

<h3 id="משיכת_ערכים_מתוצאה_של_regular_expression" style="direction: rtl;">משיכת ערכים מתוצאה של regular expression</h3>

<p dir="rtl">כאשר המתודה  <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec"> exec</a> </code>של regular expression מוצאת התאמה, היא מחזירה מערך המכיל במיקום הראשון את כל ההתאמה של המחרוזת ולאחר מכן את כל החלקים של המחרוזת שתאמה כל קבוצה בסוגריים בregular expression. השמה מפורקת מאפשרת לך למשוך את החלקים מתוך מערך זה בקלות, תוך התעלמות מההתאמה המלאה אם היא לא נחוצה.</p>

<pre class="brush:js">var url = "https://developer.mozilla.org/en-US/Web/JavaScript";

var parsedURL = /^(\w+)\:\/\/([^\/]+)\/(.*)$/.exec(url);
var [, protocol, fullhost, fullpath] = parsedURL;

console.log(protocol); // logs "https"
</pre>

<h2 id="פירוק_אובייקט" style="direction: rtl;">פירוק אובייקט</h2>

<h3 id="דוגמה_פשוטה_2" style="direction: rtl;">דוגמה פשוטה</h3>

<pre class="brush: js">var o = {p: 42, q: true};
var {p, q} = o;

console.log(p); // 42
console.log(q); // true

// Assign new variable names
var {p: foo, q: bar} = o;

console.log(foo); // 42
console.log(bar); // true  </pre>

<h3 id="השמה_ללא_הצהרה_2" style="direction: rtl;">השמה ללא הצהרה</h3>

<p style="direction: rtl;">השמה מפורקת יכולה להתבצע ללא הצהרה בעת ההשמה.</p>

<pre class="brush:js">var a, b;

({a, b} = {a:1, b:2});</pre>

<div class="note">
<p>The <code>( .. )</code> around the assignment statement is required syntax when using object literal destructuring assignment without a declaration.</p>
</div>

<h3 id="ברירות_המחדל_של_ארגומנטים_מפונקציה">ברירות המחדל של ארגומנטים מפונקציה</h3>

<h4 id="גרסת_ES5">גרסת ES5</h4>

<pre class="brush: js">function drawES5Chart(options) {
  options = options === undefined ? {} : options;
  var size = options.size === undefined ? 'big' : options.size;
  var cords = options.cords === undefined ? { x: 0, y: 0 } : options.cords;
  var radius = options.radius === undefined ? 25 : options.radius;
  console.log(size, cords, radius);
  // now finally do some chart drawing
}

drawES5Chart({
  cords: { x: 18, y: 30 },
  radius: 30
});</pre>

<h4 id="גרסת_ES2015">גרסת ES2015</h4>

<pre class="brush: js">function drawES2015Chart({size: size = 'big', cords: cords = { x: 0, y: 0 }, radius: radius = 25} = {})
{
  console.log(size, cords, radius);
  // do some chart drawing
}

drawES2015Chart({
  cords: { x: 18, y: 30 },
  radius: 30
});</pre>

<div class="note">
<p>In Firefox, default values for destructuring assignments are not yet implemented: var { x = 3 } = {} and var [foo = "bar"] = []. See {{bug(932080)}} for destructured default values in functions.</p>
</div>

<h3 id="Module_(non-ES2015)_loading">Module (non-ES2015) loading</h3>

<p>Destructuring can help to load specific subsets of a non-ES2015 module like here in the <a href="/en-US/Add-ons/SDK">Add-on SDK</a>:</p>

<pre class="brush: js">const { Loader, main } = require('toolkit/loader');
</pre>

<h3 id="Nested_object_and_array_destructuring">Nested object and array destructuring</h3>

<pre class="brush:js">var metadata = {
    title: "Scratchpad",
    translations: [
       {
        locale: "de",
        localization_tags: [ ],
        last_edit: "2014-04-14T08:43:37",
        url: "/de/docs/Tools/Scratchpad",
        title: "JavaScript-Umgebung"
       }
    ],
    url: "/en-US/docs/Tools/Scratchpad"
};

var { title: englishTitle, translations: [{ title: localeTitle }] } = metadata;

console.log(englishTitle); // "Scratchpad"
console.log(localeTitle);  // "JavaScript-Umgebung"</pre>

<h3 id="For_of_iteration_and_destructuring">For of iteration and destructuring</h3>

<pre class="brush: js">var people = [
  {
    name: "Mike Smith",
    family: {
      mother: "Jane Smith",
      father: "Harry Smith",
      sister: "Samantha Smith"
    },
    age: 35
  },
  {
    name: "Tom Jones",
    family: {
      mother: "Norah Jones",
      father: "Richard Jones",
      brother: "Howard Jones"
    },
    age: 25
  }
];

for (var {name: n, family: { father: f } } of people) {
  console.log("Name: " + n + ", Father: " + f);
}

// "Name: Mike Smith, Father: Harry Smith"
// "Name: Tom Jones, Father: Richard Jones"</pre>

<h3 id="Pulling_fields_from_objects_passed_as_function_parameter">Pulling fields from objects passed as function parameter</h3>

<pre class="brush:js">function userId({id}) {
  return id;
}

function whois({displayName: displayName, fullName: {firstName: name}}){
  console.log(displayName + " is " + name);
}

var user = {
  id: 42,
  displayName: "jdoe",
  fullName: {
      firstName: "John",
      lastName: "Doe"
  }
};

console.log("userId: " + userId(user)); // "userId: 42"
whois(user); // "jdoe is John"</pre>

<p>This pulls the <code>id</code>, <code>displayName</code> and <code>firstName</code> from the user object and prints them.</p>

<h3 id="Computed_object_property_names_and_destructuring">Computed object property names and destructuring</h3>

<p>Computed property names, like on <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names">object literals</a>, can be used with destructuring.</p>

<pre class="brush: js">let key = "z";
let { [key]: foo } = { z: "bar" };

console.log(foo); // "bar"
</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('ES2015', '#sec-destructuring-assignment', 'Destructuring assignment')}}</td>
   <td>{{Spec2('ES2015')}}</td>
   <td>Initial definition.</td>
  </tr>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-destructuring-assignment', 'Destructuring assignment')}}</td>
   <td>{{Spec2('ESDraft')}}</td>
   <td> </td>
  </tr>
 </tbody>
</table>

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

<p>{{CompatibilityTable}}</p>

<div id="compat-desktop">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Chrome</th>
   <th>Firefox (Gecko)</th>
   <th>Internet Explorer</th>
   <th>Opera</th>
   <th>Safari</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatNo}}</td>
   <td>{{ CompatGeckoDesktop("1.8.1") }}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>7.1</td>
  </tr>
  <tr>
   <td>Computed property names</td>
   <td>{{CompatNo}}</td>
   <td>{{ CompatGeckoDesktop("34") }}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
  </tr>
  <tr>
   <td>Spread operator</td>
   <td>{{CompatUnknown}}</td>
   <td>{{ CompatGeckoDesktop("34") }}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
  </tr>
 </tbody>
</table>
</div>

<div id="compat-mobile">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Android</th>
   <th>Chrome for Android</th>
   <th>Firefox Mobile (Gecko)</th>
   <th>IE Mobile</th>
   <th>Opera Mobile</th>
   <th>Safari Mobile</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{ CompatGeckoMobile("1.0") }}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>8</td>
  </tr>
  <tr>
   <td>Computed property names</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{ CompatGeckoMobile("34") }}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
  </tr>
  <tr>
   <td>Spread operator</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{ CompatGeckoMobile("34") }}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
  </tr>
 </tbody>
</table>
</div>

<h2 id="Firefox-specific_notes">Firefox-specific notes</h2>

<ul>
 <li>Firefox provided a non-standard language extension in <a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/1.7">JS1.7</a> for destructuring. This extension has been removed in Gecko 40 {{geckoRelease(40)}}. See {{bug(1083498)}}.</li>
 <li>Starting with Gecko 41 {{geckoRelease(41)}} and to comply with the ES2015 specification, parenthesized destructuring patterns, like <code>([a, b]) = [1, 2]</code> or <code>({a, b}) = { a: 1, b: 2 }</code>, are now considered invalid and will throw a {{jsxref("SyntaxError")}}. See <a class="external external-icon" href="http://whereswalden.com/2015/06/20/new-changes-to-make-spidermonkeys-and-firefoxs-parsing-of-destructuring-patterns-more-spec-compliant/">Jeff Walden's blog post</a> and {{bug(1146136)}} for more details.</li>
</ul>

<h2 dir="rtl" id="ראה_גם">ראה גם</h2>

<ul dir="rtl">
 <li><a href="/he/docs/Web/JavaScript/Reference/Operators/Assignment_Operators">אופרטורי השמה</a></li>
 <li><a href="https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/">"ES6 in Depth: Destructuring" on hacks.mozilla.org</a></li>
</ul>