Reputation: 11
request(target, function (err, resp, body) {
$ = cheerio.load(body);
links = $('a');
$(links).each(function (i, link) {
if ($(link).text().match('worker')) {
var a = $(link).attr('href').toString();
}
});
});
I want to use the output of variable a
in further program. Any pointers?
Upvotes: 0
Views: 103
Reputation: 8423
If you do like this:
JavaScript
var savedLinks;
request(target, function (err, resp, body) {
savedLinks = [];
$ = cheerio.load(body);
links = $('a');
$(links).each(function (i, link) {
if ($(link).text().match('worker')) {
var a = $(link).attr('href').toString();
savedLinks.push(a);
}
});
});
Then you can iterate through savedLinks
.
Like this:
for(var i = 0; i < savedLinks.length; i++) {
console.log(savedLinks[i]);
}
You have to call the function request
at some point for it to be initialized though of course.
Upvotes: 0
Reputation: 5201
You have two alternative ways to give the variable a
a global scope:
Declare it outside the request
function (*) and just assign it inside the each
cycle (**), i.e.:
var a; // (*)
request(target, function (err, resp, body) {
$ = cheerio.load(body);
links = $('a');
$(links).each(function (i, link) {
if ($(link).text().match('worker')) {
a = $(link).attr('href').toString(); // (**)
}
});
});
Simply remove the variable declaration inside the each
cycle (*), i.e.:
request(target, function (err, resp, body) {
$ = cheerio.load(body);
links = $('a');
$(links).each(function (i, link) {
if ($(link).text().match('worker')) {
a = $(link).attr('href').toString(); // (*)
}
});
});
(If you assign a value to a variable that has not been declared, it will automatically become a global variable).
Upvotes: 2
Reputation: 1314
the var
declaration is function
-scoped. This means it can only be used within the function it's declared in.
Explanation:
// 'a' does not exist
$(links).each(function (i, link) {
if($(link).text().match('worker')){
var a=$(link).attr('href').toString();
// 'a' exists'
}
// 'a' exists'
});
// 'a' does not exist
There are certain 'hacks' out there, like not 'declaring' it with var
, let
or const
. Doing it like that automatically makes it 'global', but this ofcourse has it drawbacks regarding memory usage and potential memory leaks (the same can be achieved with putting var
outside of the functions).
A better way to use it might be to split the functionality up a bit more and just let one function call another (or with callbacks, but I hate callbacks and they're not the solution to everything).
Upvotes: 0