简体   繁体   中英

indexOf() skipped repeated element javascript

I am trying to print the values of odd positions in the array below but it skipped 7, what could be wrong, please?

const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8];

const validateCred = (serialDigits)=>{
  //let sum = 0;
  for (let i = serialDigits.length - 1; i >= 0; i--){
    let currentDigit = serialDigits[i];
    
    if( serialDigits.indexOf(currentDigit) % 2 === 1){
      console.log(currentDigit)
        };
    }
}

console.log(validateCred(valid1));
// 0 6 0 0 6 3 4

This:

 if( serialDigits.indexOf(currentDigit) % 2 === 1){

Is not a good line because indexOf find the first occurrence in the array, therefore, do not fulfil your need. just use the variable i instead:

if (i % 2 === 1) {

Similarly, if you want to print the even indexes, you can use this code:

 const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]; const validateCred = (serialDigits) => { //let sum = 0; for (let i = serialDigits.length - 1; i >= 0; i--) { let currentDigit = serialDigits[i]; if (i % 2 === 0) { console.log(currentDigit); }; } } validateCred(valid1); // 0 6 0 0 7 6 3 4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM