JavaScript号码辅助

JavaScript号码辅助

我正在尝试创建一个页面,在该页面中提示用户输入数字,然后它会写出数字并在最后添加后缀。就像我输入3一样,它将写为3rd。我对如何解决这个问题感到困惑,我这样做只是为了好玩。

<html>
<head>
<title>Number Endings</title>
<script type="text/javascript">
// Program name: Number Endings
// Purpose: Add a suffix at the end of a number
// Date last modified: 3/29/12
var numbrentre = "";

numbrentre = prompt("What is the number integer?")

var numbrentre = "";

numbrentre = prompt("What is the number integer?")

function daySuffix(d) {
    d = String(d);
    return d.substr(-(Math.min(d.length, 2))) > 3 && d.substr(-(Math.min(d.length, 2))) < 21 ? "th" : ["th", "st", "nd", "rd", "th"][Math.min(Number(d)%10, 4)];
}

</script>
</head>
<body>
</body>
</html>

最佳答案

​var number,
    lastDigit,
    suffix;

number = prompt("What is the integer number?")​;

// Suffix is based on the last digit of the number
lastDigit = number[number.toString().length-1];

// Default to "th"
suffix = "th";
switch(lastDigit) {
    case "1": suffix = "st";
    case "2": suffix = "nd";
    case "3": suffix = "rd";
}

alert(number + suffix);

关于javascript - JavaScript号码辅助,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9927745/

10-09 14:49