简体   繁体   中英

What's wrong with this code? (Javascript)

this code works, and it alerts the variable every time.

var idNumber;
var elements;
var id;
var blockerIds=[];
var whileLoop=0;
while (whileLoop<112) {
    elements=document.getElementsByName('bid');
    id=elements[whileLoop].getAttribute('id');
    blockerIds[whileLoop]=id;
    alert(blockerIds[whileLoop]);
    whileLoop++;
}

but I tried alerting it outside of the while statement, like this:

var idNumber;
var elements;
var id;
var blockerIds=[];
var whileLoop=0;
while (whileLoop<112) {
    elements=document.getElementsByName('bid');
    id=elements[whileLoop].getAttribute('id');
    blockerIds[whileLoop]=id;
    whileLoop++;
}
alert(blockerIds);

but it only says "undefined". Does anyone know how I can use this variable outside of the while statement, or does it seem like it should work perfectly?

JSFiddle: link . Fixed your code:

var idNumber;
var elements;
var id;
var blockerIds=[];
var whileLoop=0;
elements=document.getElementsByName('bid');
while ((elements.length >= 112 && whileLoop < 112) || (whileLoop < elements.length && elements.length <= 112)) {
    id=elements[whileLoop].getAttribute('id');
    blockerIds[whileLoop]=id;
    whileLoop++;
}
alert(blockerIds);

JS is an interpreted language, when it runs, it firstly search all the definitions of var, and give them an undefined value. Even if the var is claimed to have a actual value, it will still be given an undefined value until this line has been eventually executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM