Why is indexOf not working in the array divided by the string split('\n') of the text file received in ajax?

Asked 2 years ago, Updated 2 years ago, 119 views

I wrote it in a script inside the body.

    $.ajax({
        url: "aaa.txt", 
        success: function(result){
            console.log(result);
            var rArr = result.split("\n");
            console.log(rArr);
            var ee = rArr.indexOf("01001");
            console.log(ee);
        }
    });

It's not working. aaa.txt data is

01000
01001
01139

It's simple. Anyway, if you cut it like that, I think the arrangement is good. But ee keeps returning -1. My common sense is that I should return one. Why is that?

ajax split indexof array $.get

2022-09-22 18:49

1 Answers

If you use indexOf() in the format indexOf("I want to find"), you will inevitably get a value that corresponds to 'I can't find'. The reason is explained here.

split() returns an array, so write findIndex() method.

var ee = rArr.findIndex(function(e){
  return e == '01001';
});
console.log(rArr[ee]); // Probably "01001"


2022-09-22 18:49

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.