Reputation: 2783
<script>
var data1_1 = $value;
var data1_3 = $value;
var data1_5 = $value;
</script>
The above code is hard-code which is correct.
Now I want to make the code more flexiable using for loop.
However, there is something wrong on data1_keysArr[i] = $value
.
Can anyone help me?
Thanks in advance!
<script>
var keysArr = [1, 3, 5];
for(var i=0; i<keyArr.length; i++){
data1_keysArr[i] = $value;
}
</script>
Upvotes: 0
Views: 239
Reputation: 40582
W3Schools has a great tutorial on arrays, which you should read. It will really help you out with this as it almost exactly matches your example.
Essentially, when you use "var" in the global context, you are assigning values to the window object. Thus, you could do the following:
var keysArr = [1, 3, 5];
for(var i=0; i<keysArr.length; i++) {
window['data1_'+keysArr[i]] = $value;
}
However, it would be more correct to use an array for your values (see the tutorial to understand this):
var i, key,
keysArr = [1, 3, 5],
data = [];
for(i=0; i < keysArr.length; i++) {
key = keysArr[i];
data[key] = $value;
}
Upvotes: 0
Reputation: 754943
It looks like you're trying to use a for
loop to access the previously hard coded values via constructed names. If so then try the following
var keysArr = [1, 3, 5];
for (var i = 0; i < keyArr.length; i++) {
var name = 'data1_' + keyArr[i];
window[name] = $value;
}
I would recommend against this approach though because you're essentially defining a lot of global variables on demand with this code. Instead I would put them on a single container object. For example
var parent = {};
var keysArr = [1, 3, 5];
for (var i = 0; i < keyArr.length; i++) {
var name = 'data1_' + keyArr[i];
parent[name] = $value;
}
console.log(parent.data1_1); // Prints $value
Upvotes: 2
Reputation: 1731
Try:
window['data1_' + keysArr[i]] = $value;
EDIT: And JaredPar is right: You should probably use a container object.
Upvotes: 0