2016-05-22 62 views
-2

使用一些計算我已經爲變量分配了一些值。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中賦值最高的變量?

+1

您可以使用最多的方法: Math.max(N1,N2,N3,...,NX) HTTP:// WWW。 w3schools.com/jsref/jsref_max.asp – HotTowelie

+0

會將變量的賦值變爲關聯數組嗎? – Sajal

+0

問題沒有顯示任何解決問題的嘗試。這不是一個代碼編寫服務,您至少應該展示自己解決問題的嘗試 – charlietfl

回答

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) 
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}