【问题标题】:how to define a parameter must be a number in a function [duplicate]如何定义参数必须是函数中的数字[重复]
【发布时间】:2023-01-12 15:42:27
【问题描述】:

我如何编写防御性代码行,说明参数必须是数字或 console.log '它必须是数字

function getDiscount(taxBoolean,guests) {
    getPrices(taxBoolean)
    
    let condition1 = typeof(guests) == 0
    let condition2 = condition1 > 0 && condition1 < 30
    if (condition1 && condition2) {
        let discount = 0
        if (guests < 5) {
            discount = 5
        }
        else if (guests >= 5) {
            discount = 10
        }
 console.log(`Discount is : $${discount}`)
    }
     else{
        console.log(`the secound argument must be a number between 0 and 30`)
    }
   
}

【问题讨论】:

标签: javascript function


【解决方案1】:

您可以像这样使用 typeof 运算符:

if (typeof guests === 'number') {
    // number
} else {
    console.log('not a number');
}

【讨论】:

  • 假设我们不能有一半的客人,使用Number.isInteger可能会有所改善。
猜你喜欢
  • 2019-06-06
  • 1970-01-01
  • 1970-01-01
  • 2014-05-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-16
  • 2021-02-02
  • 2016-11-26
相关资源
最近更新 更多