开发者

for loop help, unknown syntax with javascript

开发者 https://www.devze.com 2023-02-11 11:18 出处:网络
say I wanted to use variables like var userpos1 : int; var userpos2 : int; var userpos3 : int; //in a for loop like

say I wanted to use variables like

var userpos1 : int;
var userpos2 : int;
var userpos3 : int;

//in a for loop like 

var i=1;
for (i=1;i<=3;i++)
{
    userposi + 1
}

how would I place the i so that the for loop goes through all of my variables properly

var userpos1var : int;
var userpos2var : int;
var userpos3var : int;

//in a for loop like 

var i=1;
for (i=1;i<=3;i++)
{
    userposivar + 1
}

is there something I need to do to this i to make 开发者_JS百科it work properly such as a "" or a [] around it?


Create an array of those vars and go over like this

for(i = 0; i < 3; i++)
{
    func(arr[i]);
}


you should use an array of variables instead, but to do what you are wanting to do, you would write:

eval("userpos" + i + "var") + 1

eval can be unsafe to use, and does not peform well.


<script type="text/javascript">
var userpos1 = 1;
var userpos2 = 2;
var userpos3 = 3;
var i = 1;
for (i=1;i<=3;i++)
{
    alert (eval("userpos" + i));
}
</script>


Why don't you use an array... ?

var userpos = new Array(3);

for (var i=0; i<userpos.length; i++) {}
{
    userpos[i] = i;
}


This is much easier done by storing those values in a single array and iterating over the array.

someArray = new Array(1, 2, 3);
for (key in someArray)
   alert(someArray[key] ); 


Instead of doing it this way, use an array of user positions:

//Create an array of 3 positions, setting all to 0

var userPos=new Array(0, 0, 0);

//loop through each position - notice starts at 0.

for (var i = 0; i < 2; i++)

{

userPos[i] += 1;

}


Eval() would do it, but we should not encourage the use of it. Instead, construct an anonymous function.

for ( i = 1; i <= 3; i++ ) {
    alert(new Function('return userpos' + i + 'var;')()); // value of userpos1var
}

Update JSFiddle example: http://jsfiddle.net/madr/AHBrd/


What you're looking for is:

var userpos = ['a','b','c'];

for(var i=0; i < userpos.length; i++) {
    userpos[i]; // doing something with it.
}
0

精彩评论

暂无评论...
验证码 换一张
取 消