javascript - 在带有对象(第二个参数)的数组(第一个参数)上使用 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}
解决方案
你只得到一个结果,因为你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))
推荐阅读
- networking - 浏览器的开发工具中是否可以看到 WASM 网络请求?
- android - 支持后台线程的 HMS ML Kit 是否有效?
- dynamics-crm - 导入我的非托管解决方案不会更改帐户表单
- rust - 是否有类似于 recv_timeout 功能的异步功能?
- javascript - 如何使用 Jquery 制作动态 CSS 类名
- node.js - 无法读取 env 文件中未定义的属性“连接”
- sql-server - 如何从 T-SQL 过程将日志发送到 GrayLog?
- ajax - Laravel 刀片表到 AJAX
- docker - 如何轻松找到预装了选定应用程序的 docker 容器?
- ruby - 将 VSCode 指向已安装的 Ruby