1

This code is completely wrong, but I hope it gives you the idea of what I'm going for:

var qarowquestion+obj.returnIntJson;

obj.returnIntJson's value is just an integer. I want to take the value held there, for example: 2043, and add 2043 to the end of qarowquestion. Thus, I would have:

var qarowquestion2043;

Thanks.

4 Answers 4

1
var myObj = {};
myObj['qarowquestion' + obj.returnIntJson] = 'some Val';

Try the above. It will take advantage of dynamic javascript and create a qarowquestion2043 property on the myObj object.

Sign up to request clarification or add additional context in comments.

Comments

0

You cannot create variable, As TGH mentioned you can add your values as a named properties inside an object.

var obj = {};
obj['qarowquestion' + obj.returnIntJson] = 'xxx';

By this way you can give proper namespace also for your objects.

var someNameSpace = {};
someNameSpace['someObject'] = 'someVal';

Hope this will be helpful.

Comments

0

I was going through a relevant SO post on using dynamic variable names in javascript and the accepted answer brings up a very good point (emphasis is mine):

Since ECMA-/Javascript is all about Objects and Contexts (which, are also somekind of Object), every variable is stored in a such called Variable- (or in case of a Function, Activation Object).In the Global scope (= NO function context), you implicitly write those variables into the Global object (= window in a browser).

So for example (again taken from the answer):

function foobar() {
  this.a = 1;
  this.b = 2;

 var name = window['a']; // === undefined as it refers to the global context and is undefined
 alert(name);
 name = this['a']; // === 1
 alert(name); // outputs 1
 alert(a); //outputs 1

//Since we are talking about context here, you could clearly do

this['qarowquestion'+obj.returnIntJson] = "foo";
alert(qarowquestion2043); //outputs foo
}

So in essence, variables can be accessed as objects in specific contexts which can be really helpful.

Comments

0

TGH's reply was almost what I needed, or it is and I just don't know how to use it.

I changed it so that the part with the number is the value, not the key.

    var myObj = {};
    myObj['qarowquestion'] = "qarowquestion" + obj.returnIntJson;

Now, I can access it with: myObj.qarowwquestion which gives such result: qarowquestion2043

And for a specific example, in my case:

document.getElementById("qarow" + obj.returnIntJson).innerHTML = myObj.qarowquestion;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.