Javascript function returns undefined

I'm sure I'm doing it all wrong, but I have the following function returning "undefined" in the console, although it can console.log () the requested values ​​from the same place in the function as the code commented.

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; }); } 

Another thing is that after running this code in the browser, I can enter the "tags" in the browser console, and it gives the correct result ["foo", "bar"] . However, when I try to use a tag variable (for example, a text value for an element, etc.), it does not work ... What gives? JavaScript is not my first language, so I'm a little confused about how it behaves. I just do not understand.

I read almost all the "Questions that may already have my answer," but the answers were provided where I could not figure out how to apply to my function.

Note:

  • JSON from the Joomla tag table (3.1).
  • I can get the data.
  • The value val === tagId conditionally works correctly.
  • I like popcorn.
+4
source share
2 answers

The getJSON call invokes the callback function asynchronously.

If you need the getTagNames function and call it many places in your code, you can make changes to force it to execute the callback function:

 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); }); } 

and then make the following calls:

 getTagNames(tags, function(tagArray) { // do something with tagArray }); 
+9
source

Statement return tagArray; returns the result of the success getJSON handler, which, firstly, does not expect any return value, and secondly, occurs asynchronously after the completion of getTagNames .

+2
source

Source: https://habr.com/ru/post/1488751/


All Articles