我正在尝试从数组中获取最小值,并且遇到了这种奇怪的行为。 我的期望是获得89作为MinimumDistance,而不是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 );
答案 0 :(得分:2)
您需要使用数字而不是字符串进行比较。比较字符串不同于数字。 这是一些示例:
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 );
答案 1 :(得分:1)
让我们将其分解为一个最小的代码示例。您正在寻找<li>
对象中的distance
数组内edge
的属性nodes
的最小值。
问题在于distance
的值是字符串,而不是数字。因此,应将值转换为Number
,以便能够比较它们并确定distance
值中的最小值。现在,使用Number
将距离映射到+[a numeric string value]
。
要确定最小值,您可以随后将Math.min
应用于映射的数值数组。
const edge = [
{
"to": "4",
"distance": "89"
},
{
"to": "6",
"distance": "100"
},
{
"to": "8",
"distance": "500"
}
];
// map distances to numeric values
const distancesFromEdge = edge.map( val => +val.distance );
// determine the minimum value of the mapped values
const minDistance = Math.min.apply(null, distancesFromEdge);
console.log(minDistance);
答案 2 :(得分:0)
正如罗宾指出的-您正在比较字符串。如果您不能在数据源中存储整数,则可以使用parseInt()
;
if (parseInt(edge[x].distance) < minimumDistance) {
minimumDistance = parseInt(edge[x].distance);
}
答案 3 :(得分:0)
将字符串更改为距离对象中的数字。
var nodes = {
"node": [
{
"name": "test",
"id": "2",
"edges": {
"edge": [
{
"to": "4",
"distance": 89
},
{
"to": "6",
"distance": 100
},
{
"to": "8",
"distance": 500
}
]
}
}]
}