【发布时间】: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