【问题标题】:Using for in to iterate through objects values and return the highest value - Can I use it in the same way I would a for Loop使用 for in 遍历对象值并返回最高值 - 我可以像使用 for 循环一样使用它吗
【发布时间】:2022-01-01 15:00:53
【问题描述】:

我正在尝试返回传递数组的模式。我已经阅读了很多关于 for in 循环的内容,但是由于这些示例中使用了 es6 语法,我很难理解如何使用这个循环。我的问题:我想返回所有对象对中值最高的键。

即带有以下对象:

{ '4': 1, '6': 1, '7': 1, '8': 1, '10': 2, '12': 3 }

我想返回包含最大值的键。在这种情况下,它将是 12,因为 3 是这对中的最高值。

是否可以以类似于遍历数组以查找最大值的方式使用 for in 循环。 (我知道非数组对象的索引方式与数组不同,但我需要将一个键值对与循环中的下一个键值对进行比较,并且不知道如何编写代码)。即:


let highest = 0;
      for(const x in count){
        if(count[x+1] > count[x]){
         highest = count[x][i+1];
       }

当我传递下面的代码时,它返回 0,所以我假设 For In 循环没有按预期工作。

完整代码供参考:


function highestRank(arr){
  
  const count = {};
  
  for(let i=0; i<arr.length; i++){
    if(count.hasOwnProperty(arr[i]) === false){
        count[arr[i]]= 1;
      }else{
        count[arr[i]] += 1;
      }
  }
 //code below is the issue
  let highest = 0;
  for(const x in count){
    if(count[x+1] > count[x]){
     highest = count[x][i+1];
   }
  } 
  
  return highest;
}

【问题讨论】:

    标签: javascript for-loop object


    【解决方案1】:

    传统循环版本,使用变量greatest及其各自的key,循环对象属性

    const count = { '4': 1, '6': 1, '7': 1, '8': 1, '10': 2, '12': 3 };
    
    let greatest = -Infinity;
    let key;
    for (let x in count) {
      if (count[x] > greatest) {
        key = x;
        greatest = count[key];
      }
    }
    
    console.log(key, greatest);

    【讨论】:

    • 感谢您的回答-我使用此逻辑解决了我的问题^。不过有个问题,你为什么用-Infinity;而不是0?
    • @DCoderT zero 如果您确定这些值都是正数,也可以使用。
    【解决方案2】:

    您可以将 Object.entries 与 reduce 结合使用,并在累积器中使用 maxKey 和 maxValue 保留对象;

    const data = { '4': 1, '6': 1, '7': 1, '8': 1, '10': 2, '12': 3 };
    const max = Object.entries(data).reduce(({maxKey, maxValue = -Infinity}, [key, value]) => {
      if(value > maxValue){
        maxValue = value;
        maxKey = key;
      }
      return {maxKey, maxValue}
    }, {});
    
    console.log(max);
    编辑:(短版)

    const data = { '4': 1, '6': 1, '7': 1, '8': 1, '10': 2, '12': 3 };
    const max = Object.entries(data).reduce(([maxKey, maxValue], [key, value]) =>
      value > maxValue ? [key, value] : [maxKey, maxValue]
    );
    
    const maxShort = Object.entries(data).reduce((a, c) => c[1] > a[1]? c : a);
    
    
    console.log(maxShort);

    【讨论】:

    • 感谢您的回复 - 我需要学习这种语法才能完全理解这一点,所以会回来的。
    猜你喜欢
    • 1970-01-01
    • 2017-06-30
    • 1970-01-01
    • 1970-01-01
    • 2019-12-11
    • 2021-04-02
    • 2019-04-13
    • 2020-06-17
    • 1970-01-01
    相关资源
    最近更新 更多