【问题标题】:Why can't I grab a specific objects from my array?为什么我不能从我的数组中抓取特定对象?
【发布时间】:2020-10-16 08:49:33
【问题描述】:
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"
  }
}

我不明白为什么底部的不起作用。

我推入 secularScores 的数组工作正常,我可以从中获取任何特定对象,但是当我尝试从 secularScores 中获取特定对象时,它说它是未定义的。

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

这是数组(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)

【问题讨论】:

  • 你能显示数组吗?
  • 不可能 - 至少对于您显示的代码
  • 你能把console.log(secularScores);的结果贴出来吗?或者甚至只是日志?重新创建上下文非常困难,我认为查看日志可能会有所帮助。
  • 这里是数组(console.log(secularScores) 的结果)(由于字符限制,只有一部分) (23) [Array(2), Array(2), Array(2) , 数组 (2), 数组 (2), 数组 (2), 数组 (2), 数组 (2), 数组 (2), 数组 (2), 数组 (2), 数组 (2), 数组 (2) , 数组 (2), 数组 (2), 数组 (2), 数组 (2), 数组 (2), 数组 (2), 数组 (2), 数组 (2), 数组 (2), 数组 (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]
  • scores 数组是什么?我尝试在您的代码中使用您的secularScores 数组作为scores 数组,并且一切正常。您能否使用 JS sn-p 功能将您的代码变成一个最小的可运行示例?

标签: javascript arrays


【解决方案1】:

我发现我的排序功能弄乱了我的结果,导致了这个问题。 谢谢大家帮助我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 2022-01-12
    • 2016-03-11
    • 2015-12-03
    • 2021-04-11
    • 1970-01-01
    • 2021-09-10
    相关资源
    最近更新 更多