unexpected token ( for javascript

Mohammad

I want to write an algorithm into javascript and I am sure I wrote true . the algorithm gives a number from user and gives the user the result : 1+3+5+...+(2n+1) and "n" is var. the javascript gives me errors : calc() is not defined , unexpected token;

<html>
<head>
    <title>Algorithm</title>
    <script type="text/javascript">
        function calc(){
            var n = document.getElementById('value').value;
            var sum = 0, i = 1, k = 0;
            for(k=0,k<n,k++){
            sum = sum += i;
            i+=2;
            k++;
            }
            document.getElementById('answer').innerHTML = sum;
        }
    </script>
</head>
<body>
    <input type="text" id="value" placeholder="Enter your number"/>
    <button onclick="calc()">OK</button><br/>
    <h1 id="answer"></h1>
</body>

Lix

The problem is your for loop syntax. You need to use a semi-colon ; to separate the statements:

for( k = 0; k < n; k++ ){
 ...
}

Taken from the MDN documentation:

Creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.


The JavaScript engine can not parse your for loop and then it encounters the closing bracket of the loop (which it wasn't expecting as it was still trying to parse the conditions of the loop).

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related