开发者

What will this function return? An empty Array or Array of Objects

开发者 https://www.devze.com 2023-03-01 17:26 出处:网络
var rowData = []; function someName() { JsonClient.onload = fun开发者_运维技巧ction () { rowData.push(\"sasas\");
var rowData = [];

function someName() {
    JsonClient.onload = fun开发者_运维技巧ction () {
        rowData.push("sasas");
        rowData.push("sasas1");
        rowData.push("sasas2");
        rowData.push("sasas3");
    };

    return rowData;
}

This returns me an empty rowData. Why?

Guys it was an typo mistake by me while posting


The function someName is never called (e.g. someName();). Since it is never called, the push statements are never executed.

Even if it were called, the someName function just assigns an anonymous callback function to JsonClient.onload. Your code doesn't show us what JsonClient is, but it seems to be a safe assumption that it is an event handler for an HTTP Response. That function won't be called until the HTTP Response is received by the browser, by which time the return statement would already have been executed. You can't return from an Ajax request, you have to deal with the data in the callback itself.


You have a function that declares an anonymous function that will not execute until your JsonClient has loaded.

You will need to do this:

var rowData = [];
function someName(){
   JsonClient.onload = function(){
     rowData.push("sasas");
     rowData.push("sasas1");
     rowData.push("sasas2");
     rowData.push("sasas3");
     useRowData(rowData);
   };
   // here I would expect a call like JsonClient.send();
}
function useRowData(rowData) {
  alert(rowData);
}
someName(); // execute the actual function


You forgot to close quotes on each string you're trying to push.. Once you do that it will return an array of strings.


You didn't closed strings... this should work var rowData = [];

function someName(){
   JsonClient.onload = function(){
   rowData.push("sasas");
   rowData.push("sasas1");
   rowData.push("sasas2");
   rowData.push("sasas3");
};

return rowData;

}

0

精彩评论

暂无评论...
验证码 换一张
取 消