我正在寻找一种从其他变量读取变量 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;
我尝试创建一个基本示例来演示我的问题,我需要使用这种格式,因为许多其他代码依赖于计数器的动态,对其他内容进行各种检查
最佳答案
您可以使用以下代码来完成此操作: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 对象会更高效
关于javascript - Jquery/Js变量加变量输出文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41569112/