我正在尝试制作一个简单的成本估算器。 3个不同的输入有最大值。我想创建一个检查输入值的函数,并尝试确保z值始终是三者中的最低值,只要满足全局约束。
我已经制作了这个代码:
http://codepen.io/FredHair/pen/Jdberw?editors=001
这是我交换变量的代码:
function retrVals() {
var coOrds = {}; //empty object
coOrds.x = Number(document.getElementById("x").value); //define each coordinate
coOrds.y = Number(document.getElementById("y").value);
coOrds.z = Number(document.getElementById("z").value);
var min = Math.min(coOrds.x,coOrds.y,coOrds.z); //find the minimum of the three
var temp = coOrds.z; //create a temporary variable to store the current z value
var limitx = 241;
var limity = 191;
var limitz = 331;
if(min === coOrds.z && coOrds.z < limitz && coOrds.x < limitx && coOrds.y < limity){
return [coOrds.x,coOrds.y,coOrds.z]
}
else if(min === coOrds.y && coOrds.z < limity && coOrds.x < limitx && coOrds.y < limitz){
coOrds.z = coOrds.y
coOrds.y = temp
return [coOrds.x,coOrds.y,coOrds.z]
}
else if(min === coOrds.x && coOrds.z < limitx && coOrds.x < limitz && coOrds.y < limity){
coOrds.z = coOrds.y
coOrds.y = temp
return [coOrds.x,coOrds.y,coOrds.z]
}
else{
return [coOrds.x,coOrds.y,coOrds.z]
}
};
约束是:
x = 240;
y = 190;
z = 330;
所以我不想交换一个会破坏这个数量的值,而且我也总是希望尽可能地降低z。
这样做的最佳方法是什么?我使用我的代码是在正确的轨道上还是有更好的方法?
非常感谢任何帮助。
佛瑞德
答案 0 :(得分:2)
如果我理解正确,这个if语句应该做你想要的:
var temp = coOrds.z; //create a temporary variable to store the current z value
var limitx = 241, limity = 191, limitz = 331;
var xFail, yFail, zFail;
coOrds.x >= limitx ? xFail = true : xFail = false;
coOrds.y >= limity ? yFail = true : yFail = false;
coOrds.z >= limitz ? zFail = true : zFail = false;
if (zFail || (xFail && yFail)) { // z failed OR both x AND y failed, we cant ever handle this because if x failed then x is greater than 240 which wont ever fit into y
// dont accept the input, z-fail can't be handled because if it doesnt fit in z it wont fit in x or y either
} else if (yFail) { // only y failed
if (coOrds.y < limitx && coOrds.x < limity) { // can we swap x and y?
var tmp = coOrds.y;
coOrds.y = coOrds.x;
coOrds.x = tmp;
} else if (coOrds.y < limitz && coOrds.z < limity) { // can we swap z and y?
var tmp = coOrds.y;
coOrds.y = coOrds.z;
coOrds.z = tmp;
}
} else if (xFail) { // only x failed
if (coOrds.x < limity && coOrds.y < limitx) { // can we swap x and y ?
var tmp = coOrds.y;
coOrds.y = coOrds.x;
coOrds.x = tmp;
} else if (coOrds.y < limitz && coOrds.z < limity) { // can we swap z and x?
var tmp = coOrds.x;
coOrds.x = coOrds.z;
coOrds.z = tmp;
}
}
if (min < coOrds.z) { //do we need to swap at all?
coOrds.z = min; // set z to the minimum
if (min == coOrds.x && temp < limitx) { // was x the minimum and was z less than the x limit?
coOrds.x = temp; //x is the new z
} else if (temp < limity) { // y was the minimum, was z less than the y limit?
coOrds.y = temp;
} else { // could not swap, would exceed limits
coOrds.z = temp
}
}
return [coOrds.x,coOrds.y,coOrds.z];