Javascript function returns undefined

Firstly, I am new to javascript, and this is my first "project" in this language, so I apologize in advance for my mobility.

I use the booklet and D3 in this project, and I cannot force this function to return anything other than 'Undefined'. At first I, although I did not return from the function correctly, so I tried to duplicate the error on a smaller scale here:

http://jsfiddle.net/KhqwR/

However, this worked for me, so now I am a little lost what to do.

Here is a simple version of my code, I tried to delete everything that did not seem relevant to me, and changed the names to make it easier to understand:

$(function () {
  ...  
  function getThings(code) {    
    d3.csv("data.csv", function(data){
      for (var i = 0, len = data.length; i < len; i++){        
        if (data[i].code == code){                     
          alert("return 5!")
          return 5;
        }
        else{
          return 0;
        }
      }
    })
  }

  L.geoJson( features,  {
    style: function (feature) {
      return { opacity: 0, fillOpacity: 0.5, fillColor: "#0f0" };
    },
    onEachFeature: function(feature, layer){ 
      var test = getThings(5);      
      alert(test);
      ...

I consistently get to "return 5!" and then in the warning (test) I just get "Undefined".

- , ? !

+3
3

d3.csv , . , getThings return, undefined .

, return , , .

function getThings(code) {
    /* Without an explicit return, a function always evaluates
       to undefined when invoked. */
    return d3.csv("data.csv", function(data){ .. });
})

var test = getThings(..);
/* Now test is NOT undefined, but is also NOT the data
   for the asynchronous reasons discussed elsewhere.
   See the link above for correct usage. */
test.row(..);
+2

d3.csv() - . , getThings() d3.csv() undefined

d3:

HTTP GET - (CSV) URL. , RFC4180-. mime "text/csv". ,, .

+1

This is due to Javascript Async Nature. Use the callback function.

0
source

All Articles