-4
私はこのような配列を持っている:Arrayから最も近い値を取得するにはどうすればよいですか?
var array = [{top: 5, left: 50}, {top: 12, left: 44}, {top: 60, left: 11}]
私が知っていれば、私はこの配列一つだけ最寄りtop
とleft
で見つける必要があります。
var findNearest = {top:10, left:40}; //never be bigger than +5 (or lower than -5)
この場合、例えば、第2を返す必要がありますtop: 12
はtop:10
に近いので、私のfindNearest
で対象と違いはそれほど大きくはないから5.左に同じこと。
どのようにですか?
編集
私の考えは、私が検索したいものをオブジェクトと同じ値を持っている場合for
ループを作成し、すべてのオブジェクトをチェックしています。いいえの場合は、ループを増やして+1
のループを繰り返す。
私の悪い考えの例:
var increaseTop = true;
var increaseLeft = true;
function find(obj){
for(var i = 0; i < array.length; i++){
if(array[i].top == obj.top){
// found nearest .top, not increase by 1
increaseTop = false;
}
if(array[i].left == obj.left){
// found nearest .left, not increase by 1
increaseLeft = false;
}
}
// here repeat for loop if is increaseLeft OR increaseTop is true
// with increased values .top and .left
}
findNearest({top:10, left:40});
を、あなたは私たちにこれをしてください解決の試みを表示することができますか? – axelduch
これも同様の質問です。ソリューションを少し変更するだけです。 http://stackoverflow.com/questions/5728746/how-to-find-minimum-date-from-3-dates-using-javascript-function – SpiderPig
どのように動作するのかわかりませんので、私は尋ねます – Dave