简体   繁体   中英

Why can't I grab a specific objects from my array?

for (var statementCounter = 0; statementCounter < 23; statementCounter++) {
  secularScores.push([scores[statementCounter][0], scores[statementCounter][1]]);
  if (sorted == false) {
    secularScores.sort(function (a, b) {
      return b[1] - a[1]
    });
    sorted = true;
  } else {
    console.log(secularScores); // this works
    console.log(secularScores[0]); // this works
    console.log(scores[statementCounter]); // this works
    console.log(scores[statementCounter][0]); // this works
    console.log(secularScores[statementCounter]); // this doesn't work
    console.log(secularScores[statementCounter][0]); // this doesn't work"Uncaught typeError: Cannot read property of '0' of undefined"
  }
}

What I don't understand is why the bottom ones don't work.

The array that I push into secularScores works just fine, I can grab any specific object from it, but when I try to grab a specific object from secularScores, it says it's undefined.

secularScores[statementCounter] says undefined.
secularScores[statementCounter][0] says Error: cannot read property '0'of undefined.

Here's the array (the result of console.log(secularScores))

(23) [Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2),
Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), 
Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), 
Array(2), Array(2)]
0: (2) ["VVD", "63.33"]
1: (2) ["CDA", "56.67"]
2: (2) ["PVV", "50.00"]
3: (2) ["D66", 18]
4: (2) ["GroenLinks", 14]
5: (2) ["SP", 17]
6: (2) ["PvdA", 15]
7: (2) ["ChristenUnie", 20]
8: (2) ["Partij voor de Dieren", 14]
9: (2) ["SGP", 18]
10: (2) ["DENK", 18]
11: (2) ["Forum voor Democratie", 11]
12: (2) ["Lokaal in de Kamer", 12]
13: (2) ["OndernemersPartij", 15]
14: (2) ["VNL", 10]
15: (2) ["Nieuwe Wegen", 14]
16: (2) ["De Burger Beweging", 13]
17: (2) ["Piratenpartij", 18]
18: (2) ["Artikel 1", 14]
19: (2) ["Libertarische Partij", 16]
20: (2) ["50Plus", 11]
21: (2) ["Vrijzinnige Partij", 14]
22: (2) ["Niet Stemmers", 0]
length: 23
__proto__: Array(0)

I found out that my sort function is messing with my results, causing this issue. Thank you, everyone, for trying to help me.

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