Javascript 简明教程

JavaScript - Array

JavaScript Array 对象让你可以将多个值存储在一个变量中。数组用于存储同种类型或不同类型多个元素的顺序集合。在 JavaScript 中,数组是动态的,因此你无需在定义数组时指定数组长度。创建 JavaScript 数组后,数组的大小可能会减小或增加。

The JavaScript Array object lets you store multiple values in a single variable. An array is used to store a sequential collection of multiple elements of same or different data types. In JavaScript, arrays are dynamic, so you don’t need to specify the length of the array while defining the array. The size of a JavaScript array may decrease or increase after its creation.

Syntax

使用以下语法在 JavaScript 中创建数组对象 −

Use the following syntax to create an array object in JavaScript −

const arr = new Array(val1, val2, val3, ..., valN)

Parameters

  1. val1, val2, val3, …​, valN − It takes multiple values as an argument to initialize an array with them.

Return value

它返回一个数组对象。

It returns an array object.

Note − 当你将单个数字参数传递给 Array() 构造函数时,它会定义一个包含未定义值的,具有参数长度的数组。允许的最大数组长度为 4,294,967,295。

Note − When you pass the single numeric argument to the Array() constructor, it defines the array of argument length containing the undefined values. The maximum length allowed for an array is 4,294,967,295.

你可以在方括号内添加多个以逗号分隔的元素,以使用数组字面量创建数组 −

You can add multiple comma separated elements inside square brackets to create an array using the array literal −

const fruits = [ "apple", "orange", "mango" ];

你将使用序数来访问并设置数组中的值,如下所示。

You will use ordinal numbers to access and to set values inside an array as follows.

fruits[0] is the first element
fruits[1] is the second element
fruits[2] is the third element

JavaScript Array Reference

在 JavaScript 中,Array 对象允许在单个变量名称下存储多个元素的集合。它提供了多种方法和属性来对数组进行操作。在这里,我们列出了 Array 类的属性和方法。

In JavaScript, the Array object enables storing collection of multiple elements under a single variable name. It provides various methods and properties to perform operations on an array. Here, we have listed the properties and methods of the Array class.

JavaScript Array Properties

以下是 Array 对象的属性及其描述 −

Here is a list of the properties of the Array object along with their description −

Sr.No.

Name & Description

1

constructor Returns a reference to the array function that created the object.

2

length Reflects the number of elements in an array.

JavaScript Array Methods

以下是 Array 对象的方法及其描述 −

Here is a list of the methods of the Array object along with their description −

这些方法是使用 Array 类本身调用的 −

These methods are invoked using the Array class itself −

Sr.No.

Name & Description

1

from() Creates a shallow copy of the array.

2

isArray() Returns boolean values based on the argument is an array.

3

Of() Creates an array from multiple arguments.

这些方法使用 Array 类的实例调用 −

These methods are invoked using the instance of the Array class −

Sr.No.

Name & Description

1

at() To get element from the particular index.

2

concat() Returns a new array comprised of this array joined with another array (s) and/or value(s).

3

copyWithin() To Copy part of the array into the same array at different locations.

4

entries() To get each entry of the array.

5

every() Returns true if every element in this array satisfies the provided testing function.

6

fill() To fill the array with static values.

7

filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true.

8

find() To find an element satisfying the condition.

9

findIndex() To find an index of the element satisfying the condition.

10

findLast() To find an element satisfying the condition from the last.

11

findLastIndex() To find an index of the element satisfying the condition from the last.

12

flat() To flatten the array.

13

flatMap() To get a new array after flattening the array.

14

forEach() Calls a function for each element in the array.

15

Includes() Returns a boolean value if the array contains the specific element.

16

indexOf() Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.

17

join() Joins all elements of an array into a string.

18

Keys() Returns an array iterator containing the key for each array element.

19

lastIndexOf() Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.

20

map() Creates a new array with the results of calling a provided function on every element in this array.

21

pop() Removes the last element from an array and returns that element.

22

push() Adds one or more elements to the end of an array and returns the new length of the array.

23

reduce() Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value.

24

reduceRight() Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value.

25

reverse() Reverses the order of the elements of an array — the first becomes the last, and the last becomes the first.

26

shift() Removes the first element from an array and returns that element.

27

slice() Extracts a section of an array and returns a new array.

28

some() Returns true if at least one element in this array satisfies the provided testing function.

29

toSorted() Sorts the elements of an array in a specific order.

30

sort() Sorts the elements of an array.

31

splice() Adds and/or removes elements from an array.

32

toLocaleString() To convert array elements into the string.

33

toReversed() Returns a reverse of the array.

34

toSpliced() This method returns a new array with some elements removed and/or replaced at a given index.

35

toString() Returns a string representing the array and its elements.

36

unshift() Adds one or more elements to the front of an array and returns the new length of the array.

37

values() To get an iterator containing values of each array index.

38

with() This method returns a new array with the element at the given index replaced with the given value.

Basic Examples of JavaScript Array Object

在以下示例中,我们演示了 JavaScript 数组对象的基本方法和属性的使用——

In the following examples, we have demonstrated the usage of basic methods and properties of JavaScript Array Object −

Example (Creating JavaScript Array Object)

在下面的示例中,数组 “strs” 使用作为 Array() 构造函数的参数传递的字符串值进行初始化。

In the example below, the array ‘strs’ is initialized with the string values passed as an Array() constructor’s argument.

“cars” 数组包含 20 个未定义的元素。如果您传递多个数字值,它将定义包含这些元素的数组,但需要注意对 array() 构造函数传递单个数字参数。

The ‘cars’ array contains 20 undefined elements. If you pass multiple numeric values, it defines the array containing those elements but needs to be careful with a single numeric argument to the array() constructor.

<html>
<head>
   <title> JavaScript - Array() constructor </title>
</head>
<body>
   <p id = "demo"> </p>
   <script>
      const output = document.getElementById("demo");

      let strs = new Array("Hello", "World!", "Tutorials Point");
      output.innerHTML += "strs ==> " + strs + "<br>";

      let cars = new Array(20);
      output.innerHTML += "cars ==> " + cars + "<br>";
   </script>
</body>
</html>

执行以上程序以查看所需输出。

Execute the above program to see the desired output.

strs ==> Hello,World!,Tutorials Point
cars ==> ,,,,,,,,,,,,,,,,,,,

Example (Creating Arrays Using Array Literal)

在下面的示例中,我们创建了不同的数组。arr1 数组包含数字,arr2 数组包含字符串,arr3 数组包含布尔值。

In the example below, we have created different arrays. The arr1 array contains the numbers, the arr2 array contains the strings, and the arr3 array contains the boolean values.

<html>
<head>
   <title> JavaScript - Array literals </title>
</head>
<body>
   <p id = "output"> </p>
   <script>
      const output = document.getElementById("output");

      const arr1 = [10, 40, 50, 60, 80, 90];  // Array of numbers
      const arr2 = ["Hello", "Hi", "How", "are", "you?"]; // Array of strings
      const arr3 = [true, false, true, true]; // Array of booleans

      output.innerHTML += "arr1 ==>  " + arr1 + "<br>";
      output.innerHTML += "arr2 ==>  " + arr2 + "<br>";
      output.innerHTML += "arr3 ==>  " + arr3 + "<br>";
   </script>
</body>
</html>

执行以上程序以查看所需输出。

Execute the above program to see the desired output.

arr1 ==> 10,40,50,60,80,90
arr2 ==> Hello,Hi,How,are,you?
arr3 ==> true,false,true,true

Accessing JavaScript Array Elements

数组索引从 0 开始。因此,您可以使用其索引访问数组元素。

The array index starts from 0. So, you can access the array element using its index.

let number = arr[index]

在上面的语法中,“arr” 是一个数组,“index” 是我们要从中访问数组元素的一个数字。

In the above syntax, ‘arr’ is an array, and ‘index’ is a number from where we need to access the array element.

在下面的示例中,我们创建了数字数组并从数组的第 0 和第 2 个索引访问元素。第 0 个索引处的元素为 1,第 2 个索引处的元素为 6。

In the example below, we have created the array of numbers and accessed the elements from the 0th and 2nd index of the array. The element at the 0th index is 1, and the element at the 2nd index is 6.

<html>
<head>
   <title> JavaScript - Accessing array elements </title>
</head>
<body>
   <p id = "output"> </p>
   <script>
      const nums = [1, 5, 6, 8, 90];
      document.getElementById("output").innerHTML =
      "Element at 0th index is : " + nums[0] + "<br>" +
      "Element at 2nd index is : " + nums[2];
   </script>
</body>
</html>
Element at 0th index is : 1
Element at 2nd index is : 6

JavaScript Array length

数组的 “length” 属性用于查找数组的长度。

The ‘length’ property of the array is used to find the length of the array.

let len = arr.length;

在下面的示例中,“length” 属性返回 5,因为数组包含 5 个元素。

In the example below, the ‘length’ property returns 5, as array contains 5 elements.

<html>
<head>
   <title> JavaScript - Array length </title>
</head>
<body>
   <p id = "output"> </p>
   <script>
      const nums = [1, 5, 6, 8, 90];
      document.getElementById("output").innerHTML =
      "Array length is : " + nums.length;
   </script>
</body>
</html>
Array length is : 5

Adding a new element to the array

您可以使用 push() 方法在数组末尾插入元素。另一种方法是,您可以在索引等于数组长度处插入数组。

You can use the push() method to insert the element at the end of the array. Another solution is that you can insert the array at the index equal to the array length.

arr.push(ele)
OR
arr[arr.length] = ele;

在上面的语法中,“ele” 是要插入到数组中的新元素。此处,如果数组长度为 N,则数组包含从 0 到 N – 1 索引的元素。因此,我们可以在第 N 个索引处插入新元素。

In the above syntax, ‘ele’ is a new element to insert into the array. Here, if the array length is N, the array contains elements from 0 to N – 1 index. So, we can insert the new element at the Nth index.

在下面的示例中,我们使用 push() 方法将 6 插入到数组中。此外,我们使用 “length” 属性在末尾插入元素。

In the example below, we insert 6 to the array using the push() method. Also, we used the ‘length’ property to insert the element at the end.

<html>
<body>
   <p id = "output"> </p>
   <script>
      const output = document.getElementById("output");
      const nums = [1, 2, 3, 4, 5];
      nums.push(6); // Inserting 6 at the end
      output.innerHTML += "Updated array is : " + nums + "<br>";
      nums[nums.length] = 7; // Inserting 7
      output.innerHTML += "Updated array is : " + nums + "<br>"
   </script>
</body>
</html>

正如我们从输出中看到的那样,已添加提供的元素。

As we can see in the output, provided element has been added.

Updated array is : 1,2,3,4,5,6
Updated array is : 1,2,3,4,5,6,7

Updating JavaScript Array Elements

要更新任何数组元素,您可以访问数组索引并更改其值。

To update any array element, you can access the array index and change its value.

arr[index] = ele;

在上面的语法中,“index” 是我们需要使用 “ele” 值更新值的索引。

In the above syntax, ‘index’ is an index where we need to update a value with the ‘ele’ value.

在下面的示例中,我们会更新数组中第一个索引处的元素。

In the example below, we update the element at the first index in the array.

<html>
<body>
   <p id = "output"> </p>
   <script>
      const nums = [1, 2, 3, 4, 5];
      nums[0] = 100; // Updating first element
      document.getElementById("output").innerHTML =
      "Updated array is : " + nums;
   </script>
</body>
</html>
Updated array is : 100,2,3,4,5

Traversing a JavaScript Array

您可以使用循环遍历数组中的每个元素。不过,已存在一些内建方法来遍历数组,我们将在后面的章节中看到这些方法。

You can use the loop to traverse through each array element. However, some built-in methods exist to traverse the array, which we will see in later chapters.

for (let p = 0; p < nums.length; p++) {
   // Access array using the nums[p]
}

在下面的代码中,数组包含 5 个数字。我们使用 for 循环来遍历数组并打印每个元素。

In the below code, the array contains 5 numbers. We used the for loop to traverse the array and print each element.

然而,while 和 do-while 循环也能用来遍历数组。

However, while and do-while loops can also be used to traverse the array.

<html>
<body>
   <p id = "demo"> </p>
   <script>
      const output = document.getElementById("demo");
      const nums = [1, 2, 3, 4, 5];
      for (let p = 0; p < nums.length; p++) {
         output.innerHTML += "nums[" + p + "] ==> " + nums[p] + "<br>";
      }
   </script>
</body>
</html>
nums[0] ==> 1
nums[1] ==> 2
nums[2] ==> 3
nums[3] ==> 4
nums[4] ==> 5