1

I have very long code and want to simplify it. I don't think so we can use string concatination to create different variable name. Is there any other way.

If(Something){
    var a = some.Test1.x;
    var b = some.Test1.y;
    var c = some.Test1.z;
    var d = some.Test1.p;
}

If(SomethingElse){
    var a = some.Test2.x;
    var b = some.Test2.y;
    var c = some.Test2.z;
    var d = some.Test2.p;
}

If(OneMore){
    var a = some.Test3.x;
    var b = some.Test3.y;
    var c = some.Test3.z;
    var d = some.Test3.p;
}

May be create some function like this, i know this is not right but anything similar to that.

function test(s){
  a = some.s.x;
  b = some.s.y;
  c = some.s.z;
  d = some.s.p;
}
2
  • 1
    Note that you can replace o.foo with o["foo"] i.e. you can access the foo field / member of o either by literal or by string ("foo" may be a string) Commented May 21, 2015 at 16:12
  • 1
    This question is off-topic to SO and should be moved to CodeReview Commented May 21, 2015 at 16:14

2 Answers 2

3

You can use array-like syntax

function test(s) {
    var a,b,c,d;
    if (s === Something) {
        test = "Test1";
    }
    if (s === SomethingElse) {
        test = "Test2";
    }
    if (s === OneMore) {
        test = "Test3";
    }

    a = some[test].x;
    b = some[test].y;
    c = some[test].z;
    d = some[test].p;
}

This is a much improved version of the functionally equivalent, but never-to-be-used, eval syntax:

eval("a = some."+test+".x");
Sign up to request clarification or add additional context in comments.

2 Comments

so if i have something like random.x.Test1.q i would do some.x[test].q as per your answer
@Nakib don't forget to handle test === undefined in this example
1
function test(index){
  t = some["Test" + index];

  a = t.x;
  b = t.y;
  c = t.z;
  d = t.p;
}

and the execution:

test(1); test(2); test(3)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.