2

我有一个用户输入的数字 X。以及 JSON 格式的数据列表。

**114**  80  145     175     240     320
**123**  85  155     190     260     345
**132**  90  170     205     280     370

我想将 X 与第一列中最接近的数字匹配,然后在该行中返回以下值。

不确定我是否以最佳方式格式化了 JSON。但这是我到目前为止所拥有的:http: //jsfiddle.net/wuSux/

4

2 回答 2

2

尝试这样的事情:

var data = [{"Body Weight":114," Untrained": 80," Novice": 145," Intermediate": 175," Advanced": 240," Elite": 320},
            {"Body Weight":123," Untrained": 85," Novice": 155," Intermediate": 190," Advanced": 260," Elite": 345},
            {"Body Weight":132," Untrained": 90," Novice": 170," Intermediate": 205," Advanced": 280," Elite": 370}];

var x = 140,
    difference = 0,
    bestIndex = 0,
    bestDifference = Infinity,
    i, cur, bodyWeight;

for (i = 0; i < data.length; i++) {
    cur = data[i];
    bodyWeight = cur["Body Weight"];
    difference = Math.abs(x - bodyWeight);
    if (difference < bestDifference) {
        bestDifference = difference;
        bestIndex = i;
    }
}

console.log(data[bestIndex]);

演示:http: //jsfiddle.net/wuSux/2/

更改 的值x以找到最接近该数字的值。

于 2013-04-25T19:39:19.110 回答
2

更改您的数据,以便最后一个Body Weight代替320"320+"然后:

function getClosest(x) {
    for (var i = data.length - 1; i > -1; i--) {
        if (x > data[i]["Body Weight"]) break
    }
    if (i === data.length - 1) return data[i];
    if (i === -1) return data[0];

    return data[i + +(x > ((data[i]["Body Weight"] + data[i + 1]["Body Weight"]) / 2))];
}

演示:http: //jsfiddle.net/s8Xge/


或者,如果您愿意:

function getClosest(x) {
    for (var i = data.length - 1; i > -1; i--) {
        if (x > data[i]["Body Weight"]) break
    }
    return i === data.length - 1                                     ? data[i] :
           i === -1                                                  ? data[0] :
           (data[i]["Body Weight"] + data[i + 1]["Body Weight"]) / 2 ? data[i + 1] :
                                                                       data[i];
}
于 2013-04-25T19:49:08.323 回答