gpt4 book ai didi

javascript - 遍历 json 对象并返回汇总结果

转载 作者:行者123 更新时间:2023-11-30 07:34:21 24 4
gpt4 key购买 nike

我在计算 json 对象和返回平均结果时遇到问题。

这是我的json对象

var testJson = [{
"1": "0.038728952407837",
"2": "0.034420967102051",
"3": "0.034113883972168",
"4": "0.033237934112549",
"5": "0.033545017242432",
"6": "0.033923149108887",
"7": "0.033990859985352",
"8": "0.033454895019531",
"9": "0.033518075942993",
"10": "0.033759117126465",
"11": "0.033965826034546",
"12": "0.03358006477356",
"13": "0.033926010131836",
"14": "0.033300876617432",
"15": "0.033140897750854",
"16": "0.033447027206421",
"17": "0.033830165863037",
"18": "0.033417940139771",
"19": "0.033578157424927",
"20": "0.032893180847168",
}]

这是我的代码

var arr = testJson[0];
var total = 0;
for (var i = 0; i < arr.length; i++) { //loop through the array
total += arr[i]; //Do the math!
}
console.log(total)

这个结果的输出只是连接字符串

0.0387289524078370.0344209671020510.0341138839721680.0332379341125490.0335450172424320.0339231491088870.0339908599853520.0334548950195310.0335180759429930.0337591171264650.0339658260345460.033580064773560.0339260101318360.0333008766174320.0331408977508540.0334470272064210.0338301658630370.0334179401397710.0335781574249270.0328931808471680.0339531898498540.0339729785919190.0338070392608640.0332689285278320.0333919525146480.033372879028320.0353031158447270.0355949401855470.0359919071197510.036854982376099

那么,我哪里失败了?

最佳答案

这是一个类型转换问题。 testJson 上的值是字符串。 string1 + string2 连接这两个字符串并生成新字符串。您应该使用 parseFloat 函数将此值解析为 Float。

if(!Object.values){Object.values=obj=>Object.keys(obj).map(key=>obj[key])}

var arr = Object.values(testJson[0]);
var total = 0;
for (var i = 0; i < arr.length; i++) { //loop through the array
total += parseFloat(arr[i]); //Do the math!
}
console.log(total)

第二种选择;

if(!Object.values)Object.values=obj=>Object.keys(obj).map(key=>parseFloat(obj[key]))
var total = 0;
Object.values(testJson[0]).forEach(function(val){total += val});

我用的代码行,

if(!Object.values)Object.values=obj=>Object.keys(obj).map(key=>parseFloat(obj[key]))

polyfill

From Wikipedia; In web development, a polyfill is code that implements a feature on web browsers that do not support the feature. Most often, it refers to a JavaScript library that implements an HTML5 web standard, either an established standard (supported by some browsers) on older browsers, or a proposed standard (not supported by any browsers) on existing browsers. Formally, "a polyfill is a shim for a browser API".[1]

关于javascript - 遍历 json 对象并返回汇总结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38652120/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com