我试图从一个数组中获取最小值,我遇到了这个奇怪的行为。我的期望是得到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 );发布于 2019-11-24 17:35:01
为了进行比较,您需要接受一个数字而不是一个字符串。比较字符串与数字不同。下面是一些示例:
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 );
发布于 2019-11-24 17:52:00
让我们将其分解为一个最小的代码示例。您要在(imho覆盖嵌套的) nodes对象的edge数组中寻找属性distance的最小值。
问题是distance值是字符串,而不是数字。因此,应该将这些值转换为Number,以便能够对它们进行比较并确定distance值中的最小值。现在,使用+[a numeric string value]将距离映射到Number。
要确定最小值,可以随后对映射的数值数组应用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);
发布于 2019-11-24 17:38:29
正如Robin所指出的--你是在比较字符串。如果不能在数据源中存储整数,可以使用parseInt()执行以下操作;
if (parseInt(edge[x].distance) < minimumDistance) {
minimumDistance = parseInt(edge[x].distance);
} https://stackoverflow.com/questions/59016314
复制相似问题