I need to dynamically create variables inside a loop, but i have no idea how. I have read about using eval(); but all i found it's just about dynamically changing the value inside the variable.
I need something like this:
$(e).find('unidadeid').each(function () {
countUnidades++;
var Unidade[value inside countUnidades here] = $(this).text();
});
Be clear about your steps, please. I ask not for a solution, but for a help, as a learning. Thank you ;)
You have two options:
Use an array:
var unidades = [];
$(e).find('unidadeid').each(function () {
unidades.push($(this).text());
});
or
var unidades = $(e).find('unidadeid').map(function () {
return $(this).text();
}).get();
If you really, really want to have names that aren't just digits, use an object and bracketed notation:
var unidades = {}, countUnidades = 0;
$(e).find('unidadeid').each(function () {
countUnidades++
unidades['Unidade' + countUnidades] = $(this).text();
});
That creates an object, unidades, with properties like Unidade0, Unidade1, etc. Note that each receives an index, so you don't need countUnidades unless you want it for something else:
var unidades = {};
$(e).find('unidadeid').each(function (index) {
unidades['Unidade' + index] = $(this).text();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With