4

I am sure I am doing this all kinds of wrong, but I have the following function returning 'undefined' in the console even though it can console.log() the wanted values from the same place in the function as commented in the code.

var tags = [4, 5];
console.log(getTagNames(tags)); // 'undefined'

function getTagNames(tagArray) {  

    $.getJSON('js/tags.json', function(data) {
        for (var i in tagArray) {
            tagArray[i] = tagArray[i].toString();
            var val = tagArray[i];

            for (var t in data) {
                var tag = data[t];
                var tagName = tag.alias;
                var tagId = tag.id;
                if (val === tagId) {
                    tagArray[i] = tagName;
                }
            };
        }
        console.log(tagArray); // output ["foo", "bar"] 
        return tagArray;
    });
}

The other odd thing is that, after running this code in the browser, I can type "tags" into the browser console and it gives me the correct result ["foo", "bar"]. However when I try using the tags variable (i.e.: text value for an element and such), it doesn't work... What Gives? JavaScript isn't my first language so I am a little confused of exactly how it behaves. I just don't understand.

I have read almost all of the "Questions that may already have my answer", but the answers supplied where those that I couldn't figure out how to apply to my function.

NOTE:

  1. The JSON is from the Joomla(3.1) tags table.
  2. I am able to retrieve the data.
  3. The val === tagId conditional is working correctly.
  4. I like popcorn.
4

2 回答 2

9

调用getJSON异步调用您的回调函数。

如果您需要该函数getTagNames并在代码中的许多地方调用它,您可以进行更改以使其本身具有回调函数:

function getTagNames(tagArray, cb) {  

    $.getJSON('js/tags.json', function(data) {
        for (var i in tagArray) {
            tagArray[i] = tagArray[i].toString();
            var val = tagArray[i];

            for (var t in data) {
                var tag = data[t];
                var tagName = tag.alias;
                var tagId = tag.id;
                if (val === tagId) {
                    tagArray[i] = tagName;
                }
            };
        }
        console.log(tagArray); // output ["foo", "bar"] 
        cb(tagArray);
    });
}

然后像这样调用它:

getTagNames(tags, function(tagArray) {
    // do something with tagArray
});
于 2013-06-28T19:21:12.980 回答
2

语句return tagArray;返回success处理程序的结果getJSON,首先,不期望任何返回值,其次,异步发生 - 在您getTagNames完成执行之后的方式。

于 2013-06-28T19:15:48.720 回答