gpt4 book ai didi

javascript - 提醒数组内的数据细节

转载 作者:行者123 更新时间:2023-11-29 17:55:40 25 4
gpt4 key购买 nike

我遇到了 javascript 初学者的问题。我将这些数据存储在一个数组中,我试图提醒数据以查看它是否已 check out 。

我想提醒自己 all 的平均距离,而不是 both 行星,尽管在这种情况下两者都是,但我最终想要一个数组保留的不仅仅是两个。现在,它只是提醒数组列表中最后一条记录的距离,这很奇怪。我认为这将是所有人的平均水平。

此外,我如何对数组中“距离”属性的最小和最大数字进行编程,然后用它来提醒“主机名”。因此,如果我有一个按钮并单击“Closest”,“Distance [pc]” 中编号最小的主机名将被提醒。我只需要一个“距离”的代码示例,这样我就知道如何对所有其他变量执行相同的操作。

如果您愿意帮忙,谢谢!

顺便说一句,列表是 JSON 数据。提及这一点可能很重要。

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> // this array holds the json data, in this case stastics of exoplanets retrieved from nasa's website
var arr= [ {
"rowid": 684,
"Host name": "K2-15",
"Number of Planets in System": 1,
"Planet Mass or M*sin(i)[Jupiter mass]": null,
"Planet Radius [Jupiter radii]": 0.221,
"Planet Density [g": {
"cm**3]": null
},
"Distance [pc]": 437,
"Effective Temperature [K]": 5131,
"Date of Last Update": "7/16/2015"
},
{
"rowid": 687,
"Host name": "K2-17",
"Number of Planets in System": 1,
"Planet Mass or M*sin(i)[Jupiter mass]": null,
"Planet Radius [Jupiter radii]": 0.199,
"Planet Density [g": {
"cm**3]": null
},
"Distance [pc]": 134,
"Effective Temperature [K]": 4320,
"Date of Last Update": "7/16/2015"
}];

//every record is put in a variable
var rowid;
var hostName;
var numberOfPlanetsInSystem;
var planetMass;
var planetRadius;
var distance;
var effectiveTemperature;

for(var i=0;i<arr.length;i++){

rowid= arr[i]["rowid"];
hostName= arr[i]["Host name"];
numberOfPlanetsInSystem= arr[i]["Number of Planets in System"];
planetMass= arr[i]["Planet Mass or M*sin(i)[Jupiter mass]"];
planetRadius= arr[i]["Planet Radius [Jupiter radii]"];
distance= arr[i]["Distance [pc]"];
effectiveTemperature= arr[i]["Effective Temperature [K]"];
};

//alert to test it out
alert(distance);</code></pre>
</div>
</div>

最佳答案

let totalDistance = maxDistance = 0;
let minDistance = arr[0]["Distance [pc]"];
let closestHost = farthestHost = "";
for(let i = 0; i < arr.length; i ++) {
totalDistance += arr[i]["Distance [pc]"]
if (arr[i]["Distance [pc]"] < minDistance) {
minDistance = arr[i]["Distance [pc]"];
closestHost = arr[i]["Host name"];
}
if (arr[i]["Distance [pc]"] > maxDistance) {
maxDistance = arr[i]["Distance [pc]"];
farthestHost = arr[i]["Host name"];
}
}
let meanDistance = totalDistance/arr.length;

关于javascript - 提醒数组内的数据细节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39293473/

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