D
D
dimka_lubimka2019-12-29 21:37:33
JavaScript
dimka_lubimka, 2019-12-29 21:37:33

Why can't add indexof in js?

Hi, I'm learning js, doing tasks on the pile code. Here I threw in half of the solution, but for half an hour I’ve been in a stupor due to the fact that I can’t add indexOf of the array elements
console.log(typeof num); gives number and
console.log(num); NaN How is that even possible??

function addLetters(...letters) {
let alph=[];
let num;
function arrPush(a){
for(i=0;i<a.length;i++){
  b=i+1
  alph.push(a.slice(i,b));
  };
};
arrPush("abcdefghijklmnopqrstuvwxyz");
  for(i=0;i<letters.length;i++){
    num+=1+alph.indexOf(letters[i]);
    /*вот тут я вывел эту переменную*/
    console.log(typeof num);
    console.log(num);
  };
  
};
addLetters('a','b','z');

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladyslav Kliuiev, 2019-12-29
@TrueBlackBox

What is the task anyway? What is the end goal?

S
Somewhere Intech, 2020-12-30
@john36allTa

1. take the code of each letter in numerical equivalent and subtract 96('a' = 97, i.e. a = 1, counting starts from 1)
2. Sum them up
3. Take the remainder of dividing the resulting sum by 26 (number of letters) and add 97
Same with your approach:

function addLetters(...letters){
  let alphabet = 'abcdefghijklmnopqrstuvwxyz',
    len = alphabet.length,
    sum = len - 1// по умолчанию 'z'
  for (i=0;i<letters.length;i++)
    sum += alphabet.indexOf(letters[i]) + 1 // счет начинается с 1 (a=1)
  return alphabet.substr(sum % len,1) 
}

Candied version of the same:
Written based on the conditions of the skating rink

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question