如果数字以1结尾,做点什么

If number ends with 1 do something

本文关键字:什么 结尾 数字 如果      更新时间:2024-04-22

我想做这样的东西:

if(day==1 || day==11 || day==21 || day==31 || day==41 ......){
    result="dan";
}
else{
    result="dana";
}

我怎么能对每一个以1结尾的数字都这样做,当然也不写所有的数字?

只需检查除以10:的余数

if (day % 10 == 1) { 
  result = "dan";
} else {
  result = "dana";
}

%是"Modulo"或"Modulus"运算符,除非您使用的是JavaScript,在这种情况下,它是一个简单的余数运算符(不是真正的模)。它将两个数字相除,然后返回余数。

您可以使用模数运算符检查除以10的余数。

if (day % 10 == 1)
{ 
   result = "dan";
}
else
{
   result = "dana";
}

或者,如果您想避免正常的if:

result = "dan" + (day % 10 == 1 ? "" : "a");

%是Javascript Modulus运算符。它给你一个部门的剩余部分:

示例:

11 / 10 = 1 with remainder 1.
21 / 10 = 2 with remainder 1.
31 / 10 = 3 with remainder 1.
...

看到这个答案:%在JavaScript中做什么?以获得操作员操作的详细说明。

模运算符。你可以研究它,但基本上你想检测一个数字除以10后是否有1的余数:

if( day%10 == 1)

这可以通过单行解决

return (day % 10 == 1) ? 'dan' : 'dana';

您可以将数字转换为字符串并使用String.prototype.endsWith()

const number = 151
const isMatch = number.toString().endsWith('1')
let result = ''
if (isMatch) {
    result = 'dan'
} else {
    result = 'dana'
}

我在一些设置序数的代码中使用了它。例如,如果要显示1st2nd3rd4th:

        let ordinal = 'th';
        if (number.toString().endsWith('1')) {
            ordinal = 'st'
        }
        if (number.toString().endsWith('2')) {
            ordinal = 'nd'
        }
        if (number.toString().endsWith('3')) {
            ordinal = 'rd'
        }