在javascript中查找具有最高值的Object属性

时间:2014-07-27 13:56:50

标签: javascript object

说我有一个像这样动态创建的对象......

var indexes = {};
for (var i = 0; i < specchar.length; i++) {
    indexes[specchar[i]] = str.indexOf(specchar[i]);
}

我如何找到价值最高的物业?

3 个答案:

答案 0 :(得分:3)

最有效的方法是跟踪最大值,因为动态创建对象是这样的:

var indexes = {};
var maxVal = str.indexOf(specchar[0]); // contains largest value
var maxKey = ''; // contains key corresponding to largest value
for (var i = 0; i < specchar.length; i++) {
  var val = str.indexOf(specchar[i]);
  if (val > maxVal) {
    maxVal = val;
    maxKey = specchar[i];
  }
  indexes[specchar[i]] = val;
}

答案 1 :(得分:0)

您还可以使用Math.max.apply找到最大值。如果你使用object,那么首先需要获取值并推入数组。

var fixtures = {};
for (var i = 0; i < Math.random() * 20 + 5; i++) {
    fixtures[i] = Math.random() * 20 - 10;
}

// Procceed object and push values to array
var values = [],
    maxValue = 0;
for (var key in fixtures) {
    values.push(fixtures[key]);
}

// Find max value
maxValue = Math.max.apply(Math.max, values);

// Print results to console
console.dir(values);
console.log(maxValue);

但是如果你得到一个数组values并且想要找到最大值,你可以调用Math.max.apply(Math.max, values)并返回最大值。

答案 2 :(得分:0)

您还可以使用for-in

var indexes = {};
var maxIndexVal = str.indexOf(specchar[0]); // this will hold the maximum value found

for(var index in specchar){

   var foundIndex = str.indexOf(specchar[index]); // returns the index if found

   // compare values; add max values to indexes
   if(foundIndex > maxIndexVal) {
        maxIndexVal = foundIndex;
        indexes[specchar[maxIndexVal]] = maxIndexVal;
   }

}