简体   繁体   English

如何在JavaScript中动态使用变量?

[英]How to work with variables dynamically in javascript?

I need to work with variables dynamically, and get them dynamically too. 我需要动态地使用变量,并且也要动态地获取它们。 The first thing I need to know is: 我需要知道的第一件事是:

How to save a variable reference(NOT its value) in a collection? 如何在集合中保存变量引用(不包含其值)?

Example: 例:

var divA = "<div>my div A</div>";
var divB = "<div>my div B</div>";
var divC = "<div>my div C</div>";

Then, save in a collection: 然后,保存在集合中:

var mySet = new Set();

function returnDivA(){
 return divA; 
}

function returnDivB(){
 return divB; 
}

function returnDivC(){
 return divC; 
}

mySet.add(returnDivA());//I would like save the varible ref in a collection.
mySet.add(returnDivB());
mySet.add(returnDivC());

I want the Set collection to save the variables(NOT its values), it means: 我希望Set集合保存变量(而不是其值),这意味着:

var mySet = new Set(divA, divB, divC);

Then, with that, my intent is to do something like that: 然后,我的意图是执行类似的操作:

var totalOfDivs;
for(var i = 0; i < mySet.size; i++){
  totalOfDivs += mySet[i];
}

$("#anotherDIV_to_show_all_divs").html(totalOfDivs);//Then, here, I want to show all divs in the screen.

I would like suggestions, please! 我想提出建议!

It solved my problem to put variable dynamically in html using this in a for loop : 它解决了我的问题,即在for循环中使用this将变量动态地放入html中:

$("#anotherDIV_to_show_all_divs").append(mySet[i]);

About saving javascript variable reference in a Collection, I understand that I can't do that, because of the answer of the adeneo in comment: 关于在集合中保存javascript变量引用,我了解到我无法做到这一点,因为adeneo的评论如下:

"There is no "reference", all variables are pass-by-value in javascript..." “没有“引用”,所有变量都是javascript中的按值传递...”

Read the documentation about set. 阅读有关set的文档。

enter link description here 在此处输入链接说明

I guess you have to loop your set like this. 我想您必须像这样循环播放您的集合。

var totalOfDivs= "";

    for (let item of mySet.values()) {
        totalOfDivs+= item;
        //console.log(item); 
    }

$("#anotherDIV_to_show_all_divs").html(totalOfDivs);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM