angularjs:从几个变量中获取最高值

时间:2016-05-22 12:10:35

标签: javascript angularjs

使用一些计算我为变量分配了一些值。

            console.log("Gain_weight is "+ Gain_weight);
            console.log("Gain_smoking is "+ Gain_smoking);
            console.log("Gain_exercising is "+ Gain_exercising);
            console.log("Gain_foodhabits is "+ Gain_foodhabits);
            console.log("Gain_parent_heartattack is "+ Gain_parent_heartattack);
            console.log("Gain_alcohol "+ Gain_alcohol);
            console.log("Gain_occupation "+ Gain_occupation);
            console.log("Gain_workinghrs "+ Gain_workinghrs);

这里我有Gain_weight,Gain_smoking等的值。如何选择在AngularJS中分配最高值的变量?

2 个答案:

答案 0 :(得分:0)

假设您还想知道哪个值最高:

var gains = [Gain_weight, Gain_smoking, Gain_exercising, Gain_foodhabits, Gain_parent_heartattack, Gain_alcohol, Gain_occupation, Gain_workinghrs];
var gainLabels = ['Gain weight', 'Gain smoking', 'Gain exercising', 'Gain foodhabits', 'Gain parent heartattack', 'Gain alcohol', 'Gain occupation', 'Gain workinghrs'];
var maxGainValue = -Infinity;
var maxGainIndex = -1;
for (var i = 0; i < gains.length; i++) {
  if (maxGainValue < gains[i]) {
    maxGainValue = gains[i];
    maxGainIndex = i;
  }
}

console.log('The highest gain is ' + gainLabels[maxGainIndex] + ': ' + maxGainValue);

如果你只关心什么是最高值:

var maxGainValue = Math.max(Gain_weight, Gain_smoking, Gain_exercising, Gain_foodhabits, Gain_parent_heartattack, Gain_alcohol, Gain_occupation, Gain_workinghrs)

答案 1 :(得分:0)

使用正确的数据结构。对于这种情况,具有像Binary Search TreeSkip list这样的总排序的一个似乎是合适的。使用red black tree,(例如this implementation)解决方案变得微不足道了:

var RBTree = require('bintrees').RBTree;
var tree = new RBTree(function(a, b) { return a.gain - b.gain; });

tree.insert({name: 'Gain weight', gain:1});
tree.insert({name: 'Gain smoking', gain:2});
// e.t.c...

tree.max();
// => {name: 'Gain smoking', gain:2}