2016-03-11 52 views
1

我在互聯網上找到這個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']); 

而且我可以將其轉換爲正常的功能,如:

function getOrdinalFor (intNum, includeNumber) { 
    // code 
} 
+1

此代碼已被故意模糊,這將會使人們難以助陣。但是,是的,你可以逆向工程這個功能,並使其更具可讀性。這是一個立即調用的函數,它向Number模塊添加了函數('getOrdinalFor'函數)。 –

+0

謝謝你的第一個答案,我不知道立即調用函數。 – bugyt

回答

2

的代碼返回給定數的順序,例如

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; 
} 
+0

感謝您的轉換和卡爾文的回答,現在我明白了。我想最後解釋一下這段代碼是如何工作的: (x || y || z) – bugyt

+0

「返回第一個真值」我現在完全理解了,謝謝。 – bugyt