How can I create variables at run-time based on names pulled from a string?
I basically have the following string in 开发者_运维问答the format:
A,B,C:D,E,F
What I am trying to achieve is a means of pairing up left hand side JavaScript variable, to the left of the ":" with the right hand side values to the right of the ":"
I would like to have the following variables set in, so that I can use in my coding, i.e:
var A = D;
var B = E;
var C = F;
I can then use the values of A,B and C as parameters into other JavaScript functions.
I have looked at the split and slice methods for this string manipulation but unsure how to pair up left hand side with right hand side values.
With this method (attaching variables to an object), you can reference variables in code without an eval statement.
a = "A,B,C:D,E,F";
array = a.split(":"); //split on the colon, get two strings
lefts = array[0];
rights = array[1];
obj = {} //object to attach variables to.
for( var i = 0; i < lefts.length; i++ )
{
obj[lefts[i]] = rights[i]; //set the member variables of obj
}
obj.A // D
obj.B // E
obj.C // F
If you care about the wasted comma property, check if lefts[i] is equal to a comma before you set on the object.
The pairup
function here generates the code to do the pairing. You'd need to eval
the returned code to actually execute it.
<script>
function pairup(s) {
s = s.split(":");
var lhs = s[0].split(",");
var rhs = s[1].split(",");
var pairing = "";
for (var i = 0; i < lhs.length; i++) {
pairing += "var " + lhs[i] + " = " + rhs[i] + "; \n";
}
return pairing;
}
alert(pairup("A,B,C:D,E,F"));
</script>
If you have the objects ready to bind the values of the variables too, then you can do something like this:
<script>
function pairup(s, oleft, oright) {
s = s.split(":");
var lhs = s[0].split(",");
var rhs = s[1].split(",");
for (var i = 0; i < lhs.length; i++) {
oleft[lhs[i]] = oright[rhs[i]];
}
}
oleft = {};
oright = { firstName: "F", lastName: "L" };
pairup("givenName,familyName:firstName,lastName", oleft, oright);
alert(oleft.givenName + ", " + oleft.familyName);
</script>
精彩评论