动态命名变量javascript [英] Dynamically name variables javascript

查看:93
本文介绍了动态命名变量javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在循环内动态创建变量,但是我不知道如何.我已经读过有关使用eval();的信息,但我发现它只是关于动态更改变量内的值.

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.

我需要这样的东西:

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

推荐答案

您有两个选择:

  1. 使用数组:

  1. Use an array:

var unidades = [];
$(e).find('unidadeid').each(function () {
    unidades.push($(this).text());
});

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

    这会创建一个具有Unidade0Unidade1等属性的对象unidades.请注意,each会接收一个索引,因此不需要countUnidades,除非您希望将其用于其他用途:

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

  • 这篇关于动态命名变量javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆