javascript中的简单逻辑

时间:2010-06-14 04:58:53

标签: javascript

我有四个整数类型的变量 -

var tip_1, tip_2, tip_3, tip_4;

这些变量的值正在被其他逻辑填充,这些逻辑始终在1到10之间。我需要通过遵循这些规则来维护一个变量名为“key”的哈希值和值为“value”的哈希值。

  1. 具有MAX值的变量应该是散列中的第一个元素,依此类推。例如 如果tip_1 = 4,tip_2 = 1,tip_3 = 2,tip_4 = 10那么哈希应该是这样的, Hash = {tip_4,10} {tip_1,4} {tip_3,2} {tip_1,1}

  2. 如果有以下关系,则应考虑以下顺序 - tip_1> tip_2> tip_3> tip_4;

2 个答案:

答案 0 :(得分:2)

您始终可以构建自定义对象以保留所有信息,而不是在索引中对其进行编码。使排序更容易。

function Tip(type, value) {
    this.type = type;
    this.value = value;
}

var tips = [];

tips.push(new Tip(3, 4));
tips.push(new Tip(2, 4));
tips.push(new Tip(1, 3));
tips.push(new Tip(4, 10));

tips.sort(function(a, b) {
    // sort first by value, and if equal, then by type (index)
    return (b.value - a.value) || (a.type - b.type);    
});

console.log(tips); // 4=>10​, 2=>4, 3=>4, 1=>3​​​​​​​​​​​​​​​​​

更新了example

答案 1 :(得分:0)

如果您从提示中创建一个真正的数组,那么这样做会容易得多:

var tip_1 = 4, tip_2 = 1, tip_3 = 2, tip_4 = 10;

// create an array so we can sort it
var tips = [
  { key: 'tip_1', value: tip_1 }, 
  { key: 'tip_2', value: tip_2 }, 
  { key: 'tip_3', value: tip_3 }, 
  { key: 'tip_4', value: tip_4 }, 
];

tips.sort(function (a, b) {
  // sort value descending
  if (a.value < b.value) return 1;
  if (a.value > b.value) return -1;
  // if the values are equal, sort by key.
  return a.key > b.key ? 1 : b.key < a.key ? -1 : 0; 
});

// tips is now:
// [{key:"tip_4", value:10}, {key:"tip_1", value:4}, {key:"tip_2", value:2}, {key:"tip_3", value:2}]

// loop over the tips
for (var tip, i=0; tip = tips[i]; i++) {
  console.log(tip.key+": "+tip.value);
}

// Outputs:
// tip_4: 10
// tip_1: 4
// tip_3: 2
// tip_2: 1