Arrays

2018-05-15 17:26 更新
先决条件: 基本的计算机素养,基本了解HTML和CSS,了解JavaScript是什么。
目的: 了解什么是数组,以及如何在JavaScript中操作它们。

什么是数组?

数组通常被描述为"列表式对象"; 它们基本上是包含存储在列表中的多个值的单个对象。 数组对象可以存储在变量中,并以与任何其他类型的值相同的方式处理,区别在于我们可以单独访问列表中的每个值,并且对列表执行超级有用和高效的操作,例如循环 它和每一个值做同样的事情。 也许我们有一系列的产品项目和他们的价格存储在一个数组,我们想循环通过他们所有和打印出来的发票,同时总计所有的价格在一起,打印出总价格在底部。

如果我们没有数组,我们必须将每个项目存储在一个单独的变量中,然后调用执行打印的代码,并为每个项目单独添加。 这将是写得更长,效率更低,更容易出错。 如果我们有10个项目添加到发票,这将是不够的,但100个项目,或1000? 我们将在后面的文章中回到这个例子。

和前面的文章一样,让我们通过在JavaScript控制台中输入一些示例来了解数组的真正基础。 我们在下面提供了一个(您也可以 >在单独的标签或窗口中打开此控制台,或者如果愿意,可以使用浏览器开发者控制台)。

创建数组

数组由方括号构成,其中包含用逗号分隔的项目列表。

  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.

访问和修改数组项

然后,您可以使用括号符号访问数组中的各个项,方法与访问字符串中的字母相同。

  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.

查找数组的长度

您可以通过使用 mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/length"> length 属性。 尝试以下操作:

sequence.length;
// should return 7

这有其他用途,但它最常用于告诉循环继续,直到它循环通过数组中的所有项目。 例如:

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

你会在未来的文章中正确地学习循环,但简单来说,这段代码说:

  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().

一些有用的数组方法

在本节中,我们将介绍一些非常有用的数组相关方法,它们允许我们将字符串拆分成数组项,反之亦然,并将新项添加到数组中。

字符串和数组之间的转换

通常,您将看到一个包含在一个大的长字符串中的原始数据,您可能想要将有用的项目分成一个更有用的形式,然后对它们做事情,如在数据表中显示它们。 为此,我们可以使用 split() 代码> 方法。 在最简单的形式中,这需要一个参数,您想要将字符串分隔开的字符,并返回分隔符之间的子串作为数组中的项。

注意:OK,这在技术上是一个字符串方法,而不是数组方法,但我已经把它放在数组,因为它在这里。

  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;

添加和删除数组项

我们还没有涵盖添加和删除数组项 - 现在我们来看看。 我们将使用最后一节中结束的 myArray 数组。 如果您尚未遵循该部分,请先在控制台中创建数组:

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

首先,要在数组末尾添加或删除项,我们可以使用 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 href ="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/shift"> shift() 同样的方式,除了它们在数组的开头工作,而不是结束。

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

积极学习:打印这些产品!

让我们回到前面描述的例子 - 在发票上打印出产品名称和价格,然后合计价格并将其打印在底部。 在下面的可编辑示例中有包含数字的注释 - 每个标记一个地方,你必须添加一些代码。 它们如下:

  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项搜索

对于数组方法(如 push())非常有用 > 和 pop() 是在维护网络应用程序中当前活动项目的记录时。 例如,在动画场景中,您可能具有表示当前显示的背景图形的对象数组,并且出于性能或杂乱原因,您可能只需要一次显示50。 当创建新对象并将其添加到数组时,可以从数组中删除较早的对象以保持所需的数量。

在这个例子中,我们将展示一个更简单的用法 - 这里我们给你一个假搜索网站,一个搜索框。 其想法是,当在搜索框中输入条目时,在列表中显示前5个搜索项。 当术语数量超过5时,每次将新术语添加到顶部时,最后一个术语开始被删除,因此始终显示前面的5个术语。

注意:在真实的搜索应用中,您可能会点击之前的搜索字词返回以前的搜索,并显示实际的搜索结果! 我们现在只是保持简单。

要完成该应用,我们需要您:

  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.

结论

阅读本文后,我们确信你会同意,数组看起来很有用; 你会看到它们在JavaScript中随处可见,通常与用于对数组中的每个项目执行相同操作的循环相关联。 我们将教你所有有用的基础知识,在下一个模块中了解循环,但现在你应该给自己一个拍手,并采取当之无愧的休息; 你已经完成了这个模块中的所有文章!

唯一剩下要做的就是通过这个模块的评估,这将测试你对之前的文章的理解。

也可以看看

  • 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.

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号