如何防止对象数字属性的自动排序? [英] How to prevent automatic sort of Object numeric property?

查看:96
本文介绍了如何防止对象数字属性的自动排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我会遇到这个问题:我试图解决一个算法问题,我需要返回数组中大部分时间出现的数字.像 [5,4,3,2,1,1] 应该返回 1.而且当两个数字与最大出现次数同时出现时,第一个出现.像 [5,5,2,2,1] 返回 5 因为 5 先出现.我使用一个对象来存储每个数字的外观.关键是数字本身.

Why I met this problem: I tried to solve an algorithm problem and I need to return the number which appeared most of the times in an array. Like [5,4,3,2,1,1] should return 1. And also when two number appear same time as the maximum appearance return the one came first. Like [5,5,2,2,1] return 5 because 5 appear first. I use an object to store the appearance of each number. The key is the number itself.

所以当输入是 [5,5,2,2,1] 我的对象应该是Object {5: 2, 2: 2, 1: 1} 但实际上我得到了 Object {1: 1, 2: 2, 5: 2}因此,当我使用 for..in 迭代对象时,返回的是 2 而不是 5 .所以这就是我问这个问题的原因.

So When the input is [5,5,2,2,1] my object should be Object {5: 2, 2: 2, 1: 1} but actually I got Object {1: 1, 2: 2, 5: 2} So When I use for..in to iterate the object I got 2 returned instead of 5 . So that's why I asked this question.

此问题出现在 Chrome 控制台中,我不确定这是否是常见问题:当我运行以下代码时

This problem occurs in Chrome console and I'm not sure if this is a common issue: When I run the following code

var a = {};
a[0]=1;
a[1]=2;
a[2]=3;

a 是:Object {0: 1, 1: 2, 2: 3}

但是当我颠倒分配顺序时:

But when I reverse the order of assignment like:

 var a = {};
 a[2]=3;
 a[1]=2;
 a[0]=1;

a 也是:Object {0: 1, 1: 2, 2: 3}数字属性自动按升序排序.我试过前缀或后缀像

a is also:Object {0: 1, 1: 2, 2: 3} The numeric property automatic sorted in ascending order. I tried prefix or postfix the numeric property like

var a = {};
a['p'+0]=1;
a['p'+1]=2;
a['p'+2]=3;
console.log(a);//Object {p0: 1, p1: 2, p2: 3}

这保持了财产秩序.这是解决问题的最佳方法吗?无论如何要防止这种自动排序行为?这只发生在 Chrome V8 JavaScript 引擎中吗?提前谢谢你!

And this keep the property order. Is this the best way to solve the problem? And is there anyway to prevent this auto sort behavior? Is this only happen in Chrome V8 JavaScript engine? Thank you in advance!

推荐答案

您正在使用 JS object,根据定义,它不保持顺序.将其视为键 => 值映射.

You are using a JS object, that by definition does not keep order. Think of it as a key => value map.

您应该使用 array,它会保留您在插入它的 index 上插入的任何内容.把它想象成一个列表.

You should be using an array, that will keep whatever you insert on the index you inserted it into. Think of it as a list.

还要注意,您实际上没有颠倒了赋值的顺序",因为您每次都在同一个索引上插入元素.

Also notice that you did not in fact "reverse the order of the assignment", because you inserted elements on the same index every time.

这篇关于如何防止对象数字属性的自动排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆