實(shí)現(xiàn)Luhn 算法,用于驗(yàn)證各種識(shí)別號(hào)碼,例如信用卡號(hào)碼、IMEI 號(hào)碼、國家提供商標(biāo)識(shí)符號(hào)碼等。
使用String.prototype.split(),Array.prototype.reverse()和 Array.prototype.map()?結(jié)合parseInt()獲得數(shù)字?jǐn)?shù)組。
用Array.prototype.shift()獲取最后一位數(shù)字。
用Array.prototype.reduce()實(shí)現(xiàn) Luhn 算法。
如果sum能被 10 整除返回 true ,否則返回 false。
const luhnCheck = num => {
? const arr = (num + '')
? ? .split('')
? ? .reverse()
? ? .map(x => parseInt(x));
? const lastDigit = arr.shift();
? let sum = arr.reduce(
? ? (acc, val, i) => (i % 2 !== 0 ? acc + val : acc + ((val *= 2) > 9 ? val - 9 : val)),
? ? 0
? );
? sum += lastDigit;
? return sum % 10 === 0;
};
更多內(nèi)容請(qǐng)?jiān)L問:https://www.icoderoad.com