


Sparse arrays and dense arrays in JavaScript [Translation]_javascript skills
Creating a sparse array of specified length is very simple:
> 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.
> 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
>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:
> 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:
> a.length
3
> a[0]
undefined
However, you can now iterate over these arrays elements, you can also reassign a value to each element:
> 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:
> Array.apply(null, Array(3)).map(Function.prototype .call.bind(Number))
[ 0, 1, 2 ]
This is roughly equivalent to the following writing
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 :
Array.apply(null, Array(3)) .map(function (x,i) { return i })
Translator’s Note:
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:
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 :
> _.range(3)
[ 0, 1, 2 ]
Used in conjunction with map, you can fill the entire array with a specified value.
> _.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

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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 in JavaScript? When processing data, we often encounter the need to have the same ID...

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.

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. �...

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

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

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.
