开发者

get value from javascript object

when alerting a variable in javascript it shows like this.. totally 9 values(name, address, cit开发者_开发百科y, friend etc)

how to retrive the values

[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]


That looks like array of Objects, you need to loop to access each

for(var x in thatObjectArray){
     doSomethingOn(thatObjectArray[x].name);
     doSomethingOn(thatObjectArray[x].address);
     ...
}

or to test, you could do like alert(thatObjectArray[0].name)


JSON.stringify() and .toSource() are convenient for viewing [object Object].

ref: Implementing Mozilla's toSource() method in Internet Explorer

javascript:
   objRA=[
   {name:"Fred",city:"N.Y",friend:"Mike"},
   {name:"Dave",city:"S.F",friend:"Mike"},
   {name:"Dave",city:"S.F",friend:"Fred"},
   {name:"Mary",city:"S.F",friend:"Fred"},
   {name:"Mary",city:"S.F",friend:"Dave"},
   {name:"Dave",city:"S.F",friend:"Mary"},
   {name:"Fred",city:"N.Y",friend:"Mary"},
];
alert(JSON.stringify(objRA));

displays

[{"name":"Fred","city":"N.Y","friend":"Mike"},
{"name":"Dave","city":"S.F","friend":"Mike"},
{"name":"Dave","city":"S.F","friend":"Fred"},
{"name":"Mary","city":"S.F","friend":"Fred"},
{"name":"Mary","city":"S.F","friend":"Dave"},
{"name":"Dave","city":"S.F","friend":"Mary"},
{"name":"Fred","city":"N.Y","friend":"Mary"}]

BUT, if ...

javascript:
   objRA=[
        {name:"Mike"},
        {name:"Fred",city:"N.Y",friend: "?" },
        {name:"Dave",city:"S.F",friend: "?" },
        {name:"Dave",city:"S.F",friend: "?" },
        {name:"Mary",city:"S.F"},
        {name:"Mary",city:"S.F",friend: "?" },
        {name:"Dave",city:"S.F",friend: "?" },
        {name:"Fred",city:"N.Y"},
];
  objRA[1].friend=objRA[0];
  objRA[2].friend=objRA[0];
  objRA[3].friend=objRA[1];
  objRA[4].friend=objRA[1];
  objRA[5].friend=objRA[2];
  objRA[6].friend=objRA[4];
  objRA[7].friend=objRA[4];
alert(objRA.toSource().split("},").join("},\n"));

then only .toSource() can display (with a little manual persuasion):

    [#1={name:"Mike"},
     #2={name:"Fred", city:"N.Y", friend:#1#},
     #3={name:"Dave", city:"S.F", friend:#1#},
        {name:"Dave", city:"S.F", friend:#2#},
     #4={name:"Mary", city:"S.F", friend:#2#},
        {name:"Mary", city:"S.F", friend:#3#},
        {name:"Dave", city:"S.F", friend:#4#},
        {name:"Fred", city:"N.Y", friend:#4#}]
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜