![](/img/trans.png)
[英]Object.keys and Object.values return zero array of an object
[英]How to return the largest number returning from a function in which the Object.values(obj) is used in it to return an array?
在此示例中,我试图获取使用Object.values(obj)
、 Array.reduce()
和Array.length
上 object scoreObj
返回的最大数量的返回数组。 我达到了我想要从中获得最大数字的新数字(对象中每个数组的平均数字)的数组。
正如您在代码片段中看到的那样, getObjecVals()
返回 object scoreObj
中每个数组的平均数。此时我陷入了从新数组返回最大数字的困境。
我希望代码片段比我的解释更有意义。 我也有点困惑,因为当我在getObjecVals()
上使用typeof
运算符时,它会执行undefined
尽管是新的数字数组。
所以我的问题是: -
getObjecVals()
返回undefined
并同时记录一个数字数组?getObjecVals()
返回的三个数字中获得最大的数字?
let scoresObj = { johnsScore: [89, 120, 103], mikesScores: [116, 94, 123] }; const marys = scoresObj.marysScore = [97, 134, 105]; const getAverage = (arr) => arr.reduce((a, b) => (a + b), 0) / arr.length; const getObjecVals = () => { for (let value of Object.values(scoresObj)) { console.log(getAverage(value)); } } getObjecVals(); // returns 104 111 112
PS:我总是对获得所需结果的新方法持开放态度,但我宁愿找到一种方法让我自己的代码来做到这一点。
getObjecVals()
返回undefined
因为您没有为此函数返回任何值。
如果您只想获得最大值。 平均数,我将所有数据存储为一个数组并使用一些数组 function 来获得结果。
const scoresObj = { johnsScore: [89, 120, 103], mikesScores: [116, 94, 123], }; scoresObj.marysScore = [97, 134, 105]; console.log(scoresObj); const getObjecVals = scoresObj => { let maxObj = { objName: null, maxAverageValue: -1, }; for (const [key, value] of Object.entries(scoresObj)) { const average = value.reduce((a, b) => a + b, 0) / value.length; if (average > maxObj.maxAverageValue) { maxObj.objName = key; maxObj.maxAverageValue = average; } } return maxObj; }; console.log(getObjecVals(scoresObj));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.