Sparse array and dense array in JavaScript [translate] _ javascript tips-js tutorial

Source: Internet
Author: User
In general, arrays in JavaScript are sparse, that is, there can be gaps between elements in the array, because an array is actually a key-value ing. this article explains how to create sparse arrays and non-sparse arrays. 1. sparse array
It is easy to create a sparse array with a specified length:

The Code is as follows:


> Var a = new Array (3 );
>
[,]
> A. length
3
> A [0]
Undefined


When you traverse it, you will find that it does not have elements. JavaScript will skip these gaps.

The Code is as follows:


> A. forEach (function (x, I) {console. log (I + "." + x )});
> A. map (function (x, I) {return I })
[,]


Note: In other cases, sparse arrays are generated, such

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 technique for creating dense arrays in the es-discuss email discussion group:

The Code is as follows:


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



The preceding statement is equivalent:

Array (undefined, undefined, undefined)

But on the surface, it seems that this array is not much different from the sparse array:

The Code is as follows:


> A. length
3
> A [0]
Undefined


However, you can now traverse these array elements and assign a new value to each element:

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]


Note: In fact, JavaScript does not have regular arrays. All arrays are actually objects, but some "Number" attributes and length attributes are automatically managed. more directly, arrays in JavaScript do not have indexes at all, because indexes should be numbers, while arrays in JavaScript are actually strings. arr [1] is actually arr ["1"], to arr ["1000"] = 1, arr. the length is automatically changed to 1001. the root cause of these performances is that the objects in JavaScript are key-value pairs from string to any value. note that the key can only be a string. this is similar to AWK. if you do not believe this, try awk 'in in {a [1] = 1; print (a ["1"])} '. maybe this is because Brendan Eich referred to a lot of awk designs when he invented JavaScript. however, ES6 now has a Map type similar to Java and other languages. The key can be of any type. see my translated MDN document Map

3. Another skill
The email also mentions another technique:

The Code is as follows:


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


This is probably equivalent to the following statement:

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. It serves as the value of this in the Number function. this value has no significance, and is equivalent to being ignored. I prefer the following method that can be easily understood at a Glance:

The Code is as follows:


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


Note:

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 user-defined functions are clearer, user-defined functions are certainly not faster than native functions. For example:

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']


The preceding map method is used to trim the space of each array element. It is hard to understand it though native method is used. but the efficiency is high. if you cannot understand it, you can view the MDN document Array that I have translated. prototype. map ()

4. What is the actual purpose?

In actual production, using the method described above to create intensive arrays will make it difficult for others to understand your code. Therefore, it is better to encapsulate a tool function, such_. Range:

The Code is as follows:


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


With map, you can use a specified value to fill the entire array.

The Code is as follows:


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


Note: in other languages, you can easily generate an incremental number list, such as using 1 in perl and ruby .. 100. range (100) is used in python. Another common requirement is to generate a string that repeats a field. In ruby and python, "a" * 100, use "a" x100 in perl and Array (100) in JavaScript ). join ("")

5. Related Articles

  1. Iterating over arrays and objects in JavaScript (already walled)
  2. Trying out Underscore on Node. js (wall-mounted)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.