1

below are the global variables that i have defined as....

global1 ="global1 contents";
global2 ="global1 contents";

Now i want to call this in something like this

console.log(global+"1") ; 

how can we call global variable by splitting the last character?

2

1 Answer 1

1

You can access globals by using bracket notation on the window:

global1 = "global1 contents";
global2 = "global2 contents";

var varName = 'global';
alert(window[varName + '1']);

Note however that it's better practice to put your variables in to their own object to save polluting the window:

var myObj = {
    global1: "global1 contents",
    global2: "global2 contents"
}

var varName = 'global';
alert(myObj[varName + '1']);

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

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.