Dont use eval! Unless you know what eval is, why you should and shouldnt use it.
If you simply want to allow fractions then you should allow for parsing it. For instance you could simple write your code as such:
/*
* 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?"));
Or a very pretty way of writing it using @Jonasw's suggestion.
/*
* 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));
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…