javascript - 我如何记录数组中正确元素的索引,答案不是 -1
问题描述
我最多只能从 .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"
}]```
解决方案
对我来说似乎是一个数据类型问题
检查targetyear和fifaData[i].year的类型
对于不考虑数据类型的匹配,您可以修改检查以使用==而不是===
if (fifaData[i].year == targetYear)
推荐阅读
- php - 如何在 WooCommerce 中突出显示可变产品页面上的变体表单字段?
- javascript - JS New Date() 返回纪元 0
- reactjs - 为什么我不能对某些 React.Components 使用 className 属性?
- google-bigquery - 在 BigQuery 中将字符串转换为日期?
- firebase - WebStorm 是否有 Firebase 存储规则语法高亮显示?
- python - Pytest lambda 处理程序传递事件和上下文
- testing - 函数调用中的测试或 clojure 中的语句未运行
- scala - scala spark UDF过滤器数组的结构
- c - sscanf 获取字符串直到第二个符号(包括一个)
- java - Eclipse 找不到可执行 Jar 的库