Why indexOf in javascript not working?

a 夏天 提交于 2021-02-20 19:31:31

问题


I'm not sure what I'm doing wrong here. The first instance that I use indexOf it works perfectly fine, but when I use it the second time it's not returning the result that I'm expecting.

function mutation(arr) {
    //return arr;
    res = "";
    for (var x=0; x<arr[1].split("").length; x++) {
        if (arr[0].indexOf(arr[1].split("")[x]) !== -1) {
            res += "t";
        } else {
            res += "f";
        }
    }
    // res = ttt
    if (res.indexOf("f") !== -1) {
        return true;
    } else {
        return false;
    }
}

mutation(["hello", "hey"]);
// this returns true instead of false
mutation(["floor", "loo"]); 
// returns false instead of true

mutation should return false if an element from arr[1] is not present in arr[0] else return true.


回答1:


your code isn't working because when you say:

res.indexOf("f") != -1

this means: "I found an f", but you're treating it as if it means "I did not find an f".

In your case that you want to return false if you find an 'f', but you're returning true. Flip your true and false cases:

if (res.indexOf("f") != -1) {
   return false;
 } else {
   return true;
 }

ALSO your for loop is wrong because x starts at 0, so you need to go to < length not <= length of your string.

for (var x=0; x < arr[1].split("").length; x++) {

and now your code works as you wanted it to.




回答2:


Just edited your code. Click on the <p> to check:

function mutation(arr) {
  //return arr;
  res = "";
  for (var x=0; x< arr[1].split("").length; x++) {
    res += arr[0].indexOf(arr[1].split("")[x]) > -1 ? 't' : 'f';
  }
 return res.indexOf('f') > -1;
}

$('p').click(function(){
  alert(mutation(["hello", "hey"]));
  alert(mutation(["floor", "loo"]));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Click me</p>



回答3:


If you simplify the logic a bit, that's easier to check:

function mutation(arr) {
  return arr[1].split('').reduce(function(res, x) {
    return arr[0].indexOf(x) >= 0;
  }, true);
}

Thanks Leon for the correction.




回答4:


I tried to not chance your logic, the mistake are:

  • You're trying to compare with all characters on the array[0], not only the first.
  • If you find a character equals on the first character on array[0] you should return true.

Correct code:

function mutation(arr) {
  res = "";
  for (var x=0; x<=arr[1].split("").length; x++) {
    if (arr[0].split("")[0].indexOf(arr[1].split("")[x]) !== -1) {
      return true;
    }
  }
  return false;
}


来源:https://stackoverflow.com/questions/33851903/why-indexof-in-javascript-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!