Ad

Unexpected Undefined Value In JS Script

- 1 answer

I am solving this problem. I want to solve it in JS.

I have a function in JS to solve this (is_Happy), all my code is given bellow-

function myFunction() {
    var x = document.getElementById("fname");
    n = Number(x.value);
document.getElementById("output").innerHTML=
                                   is_Happy(n);
}

function is_Happy(n)
{
    if(n<10)
    {
        if(n==1 || n==7)
            return true;
        else
            return false;
    }
    else
    {
        is_Happy( calculate_value( get_digit(n) ) );
    }
}

function get_digit(number)
{
    var output = [];
    var sNumber = number.toString();

    for (var i = 0, len = sNumber.length; i < len; i += 1) {
        output.push(+sNumber.charAt(i));
    }
    return output;
}

function calculate_value(num_array)
{
    var sum=0;
    var i=0;
    while(num_array.length>i)
    {
        number = Number(num_array[i]);
        if(number>0)
            sum+=num_array[i]*num_array[i];
        i++;
    }
    return sum;
}
<p id = "output">character to upper case.</p>
Enter your name: <input type="text" id="fname" onkeyup="myFunction()">

The problem is I should have find something (true/false) if I give input any number, but I am getting undefined if I input any number greater than 9 (10 or above).

Can anyone please help?

Ad

Answer

Because you doesn't return anything in function else part.
return is_Happy

return is_Happy( calculate_value( get_digit(n) ) );

Following working code.

function myFunction() {
    var x = document.getElementById("fname");
    n = Number(x.value);
document.getElementById("output").innerHTML=
                                   is_Happy(n);
}

function is_Happy(n)
{
    if(n<10)
    {
        if(n==1 || n==7)
            return true;
        else
            return false;
    }
    else
    {
      
      return is_Happy( calculate_value( get_digit(n) ) );
      
    }
}

function get_digit(number)
{
    var output = [];
    var sNumber = number.toString();

    for (var i = 0, len = sNumber.length; i < len; i += 1) {
        output.push(+sNumber.charAt(i));
    }
    return output;
}

function calculate_value(num_array)
{
    var sum=0;
    var i=0;
    while(num_array.length>i)
    {
        number = Number(num_array[i]);
        if(number>0)
            sum+=num_array[i]*num_array[i];
        i++;
    }
    return sum;
}
<!DOCTYPE html>
<html>
<body>

<p id = "output">character to upper case.</p>
Enter your name: <input type="text" id="fname" onkeyup="myFunction()">



</body>
</html>

Ad
source: stackoverflow.com
Ad