gpt4 book ai didi

javascript - 根据最接近的数字返回值

转载 作者:行者123 更新时间:2023-11-29 14:39:52 28 4
gpt4 key购买 nike

在代码片段中,您将找到一个函数,该函数根据您在 var found = getDistanceNumber('Saturn'); 中键入的行星返回和输出属于数组内行星的距离

我想使用这段代码,而不是像现在编程那样返回行星的距离,而是离它最近的行星的名称。所以如果我有 Saturn 作为参数,我希望它检查它的距离是多少,找到数组中最近的距离,并输出属于那个的行星。在这种情况下,它就是木星。

我该怎么做?

var data = [
{
"Planet": "Mercury",
"Distance": "-92 million"
},
{
"Planet": "Venus",
"Distance": "-42 million"
},
{
"Planet": "Earth",
"Distance": "0"
},
{
"Planet": "Mars",
"Distance": "78 million"
},
{
"Planet": "Jupiter",
"Distance": "628 million"
},
{
"Planet": "Saturn",
"Distance": "1,3 billion"
},
{
"Planet": "Uranus",
"Distance": "2,7 billion"
},
{
"Planet": "Neptune",
"Distance": "4, 3 billion"
}
]


function getDistanceNumber(Planet) {
return data.filter(
function(data){return data.Planet == Planet}
);
}

var found = getDistanceNumber('Mars');

document.getElementById('output').innerHTML=found[0].Distance;
<div id="output"></div>

最佳答案

请注意,我对数据进行了一些相当微不足道的更新。我在用着 ”。”而不是“,”作为小数点分隔符。我还删除了海王星距离中的额外空间,因为它看起来像是数据输入中的错字。


我将其分解为更小的问题。即……

  • 将距离字符串转换成数值,
  • 从名称字符串中获取行星的对象,
  • 计算到输入的距离,
  • 找到最小的距离,然后
  • 使用最小距离的索引找到相应行星的名称。

console.clear()

// conver million/billion to numbers (in millions)
var conversionLUT = {'million': 1, 'billion': 1e3}

// convert distance string to number
function convertDistance(distStr){
let dist = distStr.split(" ")
return dist[0]*conversionLUT[dist[1]] || 0
}

// returns callback to calculate distance for a given planet
function distanceFrom(planetObj){
return function(elem){
return Math.abs(convertDistance(elem.Distance) - convertDistance(planetObj.Distance))
}
}

// get object from array by planet name
function getPlanetObject(planetName, dat = data){
return dat.find(d=>d.Planet === planetName)
}

// As one function
function findClosestPlanet(name, dat = data){
// get distances given planet object
let distances = dat.map(distanceFrom(getPlanetObject(name)))

// smallest distance (filter out 0 to ignore self)
let distToClosest = Math.min(...distances.filter(d => d>0))

// find index of planet whose closest dist matches
let indOfClosest = distances.findIndex(d=>d===distToClosest)

// return planet name that is closest
return data[indOfClosest].Planet
}

var data = [
{
"Planet": "Mercury",
"Distance": "-92 million"
},
{
"Planet": "Venus",
"Distance": "-42 million"
},
{
"Planet": "Earth",
"Distance": "0"
},
{
"Planet": "Mars",
"Distance": "78 million"
},
{
"Planet": "Jupiter",
"Distance": "628 million"
},
{
"Planet": "Saturn",
"Distance": "1.3 billion"
},
{
"Planet": "Uranus",
"Distance": "2.7 billion"
},
{
"Planet": "Neptune",
"Distance": "4.3 billion"
}
]

document.getElementById('output').innerHTML = findClosestPlanet('Saturn')
<div id="output"></div>

关于javascript - 根据最接近的数字返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40075380/

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