简体   繁体   English

Javascript 如何使用 window.prompt 在变量中获得数学表达式?

[英]Javascript How do i get a mathematical expression in a Variable with window.prompt?

I have this Code, which isn't working properly.我有这个代码,它不能正常工作。 As you can see i try to get a formula in to an array.如您所见,我尝试将公式放入数组中。 this is used to calculate the mathematical use later.这用于计算稍后的数学用途。 but the programm don't put the formula in the right form right where the var stands:但是程序没有将公式放在 var 所在的正确形式中:

<html>
<title> JavaScript Tutorial 1
</title>
<body>
<script language = "javascript">

var f, a, b, c, d, j, k, sum;

f = String(window.prompt("Formel"));
a = Number(window.prompt("untere grenze 1tes E"));
b = Number(window.prompt("obere grenze 1tes E"));
c = Number(window.prompt("untere grenze 2tes E"));
d = Number(window.prompt("obere grenze 2tes E"));





sum = 0;
for (j = a; j <= b; j++) {

    for (k = c ; k <= d ; k++) {
    sum += f;
    }
}

document.write(sum);

</script>
<noscript>
    <p> You have JavaScript Turned Off <p>
</noscript>
</body>
</html>

And i have this Code here, which calculate it right.我在这里有这个代码,它计算正确。 But i would like to get the formula in to a var over the window.promp但我想通过 window.promp 将公式放入 var

<html>
<title> JavaScript Tutorial 1
</title>
<body>
<script language = "javascript">

var f, a, b, c, d, j, k, sum;

//f = String(window.prompt("Formel"));
a = Number(window.prompt("untere grenze 1tes E"));
b = Number(window.prompt("obere grenze 1tes E"));
c = Number(window.prompt("untere grenze 2tes E"));
d = Number(window.prompt("obere grenze 2tes E"));

sum = 0;
for (j = a; j <= b; j++) {

    for (k = c ; k <= d ; k++) {
    sum += j * j * k;
    }
}

document.write(sum);

</script>
<noscript>
    <p> You have JavaScript Turned Off <p>
</noscript>
</body>
</html>

@ yellowsir, thank you for your input, it works well with eval and i understand the security lack. @ Yellowsir,感谢您的投入,它与 eval 配合良好,我了解安全性不足。 As i just use this project for my self there will be no risk of someone putting in some malcode ;)因为我只是为自己使用这个项目,所以不会有人输入一些恶意代码的风险;)

Here is the Solution i got out of your input:这是我从您的输入中得到的解决方案:

<html>
<title> JavaScript Tutorial 1
</title>
<body>
<script language = "javascript">

var f, a, b, c, d, j, k, sum;

a = Number(window.prompt("untere grenze 1tes E"));
b = Number(window.prompt("obere grenze 1tes E"));
c = Number(window.prompt("untere grenze 2tes E"));
d = Number(window.prompt("obere grenze 2tes E"));
f = window.prompt("Formel");

sum = 0;
for (j = a; j <= b; j++) {

    for (k = c ; k <= d ; k++) {
    sum += eval(f);
    }
}

// document.write("<br>")
document.write(sum);

</script>
<noscript>
<p> You have JavaScript Turned Off <p>
</noscript>
</body>
</html>

Hopefully everything is clear do not hesitate to ask.希望一切都清楚,不要犹豫,问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM