I don't know why the object value is NaN.

Asked 2 years ago, Updated 2 years ago, 85 views

Hello, how are you?

var b = fn('AACBDB')

I want to put the matching alphabet in the object value and increase the number if it matches I'm asking you a question as NaN.

 {
    A:2,
    B:2,
    C:1
  }

I'd like to do it this way. Below is the code text.

function fn (str) {
    var result = '';
    var characters = {};
    var strArr = str.split('');
    var strCopy = str.split('');

    for(var i = 0;i < strArr.length; i++){
        if(strArr[i] === strCopy[i]){
            characters[strArr[i]]++;
        };
    };

    console.log(characters);


    return result;
};

Thank you.

vanillacoding javascript

2022-09-21 15:28

2 Answers

In the above code, the value of each element of characters starts the operation from undefined and it seems that NaN comes out.

So I think we need to revise it as below.

function fn (str) {
    var characters = {};
    var strArr = str.split('');

    for(var i = 0;i < strArr.length; i++){
        if(characters[strArr[i]] === undefined) {
            characters[strArr[i]] = 1;
        } } else {
            characters[strArr[i]] += 1;
        }
    }

    // // console.log(characters);

    return characters;
};

var  results = fn('BBBCCCEEEYYUUTTTTTTTT');

console.log(results);

Execution result : { B: 3, C: 3, E: 3, Y: 2, U: 2, T: 8 }


2022-09-21 15:28

characters I think it's because the initial value is not set with the corresponding attribute on the object :-)

I think it will be solved if the process of checking whether the initial value is set to a number is added.


2022-09-21 15:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.