我已经在你的变量名改组,以使它更清楚一点。
// I'll use the example of 120 to demonstrate
// The total amount, e.g. 120
var amount = prompt("Enter amount ");
// First, convert the inputted string into an int
var amountAsInt = parseInt(amount, 10);
// Then, divide by 50 (which equals 2.4), and then use
// Math.floor() to "chop off" the decimal part
var numberOfFifties = Math.floor(amountAsInt/50);
// Leaving us with numberOfFifties = 2
// We can now use 'modulus' to give the amount left.
// If you haven't come across modulus before, it gives
// the remainder after dividing by the given number (here: 50)
var amountLeft = amount % 50;
// Do the same with the amount left to find the number of 20s
var numberOfTwenties = Math.floor(amountLeft/20);
if(numberOfFifties > 0){alert(numberOfFifties + " x " + "50 dollar bill(s)");}
if(numberOfTwenties > 0){alert(numberOfTwenties + " x " + "20 dollar bill(s)");}
的jsfiddle这里: http://jsfiddle.net/7p57e3u1/3/
原因NaN的
你可以看到为什么你看这个的jsfiddle得到一个NaN的原因。
http://jsfiddle.net/pto52oe5/
要设置二十到等于整个字符串,因此它是“非数”(NAN)。
alert(twenty=parseInt(fifty/50) + " x " + "50 dollar bill");
在这里,你似乎是假设
twenty=parseInt(fifty/50)
将作为一个独立的“零件”进行治疗,但事实上,它使用的整个表达式,设置twenty
是整个字符串即在警报(输出):
twenty = parseInt(fifty/50) + " x " + "50 dollar bill"
即(对于上面的例子)
twenty = "2 x 50 dollar bill"
一个有用的调试技术(以及创建更易于理解且可维护的代码)是将事情分解成非常简单的步骤,就像我在上面的示例代码中所做的那样。这(可以说)被分解得太过分了,但是用它作为第一种技术来打破这样的问题。
你'twenty'包含字符串'[数字] + “X” + “50美元的钞票”' – zvona
是的,但不应该parseInt函数转换仍然是成多少?据我所知,当转换字符串数字的一切权利的实际数字被忽略 –
@Jonon这就是'parseInt'做什么。但是,当浏览器首先评估'twenty/20',并且假设你试图将'string'除以20.它不会调用parseInt,它会使用Nubmer(二十)将它转换为数字,并且它变成'NaN '。 Ref:[Number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number)。 – fuyushimoya