开发者

Object inside of array -- works in one scope but not in another?

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?


for (var item in state)

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:

Although it may be tempting to use this as a way to iterate over an Array, this is a bad idea.


In

alert(item.fieldrid); //prints undefined

You need to access the array state[item] so before that line, prepend

item = state[item];

I think, that I'll do.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜