0

I'm looking for a way to read a variable txt from other variables that are basically from a counter of such.

example:

var txt0 = "this is txt 0"
var txt1 = "this is txt 1"
var txt2 = "this is txt 2"

counter = 0 // 1,2 or 3 etc
var a = (var+counter);  // this line output : var0;or var3 etc
$(h1').text(a);
console.log(a);
//answer I want is : this is text 0 or 1 or 2;

I tried to create a basic sample to demonstrate my issue, I need to use this format as a lot of the other code is dependent on the dynamic of counters various checks for other content

1
  • 1
    Why don't you store them inside of an array? Commented Jan 10, 2017 at 12:43

3 Answers 3

2

You cad do it with this code: var a = window['txt'+counter];

var txt0 = "this is txt 0"
var txt1 = "this is txt 1"
var txt2 = "this is txt 2"

counter = 0; // 1,2 or 3 etc
var a = window['txt'+counter];
$('h1').text(a);
console.log(a);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1></h1>

But of course using array or JSON object will be more efficient

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

5 Comments

For some reason only worked once I removed the vars for each TXT. Thanks for putting it in a simple form for me to relate.
did I post something else? :D
@Sanjay Nishad your code doesn't seem to work: jsfiddle ;P
if my code doesn't work, how is working yours? both are same :D btw window['txt'+counter] is not working with jsFiddle, doesn't matters mine or yours :)
They aren't the same: window['txt'+counter] vs window["var"+counter] - jsfiddle ^^
1

you can access using window

var a = window["var"+counter];  // this line output : var0;or var3 etc

but you should use an array or JOSN object

var obj = {txt0 :"this is txt 0", txt1: "this is txt 1", txt2 = "this is txt 2"}

and access like

obj["var"+counter]

Comments

0
var txt = ["this is text 0", "this is text 1", "this is text 2"];

var counter = 0;
/* You should make sure counter is within [0; txt.length - 1 ] */
$('h1').text(txt[counter]);

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.