[Effective JavaScript note] 46th: Use arrays instead of dictionaries to store ordered collections

Source: Internet
Author: User

object property Unordered

The JS object is a collection of unordered attributes.

var obj={};obj.a=10;obj.b=30;

attribute A and attribute B do not have anyone who said it before. For...in loops, it is possible to output which properties first.
Getting and setting different properties is independent of the order, and will produce the same result with roughly the same efficiency.
That is, access to property A and access to property B, there is no faster access to the said. The ES standard does not specify any particular order in which the attribute is stored, even if the enumeration object is not involved. The for...in Loop selects a certain order to enumerate the properties of the object, and the standard allows the JS engine to freely select a sequence whose choice subtly alters the behavior of the program.
If an object is required to represent an ordered map from string to value, an ordered report is created.

function report(highScores){    var res=‘‘;    var i=1;    for(var name in highScores){        res+=i+‘. ‘+highScores[name].name+‘:‘+highScores[name].points+‘\n‘;        i++;    }    return res;}report([{name:‘张三‘,points:1110111},        {name:‘李四‘,points:1110102},        {name:‘王五‘,points:1110911}]);/*预期的结果"1. 张三:11101112. 李四:11101023. 王五:1110911"*//*实际的结果 chrome,ff,ie"1. 张三:11101112. 李四:11101023. 王五:1110911"*/

The above code matches the order and index of the tests in several environments, but some other environments can choose to store and enumerate the properties of the object in a different order, so the report may cause different strings to be generated, resulting in incorrect reports.
The order dependency of a program on an object enumeration is not explicitly. If you have not tested your code in more than one JS environment, your program may cause changes due to the different outputs of the for...in loop.

Dependent data order

If there is a strong dependency on the order of entries in the data structure, the array is preferred instead of the dictionary. If the above report function receives an array instead of an object, it can be looped with a for to ensure that all environment order is consistent and correct.

function report(highScores){    var res=‘‘;    for(var i=0,n=highScores.length;i < n;i++){        var score=highScores[i];        res+=(i+1)+‘. ‘+score.name+‘:‘+score.points+‘\n‘;    }    return res;}report([{name:‘张三‘,points:1110111},        {name:‘李四‘,points:1110102},        {name:‘王五‘,points:1110911}]);//"1. 张三:11101112. 李四:11101023. 王五:1110911"

By receiving an array of objects, each object contains the name and points properties, and the above code can traverse all the elements in 0~highscores.length-1 order.

Floating-point operations

Suppose you have a movie dictionary that maps titles and levels.

var ratings={    ‘Good Will Hunting‘:0.8,    ‘Mystic River‘:0.7,    ‘21‘:0.6,    ‘Doubt‘:0.9};

Rounding of floating-point arithmetic operations can result in a dependency on the calculation order. See article 2nd: Understanding the floating point of JavaScript. When you combine enumerations that do not have a defined order, you can cause loops to be unpredictable.

var total=0,count=0;for(var key in ratings){    total+=ratings[key];    count++;}total/=count;total;//chrome里:0.7499999999999999

In the popular JS environment, the loop is actually executed in a different order. Some environments enumerate the key of the object in the following order to get the following value.

(0.8+0.7+0.6+0.9)/4 //0.75

Some environments always enumerate the potential array indexes first and then the other keys. Movie 21 is an integer value that can be indexed as an array, which is first enumerated to get the following result.

(0.6+0.8+0.7+0.9)/4 //0.7499999999999999

You can see that chrome above is the first to enumerate the potential array indexes.

Integer calculation floating point type

For the calculation of floating-point numbers, the floating-point numbers can be converted to integers and then converted back to floating-point numbers. The order in which integers are evaluated can be in any order. Therefore, the enumeration order of the object's property values is not important. The code is as follows

(8+7+6+9)/4/10 //0.75(6+8+7+9)/4/10 //0.75
Tips
    • Using for...in loops to enumerate object properties should be independent of order

    • If the data in the clustered Operations dictionary ensures that the aggregation operation is independent of the order

    • Use arrays instead of dictionaries to store ordered collections

[Effective JavaScript note] 46th: Use arrays instead of dictionaries to store ordered collections

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.