search
HomeWeb Front-endJS Tutorial3 things you didn't know about JavaScript arrays

In programming languages, array (Array) is a very commonly used function; it is a special variable that can be used to store multiple values ​​at the same time. However, there is much more to explore about the power of arrays when it comes to JavaScript.

In this article, we will discuss three not-so-common functions of JavaScript arrays.

1. Add custom attributes to arrays

When searching for the definition of JavaScript arrays on the Internet, you will find that almost everyone has the same definition of arrays. Same thing: an object.

In fact, everything we process with JavaScript can be regarded as an object. There are two data types in JavaScript, basic types and object types, but basic types are basically included in object types.

Arrays, functions, and Date are all predefined objects in JavaScript, and they all contain methods, properties, and their own standardized syntax.

JavaScript arrays have the following three different properties:

1 The index of the array is also its property

2 Built-in properties

3 You can add your own Define attributes

The first two attributes are well-known to everyone, and you may use them every day, but I still want to say a few more words here, and then talk about how to add custom attributes to an array.

Use index as attribute

JavaScript arrays can use square bracket syntax, such as var ary = ["orange","apple","lychee"];.

The index of an array element is basically an attribute, and the name of its attribute is always a non-negative integer.

The index element pair of an array is similar to the key-value pair of an object. Indexes are a unique property of array objects, unlike other built-in properties, they can be configured individually via square brackets, such as ary[3] = "peach";.

Built-in properties

Arrays have built-in properties, such as array.length. The length attribute contains an integer value representing the length of the array.

Generally, built-in properties can often be found in predefined JavaScript objects such as arrays. Built-in properties and built-in methods are combined to customize ordinary objects to meet different needs.

When accessing built-in properties, you can use two syntaxes: object.key or object["key"]. In other words, when getting the length of an array, you can write ary["length"].

Creating custom properties for array objects

Now let’s talk about how to add custom properties to arrays. An array is a predefined object that stores different kinds of values ​​in different indices.

Normally, we don’t need to add custom attributes to arrays; for this reason, when we first learned JavaScript, no one told us that we could add attributes to arrays. In fact, if you want to add key-value pairs to an array in the same way as a regular object, you can also use a regular object for that purpose. However, this is not to say that there are no special cases at all. In some cases, you can take advantage of the fact that an array is an object and add one or more custom properties to it.

For example, you can add a custom attribute to the array that identifies the "kind" or "class" of the element. Please see the example below for details:

 var ary = ["orange","apple","lychee"];

ary.itemClass = "fruits";

console.log(ary + " are " + ary.itemClass);

Please note that the custom attributes you add to the array are all countable, that is to say, it can be selected by for...in and other loops.

2. Looping through array elements

You may say: "I've known this for a long time." Yes, you already know how to index array elements. But you may feel that the statement "looping through array elements" is a bit abstract, because what we really loop through is the index of the array.

Since array indexes are composed of non-negative integers, usually we will start from 0 until the full length of the array, iterate the integer value, and then use the iterated value to get an array element based on a specific index.

However, since the emergence of ECMAScript6, we can no longer care about the index and directly loop through the array value, and this operation can be completed using a for...of loop.

In an array, the for...of loop can loop through the array elements according to the order of the index. In other words, it can control the iteration of the index and obtain an existing array value according to the given index. This loop is useful if you just want to loop through all array elements and use them.

 var ary = ["orange","apple","lychee"];

for (let item of ary){

  console.log(item);

}

For comparison, with the regular for loop, we get the indices instead of the values as output.

 

var ary = ["orange","apple","lychee"];

for (var item = 0; item < ary.length; item++){

  console.log(item);

}

3. The number of elements is not equal to its length

Generally, when we talk about the length of an array, we think that its length is either the number of array values, or It is the length we set manually for the array. But in fact, the length of the array depends on the largest existing index inside it.

长度是一个非常灵活的属性。无论你是否曾实现调整了数组的长度,只要你不断的给数组添加新的值,它的长度也会随之增长。

 var ary = [];

ary.length = 3;

console.log(ary.length);

ary[5] = "abcd";

console.log(ary.length);

在上面的例子中,你可以看到我给数组的索引5只指定了一个值,之后长度变成了6。现在,如果你觉得给index 5添加一个值,数组就会自动创建索引0-4,那么你的推测就出现了错误。数组中并没有应经存在的索引0-4。你可以使用in operator来查看。

 var ary = [];

ary.length = 3;

console.log(ary.length);

ary[5] = "abcd";

console.log(ary.length);

console.log(0 in ary);

上面的ary数组被我们成为稀疏数组(sparse array),这个数组的索引不会持续的被创建,而且索引之间有空气。sparse数组的对立面为密集数组(dense array)。密集数组的索引会被持续的创建,其元素的数量等于其长度。

数组的长度属性也可以用来缩短数字,确保数组中索引的最大数量永远小于数组本身,因为在默认情况下,长度的数值永远会大于索引数量的最高值。

在下面的例子中,你可以看到,我利用减少ary数组长度的方式,社区了索引5中的元素。

var ary = [];

ary.length = 3;

console.log(ary.length);

ary[5] = "abcd";

console.log(ary.length);

ary.length = 2;

console.log(ary.length);

console.log(ary[5]);

 以上就是关于JavaScript数组,你所不知道的3件事的内容,更多相关内容请关注PHP中文网(www.php.cn)! 



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
The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!