“Luhn Algoritma Javascript” Kode Jawaban

Luhn Algoritma Javascript

/*
HTML:
<form action="">
      <label for="cardNum">Card Number</label><br>
      <input type="text" id="cardNum" placeholder="Please type your credit card number here..."><br>
</form>
<button onclick="checkIfPassLuhn()" class="checker">Check if the above number passes the Luhn Algorithm</button>
*/

function checkIfPassLuhn() {
    var num = document.getElementById("cardNum").value;
    var array = (num + '').split('').reverse().map(x => parseInt(x));
    var theLastDig = array.shift();
    let sum = array.reduce((prevVal, curVal, index) => (index % 2 !== 0 ? prevVal + curVal : prevVal + ((curVal *= 2) > 9 ? curVal - 9 : curVal)), 0);
    sum += theLastDig;
    if(sum % 10 === 0){
        alert("Your number is correct!");
    }else{
        alert("Your number is incorrect");
    }
}
//Call the method with an HTML element
Fair Flamingo

Luhn Algoritma Javascript

/**
 * Luhn algorithm in JavaScript: validate credit card number supplied as string of numbers
 * @author ShirtlessKirk. Copyright (c) 2012.
 * @license WTFPL (http://www.wtfpl.net/txt/copying)
 */
var luhnChk = (function (arr) {
    return function (ccNum) {
        var 
            len = ccNum.length,
            bit = 1,
            sum = 0,
            val;

        while (len) {
            val = parseInt(ccNum.charAt(--len), 10);
            sum += (bit ^= 1) ? arr[val] : val;
        }

        return sum && sum % 10 === 0;
    };
}([0, 2, 4, 6, 8, 1, 3, 5, 7, 9]));
Undefined

Jawaban yang mirip dengan “Luhn Algoritma Javascript”

Pertanyaan yang mirip dengan “Luhn Algoritma Javascript”

Lebih banyak jawaban terkait untuk “Luhn Algoritma Javascript” di JavaScript

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya