[Translation] sparse array and dense array in Javascript

Source: Internet
Author: User

Original (Wall): http://www.2ality.com/2012/06/dense-arrays.html

 

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:

 
> Var A = new array (3);> A [,]> A. length3> A [0] undefined

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

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

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

 
> Var arr = [];> arr [0] = 0;> arr [100] = 100>. 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:

 
> Var A = array. Apply (null, array (3);> A [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:

 
> A. length3> A [0] undefined

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

 
>. Foreach (function (x, I) {console. log (I + ". "+ x)}); 0. undefined1. undefined2. undefined>. 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:

 
> Array. Apply (null, array (3). Map (function. Prototype. Call. BIND (number) [0, 1, 2]

This is probably equivalent to the following statement:

 
> Array. Apply (null, array (3). Map (function. Prototype. Call. BIND (number) [0, 1, 2]

Note,XIs the first parameter of the call method.This valueThis value is meaningless and is equivalent to being ignored. I prefer the following method that can be easily understood at a Glance:

Array. Apply (null, array (3). Map (function (x, I) {return I })

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

 
VaR A = ["AAA", "BBB", "CCC"]. map (function (x) {return X. trim () ;}); // ['aaa', 'bbb ', 'ccc']. 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 hard for others to understand yourCodeSo it would be better to encapsulate it into a tool function, such_. Range:

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

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

 
> _. Range (3). Map (function () {return "A"}) ['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 Article
    1. Iterating over arrays and objects in JavaScript (already walled)
    2. Trying out underscore on node. js (wall-mounted)
Related Article

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.