简体   繁体   English

JavaScript条件语句不起作用

[英]JavaScript Conditional Statement Not Working

What's wrong with this JavaScript? 这个JavaScript有什么问题?

var numPackages == 0;

if (coffeeProducts <= 12) {
  numPackages == 1;
} else if (coffeeProducts % 12 == 0) {
  numPackages == coffeeProducts/12;
} else {
  numPackages == (coffeeProducts/12) + 1;
}

Basically, it needs to calculate the number of boxes/packages necessary to ship an amount of items (12 per box). 基本上,它需要计算运送一定数量物品(每箱12个)所需的箱子/包装数量。 Is there a better way to do this, perhaps using round()? 是否有更好的方法可以执行此操作,也许使用round()?

== is condition. ==是条件。

= is assignment. =是分配。

The better way is to use Math.ceil() to round to next integer. 更好的方法是使用Math.ceil()舍入到下一个整数。

So: 所以:

var numPackages = Math.ceil(coffeeProducts/12);

All the others explained your mistake with the comparing operator == and the assigning operator = . 其他所有人都用比较运算符==和赋值运算符=解释了您的错误。

The shortest way to solve it would be 解决它的最短方法是

var numPackages = Math.ceil( coffeeProducts / 12 );

Make each statement look like this: 使每个语句如下所示:

if (coffeeProducts <= 12) {
    numPackages = 1; // just "=", not "=="
}

Single equals (=) for assignment: x = 10 分配等于(=): x = 10

Double equals (==) for comparison: if (x == 10) 双等于(==)进行比较: 如果(x == 10)

Triple equals for special cases where type is important as well as the value. 对于类型和值都很重要的特殊情况,三重等于。

Change your two numPackages lines to a single equals and you're good to go :) 将您的两个numPackages行更改为一个等于,您就可以开始了:)

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

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