Ok I’ve been learning some of the more advanced aspects of Javascript and now trying to use this I’m stuck.
Here is my code:
function Data(){}
function init(state){
var item;
item=new Data();
item.fieldrid=17;
item.description='foo';
state.push(item);
};
function findInState(state,fieldrid) {
for (var item in state) {
alert(item.fieldrid); //prints undefined
if (item.fieldrid == fieldrid) {
return item;
}
}
return null;
}
var s=[];
init(s);
alert(s[0].fieldrid); //prints 17 (expected)
alert(findInState(s,17).fieldrid); //exception here. function returns null.
A running example is here at jsbin
Why does this not work? I would expect the alert in findInState to yield 17 but instead it yields undefined.
What am I doing wrong?
You should not loop over an array using
for..in.It works as expected when using
for (var i = 0; i < state.length; i++).See https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/for…in: