首页 > 解决方案 > Access to Array of objects elements :I am trying to print the submitter with highest number of metric :which is redness or plumpness

问题描述

const judgeVegetable=function(vegetables,metric){
   var max=0,position=0,i=0;
if(metric ==='redness'){
 for(i=0;i<vegetables.length;i++){
  //for(let veg in vegetables) {
     if(vegetables.redness[i] > max){
       max=vegetables.redness[i];
       position=i;
     }
    }
}

If I call the function with the parametres below then ;

const vegetables = [
  {
    submitter: 'Old Man Franklin',
    redness: 10,
    plumpness: 5
  },
  {
    submitter: 'Sally Tomato-Grower',
    redness: 2,
    plumpness: 8
  },
  {
    submitter: 'Hamid Hamidson',
    redness: 4,
    plumpness: 3
  }
]

const metric = 'redness';

console.log(judgeVegetable(vegetables, metric));

OUTPUT SHOULD BE :Old Man Franklin (my code is giving error and i don't know where)

标签: javascript

解决方案


按原样运行代码会出现以下错误:

SyntaxError: Unexpected end of input

那是因为您忘记了函数定义的右大括号。确保在代码中使用适当的缩进和间距,这样您就可以轻松发现此类错误。例子:

const judgeVegetable = function(vegetables,metric) {
  var max = 0, position = 0, i = 0;

  if(metric ==='redness') {
  for(i = 0; i < vegetables.length; i++) {
    //for(let veg in vegetables) {
      if(vegetables.redness[i] > max) {
        max=vegetables.redness[i];
        position=i;
      }
    //}
  }
}

另请注意,我将 disabledfor与相应的 disabled 右括号一起包括在内。

但是仅仅修复它还不会产生预期的结果,因为您的代码中还有其他错误。我带你走过:

for通过评论禁用了第二个循环,让我们将其完全删除,以免混淆您。

您无法访问vegetables.redness[i],因为vegetables是数组,而不是数组,redness它是数组内对象内的字段vegetables。所以让我们修复它并删除禁用的for循环:

const judgeVegetable = function(vegetables,metric) {
  var max = 0, position = 0, i = 0;

  if(metric === 'redness') {
    for(i = 0; i < vegetables.length; i++) {
      if(vegetables[i].redness > max) {
        max = vegetables[i].redness;
        position = i;
      }
    }
  }
}

现在代码没有产生任何错误,但它也没有返回任何东西,你需要返回找到的值,所以:

const judgeVegetable = function(vegetables,metric) {
  var max = 0, position = 0, i = 0;

  if(metric === 'redness') {
    for(i = 0; i < vegetables.length; i++) {
      if(vegetables[i].redness > max) {
        max = vegetables[i].redness;
        position = i;
      }
    }
  }
  return vegetables[position].submitter;
}

现在正在工作:) 好吧,几乎,如果度量标准是 ,您仍然必须编写代码来选择正确的答案plumpness。这使我简化了您的代码,这也解决了这个问题:删除 if 并使用metric参数访问正确的字段:

const judgeVegetable = function(vegetables, metric) {
  var max = 0, position = 0, i = 0;
 
  for(i = 0; i < vegetables.length; i++) {
    if(vegetables[i][metric]> max) {
      max = vegetables[i][metric];
      position = i;
    }
  }
  return vegetables[position].submitter;
}
 
console.log(judgeVegetable(vegetables, 'redness')); // Old Man Franklin
console.log(judgeVegetable(vegetables, 'plumpness')); // Sally Tomato-Grower

其他供您考虑的建议:

  • 无需将函数分配给变量(const在这种情况下),您可以以传统方式定义函数:
function judgeVegetable(vegetables, metric) { ...

或者使用新的箭头函数语法:

const judgeVegetable = (vegetables, metric) => { ...
  • i参数可以在循环中声明和初始化,for所以不需要事先做

  • 不使用var,使用constlet适当


推荐阅读