How do I declare and use dynamic variables in JavaScript?

后端 未结 7 2089
野的像风
野的像风 2020-11-27 16:01

Suppose I need to declare a JavaScript variable based on a counter, how do I do so?

var pageNumber = 1;
var \"text\"+pageNumber;

The above

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 16:15

    Assuming that the variable is in the global scope, you could do something like this:

    var x = 1;
    var x1 = "test"
    console.log(window["x" + x]); //prints "test"
    

    However, a better question might be why you want such behaviour.

提交回复
热议问题