开发者

going through substr with loop and then want to identify the index

开发者 https://www.devze.com 2023-02-08 01:52 出处:网络
Im trying to get the index number of corresponding characters in a string. I mean a loop does make it possible to treat characters in a string like an \'array\' of characters with the string method ch

Im trying to get the index number of corresponding characters in a string. I mean a loop does make it possible to treat characters in a string like an 'array' of characters with the string method charAt() and indexOf(), right?

here's the code:

/** ****** WINDOW ONLOAD EVENT HANDLER **************** */
window.onload = function(){
    // DOM elements
    var theButton = document.getElementById('theButton');
    var form = document.formISBN;
    var numberField = document.getElementById('theInput')

    theButton.onclick = function(){
        var number = numberField.value;
        console.log(number)
        controlNr = calculControlNr(number);
        // console.log(controlNr);
    }
}

function calculControlNr(number) {
    number = number.replace(' ','','g');
    number = number.replace('-','','g');
    var sum = 0;
    var sumEven = 0;
    var sumUneven = 0;
    var factor = 3;
    var numberExtract = number.substr(0,11);

    console.log(numberExtract.length)
    for (var i = 0; i < numberExtract.length; i++) {
        console.log(numberExtract.indexOf(numberExt开发者_Go百科ract.charAt(i)));
    }
}


How about

var numberExtract = number.split('');

console.log(numberExtract.length)
for (var i = 0; i < numberExtract.length; i++) {
    if (i==11) break; // you only wanted the first 11?
    console.log(i+':'+numberExtract[i]);
}

But your code does work anyway. Here is what I did to test it

<script>
/** ****** WINDOW ONLOAD EVENT HANDLER **************** */
window.onload = function(){
    // DOM elements
    var theButton = document.getElementById('theButton');
    var form = document.formISBN;
    var numberField = document.getElementById('theInput')

    theButton.onclick = function(){
        var number = numberField.value;
        alert(number)
        controlNr = calculControlNr(number);
        // alert(controlNr);
    }
}

function calculControlNr(number) {
    number = number.replace(' ','','g');
    number = number.replace('-','','g');
    var sum = 0;
    var sumEven = 0;
    var sumUneven = 0;
    var factor = 3;
    var numberExtract = number.substr(0,11);

    alert(numberExtract.length+':'+numberExtract);
    for (var i = 0; i < numberExtract.length; i++) {
        alert(i+':'+numberExtract.indexOf(numberExtract.charAt(i)));
    }
}
</script>
<form name="formISBN">
<input id="theInput" type="text" value="01234567890-A A" />
<input id="theButton" type="button" value="click"/>
</form>
0

精彩评论

暂无评论...
验证码 换一张
取 消