javascript - JavaScript 函数不适用于整数
问题描述
我有一个 javascript 函数,应该询问用户他们想订购多少产品。当他们订购的产品少于一种时,该功能应该给出一条消息。它还应该发送一条警告说“订购(数量)(产品)[s]”。这些似乎无法正常工作。
我试过返回数量,但这似乎只是将网页更改为数量。然而,这确实表明数量正在发挥作用。
function promptQuantity(product) {
var quantity = prompt("How many " + product + "s would you like?");
if (quantity > 1) {
var plural = "s";
}
if (quantity = 1) {
var plural = "";
}
if (quantity < 1) {
alert("Don't be ridiculous! You can't order less than one " + product + "!");
}
if (quantity > 0) {
alert("Ordering " + quantity + " " + product, plural);
}
}
我希望这个函数向用户发送警报,告诉他们他们已经订购了一定数量的产品,但它只是返回说“订购 1(产品)”
解决方案
这段代码if (quantity = 1)
是错误的,你正在做和赋值,quantity
将被设置为1
,以供比较使用if (quantity == 1)
。但是,您的代码可以像这样重组:
function promptQuantity(product)
{
var quantity = prompt("How many " + product + "s would you like?");
var plural = quantity > 1 ? "s" : "";
if (quantity < 1)
alert("Don't be ridiculous! You can't order less than one " + product + "!");
else
alert("Ordering " + quantity + " " + product + plural);
}
promptQuantity("Short");
推荐阅读
- flutter - 如何在构建中更新 TextEditingController 文本?
- python - 理解 scikit 中的问题 learn in Python
- python-3.x - 当试图让 yahoo_fin 返回代码列表的价格时,是什么导致了这个问题?
- filter - 从过滤页面中删除由 Yoast SEO 插件添加的 rel canonical
- java - 当我在没有将电缆插入 android studio 的情况下测试我的应用程序时出现 Android 应用程序错误
- pine-script - 对 plotshape 使用条件 if 语句
- python - 在Python中使用正则表达式获取字符之前/之后的单词
- python - 如何使用加权邻接矩阵绘制边缘权重?
- python - 无法在 vs 代码中使用 python 基础环境
- sql - 如何正确使用 SUM 和 GROUP BY 演示发票