Table of Contents
Array object instance properties and methods
Create array
Add and update values ​​in arrays
Length and index
设置数组长度可以添加或删除值
包含其他数组的数组(又名多维数组)
前后循环数组
结论
Home Web Front-end JS Tutorial Reconstruct an array

Reconstruct an array

Sep 03, 2023 am 08:37 AM
Array construction rebuild Array reorganization

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

使用预定义的 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>
Copy after login

提供预定义的 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>
Copy after login

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

由于数组可以保存任何有效的 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>
Copy after login

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


前后循环数组

循环数组的最简单且可以说是最快的方法是使用 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>
Copy after login

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

示例: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>
Copy after login

结论

现在,如果您想知道为什么我没有在这里显示 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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Can PowerPoint run JavaScript? Can PowerPoint run JavaScript? Apr 01, 2025 pm 05:17 PM

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

See all articles