简体   繁体   中英

How to access Attributes of an Object inside an Array?

var ppArr [];  // An Array filled with Objects
var ppSort []; // Empty Array
var i = 0; // Counter
for ( ; ; i++) // Increase "i"
if ( ... )  // does not matter here
{
     var ppInfo = { SortIndex : ppArr[i].SortIndex, PPCount : 1, SortedArr : newArray() };
     ppInfo.SortedArr.push(ppArr[i]);
     ppSort.push(ppInfo);

}
else { // Neither dose that part
 ... 
     }
}

https://repl.it/E4xO/19

Hello Guys,

i am having a problem with accessing an Attribute of an Object through an Array in Javascript.

As you can see I am pusing the "ppInfo" objects into the empty Array called "ppSort".

How is it possible to access the SortIndex of this object?

I have tried the following :

  • ppSort.ppInfo.SortIndex
  • ppSort[i].ppInfo.SortIndex

I am not sure what else I could try. Am I doing something comlpetly wrong? I can access the SortIndex with "ppInfo.SortIndex" but this object is changed after every run.

Thank you and best regards,

The 'undefined' you see is just repl.it telling you the code ran without returning any values or throwing any errors. If you try it in a browser or a different test environment such as jsfiddle.net, you won't see the 'undefined'. Ori already gave you the answer, but if you want to see it working:

 var ppArr = []; ppArr[0] = { Code: "Test", SortIndex: 100 }; ppArr[1] = { Code: "Test", SortIndex: 200 }; var ppSort = []; for (var i = 0; i < 2; i++) // Increase "i" { if (i < 2) // does not matter here { var ppInfo = { SortIndex: ppArr[i].SortIndex, PPCount: 1, SortedArr: new Array() }; ppInfo.SortedArr.push(ppArr[i]); ppSort.push(ppInfo); } } var r1 = '1st value: ' + ppSort[0].SortIndex; var r2 = '2nd value: ' + ppSort[1].SortIndex; alert(r1 + '\\n' + r2); 

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