Javascript loop and build array but variable indexed undefined - Stack Overflow

dont laugh think im having a long day work blonde moment as im a bit out of practice with JS. Any helpe

dont laugh think im having a long day work blonde moment as im a bit out of practice with JS. Any helped appreciated for what I think is a stupidly simple problem.

optionarray = [];

for(i=0;i<response.length;i++) {

    optionarray[i]['content'] = response[i]['name'];
    optionarray[i]['value'] = response[i]['id'];
}

I keep getting optionarray[i] is undefined when trying to add it to the array and build it. I know im doing something ridiculously stupid I just can't remember what :)

Many thanks for any help in advance.

dont laugh think im having a long day work blonde moment as im a bit out of practice with JS. Any helped appreciated for what I think is a stupidly simple problem.

optionarray = [];

for(i=0;i<response.length;i++) {

    optionarray[i]['content'] = response[i]['name'];
    optionarray[i]['value'] = response[i]['id'];
}

I keep getting optionarray[i] is undefined when trying to add it to the array and build it. I know im doing something ridiculously stupid I just can't remember what :)

Many thanks for any help in advance.

Share Improve this question asked Sep 15, 2011 at 19:21 JimboJimbo 1372 silver badges11 bronze badges 1
  • Thank you everyone for your help. I was being dumb :) Thinking too much the PHP way ;) – Jimbo Commented Sep 15, 2011 at 20:34
Add a ment  | 

4 Answers 4

Reset to default 3
optionarray = [];

for(i=0;i<response.length;i++) {

    optionarray[i] = {
            'content' :response[i]['name'], 
            'value': response[i]['id']
    };

}

You are trying to access properties of optionarray[i], which does not exist.

What you should be doing in each iteration is

  1. adding a new object to optionarray
  2. setting that object's properties

You can do both at once like this:

optionarray = [];

for(i=0;i<response.length;i++) {
    optionarray.push({
        content: response[i]['name'],
        value: response[i]['id']
    });
}

I think you just need to initialize the optionarray[i] object within your for loop:

var optionarray = []; //NOTE: I added var here so because otherwise it's an implicit global

for(i=0;i<response.length;i++) {
    optionarray[i] = {};
    optionarray[i]['content'] = response[i]['name'];
    optionarray[i]['value'] = response[i]['id'];
    // BETTER: optionarray.push({content: response[i]['name'], value: response[i]['id']});
}

if I'm not mistaken.

Try this one

optionarray[i] = [];
optionarray[i]['content'] = response[i]['name'];     
optionarray[i]['value'] = response[i]['id']; 

You need to define optionarray[i] as array first

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745230152a4617640.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信