javascript - How can a number in a dictionary in an array be NaN directly after I inserted 1? -


i have piece of code includes this:

var clustercenters = [{"x": 1,"y": 1},{"x": 10,"y": 10}]; console.log(clustercenters); 

in chrome 26:

enter image description here

in firefox 21:

enter image description here

why error occur?

i guess error has in following function.

function getkmeansinfo(k, mousex, mousey) {     // choose cluster centers     var clustercenters = [{"x": 1,"y": 1},{"x": 10,"y": 10}];     console.log(clustercenters);      (iteration=0;iteration< 20;iteration++) {         // each object, check cluster nearest         (i=0; i<points.length; i++) {             var distmin = 1000000;             var clustermin = 0;             for(j=0; j<k; j++) {                 var dist = euklideandist(clustercenters[j], points[i]);                 if (dist < distmin) {                     distmin = dist;                     clustermin = j                 }             }             points[i]["cluster"] = clustermin;         }          // calculate center of cluster         var clustersum = new array(k);         (i=0; i<k; i++) {             clustersum[i] = {"x":0, "y":0, "n":0};         }         (i=0; i<points.length; i++) {             clustersum[points[i]["cluster"]]["x"] += points[i]["cluster"]["x"];             clustersum[points[i]["cluster"]]["y"] += points[i]["cluster"]["y"];             clustersum[points[i]["cluster"]]["n"] += 1;         }         (i=0; i<k; i++) {             if (clustersum[i]["n"] > 0) {                 clustercenters[i] = {                     "x":clustersum[i]["x"]/clustersum[i]["n"],                     "y":clustersum[i]["y"]/clustersum[i]["n"]};             }         }     }      return {"cluster":1, "radius":10}; } 

the full source on github.

edit: complete example still online.

any recommendations use of javascript welcome (i'm new javascript).

i've recognized using floating point numbers in example above gives less errors ... error still occurs. never divide through "x" or "y", through "n" (and check if n 0 bevore dividing) don't see how can nan.

as has been mentioned console logging can tricky. chrome, in particular displays single valued objects in live format.

if logging multiple times see evolution of object, use following :

 console.log (json.stringify (obj)); 

this ensure see value @ time console.log executed. rely on json.stringify , fail complex, recursive objects won't dom objects example.

debugging javascript

when want debug javascript, can either use firefox firebug or chrome , built-in developer tools. open them ctrl+shift+i. this:

enter image description here

with developer tools, can set breakpoints makes debugging easier.


Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

java - Using an Integer ArrayList in Android -