global variable in javascript?

javascript, jquery

Solution

Define `links` outside the loop:

var links = [];
$(".link").each(function() {
  group += 1;
  text += 1;
  links[group] = [];
  links[group][text] = $(this).val();
});
var jsonLinks = $.toJSON(links);

I should also point out that this doesn't make a lot of sense because you will end up element 7, for example, being an array with a single element (indexed as 7) to the value. Is this really what you want?

What I imagine you want is an array of the values. If so, why not use `map()`?

var links = $(".link").map(function(i, val) {
  return $(val).val();
});

Problem

i have this code: ``` $(".link").each(function() { group += 1; text += 1; var links = []; links[group] = []; links[group][text] = $(this).val(); } }); var jsonLinks = $.toJSON(links); ``` after it has looped every .link it will exit the each loop and encode the array 'links' to json. but the array 'links' is a local variable inside the each-loop. how can i make it global outside the loop?

Original source