Home  >  Article  >  Web Front-end  >  Reconstruct an array

Reconstruct an array

PHPz
PHPzOriginal
2023-09-03 08:37:11556browse

Reconstruct an array

An array is an ordered list of values, usually created for looping over numerically indexed values, starting at index zero. What you need to know is that an array is a collection in numerical order, not an object with property names associated with values ​​that are not in numerical order. Essentially, arrays use numbers as lookup keys, while objects have user-defined property names. JavaScript does not have a true associative array, but you can use objects to implement the functionality of an associative array.

In the example below, I store four strings in myArray and I can access them using numeric indexing. I compare and contrast myArray with object literals that mimic associative arrays.

Example: sample133.html

<!DOCTYPE html><html lang="en"><body><script>

	var myArray = ['blue', 'green', 'orange', 'red'];

	console.log(myArray[0]); // Logs blue using the 0 index to access the string in myArray.

	// Versus

	var myObject = { // aka an associative array/hash, known as an object in JavaScript.
		'blue': 'blue',
		'green': 'green',
		'orange': 'orange',
		'red': 'red'
	};

	console.log(myObject['blue']); // Logs blue.

</script></body></html>

Arrays can hold values ​​of any type, and these values ​​can be updated or deleted at any time.

If you need hashes (also called associative arrays), objects are the closest solution.

Array() is just a special type of Object(). That is, an Array() instance is basically an Object() instance, with a few extra functions (.length and built-in numeric indexing).

The values ​​contained in an array are often called elements.


Array() Parameters

You can pass the value of an array instance to the constructor as comma-separated arguments (new Array('foo', 'bar');). Array() The constructor can take up to 4,294,967,295 parameters.

However, if only one argument is sent to the Array() constructor, and that value is an integer ('1', '123', or '1.0'), then it will be used to set The length of the array and will not be used as the value contained in the array.

Example: sample134.html

<!DOCTYPE html><html lang="en"><body><script>

	var foo = new Array(1, 2, 3);
	var bar = new Array(100);

	console.log(foo[0], foo[2]); // Logs '1 3'.
	console.log(bar[0], bar.length); // Logs 'undefined 100'.

</script></body></html>

Array() Properties and methods

Array() The object has the following properties (excluding inherited properties and methods):

Properties (Array.prototype):

  • prototype

Array object instance properties and methods

Array object instances have the following properties and methods (excluding inherited properties and methods):

Instance properties (var myArray = ['foo', 'bar']; myArray.length;):

  • Constructor
  • length

Instance method (var myArray = ['foo']; myArray.pop();):

  • pop()
  • push()
  • Reverse()
  • shift()
  • sort()
  • splice()
  • unshift()
  • concat()
  • join()
  • slice()

Create array

Like most objects in JavaScript, array objects can be created using the new operator in combination with the Array() constructor or using literal syntax.

In the following example, I use the Array() constructor to create an array of myArray1 with predefined values, and then use literal notation to create myArray2.

Example: sample135.html

<!DOCTYPE html><html lang="en"><body><script>

	// Array() constructor.
	var myArray1 = new Array('blue', 'green', 'orange', 'red');

	console.log(myArray1); // Logs ["blue", "green", "orange", "red"]

	// Array literal notation.
	var myArray2 = ['blue', 'green', 'orange', 'red'];

	console.log(myArray2); // logs ["blue", "green", "orange", "red"]

</script></body></html>

It is more common to define an array using literal syntax, but it should be noted that this shortcut only hides the use of the Array() constructor.

In fact, an array literal is usually all you need.

No matter how the array is defined, if you don't provide any predefined values ​​to the array, it will still be created, but it will not contain any values.


Add and update values ​​in arrays

Values ​​can be added to the array at any time at any index. In the following example, we add a value to the numeric index 50 of an empty array. What about all indices before 50? Well, like I said, you can add a value to an array at any time at any index. However, if you add a value to numeric index 50 of an empty array, JavaScript will fill all necessary indices before it with undefined values.

Example: sample136.html

<!DOCTYPE html><html lang="en"><body><script>

	var myArray = [];
	myArray[50] = 'blue';
	console.log(myArray.length); /* Logs 51 (0 is counted) because JS created values 0 to 50 before "blue".*/

</script></body></html>

Additionally, given the dynamic nature of JavaScript and the fact that JavaScript is not strongly typed, array values ​​can be updated at any time and the values ​​contained in the index can be any legal value. In the example below, I change the value at numeric index 50 to an object.

Example: sample137.html

<!DOCTYPE html><html lang="en"><body><script>

	var myArray = [];
	myArray[50] = 'blue';
	myArray[50] = { 'color': 'blue' }; // Change object type from string to Object() object.
	console.log(myArray[50]); // Logs 'Object {color="blue"}'.

	// Using brackets to access the index in the array, then the property blue.
	console.log(myArray[50]['color']); // Logs 'blue'.

	// Using dot notation.
	console.log(myArray[50].color); // Logs 'blue'.

</script></body></html>

Length and index

Array index values ​​start from zero. This means that the first numeric slot in the array that holds the value looks like myArray[0]. This can be a bit confusing, if I create an array containing a single value, the value's index is 0, and the length of the array is 1. Make sure you understand that the length of an array represents the number of values ​​contained in the array, and that numerical indexing of arrays starts at zero.

In the following example, the string value blue is contained at numeric index 0 in the myArray array, but since the array contains a value, the length of the array is 1 .

Example: sample138.html

<!DOCTYPE html><html lang="en"><body><script>

	var myArray = ['blue'] // The index 0 contains the string value 'blue'.
	console.log(myArray[0]); // Logs 'blue'.
	console.log(myArray.length); // Logs 1.

</script></body></html>

使用预定义的 length 定义数组

正如我之前提到的,通过将单个整数参数传递给 Array() 构造函数,可以预定义数组长度或其将包含的值的数量。在这种情况下,构造函数会抛出一个异常,并假设您要设置数组的长度,而不是用值预先填充数组。

在下一个示例中,我们设置了预定义长度为 3 的 myArray 数组。同样,我们配置数组的长度,而不是向其传递要存储在 0 索引处的值。

示例:sample139.html

<!DOCTYPE html><html lang="en"><body><script>

	var myArray = new Array(3);
	console.log(myArray.length); // Logs 3 because we are passing one numeric parameter.
	console.log(myArray[0]); // Logs undefined.

</script></body></html>

提供预定义的 length 将为每个数字索引(最多指定的长度)提供 undefined 的关联值。

您可能想知道是否可以创建一个仅包含一个数值的预定义数组。是的,它是通过使用文字形式 var myArray = [4].


设置数组长度可以添加或删除值

数组对象的 length 属性可用于获取或设置数组的长度。如前所示,设置长度大于数组中包含的实际值数会将 undefined 值添加到数组中。您可能没想到的是,您实际上可以通过将长度值设置为小于数组中包含的值的数量来从数组中删除值。

示例:sample140.html

<!DOCTYPE html><html lang="en"><body><script>

	var myArray = ['blue', 'green', 'orange', 'red'];
	console.log(myArray.length); // Logs 4.
	myArray.length = 99;
	console.log(myArray.length); // Logs 99, remember we set the length, not an index.
	myArray.length = 1; // Removed all but one value, so index [1] is gone!
	console.log(myArray[1]); // Logs undefined.

	console.log(myArray); // Logs '["blue"]'.

</script></body></html>

包含其他数组的数组(又名多维数组)

由于数组可以保存任何有效的 JavaScript 值,因此数组可以包含其他数组。完成此操作后,包含封装数组的数组将被视为多维数组。访问封装的数组是通过括号链接完成的。在下面的示例中,我们创建一个包含一个数组的数组文字,在其中创建另一个数组文字,在其中创建另一个数组文字,其中包含索引 0 处的字符串值。

示例:sample141.html

<!DOCTYPE html><html lang="en"><body><script>

	var myArray = [[[['4th dimension']]]];
	console.log(myArray[0][0][0][0]); // Logs '4th dimension'.

</script></body></html>

这个代码示例相当愚蠢,但您会明白数组可以包含其他数组,并且您可以无限期地访问封装的数组。


前后循环数组

循环数组的最简单且可以说是最快的方法是使用 while 循环。

在下面的代码中,我们从索引的开头循环到结尾。

示例:sample142.html

<!DOCTYPE html><html lang="en"><body><script>

	var myArray = ['blue', 'green', 'orange', 'red'];

	var myArrayLength = myArray.length; // Cache array length to avoid unnecessary lookup.
	var counter = 0; // Set up counter.

	while (counter < myArrayLength) { // Run if counter is less than array length.
		console.log(myArray[counter]); // Logs 'blue', 'green', 'orange', 'red'.
		counter++; // Add 1 to the counter.
	}

</script></body></html>

现在我们从索引末尾循环到开头。

示例:sample143.html

<!DOCTYPE html><html lang="en"><body><script>

	var myArray = ['blue', 'green', 'orange', 'red'];

	var myArrayLength = myArray.length;
	while (myArrayLength--) {                // If length is not zero, loop and subtract 1.
		console.log(myArray[myArrayLength]);  // Logs 'red', 'orange', 'green', 'blue'.
	}

</script></body></html>

结论

现在,如果您想知道为什么我没有在这里显示 for 循环,那是因为 while 循环的移动部分较少,而且我相信它们更容易阅读。

关于数组的这篇文章就这样结束了。

The above is the detailed content of Reconstruct an array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn