我需要将“100% - 1”
转换为300 - 1
,其中300 - Canvas 宽度?如何评估(批量)此操作?
//for example:
var value = batch("100% - 1", canvas.width); //Must 299, because canvas.width is 300
var secondary = batch("50% + 10", canvas.width); //Must 160
//where first argument - arithmetic operation, second - relativity value.
这个问题不是科幻小说的范畴,而是一个非常严肃、现实的问题。
更新!但是如果只需要转换百分比?
var value = hack("75%", 300); //Must 255
var operation = hack("30%", 100) + 10; //Must 40
var end = hack("1em", somearg); //EM?
更新2!如果我使用new Function("a", "b", "return (%%Expression%%)")
而不是评估
?
例如:
var operation = "90% - 10";
致:
new Function("a", "return ((a * 90 / 100) - 10)");
如何制作?
最佳答案
如果批处理中有两个部分,并且第一个始终是百分比,第二个是值,那么您可以这样做
function batch(operation, value){
var values = operation.match(/\d+|[+-/*]/g),
percent = parseFloat(values[0])/100,
relative = parseFloat(values[2]),
math = values[1],
applied = percent*value;
switch(math){
case '+': return applied + relative;
case '-': return applied - relative;
case '/': return applied / relative;
case '*': return applied * relative;
}
}
关于javascript - 转换字符串(算术运算),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14021375/