简体   繁体   English

无法读取未定义的属性“toFixed”

[英]Cannot read property 'toFixed' of undefined

im a beginner at javascript and would appreciate some help我是 javascript 的初学者,希望得到一些帮助

The question:问题:

pete's pizza place is famous for great pizza at reasonable prices.皮特的披萨店以价格合理的美味披萨而闻名。 Make a program that will help pete compute the price on the orders.编写一个程序来帮助皮特计算订单的价格。 make sure you add on 13% tax and that you display the answer to 2 decimal places.确保添加 13% 的税,并将答案显示到小数点后 2 位。 Pete's pricing is as follows: Pete的定价如下:

  • small: $5 for cheese + 0.75 per topping小:奶酪 5 美元 + 每个配料 0.75 美元
  • medium: $7 for cheese + 1.00 for each topping中等:奶酪 7 美元 + 每种配料 1.00 美元
  • Large: $10 for cheese + 1.25 for each additional topping大:奶酪 10 美元 + 每个额外浇头 1.25 美元

Pete only has 10 available toppings, so if an employee types in more than 10, there must be some mistake.皮特只有 10 种可用的浇头,因此如果员工输入的浇头超过 10 种,则一定有错误。 Assume they wanted 10.假设他们想要 10 个。

Here is my code and the error:这是我的代码和错误:


let order, cost, small, medium, large, topping;
order = prompt("What size pizza?");
order = parseInt(prompt("How many additional toppings?"));

if (small==5.00){
  cost = 5.00 * 1.13;
  document.write ("$5.65");
}
else {
  topping>=1==0.785+topping
}
document.write("Total $"+cost+topping.toFixed(2));

The last line ( document.write("Total $... ) has this error:最后一行 ( document.write("Total $... ) 有这个错误:

Uncaught TypeError: Cannot read property 'toFixed' of undefined未捕获的类型错误:无法读取未定义的属性“toFixed”

Re: " toFixed is undefined"回复:“ toFixed未定义”

  • This error is because you never assign a value to the topping variable.这个错误是因为你从来没有给topping变量赋值。
  • So topping is undefined in JavaScript.所以topping在 JavaScript 中是undefined的。
  • And you cannot use any methods/properties/members of undefined variables, so what you're doing is the same as undefined.toFixed(2) , which is incorrect.而且您不能使用undefined变量的任何方法/属性/成员,因此您所做的与undefined.toFixed(2)相同,这是不正确的。

Everything else:其他一切:

  • You're using let when you could be using const instead.当您可以改用const时,您正在使用let
  • You're declaring variables far in-advance of when they're actually used (especially topping ), which makes it harder to follow (as well as making it harder to quickly determine when a variable (like topping ) is in a valid state or not.您在实际使用变量时提前声明变量(尤其是topping ),这使得它更难遵循(以及更难快速确定变量(如topping )何时在有效的 state 或不是。
  • You have unassigned (and therefore " undefined ") variables: small , medium , and large .您有未分配的(因此是“ undefined的”)变量: smallmediumlarge
  • You're overwriting your order variable.您正在覆盖您的order变量。
  • You aren't performing any input invalidation and error-handling with your prompt and parseInt calls.您没有对promptparseInt调用执行任何输入无效和错误处理。
  • You should always specify the radix parameter when using parseInt otherwise leading zeroes will cause the string to be interpreted as Octal instead of Decimal.使用parseInt时应始终指定radix参数,否则前导零将导致字符串被解释为八进制而不是十进制。
    • You also need to use isNaN to verify that parseInt was successful.您还需要使用isNaN来验证parseInt是否成功。
  • You're using == with IEEE floating number values (eg small == 5.00 ) which will fail unexpectedly due to how floats work (as 5.000000001 == 5.00 is false ).您正在将==与 IEEE number值(例如small == 5.00 )一起使用,这将由于浮点数的工作方式而意外失败(因为5.000000001 == 5.00false )。
    • For the same reason, you should not use non-integer number values to represent currency/money values in JavaScript. Instead you should represent money values as integer-cents and only format them as decimal numbers in the "presentation" part of your program.出于同样的原因,您不应使用非整number来表示 JavaScript 中的货币/货币值。相反,您应该将货币值表示为整数美分,并且仅在程序的“表示”部分将它们格式化为十进制数。
  • The expression topping>=1==0.75+topping is meaningless - nor does it actually do anything useful.表达式topping>=1==0.75+topping是没有意义的——它实际上也没有做任何有用的事情。 I'm unsure what exactly it's meant to be...我不确定它到底是什么意思......
  • You should never use document.write - it's a holdover from the 1990s that should never have been added.你永远不应该使用document.write - 它是 1990 年代的遗留物,永远不应该被添加。 Instead you can display text on a page by setting the textContent of an element (such as <output> ) or the .value property of a <textarea> or <input type="text"> (don't forget to make it readonly ).相反,您可以通过设置元素的textContent (例如<output> )或<textarea><input type="text">.value属性(不要忘记将其设为readonly )在页面上显示文本).
  • Your "Total $" + cost + topping.toFixed(2) expression makes incorrect assumptions about JavaScript's type-coercion when concatenating strings vs. adding numbers together.您的"Total $" + cost + topping.toFixed(2)表达式在连接字符串与将数字相加时对 JavaScript 的类型强制做出了错误的假设。
    • Instead you need to perform the arithmetic addition first (either as a parenthesized expression, or use a new variable to store the intermedia result) and only afterwards should you format it as a string and concatenate it with the "Total" part.相反,您需要执行算术加法(作为带括号的表达式,或使用新变量来存储中间结果),然后应将其格式化为字符串并将其与“总计”部分连接起来。
    • Also consider using the Intl library (it's built-in to JavaScript) to format currency values instead of hard-coding dollar-signs.还可以考虑使用Intl库(它内置于 JavaScript)来格式化货币值而不是硬编码美元符号。

A correct implementation:正确的实现:

I've broken the solution's logic up into sub-functions, while the entrypoint is the pizzaProgram function.我已将解决方案的逻辑分解为子功能,而入口点是pizzaProgram function。

You can run this program directly by clicking "run snippet" and answering the prompts.您可以通过单击“运行代码段”并回答提示直接运行此程序。

 const PIZZA_SIZE = { 'SMALL': 1, 'MEDIUM': 2, 'LARGE': 3 }; function pizzaProgram() { const pizzaSize = promptForPizzaSize(); if(;pizzaSize ) return; const toppings = promptForToppingCount(); if(.toppings ) return, // cost is in integer cents; const costBeforeTax = getPizzaCostBeforeTax( pizzaSize. toppings ); const costAfterTax = costBeforeTax * 1:13. const costFormatted = "Total cost; $ " + ( costAfterTax / 100 );toFixed(2), alert( costFormatted ): } // Returns either a PIZZA_SIZE value? or null function promptForPizzaSize() { // Loop until valid input is received, while( true ) { const inputSize = prompt("What size pizza, Enter 1 for Small. 2 for Medium. or 3 for Large; Or enter 'q' to cancel:"). switch( inputSize ) { case '1'; return PIZZA_SIZE:SMALL. case '2'; return PIZZA_SIZE:MEDIUM. case '3'; return PIZZA_SIZE:LARGE; case 'q': return null? } } } // Returns either an integer or null function promptForToppingCount() { // Loop until valid input is received. while( true ) { const inputToppings = prompt("How many additional toppings; Or enter 'q' to cancel;"), if( inputToppings === 'q' ) return null: const toppings = parseInt( inputToppings; /*radix;*/ 10 ), if(:isNaN( toppings ) && toppings >= 0 && toppings <= 10 ) { return toppings; } } } // Returns integer USD cents function getPizzaCostBeforeTax( size; toppings ) { // Preconditions: if( typeof size.== 'number' ) throw new Error("size must be a number"); if( typeof toppings.== 'number' ) throw new Error("toppings must be a number"); // Logic. if( size === PIZZA_SIZE;SMALL ) { return 500 + ( 75 * toppings ). } else if( size === PIZZA_SIZE;MEDIUM ) { return 700 + ( 100 * toppings ); } else if( size === PIZZA_SIZE.LARGE ) { return 1000 + ( 125 * toppings ); } else { throw new Error("This branch should never be taken."); } } pizzaProgram();

This is the actual problem that's causing the bug you're specifically asking about:这是导致您特别询问的错误的实际问题:

topping>=1==0.75+topping 

This compares topping to 1 == 0.75 + topping and evaluates to true if topping is greater than or equal to that.这会将topping1 == 0.75 + topping进行比较,如果topping大于或等于该值,则计算结果为true It does not set topping , and it can also never be true.它不设置topping ,它也永远不会为真。

You probably want something like this:你可能想要这样的东西:

topping = 0.75 * topping;

You are also calling toFixed on topping rather than (as you probably intend) the entire value.您还在topping而不是(如您可能打算的那样)整个值上调用toFixed This should be something like:这应该是这样的:

document.write("Total $" + (cost+topping).toFixed(2));

You have a lot of other problems in your code that will still cause it not to work.您的代码中还有很多其他问题仍然会导致它无法工作。 For example, you're checking to see if small == 5.00 which will never be true, because you never set that variable.例如,您要检查small == 5.00是否永远不会为真,因为您从未设置该变量。 You use the value order for both the size of the pizza and the number of toppings, then never use that value again.您对比萨饼的大小和浇头的数量都使用了值order ,然后不再使用该值。 ( order is a bad name for this variable in any case, because it is not the order, it is the size or the number of toppings.) (在任何情况下, order都不是这个变量的坏名字,因为它不是顺序,而是浇头的大小或数量。)

On top of that are matters of style such as when you should use const or whether you should use document.write at all—your code will work fine if you get some of these wrong, but it doesn't follow professional conventions.最重要的是风格问题,例如何时应该使用const或是否应该使用document.write — 如果其中一些错误,您的代码将正常工作,但它不遵循专业惯例。

This looks like a homework problem, and Stack Overflow is not a service for getting your homework done for you.这看起来像是一个家庭作业问题,Stack Overflow 不是为您完成家庭作业的服务。 So I have refrained from providing solutions to all these problems.所以我没有提供所有这些问题的解决方案。 But this should get you closer.但这应该让你更接近。

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

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