快速获取对象属性中的最小/最大值 [英] Fast way to get the min/max values among properties of object

查看:967
本文介绍了快速获取对象属性中的最小/最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在javascript中有一个像这样的对象:

I have an object in javascript like this:

{ "a":4, "b":0.5 , "c":0.35, "d":5 }

是否有快速获得最小值的方法属性中的最大值,而不必遍历它们全部?因为我拥有的物体很大,我需要每两秒钟获得一次最小值/最大值。 (对象的值不断变化)。

Is there a fast way to get the minimum and maximum value among the properties without having to loop through them all? because the object I have is huge and I need to get the min/max value every two seconds. (The values of the object keeps changing).

推荐答案

在没有循环的情况下,无法在一般情况下找到最大值/最小值通过所有 n 元素(如果你从1到n-1,你怎么知道元素 n 是不是比当前更大(或更小)最大/分钟?

There's no way to find the maximum / minimum in the general case without looping through all the n elements (if you go from, 1 to n-1, how do you know whether the element n isn't larger (or smaller) than the current max/min)?

您提到值每隔几秒就会改变一次。如果您确切地知道哪些值发生了变化,您可以从先前的最大/最小值开始,并且只与新的值进行比较,但即使在这种情况下,如果其中一个值被修改为您的旧最大值/分钟,您可以需要再次遍历它们。

You mentioned that the values change every couple of seconds. If you know exactly which values change, you can start with your previous max/min values, and only compare with the new ones, but even in this case, if one of the values which were modified was your old max/min, you may need to loop through them again.

另一种选择 - 再次,只有当变化的值的数量很小时 - 才会将值存储在诸如树或堆,当新值到达时,您可以适当地插入(或更新)它们。但是,基于你的问题,你能否做到这一点并不明确。

Another alternative - again, only if the number of values which change are small - would be to store the values in a structure such as a tree or a heap, and as the new values arrive you'd insert (or update) them appropriately. But whether you can do that is not clear based on your question.

这篇关于快速获取对象属性中的最小/最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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