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

时间:2018-01-07 00:31:11

标签: javascript

var i = 1

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

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

var currentPat = "pattern" + i

alert(currentPat)

currentPat变量返回字符串pattern1,它不返回数组。我做错了什么?

2 个答案:

答案 0 :(得分:2)

你应该将模式作为数组的2个元素,然后你可以使用它:

int stringToInt(String value, int defaultValue) {
    try {
        return Integer.parseInt(value);    
    } catch(NumberFormatException e) {
        return defaultValue;
    }
} 

如果您无法更改模式的定义方式,则可以使用var i = 1 var pattern = []; pattern[1] = ["apple", "pear", "orange", "carrot"] pattern[2] = ["apple", "pear", "orange", "carrot"] var currentPat = pattern[i] alert(currentPat) ,但不建议这样做,因为它会使代码难以阅读,并且如果与之一起使用可能会导致一些安全问题用户输入。

答案 1 :(得分:2)

要使用变量属性名称,您需要通过方括号语法访问它:

var i = 1

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

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

var currentPat = window["pattern" + i]

console.log(currentPat)

因为示例中的pattern1pattern2都是全局变量,所以它们会自动成为全局对象的属性(在浏览器中是window对象)。

window.pattern1

完全相同
var prop = "pattern1"
window[prop]

window["pattern1"]