简体   繁体   English

如何在变量而不是字符串javascript中返回数组

[英]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. currentPat变量返回字符串pattern1,而不返回数组。 What am i doing wrong? 我究竟做错了什么?

You should have the patterns as 2 elements of an array and then you can use this: 您应该将模式作为数组的2个元素,然后可以使用此模式:

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. 如果无法更改模式的定义方式,则可以使用eval("pattern"+i)但是不建议这样做,因为它会使代码更难阅读,并且如果与用户输入一起使用,可能会导致一些安全问题。

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). 因为在您的示例中pattern1pattern2都是全局变量,所以它们自动成为全局对象的属性(在浏览器中是window对象)。

window.pattern1

does exactly the same as 与...完全相同

var prop = "pattern1"
window[prop]

or as 或作为

window["pattern1"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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