【问题标题】:How can i log the index of the correct element in array with an answer that is NOT -1我如何记录数组中正确元素的索引,答案不是 -1
【发布时间】:2020-07-16 02:07:06
【问题描述】:

我最多只能从 .indexOf、.findIndex、returning、console.logging 等各种方法中得到“-1”。 有一个名为 fifaData.js 的单独数组文件,我可以检索一些信息,而不是索引。我猜这是一个语法错误,但我已经做了好几天了,无法弄清楚。这是我的第一个问题,如果我很糟糕,我很抱歉。我发现的其他答案都导致'-1'。这绝对不是我想要退货的。

const popupQuery=prompt("Enter the Year , Data sought","1930,Home Team Name"), targetYear=popupQuery.split(",")[0],targetData=popupQuery.split(",")[1];

function fifaParse(targetYear){
    for(let i=0; i<fifaData.length; i++) {
        if (fifaData[i].year === targetYear && fifaData[i].Stage == "Group 4") {
            console.log('i: ', i);}}}

fifaParse(targetYear)```

 Example (fifa.js) :
```export const fifaData = [
  {
    "Year": 1930,
    "Datetime": "13 Jul 1930 - 15:00",
    "Stage": "Group 1",
    "Stadium": "Pocitos",
    "City": "Montevideo",
    "Home Team Name": "France",
    "Home Team Goals": 4,
    "Away Team Goals": 1,
    "Away Team Name": "Mexico",
    "Win conditions": "",
    "Attendance": 4444,
    "Half-time Home Goals": 3,
    "Half-time Away Goals": 0,
    "Referee": "LOMBARDI Domingo (URU)",
    "Assistant 1": "CRISTOPHE Henry (BEL)",
    "Assistant 2": "REGO Gilberto (BRA)",
    "RoundID": 201,
    "MatchID": 1096,
    "Home Team Initials": "FRA",
    "Away Team Initials": "MEX"
  },
  {
    "Year": 1930,
    "Datetime": "13 Jul 1930 - 15:00",
    "Stage": "Group 4",
    "Stadium": "Parque Central",
    "City": "Montevideo",
    "Home Team Name": "USA",
    "Home Team Goals": 3,
    "Away Team Goals": 0,
    "Away Team Name": "Belgium",
    "Win conditions": "",
    "Attendance": 18346,
    "Half-time Home Goals": 2,
    "Half-time Away Goals": 0,
    "Referee": "MACIAS Jose (ARG)",
    "Assistant 1": "MATEUCCI Francisco (URU)",
    "Assistant 2": "WARNKEN Alberto (CHI)",
    "RoundID": 201,
    "MatchID": 1090,
    "Home Team Initials": "USA",
    "Away Team Initials": "BEL"
  }]```

【问题讨论】:

  • 如果不分享至少一个与fifaData.js 的结构相匹配的JSON 示例,那么没有人能够帮助您。
  • 请提供变量“fifaData”数据结构信息,这将有助于我们更好地理解问题

标签: javascript arrays indexing


【解决方案1】:

对我来说似乎是数据类型问题

检查 targetyear 和 fifaData[i].year

的类型

对于不考虑数据类型的匹配,您可以修改检查以使用 == 而不是 ===

if (fifaData[i].year == targetYear)

【讨论】:

  • 您在很大程度上是正确的。我现在看到我没有大写 .Year。 == 建议也很有帮助。事实证明,“-1”表示条件从未满足。如果我知道我会更敏锐。 ;) 非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-18
  • 1970-01-01
  • 2019-05-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-13
  • 2015-05-19
相关资源
最近更新 更多