如何将字符串值转换为javascript中的变量? [英] How to convert a string value to a variable in javascript?
问题描述
var test1;
$(document).ready(function () {
test1 = $("#test1ID").jQueryPlugin();
});
var test2;
$(document).ready(function () {
test2 = $("#test2ID").jQueryPlugin();
});
...
这样做是为了让我们可以只做 test1.foo()
... foo 是 jQueryPlugin 中的一个函数,可以使用 test1.foo()
语法访问;
This is done so we could just do test1.foo()
... foo is a function inside the jQueryPlugin that is accessible using test1.foo()
syntax;
所以我们有一个包含 (test1, test2, ...) 的字符串数组我们需要在循环中访问 foo() :
So we have an array of strings which contains (test1, test2, ...) and we need to access foo() while on the loop:
for(i=0; i < theArrayOfStrings.length; i++){
theArrayOfStrings[i].foo();
//so here is the problem... we can't do test1.foo(), test2.foo() ... =(
}
知道如何在循环中调用函数 foo() 吗?或者我们可以在javascript中将字符串值转换为变量吗?
Any idea on how to call function foo() while on the loop? Or can we convert a string value to a variable in javascript?
推荐答案
eval() 函数 用于评估字符串变量中的脚本.例如:
eval() function is used to evaluate script in a string variable. For example :
var test1;
eval("test1=" + theArrayOfStrings[i]);
test1.foo();
但是在使用之前先看看这个问题 JavaScript 的 eval() 什么时候不邪恶?
But take a lok at this question before use When is JavaScript’s eval() not evil?
这篇关于如何将字符串值转换为javascript中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!