简体   繁体   中英

JS findIndex method always returns -1

This:

const pageID: number = 4;

and this:

this.charts.findIndex((chart: IChart) => {
  return chart.pageID === pageID;
}));

this.charts is an array of IChart[] which contains:

[
     {
          "pageID": 3,
          "zoomable": false
     },
     {
          "pageID": 4,
          "zoomable": false
     },
     {
          "pageID": 5,
          "zoomable": false
     }
]

Amazingly, this always returns -1 . Even if I change the value of pageID to 4 or 5 .

Usually this works, but it's driving me nuts. The only thing I am doing before trying to find the index is merging two arrays and removing duplicate values based on the pageID parameter, like this:

  let unique = {};
  this.charts = charts[0].concat(charts[1])
    .filter((chart) => !unique[chart.pageID] && (unique[chart.pageID] = true))
    .sort((a, b) => a.pageID - b.pageID);

The output of this.charts is the array pasted above with zoomable and pageID properties.

--

It's not rocket science even running the above in the proper sequence inside node returns the proper index which is 1 in my case. Does anyone have any insights on this issue?

Note: this is running in a Cordova app on iOS wkwebview.

Thank you.

Your code seems to run just fine.

 const allCharts = [[ { 'pageID': 3, 'zoomable': false }, { 'pageID': 4, 'zoomable': false }, { 'pageID': 5, 'zoomable': false } ], [ { 'pageID': 3, 'zoomable': false }, { 'pageID': 6, 'zoomable': false }, { 'pageID': 7, 'zoomable': false } ]]; let unique = {}; const charts = allCharts[0].concat(allCharts[1]) .filter(chart => !unique[chart.pageID] && (unique[chart.pageID] = true)) .sort((a, b) => a.pageID - b.pageID); const pageID = 4; const idx = charts.findIndex(chart => { return chart.pageID === pageID; }); console.log(JSON.stringify(charts)); console.log('idx of pageId 4 is:', idx); 

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