Javascript处理变量中的分数

时间:2017-10-05 22:08:31

标签: javascript

我是编程的新手,并且正在尝试编写一个简单的程序来查找一条线的斜率,我想知道如何处理其中包含分数的变量。目前,如果我将任何变量指定为分数,我将收到错误。

var oneX = prompt ("what is the X of the first coordinate?");
var oneY = prompt ("what is the Y of the first coordinate?");
var twoX = prompt ("what is the X of the second coordinate?");
var twoY = prompt ("what is the Y of the second coordinate?");

console.log(oneX);
console.log(oneY);
console.log(twoX);
console.log(twoY);

var yRes = twoY-oneY;
var xRes = twoX-oneX;

console.log(yRes);
console.log(xRes);

var slope = yRes/xRes

console.log(slope);

如果你有任何建议让这个程序更整洁,我会很高兴。谢谢!

1 个答案:

答案 0 :(得分:1)

不要使用eval!除非你知道什么是eval,否则你应该和不应该使用它。

如果您只是想允许分数,那么您应该允许解析它。例如,您可以简单地编写代码:

/*
* Tries to parse a users input, returns {@param input} as a number or
* attempts to parse the input as a fraction.
* @return Number or NaN if an invalid number or unparseable
*/
function parseUserInput(input) {
    var res = +input;
    if(isNaN(res)) {
        // try parsing as fraction
        var strval = String(input);
        var ix = strval.indexOf('/');
        if(ix !== -1) {
            try {
                res = strval.substring(0, ix) / strval.substring(ix+1);
            } catch(e) {
            }
        }
    }
    return isFinite(res) ? res : NaN;
}

var oneX = parseUserInput(prompt ("what is the X of the first coordinate?"));
var oneY = parseUserInput(prompt ("what is the Y of the first coordinate?"));
var twoX = parseUserInput(prompt ("what is the X of the second coordinate?"));
var twoY = parseUserInput(prompt ("what is the Y of the second coordinate?"));

或者用@ Jonasw的建议写一个非常漂亮的方式。

/*
* Tries to parse a users input, returns {@param input} as a number or
* attempts to parse the input as a fraction.
* @return Number or NaN if an invalid number or unparseable
*/
function parseUserInput(input) {
  return +input.split("/").reduce((a,b)=> a/(+b||1));
}