JavaScript: Dynamically Creating Variables for Loops
You should use an array:
function createVariables(){
var accounts = [];
for (var i = 0; i <= 20; ++i) {
accounts[i] = "whatever";
}
return accounts;
}
You then have access to accounts[0]
through accounts[20]
.
How can you dynamically create variables?
Unless there is an overwhelming need to create a mess of variable names, I would just use a dictionary, where you can dynamically create the key names and associate a value to each.
a = {}
k = 0
while k < 10:
# dynamically create key
key = ...
# calculate value
value = ...
a[key] = value
k += 1
There are also some interesting data structures in the collections
module that might be applicable.
Dynamically creating a variable
In python we tend to avoid this kind of dynamic variables, but anyway your answer is:
a = 'test'
globals()[a] = 123
print(test)
Better approach is by using a dictionnary.
a = 'test'
myVar = {}
myVar[a] = 123
print(myVar['test'])
Is it a good idea to dynamically create variables?
I think it's preferable to use a dictionnary if it's possible:
vars_dict = {}
vars_dict["my_variable"] = 'Some Value'
vars_dict["my_variable2"] = 'Some Value'
I think it's more pythonic.
How to create variables dynamically in Java?
A Map allows you to relate any key with any value. In this case, the key is the name of the variable, and the value is the value
Map<String, String> details = new HashMap<>();
for (int i = 1; i <101; i++) {
if (i<60) {
details.put("person" + i, "female");
}
else {
details.put("person" + i, "male");
}
}
How to dynamically create variable with loop?
You need to give the emails a name to submit them
Also I removed the onsubmit form the submit button. It does not belong there and can be removed. You have a submit event handler and that should do it
const container = document.getElementById("container");
document.getElementById("nameForm").addEventListener("submit", tableGen);
document.getElementById("okButton").addEventListener("click", emailGen);
//fuction to genrate email field
function emailGen() {
const quant = document.getElementById("quantity").value;
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (let i = 0; i < quant; i++) {
var emailGen = document.createElement("input");
emailGen.type = "email";
emailGen.id = "email" + i;
emailGen.name = "email" + i;
emailGen.placeholder = "Member's Email";
container.appendChild(emailGen);
}
}
//function for table generator
function tableGen(e) {
e.preventDefault();
const body = document.querySelector("body");
const table = document.createElement("table");
const tblbody = document.createElement("tbody");
const input1 = document.getElementById("input1").value;
const quan = document.getElementById("quantity").value;
const emails = container.querySelectorAll("[type=email]")
console.log(emails.length)
//table rows loop
for (let i = 0; i < quan; i++) {
const tblrow = document.createElement("tr");
for (let j = 0; j < emails.length; j++) {
const tblcell = document.createElement("td");
//table column loop
const pname = document.createTextNode(input1);
tblcell.appendChild(pname);
const tname = document.createTextNode(emails[j].value);
tblcell.appendChild(tname);
tblrow.appendChild(tblcell);
}
tblbody.appendChild(tblrow);
}
console.log
table.appendChild(tblbody);
body.appendChild(table);
table.setAttribute("border", "4");
}
<form id="nameForm">
<input type="text" id="input1" placeholder="Name"><br/>
<input type="number" id="quantity" name="quantity" placeholder="Total Members(max 10)" min="1" max="10">
<button type="button" id="okButton">OK</button>
<div id="container"></div>
<br/>
<input type="submit" value="submit">
</form>
how to Dynamically generate different variables in Angular?
define a variable type array of boolean and use in the table.
check:boolean[]=[]; //<--see that you equal to an array
I suppose you has some like
<tr *ngFor="let item of listItems;let i=index">
<td>{{item.invoiceAmmount}}</td>
...
<td><input type="checkbox" [(ngModel)]="check[i]"></td>
</tr>
Then you can use a getter to total
get total()
{
let total=0;
this.listItems.forEach((x,index)=>{
if (check[index])
total+=x.invoiceAmmount;
})
return total;
}
And in your .html
Total:{{total}}
<div *ngIf="total>max_ammount">You has execeded tha ammout!</div>
NOTE: If you dont want use a getter you can use
<td><input type="checkbox" [ngModel]="check[i]"
(ngModelChange)="check[i]=$event;getTotal()">
</td>
getTotal() //<--your function getTotal
{
let total=0;
this.listItems.forEach((x,index)=>{
if (check[index])
total+=x.invoiceAmmount;
})
this.total=total //<--store the total in a variable "total"
}
How do I create dynamic variable names inside a loop?
Use an array for this.
var markers = [];
for (var i = 0; i < coords.length; ++i) {
markers[i] = "some stuff";
}
Related Topics
Listing Available Devices in Python-Opencv
How to Select Rows from a Dataframe Based on Column Values
Is There a Difference Between "==" and "Is"
Replacements For Switch Statement in Python
How to Parse Xml and Get Instances of a Particular Node Attribute
How to Break Out of Multiple Loops
Why Dict.Get(Key) Instead of Dict[Key]
Difference Between Shallow Copy, Deepcopy and Normal Assignment Operation
Get Difference Between Two Lists
Why Is Nothing Drawn in Pygame At All
Store Large Data or a Service Connection Per Flask Session
How to Execute a Program or Call a System Command
Of the Many Findelement(S)/By Functions in Selenium, When Would You Use One Over the Other
Why Does Comparing Strings Using Either '==' or 'Is' Sometimes Produce a Different Result
Flattening a Shallow List in Python
Local Variables in Nested Functions