最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Dynamically name variables javascript - Stack Overflow

programmeradmin2浏览0评论

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

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

Share Improve this question asked Apr 3, 2013 at 11:48 ghaschelghaschel 1,3553 gold badges20 silver badges42 bronze badges 6
  • 1 Consider using Arrays instead. – Vimal Stan Commented Apr 3, 2013 at 11:50
  • 1 use of eval() is not recommend. could you explain why do you want to create variables on run time? you could use Arrays instead. – nandu Commented Apr 3, 2013 at 11:51
  • I dindn't know i could use arrays, instead. Thanks. I don't like asking on stackoverflow. Because of being negativated, i feel like a compltete noob. – ghaschel Commented Apr 3, 2013 at 11:53
  • Try a javascript book. There are plenty out there. This is basic stuff, it is faster to learn on your own. If you are serious about programming, take half an hour a day an read some. – oxygen Commented Apr 3, 2013 at 11:56
  • 1 Good tutorial: eloquentjavascript.net. – Felix Kling Commented Apr 3, 2013 at 12:08
 |  Show 1 more comment

5 Answers 5

Reset to default 8

You have two options:

  1. 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();
    
  2. 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();
    });
    

You can always use array:

var Unidade = [],
    countUnidades = 0;

$(e).find("unidadeid").each(function(i) {
    Unidade[countUnidades++] = $(this).text();

    // ... or Unidade.push($(this).text());
    // ... or Unidade[i] = $(this).text();
});

Don't forget that DOM elements should always have unique IDs, so each iteration is not required here, if unidadeid refers to ID of some element.

Your example is simply adding to what I assume is an array with incremental values. Unidade would look something like this in JSON:

[
    0: "text0",
    1: "text1",
    2: "text2"
]

But if you wanted to add this to an object, you would just iterate through an array of strings where the array is of the same length as your list of items. In fact you might want to attach this value to a data attribute where the value is the variable name and the text is the content of the element. So the HTML would be something like this:

<div data-var="a">Text1</div>
<div data-var="b">Text2</div>
<div data-var="c">Text3</div>

Would require this JS:

var unidade = {};

$("div").find('unidadeid').each(function() {
    unidade[$(this).data('var')] = $(this).text();
});

console.log(unidade);

And the object would look like this:

{
    "a": "Text1",
    "b": "Text2",
    "c": "Text3"
}

I doubt you need to create variables dynamically. That's very rarely helpful.

You probably want to learn about data structures; in particular I think you just want an array:

var unidades = []; // declare the array outside the loop
$(e).find('unidadeid').each(function () {
    countUnidades++;
    unidades[countUnidades] = $(this).text();
});

And now you have an array, unidades whose values are the text() contents of your elements.

I'm not sure if find('unidadeid') is what you want - that's finding all <unidadeid> elements, which is not an HTML element, but maybe you're processing custom XML, or maybe it was just an example.

Well, just for completeness, here is exactly what you asked for, eventhough it's a terrible idea:

$(e).find('unidadeid').each(function () {
  countUnidades++;
  var t = $(this).text();
  eval('Unidade' + countUnidades + ' = t;');
});

Note:

  • eval is hard to use without opening up security holes.
  • eval is slow.
  • Creating variables dynamically is rather pointless because you need to access them dynamically also.
  • The variables are global (as otherwise they would be local to the callback function and go away right after being created).

Normally you would use an array instead:

var Unidade = [];
$(e).find('unidadeid').each(function () {
  Unidade.push($(this).text());
});
发布评论

评论列表(0)

  1. 暂无评论