Matt
Matt

Reputation: 173

How to return array in variable instead of string javascript

var i = 1

var pattern1 = ["apple", "pear", "orange", "carrot"]

var pattern2 = ["apple", "pear", "orange", "carrot"]

var currentPat = "pattern" + i

alert(currentPat)

The currentPat variable is returning the string pattern1, its not returning the array. What am i doing wrong?

Upvotes: 1

Views: 56

Answers (2)

connexo
connexo

Reputation: 56823

To use a variable property name, you need to access that via the square brackets syntax:

var i = 1

var pattern1 = ["apple", "pear", "orange", "carrot"]

var pattern2 = ["apple", "pear", "orange", "carrot"]

var currentPat = window["pattern" + i]

console.log(currentPat)

Because both pattern1 and pattern2 are global variables in your example, they automatically become properties of the global object (which in a browser, is the window object).

window.pattern1

does exactly the same as

var prop = "pattern1"
window[prop]

or as

window["pattern1"]

Upvotes: 2

mdatsev
mdatsev

Reputation: 3879

You should have the patterns as 2 elements of an array and then you can use this:

var i = 1
var pattern = [];
pattern[1] = ["apple", "pear", "orange", "carrot"] 
pattern[2] = ["apple", "pear", "orange", "carrot"] 
var currentPat = pattern[i]
alert(currentPat)

If you can't change how the patterns are defined you could use eval("pattern"+i) but this isn't recommended since it makes the code harder to read and could lead to some security problems if used with user input.

Upvotes: 2

Related Questions