chr*_*ude 1 javascript parsing integer
我有一个阵列.该数组responses[1]中的一个值是整数.此整数可以是1到您想要的任何数字.我需要得到整数中的最后一个数字,并根据该数字确定是否应该使用'st','nd','rd'或'th'结束数字.我怎么做?我试过了:
var placeEnding;
var placeInt = response[1]; //101
var stringInt = placeInt.toString();
var lastInt = stringInt.charAt(stringInt.length-1);
if (lastInt == '1'){
placeEnding = 'st';
} else if (lastInt == '2'){
placeEnding = 'nd';
} else if (lastInt == '3'){
placeEnding = 'rd';
} else {
placeEnding = 'th';
}
Run Code Online (Sandbox Code Playgroud)
但那没用.每当我尝试打印时placeEnding,无论是否应该是'st','rd'或'nd',它总是'th'.当我尝试打印placeInt时stringInt,或者lastInt它们都是打印"而不是数字.为什么会这样?当我responses[1]稍后在脚本中打印时,我没有问题得到正确的答案.
干得好:
var ends = {
'1': 'st',
'2': 'nd',
'3': 'rd'
}
response[1] += ends[ response[1].toString().split('').pop() ] || 'th';
Run Code Online (Sandbox Code Playgroud)
正如其他人所指出的那样,使用模数10更有效:
response[1] += ends[ parseInt(response[1], 10) % 10 ] || 'th';
Run Code Online (Sandbox Code Playgroud)
但是,如果数字中包含小数,则会中断.如果您认为可能,请使用以前的解决方案.
| 归档时间: |
|
| 查看次数: |
3840 次 |
| 最近记录: |