我正在寻找一种从其他变量中读取变量txt的方法,这些变量基本上来自这样的计数器。
示例:
var txt0 = "this is txt 0"
var txt1 = "this is txt 1"
var txt2 = "this is txt 2"
counter = 0 // 1,2 or 3 etc
var a = (var+counter); // this line output : var0;or var3 etc
$(h1').text(a);
console.log(a);
//answer I want is : this is text 0 or 1 or 2;
我尝试创建一个基本示例来演示我的问题,我需要使用这种格式,因为很多其他代码依赖于计数器的动态各种检查其他内容
答案 0 :(得分:2)
您使用以下代码执行此操作:var a = window['txt'+counter];
var txt0 = "this is txt 0"
var txt1 = "this is txt 1"
var txt2 = "this is txt 2"
counter = 0; // 1,2 or 3 etc
var a = window['txt'+counter];
$('h1').text(a);
console.log(a);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1></h1>
但是当然使用数组或JSON对象会更有效率
答案 1 :(得分:1)
您可以使用window
var a = window["var"+counter]; // this line output : var0;or var3 etc
但你应该使用数组或JOSN对象
var obj = {txt0 :"this is txt 0", txt1: "this is txt 1", txt2 = "this is txt 2"}
和访问类似
obj["var"+counter]
答案 2 :(得分:0)
var txt = ["this is text 0", "this is text 1", "this is text 2"];
var counter = 0;
/* You should make sure counter is within [0; txt.length - 1 ] */
$('h1').text(txt[counter]);