Assign string variable to array using for loop - javascript

I have a list of string variables and I want to assign all of these to an array, but the list is to much, is there any possible for me to using for loop to assign it.
var class_1 = "some description..";
var class_2 = "some description..";
var class_3 = "some description..";
var class_4 = "some description..";
var class_5 = "some description..";
.
.
var class_100 = "some description..";
var classes = [];
for(var i = 0; i < 100; i++){
//loop string variables to array
}
I think it is not possible for me to assign 100 variables manually to the array. Anyone know any technique? Thank you.
[UPDATE] It requires in SystemVerilog syntax, since I not familiar in that language, so I present the idea in Javascript.

There is no way in SystemVerilog to build an array of values from a list of independently named variables without manually assigning each variable to an element of an array.
classes[0] = class_0;
classes[1] = class_1;
classes[2] = class_2;
...
The fact that the identifiers used for variables names have a numerical sequence is of no consequence because you cannot access identifiers except by the exact name.
If you want to automate this, you will need to change the way the string variables are defined. As people have already posted, this should been modeled using an array to begin with, perhaps using an associative array:
string classes[string];
classes["class_1"] = "some description..";
classes["class_2"] = "some description..";
classes["class_3"] = "some description..";
foreach(classes[name])
// do something with classes[name]
Another option is to use a SystemVerilog class object for each variable
class stringvar;
string m_name;
static stringvar list[$];
function new(string name);
m_name = name;
list.push_back(this);
endfunction
endclass
stringvar class_0 = new("some description..");
stringvar class_1 = new("some description..");
stringvar class_2 = new("some description..");
...
foreach(stringvar::list[item])
// do something with item.m_name

Something like this:
var class_1 = "some description..";
var class_2 = "some description..";
var class_3 = "some description..";
var class_4 = "some description..";
var class_5 = "some description..";
var class_100 = "some description..";
var classes = [];
for(var i = 0; i < 100; i++){
classes.push(window['class_'+i])
}

You have 100 variables? You should sort that out first
I think there is some truth to that comment. But to answer your question: Assuming your variables follow the same naming convention that you example above shows, you can assign predefined variables with array values like so:
var a = []
for(var i = 0; i < num_vars; i++){
var key = 'class_' + (i + 1)
if (this[key])
a.push(this[key])
}

You perhaps can use eval. something like this:
for (var i = 0; i < 100; i++) {
var toEval = "classes.push(class_" + i + ")";
eval(toEval);
}

Related

Using a variable increment to create new variables in Javascript

It might be a beginner's question, but I can't seem to find an answer on this.
The data it is getting is data out of a JSon file. I want it to loop through all the rows it is seeing. The loop works how it is written below and returns me the info I need with the rest of the code. I am trying to create multiple variables like testVar1, testVar2, testVar3, .... I don't know if it is possible to do it this way, or if I need to find another solution.
var i = 0;
for (var x in data) {
var testVar1 = data[0][1]; // works
var testVar[i] = data[0][1]; // doesn't
i += 1;
}
How can I make the testVar[i] work ?
What is the correct syntax for this?
Your code misses the initialization of your array variable: var testVar = [];.
⋅
⋅
⋅
Anyway, you may want to create those variables in the window object :
for (var i = 0; i <= 2; i++) {
name = 'var' + i;
window[name] = "value: " + i;
}
console.log(var0);
console.log(var1);
console.log(var2);
That way you can keep using the "short" variable name.
You can wrap all those variables in an object.
instead of:
var testVar1 = data[0][1];
Try:
var Wrapper = {};
//inside the for loop:
Wrapper["testVar" + i] = data[0][i];
...and so on.
You'd access them as Wrapper.testVar1 or Wrapper["testVar" + 1].
The problem you're having is pretty simple. You try to declare a variable as an array and in the same statement try to assign assign a value to a certain index. The reason this doesn't work is because the array needs to be defined explicitly first.
var testVar[i] = data[0][1];
Should be replaced with:
var testVar = []; // outside the loop
testVar[i] = data[0][1]; // inside the loop
Resulting in:
var i = 0,
testVar = [],
data = [
['foo', 'bar', 'baz'],
['kaas', 'is', 'baas']
];
for (var x in data) {
var testVar1 = data[0][1];
testVar[i] = data[0][1];
i += 1;
}
console.log('testVar1', testVar1);
console.log('testVar', testVar);
console.log('testVar[0]', testVar[0]);
console.log('testVar[1]', testVar[1]);
If i isn't an integer you should use an object instead. This can be seen in the answer of Tilepaper, although I advise against the use variables starting with a capital letter since they suggest a constant or a class.

Is there a way to loop this?

Is there a way to loop a declaration of a variable? just a loop to help me declare the variables so i dont have to do the monotonous work of change the numbers of the variable
var height1 = document.getElementById('height1').value;
var height2 = document.getElementById('height2').value;
var height3 = document.getElementById('height3').value;
var height4 = document.getElementById('height4').value;
var height5 = document.getElementById('height5').value;
var height6 = document.getElementById('height6').value;
var height7 = document.getElementById('height7').value;
var height8 = document.getElementById('height8').value;
var height9 = document.getElementById('height9').value;
var height10 = document.getElementById('height10').value;
var height11 = document.getElementById('height11').value;
var height12 = document.getElementById('height12').value;
var height13 = document.getElementById('height13').value;
var height14 = document.getElementById('height14').value;
var height15 = document.getElementById('height15').value;
var height16 = document.getElementById('height16').value;
This is not a right way of coding that, Just do like,
var heights = [];
Array.from(document.querySelectorAll("input[id^=height]")).forEach(function(itm){
heights.push(itm.value);
});
And now you can iterate the array heights to manipulate the values as per your requirement.
The logic behind the code is, querySelectorAll("input[id^=height]") will select the input elements that has id starts with the text height. Since the return value of querySelectorAll is a nodelist, we have to convert it as an array before using array functions over it. So we are using Array.from(nodelist). That will yield an array for us. After that we are iterating over the returned array by using forEach and pushing all element's value into the array heights.
This is almost always an indication that you want an array. Something like this:
var heights = [];
for (var i = 1; i <= 16; i++) {
heights.push(document.getElementById('height' + i).value);
}
Then you can reference a value from the array with something like:
heights[1]
Though technically since in JavaScript your window-level variables are indexable properties of the window object, you can essentially do the same thing with variable names themselves:
for (var i = 1; i <= 16; i++) {
window['height' + i] = document.getElementById('height' + i).value;
}
Then you can still use your original variables:
height1
Though in the interest of keeping things outside of window/global scope, maintaining the array seems a bit cleaner (and semantically more sensible).
This seems to be a good use case for an object:
var heights = {};
for (var i = 1; i <= 16; i++) {
heights[i] = document.getElementById('height' + i).value;
}
Maybe its time to introduce function:
Generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function will return a value.
function getHeight(id) {
return document.getElementById(id).value;
}
Call with the wanted id and use it like a variable.
getHeight('height1')
Normally you would put them in an array.
var heights = []
for (i = 1; i < 17; i++) {
heights[i] = document.getElementById('height' + i).value;;
}
Beware this will give you a hole at the start of the array ie heights[0] has nothing in it. If you use this to iterate it won't matter...
for (var i in heights) {
alert(heights[i]);
}

Create variables based on array

I have the following array and a loop fetching the keys (https://jsfiddle.net/ytm04L53/)
var i;
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
for (i = 0; i < feeds.length; i++) {
var feed = feeds[i];
alert(feed.match(/\d+$/));
}
The array will always contain different number of keys, What I would like to do is either use these keys as variables and assign the value after the : semicolon as its value or just create a new set of variables and assign the values found on these keys to them.
How can I achieve this? so that I can then perform some sort of comparison
if (test_user > 5000) {dosomething}
update
Thanks for the answers, how can I also create a set of variables and assign the array values to them? For instance something like the following.
valCount(feeds.split(","));
function valCount(t) {
if(t[0].match(/test_user_.*/))
var testUser = t[0].match(/\d+$/);
}
Obviously there is the possibility that sometimes there will only be 1 key in the array and some times 2 or 3, so t[0] won't always be test_user_
I need to somehow pass the array to a function and perform some sort of matching, if array key starts with test_user_ then grab the value and assign it to a define variable.
Thanks guys for all your help!
You can't (reasonably) create variables with dynamic names at runtime. (It is technically possible.)
Instead, you can create object properties:
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
var obj = {};
feeds.forEach(function(entry) {
var parts = entry.split(":"); // Splits the string on the :
obj[parts[0]] = parts[1]; // Creates the property
});
Now, obj["test_user_201508_20150826080829.txt"] has the value "12345".
Live Example:
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
var obj = {};
feeds.forEach(function(entry) {
var parts = entry.split(":");
obj[parts[0]] = parts[1];
});
snippet.log(obj["test_user_201508_20150826080829.txt"]);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
You can do it like this, using the split function:
var i;
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
for (i = 0; i < feeds.length; i++) {
var feed = feeds[i];
console.log(feed.split(/[:]/));
}
This outputs:
["test_user_201508_20150826080829.txt", "12345"]
["test_user_list20150826", "666"]
["test_list_Summary20150826.txt", "321"]
Use the split method
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
feedMap = {}
for (i = 0; i < feeds.length; i++) {
var temp = feeds[i].split(':');
feedMap[temp[0]] = temp[1];
}
Yields:
{
"test_user_201508_20150826080829.txt":"12345",
"test_user_list20150826":"666",
"test_list_Summary20150826.txt":"321"
}
And can be accessed like:
feedMap["test_user_201508_20150826080829.txt"]
Here is a codepen
it is not very good idea but if you really need to create variables on-the-run here's the code:
for (i = 0; i < feeds.length; i++)
{
var feed = feeds[i];
window[feed.substring(0, feed.indexOf(":"))] = feed.match(/\d+$/);
}
alert(test_user_201508_20150826080829)
Of course you cannot have any variable-name-string containing banned signs (like '.')
Regards,
Michał

Variable name within a loop

I suspect I am making a mistake in a basic JavaScript syntax.
var my_array = new Array(10);
for (var count=0; count<my_array.length; count++) {
var my_array+count = "This is a variable number "+count+".";
document.write(my_array+count);
}
I want the loop to create series of variables that should be called my_array0, my_array1, my_array2, and so on. The code above is how I tried to do that, but it doesn't work. What's the correct way of naming the variable inside the loop?
EDIT: I know I could use my_array[count], but that's not what I'm looking for. What I need is to be able to name a variable inside the loop, using the index as part of the name of the variable.
If you want to set the elements of an array, use the [] syntax:
var my_array = new Array(10);
for (var count=0; count<my_array.length; count++) {
my_array[count] = "This is a variable number "+count+".";
document.write( my_array[count] );
}
Furthermore, when specifying just an element of an array and not the array itself, drop the var in front of it!
This pattern is questionable, and the array seems unnecessary; however, here is one way to do it:
var my_array = new Array(10);
for (var count = 0; count < my_array.length; count++) {
window['my_array' + count] = "This is a variable number " + count + ".";
document.write(window['my_array' + count]);
}
What's the correct way of naming the variable inside the loop? You don't.
If you just want a variable to hold that particular value, just use an ordinary variable. If you want lots of different values, stick it inside an array or object. But that's redundant here since you already have an array, so I'm really not sure what you're trying to achieve.
And if none of the previous answers suits you, you can always use eval()
var varName = 'my_array'
for (var count=0; count<my_array.length; count++) {
eval(varName+count +" = This is a variable number "+count+".");
}
Edit: #Noah Freitas provides a better answer, without using eval().
You're redefining my_array inside the loop, and not accessing the variable correctly either. Try:
var my_array = new Array(10);
for (var count=0; count<my_array.length; count++) {
my_array[count] = "This is a variable number "+count+".";
console.log(my_array[count]);
}
JS Fiddle
You can't execute on the left-hand side of the assignment operator (=), you can only assign. Execution, in javascript, takes place on the right hand side.
var my_array = new Array(10);
var var_hashmap = {}; // create a new object to hold our variables.
for (var count = 0; count < my_array.length; count++) {
var key = "my_array" + count;
var value = "This is a variable number " + count + ".";
var_hashmap[key] = value;
document.write(var_hashmap[key]);
};
var my_array = new Array(10);
for (var count=0; count<my_array.length; count++)
{
eval("var my_array" + count + " = 'This is a variable number'+count+' and the variable name is my_array'+count");
}
alert(my_array0);
alert(my_array1);
alert(my_array2);
alert(my_array3);
alert(my_array4);
alert(my_array5);
alert(my_array6);
alert(my_array7);
alert(my_array8);
alert(my_array9);
http://jsfiddle.net/pe97W/4/
You should use an array.
var myarray = new Array();
myarray[0] = "1";
myarray[1] = "2";
myarray[2] = "3";

How to use contents of array as variables without using eval()?

I have a list of variables or variable names stored in an array. I want to use them in a loop, but I don't want to have to use eval(). How do I do this? If I store the values in an array with quotes, I have to use eval() on the right side of any equation to render the value. If I store just the variable name, I thought I'd be storing the actual variable, but it's not working right.
$(data.xml).find('Question').each(function(){
var answer_1 = $(this).find("Answers_1").text();
var answer_2 = $(this).find("Answers_2").text();
var answer_3 = $(this).find("Answers_3").text();
var answer_4 = $(this).find("Answers_4").text();
var theID = $(this).find("ID").text();
var theBody = $(this).find("Body").text();
var answerArray = new Array();
answerArray = [answer_1,answer_2,answer_3,answer_4,theID,theBody]
for(x=0;x<=5;x++) {
testme = answerArray[x];
alert("looking for = " + answerArray[x] + ", which is " + testme)
}
});
You can put the values themselves in an array:
var answers = [
$(this).find("Answers_1").text(),
$(this).find("Answers_2").text(),
$(this).find("Answers_3").text(),
$(this).find("Answers_4").text()
];
for(x=0;x<=5;x++) {
alert("looking for = " + x + ", which is " + answers[x])
}
EDIT: Or even
var answers = $(this)
.find("Answers_1, Answers_2, Answers_3, Answers_4")
.map(function() { return $(this).text(); })
.get();
If your answers share a common class, you can change the selector to $(this).find('.AnswerClass').
If you need variable names, you can use an associate array:
var thing = {
a: "Hello",
b: "World"
};
var name = 'a';
alert(thing[name]);
This would make it easier to get the array populated.
var answers = new Array();
$("Answers_1, Answers_2, Answers_3, Answers_4", this).text(function(index, currentText) {
answers[index] = currentText;
});
As others have mentioned, if you can put the variables in an array or an object, you will be able to access them more cleanly.
You can, however, access the variables through the window object:
var one = 1;
var two = 2;
var three = 3;
var varName = "one";
alert(window[varName]); // -> equivalent to: alert(one);
Of course, you can assign the varName variable any way like, including while looping through an array.

Categories

Resources