2

So I am trying to write this function that calculates the average based on values in a string by first converting it to an array with JSON.parse. I am getting an error on the JSON.parse and I am not sure why.

"Uncaught SyntaxError: Unexpected token N" line: var elmt = JSON.parse('[' + string + ']');

    function averageRisk() {
            var sum = 0;
            var string = +health_grab; 
            // this returns a string from my database like this: 8,5,3,5,2,6,8,9

            var elmt = JSON.parse('[' + string + ']');

            console.log("healthLevels: " + elmt);

            for (var i = 0; i < elmt.length; i++) {
                        sum += parseInt(elmt[i].value, 10); 
            }

            if (isNaN(sum)) {
                        return false;
            }

            avg = Math.round(sum / elmt.length);

            console.log("Sum: " + sum);
            console.log("Average: " + avg);
    }
1
  • 6
    your string is NaN, what is the plus in +health_grab for? Commented Feb 25, 2016 at 0:10

2 Answers 2

5

You have a unary plus + operator on +health_grab. This attempts to convert it into a number. This doesn't work and it produces NaN.

JSON.parse() tries and fails to parse NaN resulting in the error when it reaches the first character N.

Uncaught SyntaxError: Unexpected token N

Remove the + and it should fix the error.

Sign up to request clarification or add additional context in comments.

1 Comment

this fixed it. I thought that I needed the "+" to bring it in from the database as numbers. Thank you
0

I think you have a typo on your third line. You have an extra "+". When I test this in Node.JS I get the same error as you. Remove the "+" and it should work.

If this isn't a typo, what were you attempting to achieve with the prefixed "+"?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.