问题
I have a Javascript function that isn't returning the result I expected. I am trying to determine if an x,y point exists within a rectangle based on 2 other x,y points. In my code x and y are the original point in question. z1 and z2 are the top left coordinates of the rectangle and z3 and z4 are the bottom right coordinates.
function isInside(x,y,z1,z2,z3,z4){
x1 = Math.min(z1, z3);
x2 = Math.max(z1, z3);
y1 = Math.min(z2, z4);
y2 = Math.max(z2, z4);
if ((x1 <= x <= x2) && (y1 <= y <= y2)) {
console.log (x1 + "," + x + "," + x2);
console.log (y1 + "," + y + "," + y2);
return true;
} else {
return false;
};
};
If I evaluate isInside(110,175,50,50,100,100) I am getting true. This is unexpected as point 110,175 does not exist within a rectangle of 50,50 and 100,100. Any help would be appreciated.
回答1:
(x1 <= x <= x2)
doesn't do what you want it to do in Javascript: you have to use x1 <= x && x <= x2
.
If you plug in actual numbers in for those variables and try this out in Chrome's console, you can see that the whole statement always evaluates to true:
1 <= 3 <= 5
true
9 <= 3 <= 5
true
回答2:
here is the answer
function isInside(x, y, z1, z2, z3, z4) {
x1 = Math.min(z1, z3);
x2 = Math.max(z1, z3);
y1 = Math.min(z2, z4);
y2 = Math.max(z2, z4);
if ((x1 <= x ) && ( x <= x2) && (y1 <= y) && (y <= y2)) {
console.log(x1 + "," + x + "," + x2);
console.log(y1 + "," + y + "," + y2);
return true;
} else {
return false;
};
};
if you need to check if x
is between a
and b
you have to talk to computer like,
if x is greater than a and x is less than b, then it will give your proper result
if(x >= a && x <= b){
// true
}
来源:https://stackoverflow.com/questions/15019176/javascript-function-to-determine-if-a-point-is-in-between-a-rectangle