首页 > 解决方案 > 在带有对象(第二个参数)的数组(第一个参数)上使用 for 循环迭代

问题描述

const championObj = {1: "Annie", 2: "Olaf", 3: "Galio", 4: "Fizz"}
const championList = ['1','2','1','3','4','3','1']

function countChampions(championObj, championList) {
  //create an empty object to store values
  let obj = {}

  //loop over championList array to compare with championObj object
  for(var i = 0; i < championList.length; i++) {

    //if the index is not in the object, add it into empty object and make the value 1
    if(obj[championObj[championList[i]]] === undefined) {
      obj[championObj[championList[i]]] = 1

    //else if the index is already found in the object, increment the value by + 1 
    } else if (obj[championObj[championList[i]]] !== undefined) {
      obj[championObj[championList[i]]] += 1
    }

    //return the object
    return obj
  }
}

console.log(countChampions(championObj, championList))

当我运行这个函数时,我只得到{ Annie: 1 }

输出应该是 = {"Annie" : 3, "Olaf" : 1, "Galio": 2, "Fizz": 1}

标签: javascript

解决方案


你只得到一个结果,因为你return obj在循环中,所以在第一次迭代时你结束了函数。obj解决方法是在for阻塞后返回

const championObj = {
  1: "Annie",
  2: "Olaf",
  3: "Galio",
  4: "Fizz"
}
const championList = ['1', '2', '1', '3', '4', '3', '1']

function countChampions(championObj, championList) {
  //create an empty object to store values
  let obj = {}

  //loop over championList array to compare with championObj object
  for (var i = 0; i < championList.length; i++) {

    //if the index is not in the object, add it into empty object and make the value 1
    if (obj[championObj[championList[i]]] === undefined) {
      obj[championObj[championList[i]]] = 1

      //else if the index is already found in the object, increment the value by + 1 
    } else if (obj[championObj[championList[i]]] !== undefined) {
      obj[championObj[championList[i]]] += 1
    }

  }
  //return the object
  return obj
}

console.log(countChampions(championObj, championList))

此外,由于您if无缘无故地检查了两次并且仅使用数组的值而不是索引本身,因此我希望建议您对代码进行改进:

const championObj = {
  1: "Annie",
  2: "Olaf",
  3: "Galio",
  4: "Fizz"
}
const championList = ['1', '2', '1', '3', '4', '3', '1']

function countChampions(championObj, championList) {
  let obj = {}

  for (let value of championList) {
    if (obj[championObj[value]]) {
      obj[championObj[value]]++;
    } else {
      obj[championObj[value]] = 1;
    }
  }

  return obj
}

console.log(countChampions(championObj, championList))


推荐阅读