的代碼返回給定數的順序,例如
Number.getOrdinalFor(1) // returns "st"
Number.getOrdinalFor(2) // returns "nd"
Number.getOrdinalFor(3) // returns "rd"
Number.getOrdinalFor(4, true) // returns "4th"
// ^include number in output
要將其轉換爲常規功能可以稱爲
getOrdinalFor(1);
會這麼簡單
function getOrdinalFor(intNum, includeNumber) {
var o = [, 'st', 'nd', 'rd'];
return (includeNumber ? intNum : '') + (o[((intNum = Math.abs(intNum % 100)) - 20) % 10] || o[intNum] || 'th');
}
有點更具可讀性,有評論
function getOrdinalFor(intNum, includeNumber) {
var ordinals = [, 'st', 'nd', 'rd']; // the ordinals, except "th", in an array,
// with the first index starting at 1
var start = includeNumber ? intNum : ''; // start with the number, or empty string
// depending on includeNumber argument
intNum = Math.abs(intNum % 100); // set intNum to the result of "modulus 100" on it self
// this shortens down hundreds, thousands, and bigger
// numbers to max two digits. For instance
// 2 = 2
// 12 = 12
// 233 = 33
// 3444 = 44
// 111111111 = 11
// ...etc
var calc = (intNum - 20) % 10; // then subtract 20, and do "modulus" 10
// this shortens it to one integer,
// positive or negative, for instance
// 2 = -8
// 12 = -8
// 33 = 3
// 44 = 4
// 11 = -9
// ...etc
var result = ordinals[calc] || ordinals[intNum] || 'th'; // start at the left hand,
// and return first truthy value
// for instance, using the results of the numbers above
// ordinals[-8] does not exist (falsy), move along, ordinals[2] is "nd", so return "2nd"
// ordinals[-8] does not exist (falsy), move along, ordinals[12] is falsy as well, so return "12th"
// ordinals[3] is truthy, so return "33rd"
// ...etc
return result;
}
此代碼已被故意模糊,這將會使人們難以助陣。但是,是的,你可以逆向工程這個功能,並使其更具可讀性。這是一個立即調用的函數,它向Number模塊添加了函數('getOrdinalFor'函數)。 –
謝謝你的第一個答案,我不知道立即調用函數。 – bugyt