Arrays

2018-05-15 17:26 更新
先決條件: 基本的計算機素養(yǎng),基本了解HTML和CSS,了解JavaScript是什么。
目的: 了解什么是數(shù)組,以及如何在JavaScript中操作它們。

什么是數(shù)組?

數(shù)組通常被描述為"列表式對象"; 它們基本上是包含存儲在列表中的多個值的單個對象。 數(shù)組對象可以存儲在變量中,并以與任何其他類型的值相同的方式處理,區(qū)別在于我們可以單獨訪問列表中的每個值,并且對列表執(zhí)行超級有用和高效的操作,例如循環(huán) 它和每一個值做同樣的事情。 也許我們有一系列的產(chǎn)品項目和他們的價格存儲在一個數(shù)組,我們想循環(huán)通過他們所有和打印出來的發(fā)票,同時總計所有的價格在一起,打印出總價格在底部。

如果我們沒有數(shù)組,我們必須將每個項目存儲在一個單獨的變量中,然后調(diào)用執(zhí)行打印的代碼,并為每個項目單獨添加。 這將是寫得更長,效率更低,更容易出錯。 如果我們有10個項目添加到發(fā)票,這將是不夠的,但100個項目,或1000? 我們將在后面的文章中回到這個例子。

和前面的文章一樣,讓我們通過在JavaScript控制臺中輸入一些示例來了解數(shù)組的真正基礎。 我們在下面提供了一個(您也可以 >在單獨的標簽或窗口中打開此控制臺,或者如果愿意,可以使用瀏覽器開發(fā)者控制臺)。

創(chuàng)建數(shù)組

數(shù)組由方括號構成,其中包含用逗號分隔的項目列表。

  1. Let's say we wanted to store a shopping list in an array — we'd do something like the following. Enter the following lines into your console:
    var shopping = ['bread', 'milk', 'cheese', 'hummous', 'noodles'];
    shopping;
  2. In this case, each item in the array is a string, but bear in mind that you can store any item in an array — string, number, object, another variable, even another array. You can also mix and match item types — they don't all have to be numbers, strings, etc. Try these:
    var sequence = [1, 1, 2, 3, 5, 8, 13];
    var random = ['tree', 795, [0, 1, 2]];
  3. Try creating a couple of arrays of your own, before you move on.

訪問和修改數(shù)組項

然后,您可以使用括號符號訪問數(shù)組中的各個項,方法與訪問字符串中的字母相同。

  1. Enter the following into your console:
    shopping[0];
    // returns "bread"
  2. You can also modify an item in an array by simply giving a single array item a new value. Try this:
    shopping[0] = 'tahini';
    shopping;
    // shopping will now return [ "tahini", "milk", "cheese", "hummous", "noodles" ]
    Note: We've said it before, but just as a reminder — computers start counting from 0!
  3. Note that an array inside an array is called a multidimensional array. You can access an item inside an array that is itself inside another array by chaining two sets of square brackets together. For example, to access one of the items inside the array that is the third item inside the random array (see previous section), we could do something like this:
    random[2][2];
  4. Try further playing with, and making some more modifications to, your array examples before moving on.

查找數(shù)組的長度

您可以通過使用 mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/length"> length 屬性。 嘗試以下操作:

sequence.length;
// should return 7

這有其他用途,但它最常用于告訴循環(huán)繼續(xù),直到它循環(huán)通過數(shù)組中的所有項目。 例如:

var sequence = [1, 1, 2, 3, 5, 8, 13];
for (var i = 0; i < sequence.length; i++) {
  console.log(sequence[i]);
}

你會在未來的文章中正確地學習循環(huán),但簡單來說,這段代碼說:

  1. Start looping at item number 0 in the array.
  2. Stop looping at the item number equal to the length of the array. This will work for an array of any length, but in this case it will stop looping at item number 7 (this is good, as the last item — which we want the loop to cover — is 6.
  3. For each item, print it out to the browser console with console.log().

一些有用的數(shù)組方法

在本節(jié)中,我們將介紹一些非常有用的數(shù)組相關方法,它們允許我們將字符串拆分成數(shù)組項,反之亦然,并將新項添加到數(shù)組中。

字符串和數(shù)組之間的轉換

通常,您將看到一個包含在一個大的長字符串中的原始數(shù)據(jù),您可能想要將有用的項目分成一個更有用的形式,然后對它們做事情,如在數(shù)據(jù)表中顯示它們。 為此,我們可以使用 split() 代碼> 方法。 在最簡單的形式中,這需要一個參數(shù),您想要將字符串分隔開的字符,并返回分隔符之間的子串作為數(shù)組中的項。

注意:OK,這在技術上是一個字符串方法,而不是數(shù)組方法,但我已經(jīng)把它放在數(shù)組,因為它在這里。

  1. Let's play with this, to see how it works. First, create a string in your console:
    var myData = 'Manchester,London,Liverpool,Birmingham,Leeds,Carlisle';
  2. Now let's split it at each comma:
    var myArray = myData.split(',');
    myArray;
  3. Finally, try finding the length of your new array, and retrieving some items from it:
    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
  4. You can also go the opposite way using the join() method. Try the following:
    var myNewString = myArray.join(',');
    myNewString;

添加和刪除數(shù)組項

我們還沒有涵蓋添加和刪除數(shù)組項 - 現(xiàn)在我們來看看。 我們將使用最后一節(jié)中結束的 myArray 數(shù)組。 如果您尚未遵循該部分,請先在控制臺中創(chuàng)建數(shù)組:

var myArray = ['Manchester', 'London', 'Liverpool', 'Birmingham', 'Leeds', 'Carlisle'];

首先,要在數(shù)組末尾添加或刪除項,我們可以使用 push"> push() "> pop() 。

  1. Let's use push() first — note that you need to include one or more items that you want to add to the end of your array. Try this:
    myArray.push('Cardiff');
    myArray;
    myArray.push('Bradford', 'Brighton');
    myArray;
    
  2. 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:
    var newLength = myArray.push('Bristol');
    myArray;
    newLength;
  3. Removing the last item from the array is as simple as running pop() on it. Try this:
    myArray.pop();
  4. The item that was removed is returned when the method call completes. You could also do this:
    var removedItem = myArray.pop();
    myArray;
    removedItem;

unshift() a > shift() 同樣的方式,除了它們在數(shù)組的開頭工作,而不是結束。

  1. First unshift() — try the following commands:
    myArray.unshift('Edinburgh');
    myArray;
  2. Now shift(); try these!
    var removedItem = myArray.shift();
    myArray;
    removedItem;

積極學習:打印這些產(chǎn)品!

讓我們回到前面描述的例子 - 在發(fā)票上打印出產(chǎn)品名稱和價格,然后合計價格并將其打印在底部。 在下面的可編輯示例中有包含數(shù)字的注釋 - 每個標記一個地方,你必須添加一些代碼。 它們?nèi)缦?

  1. Below the // number 1 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 products.
  2. On the same line as the // number 2 comment is the beginning of a for loop. In this line we currently have i <= 0, which is a conditional test that causes the for loop to stop immediately, because it is saying "stop when i is no longer less than or equal to 0", and i starts at 0. We'd like you to replace this with a conditional test that stops the loop when i is no longer less than the products array's length.
  3. Just below the // number 3 comment we want you to write a line of code that splits the current array item (name:price) 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 Useful string methods article for some help, or even better, look at the Converting between strings and arrays section of this article.
  4. 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 first strings article.
  5. There is a variable called total that is created and given a value of 0 at the top of the code. Inside the loop (below // number 4) 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 assignment operator to do this.
  6. We want you to change the line just below // number 5 so that the itemText 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, so you should be OK with this.

主動學習:前5項搜索

對于數(shù)組方法(如 push())非常有用 > 和 pop() 是在維護網(wǎng)絡應用程序中當前活動項目的記錄時。 例如,在動畫場景中,您可能具有表示當前顯示的背景圖形的對象數(shù)組,并且出于性能或雜亂原因,您可能只需要一次顯示50。 當創(chuàng)建新對象并將其添加到數(shù)組時,可以從數(shù)組中刪除較早的對象以保持所需的數(shù)量。

在這個例子中,我們將展示一個更簡單的用法 - 這里我們給你一個假搜索網(wǎng)站,一個搜索框。 其想法是,當在搜索框中輸入條目時,在列表中顯示前5個搜索項。 當術語數(shù)量超過5時,每次將新術語添加到頂部時,最后一個術語開始被刪除,因此始終顯示前面的5個術語。

注意:在真實的搜索應用中,您可能會點擊之前的搜索字詞返回以前的搜索,并顯示實際的搜索結果! 我們現(xiàn)在只是保持簡單。

要完成該應用,我們需要您:

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

結論

閱讀本文后,我們確信你會同意,數(shù)組看起來很有用; 你會看到它們在JavaScript中隨處可見,通常與用于對數(shù)組中的每個項目執(zhí)行相同操作的循環(huán)相關聯(lián)。 我們將教你所有有用的基礎知識,在下一個模塊中了解循環(huán),但現(xiàn)在你應該給自己一個拍手,并采取當之無愧的休息; 你已經(jīng)完成了這個模塊中的所有文章!

唯一剩下要做的就是通過這個模塊的評估,這將測試你對之前的文章的理解。

也可以看看

  • Indexed collections — an advanced level guide to arrays and their cousins, typed arrays.
  • Array — the Array object reference page — for a detailed reference guide to the features discussed in this page, and many more.

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號