aboutsummaryrefslogtreecommitdiff
path: root/files/zh-tw/learn/javascript/first_steps/arrays/index.html
blob: 8ded53e5e3328d7975f3a8e8425d99b6b9ddaa84 (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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
---
title: Arrays
slug: Learn/JavaScript/First_steps/Arrays
translation_of: Learn/JavaScript/First_steps/Arrays
---
<div>{{LearnSidebar}}</div>

<div>{{PreviousMenuNext("Learn/JavaScript/First_steps/Useful_string_methods", "Learn/JavaScript/First_steps/Silly_story_generator", "Learn/JavaScript/First_steps")}}</div>

<p class="summary">在本單元的最後一篇文章中,我們將介紹陣列——一種在單個變數名下儲存資料項列表的簡潔方法。在這裡,我們看看為什麼這很有用,然後探討如何建立陣列,檢索、增加和刪除儲存在陣列中的項目等等。</p>

<table class="learn-box standard-table">
 <tbody>
  <tr>
   <th scope="row">先備知識:</th>
   <td>基本計算機知識、基本理解 HTML 與 CSS、知道 JavaScript 是什麼。</td>
  </tr>
  <tr>
   <th scope="row">目標:</th>
   <td>理解何謂陣列並在 JavaScript 操作之。</td>
  </tr>
 </tbody>
</table>

<h2 id="什麼是陣列?">什麼是陣列?</h2>

<p>陣列通常描述為「像列表的物件」:也就是一個列表物件,裡面含有幾個數值。陣列物件能放在變數裡面,處理方式也與資料型別大致相同。不過主要差異為,陣列可以獨立存取、並高效處理裡面的數值:像是利用迴圈,對每個數值作相同處理。例如我們的陣列是一組有項目和價格的產品、我們可以用迴圈把單價印在發票上、最後在發票底下印出合計。</p>

<p>不用陣列的話,就會需要註冊、並單獨呼叫很多獨立變數。這樣會花更多時間寫程式、效率更低、還更容易寫錯。只有十個的話還好解決,但如果有一百個,甚至一千個呢?我們會在接下來闡述之。</p>

<p>與前幾篇文章一樣,讓我們在 JavaScript 控制台中輸入一些示例,來了解陣列的基礎知識吧。</p>

<h3 id="建立陣列">建立陣列</h3>

<p>陣列用方括弧包起來,每個單位會用逗號分隔起來。</p>

<ol>
 <li>來作一個購物清單的陣列吧:我們會做類似下面的事情。在主控台中輸入以下程式:
  <pre class="brush: js notranslate">var shopping = ['bread', 'milk', 'cheese', 'hummus', 'noodles'];
shopping;</pre>
 </li>
 <li>在此,陣列的每個單位都是字串。但請記住,陣列可以儲存任何單位:字串、數字、物件、另一個變數、甚至是另一個陣列。也可以混合單位的型別:它們不一定都要是數字或字串。來試試這個:
  <pre class="brush: js notranslate">var sequence = [1, 1, 2, 3, 5, 8, 13];
var random = ['tree', 795, [0, 1, 2]];</pre>
 </li>
 <li>看下去之前,試著自己作幾個陣列。</li>
</ol>

<h3 id="存取並修改陣列的單位">存取並修改陣列的單位</h3>

<p>你可以使用括號標記法存取個別單位,同時也可以<a href="/en-US/Learn/JavaScript/First_steps/Useful_string_methods#Retrieving_a_specific_string_character">存取字串中的字母</a></p>

<ol>
 <li>在主控台輸入以下程式:
  <pre class="brush: js notranslate">shopping[0];
// returns "bread"</pre>
 </li>
 <li>也可以透過賦予陣列新數值修改該單位。試試這個:
  <pre class="brush: js notranslate">shopping[0] = 'tahini';
shopping;
// shopping 回傳 [ "tahini", "milk", "cheese", "hummus", "noodles" ]</pre>

  <div class="note"><strong>注:</strong>前面有說過,但還是提醒下:電腦從 0 開始數!</div>
 </li>
 <li>請注意,陣列裡面的陣列稱為多維陣列(multidimensional array)。你可以撰寫兩組方括弧,來存取陣列裡面的陣列單位。例如說,存取前述 <code>random</code> 變數內的陣列單位就可以這麼寫:
  <pre class="brush: js notranslate">random[2][2];</pre>
 </li>
 <li>看下去之前,試著進一步使用並修改陣列。</li>
</ol>

<h3 id="找出陣列長度">找出陣列長度</h3>

<p>找出陣列長度(意即有幾個單位在陣列內)的方法,跟找出字串長度(含有幾個字元)的方式一樣——都是使用 {{jsxref("Array.prototype.length","length")}} 屬性。試試下方程式行:</p>

<pre class="brush: js notranslate">shopping.length;
// should return 5</pre>

<p>這還有其他用途,但最常見的用法是讓迴圈一直循環直到所有的單元都走過一次。 舉個例子:</p>

<pre class="brush: js notranslate">var sequence = [1, 1, 2, 3, 5, 8, 13];
for (var i = 0; i &lt; sequence.length; i++) {
  console.log(sequence[i]);
}</pre>

<p>在後續的章節,你會學到更多關於迴圈的部分;簡而言之,上述程式碼的意思是:</p>

<ol>
 <li>從陣列中索引為 0 的單元開始循環。</li>
 <li>當索引值等於陣列的長度時,停止循環。這個方法對任何長度的陣列都可行,但在這個例子中,迴圈會當索引等於 7 時停止循環(這樣很好,因為最後一個單元——我們希望有包含到的——是6)。</li>
 <li>我們在瀏覽器 console 中用 <code><a href="/en-US/docs/Web/API/Console/log">console.log()</a></code> 將每個單元列印出來。</li>
</ol>

<h2 id="好用的陣列方法">好用的陣列方法</h2>

<p>在這個小節中,我們會介紹一些相當有用、有關陣列的方法。例如將字串拆分為陣列,反之亦然,以及增加新的單位到陣列中。</p>

<h3 id="在字串與陣列之間轉換">在字串與陣列之間轉換</h3>

<p>通常你會看到一組含有原始資料的長字串,而你可能會希望將有用的單元拆分、組成更好用的形式,對他進行操作。為了達成這個目的,我們可以使用 {{jsxref("String.prototype.split()","split()")}} 方法。它最簡單的形式是只使用一個參數,你想分離的字串位置的字元(分隔符),而後它會返回陣列中在分隔符之間的子字串。</p>

<div class="note">
<p><strong>Note</strong>: 好的,在技術上它屬於字串的方法,而非陣列的方法。但因為它可以很順利地對陣列進行操作,因此我們把它列在這邊。</p>
</div>

<ol>
 <li>來試試這個,看它如何運作。首先,建立一個字串在你的 console:
  <pre class="brush: js notranslate">var myData = 'Manchester,London,Liverpool,Birmingham,Leeds,Carlisle';</pre>
 </li>
 <li>現在我們用逗點來分隔字串:
  <pre class="brush: js notranslate">var myArray = myData.split(',');
myArray;</pre>
 </li>
 <li>最後,試著找出你新的陣列的長度,並且從中取出一些單元:
  <pre class="brush: js notranslate">myArray.length;
myArray[0]; // the first item in the array
myArray[1]; // the second item in the array
myArray[myArray.length-1]; // the last item in the array</pre>
 </li>
 <li>相對地,你也可以用 {{jsxref("Array.prototype.join()","join()")}} 方法。試試下面這段:
  <pre class="brush: js notranslate">var myNewString = myArray.join(',');
myNewString;</pre>
 </li>
 <li>另一個將陣列轉換為字串的方法是用 {{jsxref("Array.prototype.toString()","toString()")}}<code>toString()</code> 因為不需要參數而比 <code>join()</code> 更簡潔,但因此也更多限制。使用 <code>join()</code> 你可以使用特定的分隔符(試著使用其他不同的字元來執行步驟 4)。
  <pre class="brush: js notranslate">var dogNames = ['Rocket','Flash','Bella','Slugger'];
dogNames.toString(); //Rocket,Flash,Bella,Slugger</pre>
 </li>
</ol>

<h3 id="新增與移除陣列單位">新增與移除陣列單位</h3>

<p>我們還沒談到增加與移除陣列的單位,現在來看看吧!我們使用上一個小節中的 <code>myArray</code> 陣列。如果你沒跟隨到上一個小節,那就先在你的 console 建立下面這個陣列:</p>

<pre class="brush: js notranslate">var myArray = ['Manchester', 'London', 'Liverpool', 'Birmingham', 'Leeds', 'Carlisle'];</pre>

<p>首先,我們可以分別使用 {{jsxref("Array.prototype.push()","push()")}}{{jsxref("Array.prototype.pop()","pop()")}} 來增加或移除一個在陣列最末端的單元 。</p>

<ol>
 <li>Let's use <code>push()</code> first — note that you need to include one or more items that you want to add to the end of your array. Try this:

  <pre class="brush: js notranslate">myArray.push('Cardiff');
myArray;
myArray.push('Bradford', 'Brighton');
myArray;
</pre>
 </li>
 <li>The new length of the array is returned when the method call completes. If you wanted to store the new array length in a variable, you could do something like this:
  <pre class="brush: js notranslate">var newLength = myArray.push('Bristol');
myArray;
newLength;</pre>
 </li>
 <li>Removing the last item from the array is as simple as running <code>pop()</code> on it. Try this:
  <pre class="brush: js notranslate">myArray.pop();</pre>
 </li>
 <li>The item that was removed is returned when the method call completes. To save that item in a new variable, you could do this:
  <pre class="brush: js notranslate">var removedItem = myArray.pop();
myArray;
removedItem;</pre>
 </li>
</ol>

<p>{{jsxref("Array.prototype.unshift()","unshift()")}} and {{jsxref("Array.prototype.shift()","shift()")}} work in exactly the same way as <code>push()</code> and <code>pop()</code>, respectively, except that they work on the beginning of the array, not the end.</p>

<ol>
 <li>First <code>unshift()</code> — try the following commands:

  <pre class="brush: js notranslate">myArray.unshift('Edinburgh');
myArray;</pre>
 </li>
 <li>Now <code>shift()</code>; try these!
  <pre class="brush: js notranslate">var removedItem = myArray.shift();
myArray;
removedItem;</pre>
 </li>
</ol>

<h2 id="Active_learning_Printing_those_products!">Active learning: Printing those products!</h2>

<p>Let's return to the example we described earlier — printing out product names and prices on an invoice, then totaling the prices and printing them at the bottom. In the editable example below there are comments containing numbers — each of these marks a place where you have to add something to the code. They are as follows:</p>

<ol>
 <li>Below the <code>// number 1</code> comment are a number of strings, each one containing a product name and price separated by a colon. We'd like you to turn this into an array and store it in an array called <code>products</code>.</li>
 <li>On the same line as the <code>// number 2</code> comment is the beginning of a for loop. In this line we currently have <code>i &lt;= 0</code>, which is a conditional test that causes the <a href="/en-US/Learn/JavaScript/First_steps/A_first_splash#Loops">for loop</a> to stop immediately, because it is saying "stop when <code>i</code> is no longer less than or equal to 0", and <code>i</code> starts at 0. We'd like you to replace this with a conditional test that stops the loop when <code>i</code> is no longer less than the <code>products</code> array's length.</li>
 <li>Just below the <code>// number 3</code> comment we want you to write a line of code that splits the current array item (<code>name:price</code>) into two separate items, one containing just the name and one containing just the price. If you are not sure how to do this, consult the <a href="/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods">Useful string methods</a> article for some help, or even better, look at the <a href="#在字串與陣列之間轉換">Converting between strings and arrays</a> section of this article.</li>
 <li>As part of the above line of code, you'll also want to convert the price from a string to a number. If you can't remember how to do this, check out the <a href="/en-US/Learn/JavaScript/First_steps/Strings#Numbers_versus_strings">first strings article</a>.</li>
 <li>There is a variable called <code>total</code> that is created and given a value of 0 at the top of the code. Inside the loop (below <code>// number 4</code>) we want you to add a line that adds the current item price to that total in each iteration of the loop, so that at the end of the code the correct total is printed onto the invoice. You might need an <a href="/en-US/Learn/JavaScript/First_steps/Math#Assignment_operators">assignment operator</a> to do this.</li>
 <li>We want you to change the line just below <code>// number 5</code> so that the <code>itemText</code> variable is made equal to "current item name — $current item price", for example "Shoes — $23.99" in each case, so the correct information for each item is printed on the invoice. This is just simple string concatenation, which should be familiar to you.</li>
</ol>

<div class="hidden">
<h6 id="Playable_code">Playable code</h6>

<pre class="brush: html notranslate">&lt;h2&gt;Live output&lt;/h2&gt;

&lt;div class="output" style="min-height: 150px;"&gt;

&lt;ul&gt;

&lt;/ul&gt;

&lt;p&gt;&lt;/p&gt;

&lt;/div&gt;

&lt;h2&gt;Editable code&lt;/h2&gt;

&lt;p class="a11y-label"&gt;Press Esc to move focus away from the code area (Tab inserts a tab character).&lt;/p&gt;

&lt;textarea id="code" class="playable-code" style="height: 410px;width: 95%"&gt;
var list = document.querySelector('.output ul');
var totalBox = document.querySelector('.output p');
var total = 0;
list.innerHTML = '';
totalBox.textContent = '';
// number 1
                'Underpants:6.99'
                'Socks:5.99'
                'T-shirt:14.99'
                'Trousers:31.99'
                'Shoes:23.99';

for (var i = 0; i &lt;= 0; i++) { // number 2
  // number 3

  // number 4

  // number 5
  itemText = 0;

  var listItem = document.createElement('li');
  listItem.textContent = itemText;
  list.appendChild(listItem);
}

totalBox.textContent = 'Total: $' + total.toFixed(2);
&lt;/textarea&gt;

&lt;div class="playable-buttons"&gt;
  &lt;input id="reset" type="button" value="Reset"&gt;
  &lt;input id="solution" type="button" value="Show solution"&gt;
&lt;/div&gt;
</pre>

<pre class="brush: js notranslate">var textarea = document.getElementById('code');
var reset = document.getElementById('reset');
var solution = document.getElementById('solution');
var code = textarea.value;
var userEntry = textarea.value;

function updateCode() {
  eval(textarea.value);
}

reset.addEventListener('click', function() {
  textarea.value = code;
  userEntry = textarea.value;
  solutionEntry = jsSolution;
  solution.value = 'Show solution';
  updateCode();
});

solution.addEventListener('click', function() {
  if(solution.value === 'Show solution') {
    textarea.value = solutionEntry;
    solution.value = 'Hide solution';
  } else {
    textarea.value = userEntry;
    solution.value = 'Show solution';
  }
  updateCode();
});

var jsSolution = 'var list = document.querySelector(\'.output ul\');\nvar totalBox = document.querySelector(\'.output p\');\nvar total = 0;\nlist.innerHTML = \'\';\ntotalBox.textContent = \'\';\n\nvar products = [\'Underpants:6.99\',\n \'Socks:5.99\',\n \'T-shirt:14.99\',\n \'Trousers:31.99\',\n \'Shoes:23.99\'];\n\nfor(var i = 0; i &lt; products.length; i++) {\n var subArray = products[i].split(\':\');\n var name = subArray[0];\n var price = Number(subArray[1]);\n total += price;\n itemText = name + \' — $\' + price;\n\n var listItem = document.createElement(\'li\');\n listItem.textContent = itemText;\n list.appendChild(listItem);\n}\n\ntotalBox.textContent = \'Total: $\' + total.toFixed(2);';
var solutionEntry = jsSolution;

textarea.addEventListener('input', updateCode);
window.addEventListener('load', updateCode);

// stop tab key tabbing out of textarea and
// make it write a tab at the caret position instead

textarea.onkeydown = function(e){
  if (e.keyCode === 9) {
    e.preventDefault();
    insertAtCaret('\t');
  }


  if (e.keyCode === 27) {
    textarea.blur();
  }
};

function insertAtCaret(text) {
  var scrollPos = textarea.scrollTop;
  var caretPos = textarea.selectionStart;

  var front = (textarea.value).substring(0, caretPos);
  var back = (textarea.value).substring(textarea.selectionEnd, textarea.value.length);
  textarea.value = front + text + back;
  caretPos = caretPos + text.length;
  textarea.selectionStart = caretPos;
  textarea.selectionEnd = caretPos;
  textarea.focus();
  textarea.scrollTop = scrollPos;
}

// Update the saved userCode every time the user updates the text area code

textarea.onkeyup = function(){
  // We only want to save the state when the user code is being shown,
  // not the solution, so that solution is not saved over the user code
  if(solution.value === 'Show solution') {
    userEntry = textarea.value;
  } else {
    solutionEntry = textarea.value;
  }

  updateCode();
};</pre>



<pre class="brush: css notranslate">html {
  font-family: sans-serif;
}

h2 {
  font-size: 16px;
}

.a11y-label {
  margin: 0;
  text-align: right;
  font-size: 0.7rem;
  width: 98%;
}

body {
  margin: 10px;
  background-color: #f5f9fa;
}</pre>
</div>

<p>{{ EmbedLiveSample('Playable_code', '100%', 730, "", "", "hide-codepen-jsfiddle") }}</p>

<h2 id="Active_learning_Top_5_searches">Active learning: Top 5 searches</h2>

<p>A good use for array methods like {{jsxref("Array.prototype.push()","push()")}} and {{jsxref("Array.prototype.pop()","pop()")}} is when you are maintaining a record of currently active items in a web app. In an animated scene for example, you might have an array of objects representing the background graphics currently displayed, and you might only want 50 displayed at once, for performance or clutter reasons. As new objects are created and added to the array, older ones can be deleted from the array to maintain the desired number.</p>

<p>In this example we're going to show a much simpler use — here we're giving you a fake search site, with a search box. The idea is that when terms are entered in the search box, the top 5 previous search terms are displayed in the list. When the number of terms goes over 5, the last term starts being deleted each time a new term is added to the top, so the 5 previous terms are always displayed.</p>

<div class="note">
<p><strong>Note</strong>: In a real search app, you'd probably be able to click the previous search terms to return to previous searches, and it would display actual search results! We are just keeping it simple for now.</p>
</div>

<p>To complete the app, we need you to:</p>

<ol>
 <li>Add a line below the <code>// number 1</code> comment that adds the current value entered into the search input to the start of the array. This can be retrieved using <code>searchInput.value</code>.</li>
 <li>Add a line below the <code>// number 2</code> comment that removes the value currently at the end of the array.</li>
</ol>

<div class="hidden">
<h6 id="Playable_code_2">Playable code 2</h6>

<pre class="brush: html notranslate">&lt;h2&gt;Live output&lt;/h2&gt;
&lt;div class="output" style="min-height: 150px;"&gt;

&lt;input type="text"&gt;&lt;button&gt;Search&lt;/button&gt;

&lt;ul&gt;

&lt;/ul&gt;

&lt;/div&gt;

&lt;h2&gt;Editable code&lt;/h2&gt;

&lt;p class="a11y-label"&gt;Press Esc to move focus away from the code area (Tab inserts a tab character).&lt;/p&gt;


&lt;textarea id="code" class="playable-code" style="height: 370px; width: 95%"&gt;
var list = document.querySelector('.output ul');
var searchInput = document.querySelector('.output input');
var searchBtn = document.querySelector('.output button');

list.innerHTML = '';

var myHistory = [];

searchBtn.onclick = function() {
  // we will only allow a term to be entered if the search input isn't empty
  if (searchInput.value !== '') {
    // number 1

    // empty the list so that we don't display duplicate entries
    // the display is regenerated every time a search term is entered.
    list.innerHTML = '';

    // loop through the array, and display all the search terms in the list
    for (var i = 0; i &lt; myHistory.length; i++) {
      itemText = myHistory[i];
      var listItem = document.createElement('li');
      listItem.textContent = itemText;
      list.appendChild(listItem);
    }

    // If the array length is 5 or more, remove the oldest search term
    if (myHistory.length &gt;= 5) {
      // number 2

    }

    // empty the search input and focus it, ready for the next term to be entered
    searchInput.value = '';
    searchInput.focus();
  }
}
&lt;/textarea&gt;

&lt;div class="playable-buttons"&gt;
  &lt;input id="reset" type="button" value="Reset"&gt;
  &lt;input id="solution" type="button" value="Show solution"&gt;
&lt;/div&gt;</pre>





<pre class="brush: css notranslate">html {
  font-family: sans-serif;
}

h2 {
  font-size: 16px;
}

.a11y-label {
  margin: 0;
  text-align: right;
  font-size: 0.7rem;
  width: 98%;
}

body {
  margin: 10px;
  background: #f5f9fa;
}</pre>







<pre class="brush: js notranslate">var textarea = document.getElementById('code');
var reset = document.getElementById('reset');
var solution = document.getElementById('solution');
var code = textarea.value;
var userEntry = textarea.value;

function updateCode() {
  eval(textarea.value);
}

reset.addEventListener('click', function() {
  textarea.value = code;
  userEntry = textarea.value;
  solutionEntry = jsSolution;
  solution.value = 'Show solution';
  updateCode();
});

solution.addEventListener('click', function() {
  if(solution.value === 'Show solution') {
    textarea.value = solutionEntry;
    solution.value = 'Hide solution';
  } else {
    textarea.value = userEntry;
    solution.value = 'Show solution';
  }
  updateCode();
});

var jsSolution = 'var list = document.querySelector(\'.output ul\');\nvar searchInput = document.querySelector(\'.output input\');\nvar searchBtn = document.querySelector(\'.output button\');\n\nlist.innerHTML = \'\';\n\nvar myHistory= [];\n\nsearchBtn.onclick = function() {\n if(searchInput.value !== \'\') {\n myHistory.unshift(searchInput.value);\n\n list.innerHTML = \'\';\n\n for(var i = 0; i &lt; myHistory.length; i++) {\n itemText = myHistory[i];\n var listItem = document.createElement(\'li\');\n listItem.textContent = itemText;\n list.appendChild(listItem);\n }\n\n if(myHistory.length &gt;= 5) {\n myHistory.pop();\n }\n\n searchInput.value = \'\';\n searchInput.focus();\n }\n}';
var solutionEntry = jsSolution;

textarea.addEventListener('input', updateCode);
window.addEventListener('load', updateCode);

// stop tab key tabbing out of textarea and
// make it write a tab at the caret position instead

textarea.onkeydown = function(e){
  if (e.keyCode === 9) {
    e.preventDefault();
    insertAtCaret('\t');
  }

  if (e.keyCode === 27) {
    textarea.blur();
  }
};

function insertAtCaret(text) {
  var scrollPos = textarea.scrollTop;
  var caretPos = textarea.selectionStart;

  var front = (textarea.value).substring(0, caretPos);
  var back = (textarea.value).substring(textarea.selectionEnd, textarea.value.length);
  textarea.value = front + text + back;
  caretPos = caretPos + text.length;
  textarea.selectionStart = caretPos;
  textarea.selectionEnd = caretPos;
  textarea.focus();
  textarea.scrollTop = scrollPos;
}

// Update the saved userCode every time the user updates the text area code

textarea.onkeyup = function(){
  // We only want to save the state when the user code is being shown,
  // not the solution, so that solution is not saved over the user code
  if(solution.value === 'Show solution') {
    userEntry = textarea.value;
  } else {
    solutionEntry = textarea.value;
  }

  updateCode();
};</pre>






</div>

<p>{{ EmbedLiveSample('Playable_code_2', '100%', 700, "", "", "hide-codepen-jsfiddle") }}</p>

<h2 id="Conclusion">Conclusion</h2>

<p>After reading through this article, we are sure you will agree that arrays seem pretty darn useful; you'll see them crop up everywhere in JavaScript, often in association with loops in order to do the same thing to every item in an array. We'll be teaching you all the useful basics there are to know about loops in the next module, but for now you should give yourself a clap and take a well-deserved break; you've worked through all the articles in this module!</p>

<p>The only thing left to do is work through this module's assessment, which will test your understanding of the articles that came before it.</p>

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

<ul>
 <li><a href="/en-US/docs/Web/JavaScript/Guide/Indexed_collections">Indexed collections</a> — an advanced level guide to arrays and their cousins, typed arrays.</li>
 <li>{{jsxref("Array")}} — the <code>Array</code> object reference page — for a detailed reference guide to the features discussed in this page, and many more.</li>
</ul>

<p>{{PreviousMenuNext("Learn/JavaScript/First_steps/Useful_string_methods", "Learn/JavaScript/First_steps/Silly_story_generator", "Learn/JavaScript/First_steps")}}</p>



<h2 id="In_this_module">In this module</h2>

<ul>
 <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript">What is JavaScript?</a></li>
 <li><a href="/en-US/docs/Learn/JavaScript/First_steps/A_first_splash">A first splash into JavaScript</a></li>
 <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong">What went wrong? Troubleshooting JavaScript</a></li>
 <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Variables">Storing the information you need — Variables</a></li>
 <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Math">Basic math in JavaScript — numbers and operators</a></li>
 <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Strings">Handling text — strings in JavaScript</a></li>
 <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods">Useful string methods</a></li>
 <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Arrays">Arrays</a></li>
 <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Silly_story_generator">Assessment: Silly story generator</a></li>
</ul>