[英]Can you explain me this function I didn't understand and how to convert it in “normal” function?
I find this javascript function on Internet and I don't understand how it works. 我在Internet上发现了此javascript函数,但我不知道它是如何工作的。
(function(o) {
Number.getOrdinalFor = function(intNum, includeNumber) {
return (includeNumber ? intNum : '') + (o[((intNum = Math.abs(intNum % 100)) - 20) % 10] || o[intNum] || 'th');
};
})([, 'st', 'nd', 'rd']);
And can I convert it to a normal function like : 我可以将其转换为普通函数吗:
function getOrdinalFor (intNum, includeNumber) {
// code
}
The code returns an ordinal for a given number, for instance 该代码返回给定数字的序数,例如
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
To convert it to a regular function that can be called like 将其转换为可以像这样调用的常规函数
getOrdinalFor(1);
would be as simple as 就像
function getOrdinalFor(intNum, includeNumber) {
var o = [, 'st', 'nd', 'rd'];
return (includeNumber ? intNum : '') + (o[((intNum = Math.abs(intNum % 100)) - 20) % 10] || o[intNum] || 'th');
}
Somewhat more readable, with comments 可读性更高,带有注释
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.