Home Web Front-end JS Tutorial Sparse arrays and dense arrays in JavaScript [Translation]_javascript skills

Sparse arrays and dense arrays in JavaScript [Translation]_javascript skills

May 16, 2016 pm 05:49 PM

1. Sparse array
Creating a sparse array of specified length is very simple:
Copy code Code As follows:

> var a = new Array(3);
> a
[ , , ]
> a.length
3
> a[0]
undefined

When you iterate through it, you will find that it has no elements. JavaScript will skip these gaps.
Copy code The code is as follows:

> a.forEach(function (x, i) { console.log(i ". " x) });
> a.map(function (x, i) { return i })
[ , , ]

Translator’s Note: There are some other situations A sparse array will be generated, such as
Copy code The code is as follows:

>var arr = [ ];
>arr[0] = 0;
>arr[100] = 100>a.forEach(function (x, i) { console.log(i ". " x) }); 0. 0100. 100

2. Dense array

Brandon Benvie recently mentioned a tip for creating dense arrays in the es-discuss email discussion group:

Copy code The code is as follows:

> var a = Array.apply(null, Array(3));
> ; a
[ undefined, undefined, undefined ]


The above statement is actually equivalent to:

Array(undefined, undefined, undefined)

But on the surface, it seems that there is not much difference between this array and the previous sparse array:
Copy code The code is as follows :

> a.length
3
> a[0]
undefined

However, you can now iterate over these arrays elements, you can also reassign a value to each element:
Copy code The code is as follows:

> a.forEach(function (x, i) { console.log(i ". " x) });
0. undefined
1. undefined
2. undefined

> a.map(function (x, i) { return i })
[ 0, 1, 2 ]

Translator’s Note: In fact, JavaScript does not have a conventional array. All arrays are actually objects, but they automatically manage some "number" attributes and length attributes. To put it more directly, arrays in JavaScript have no index at all, because the index should be a number, and the index of an array in JavaScript is actually It is a string. arr[1] is actually arr["1"]. If arr["1000"] = 1, arr.length will automatically become 1001. The fundamental reason for these performances is that objects in JavaScript are characters Key-value pairs string to any value. Note that the key can only be a string. This is similar to AWK. If you don't believe it, try awk 'BEGIN{a[1]=1;print(a["1"])}'. Maybe This is because Brendan Eich when inventing JavaScript referred to a lot of awk designs . However, currently, ES6 already has a Map type similar to Java and other languages, and the keys can It is a value of any type. Please refer to the MDN document I translated Map

3. Another trick
Another trick was also mentioned in the email:
Copy code The code is as follows:

> Array.apply(null, Array(3)).map(Function.prototype .call.bind(Number))
[ 0, 1, 2 ]

This is roughly equivalent to the following writing
Copy Code The code is as follows:

Array.apply(null, Array(3)).map(
function (x,i,...) { return Number.call(x,i,...) })

Note that x is the first parameter of the call method, which is used as the this value in the Number function. This value has no meaning and is equivalent to being ignored. I prefer the following writing method that can be understood at a glance :
Copy code The code is as follows:

Array.apply(null, Array(3)) .map(function (x,i) { return i })

Translator’s Note:
Copy code The code is as follows:

Array.apply(null, Array(3)).map(Function.prototype.call.bind(Number))
//Equivalent to Array.apply (null, Array(3)).map(Function.prototype.call,Number)

Although it is clearer to use a custom function, the custom function is definitely not as fast as the native method. For example Example:

Copy code The code is as follows:

var a = ["aaa " , " bbb", " ccc "]
a.map(function(x) { return x.trim(); }); // ['aaa', 'bbb', 'ccc']
a .map(Function.prototype.call, String.prototype.trim); // ['aaa', 'bbb', 'ccc']

Use the map method above to trim each array Although it is difficult to understand the spaces of elements using the native method, it is very efficient. If you don’t understand, you can check the MDN document I translated Array.prototype.map()

4. Actual Purpose?

In actual production, using the method of creating dense arrays mentioned above will make it impossible for others to read your code. Therefore, it would be better to encapsulate it into a tool function, such as _.range :

Copy code The code is as follows:

> _.range(3)
[ 0, 1, 2 ]

Used in conjunction with map, you can fill the entire array with a specified value.
Copy the code The code is as follows:

> _.range(3).map(function () { return "a" })
[ 'a ', 'a', 'a' ]

Translator's Note: In other languages, there are convenient ways to generate increasing lists of numbers, such as using 1..100 in perl and ruby, and python Using range(100), another common requirement is to generate a string that repeats a certain field. In ruby ​​and python, you can use "a"*100, in perl, use "a"x100, in JavaScript , you can use Array(100).join("a")

5. Related articles

  1. Iterating over arrays and objects in JavaScript(walled)
  2. Trying out Underscore on Node.js(walled)
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. �...

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

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

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