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

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

问题描述

为什么我遇到这个问题: 我试图解决算法问题,并且需要返回大多数情况下出现在数组中的数字.像[5,4,3,2,1,1]应该返回1. 而且,当两个数字与最大出现次数同时出现时,第一个出现.像[5,5,2,2,1,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,根据定义,该JS不保持顺序.将其视为键=>值映射.

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.

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

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