gpt4 book ai didi

javascript - 无法从数组(Javascript)中获取最小值?

转载 作者:行者123 更新时间:2023-11-29 18:38:24 29 4
gpt4 key购买 nike

我试图从数组中获取最小值,但我遇到了这种奇怪的行为。我的期望是获得 89 作为最小距离,而不是我得到 100。谁能解释一下?

// List 

var nodes = {
"node": [
{
"name": "test",
"id": "2",
"edges": {
"edge": [
{
"to": "4",
"distance": "89"
},
{
"to": "6",
"distance": "100"
},
{
"to": "8",
"distance": "500"
}
]
}
}]
}

// Initialization
startNode = 0
currentNode = startNode;


edge = nodes.node[currentNode].edges.edge;
var minimumDistance = 99999;

// Loop through the Neighbors of one Node
for (x= 0; x<edge.length; x++) {
if (edge[x].distance < minimumDistance) {
minimumDistance = edge[x].distance;
}
document.write('Neighbor: ' + edge[x].to + ', Distance: ' + edge[x].distance);
document.write('</br>');
}
document.write('</br>');
document.write('Minimum Distance: ' + minimumDistance );

最佳答案

您需要取一个数字而不是字符串进行比较。比较字符串不同于数字。这是一些示例:

var nodes = { node: [{ name: "test", id: "2", edges: { edge: [{ to: "4", distance: "89" }, { to: "6", distance: "100" }, { to: "8", distance: "500" }] } }] },
startNode = 0,
currentNode = startNode,
edge = nodes.node[currentNode].edges.edge,
minimumDistance = Infinity, // greatest value
x;

for (x = 0; x < edge.length; x++) {
if (+edge[x].distance < minimumDistance) { // unary plus for getting a number
minimumDistance = edge[x].distance;
}
document.write('Neighbor: ' + edge[x].to + ', Distance: ' + edge[x].distance);
document.write('</br>');
}
document.write('</br>');
document.write('Minimum Distance: ' + minimumDistance );

关于javascript - 无法从数组(Javascript)中获取最小值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59016314/

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