简体   繁体   中英

how does this stop criterion (for-loop) work?

I was looking for a way to take input from my HTML form to my javascript code without a server inbetween and found this post on Stackoverflow: How to use HTML forms without a server

There, the first answer included the following link to a code example on js.fiddle: http://jsfiddle.net/wG8K4/1/

 function updateBackgroundColor(color) { document.body.style.backgroundColor = color; } function displayFormContents(someForm) { var out = ''; for (var i=0, el; el = someForm.elements[i]; i++) { if (el.name) { out += el.name + ' = ' + el.value + '\\n'; } } alert(out); } 
 <form> <select name='gender' onchange='updateBackgroundColor(this.value);return false;'> <option value=''>Select A Gender</option> <option value='blue'>Male</option> <option value='pink'>Female</option> </select><br/> type your nickname: <input type='text' name='nickname' /><br /> <input type='button' value='Display Form Contents' onclick='displayFormContents(this.form);return false;' /> </form> 

I've tried out this approach in my own code and it works. However, I don't understand how this stop criterion works Oo

 el = someForm.elements[i] 

does this stop criterion kick in when the index hits a value where there is no corresponding array element anymore (the array thus probably returning something like undefined/false)? I guess so, because I could also observe that the loop iterates just 2 times (index 0 and 1). However, I have no way of verifying this assumption and thats why I wanted to ask here.

el = undefined is undefined which is a falsy value that stops the loop.

That means that the loop stops as soon as i is bigger or equal to someForm.elements.length (when someForm.elements[i] is undefined ).

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