简体   繁体   中英

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?

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.

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"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM