简体   繁体   中英

javascript-comparing two strings in an array to see if they are equal

I am trying to compare the word hello and hey both of which are in an array if they are equal and my code is returning true and yet they are not. how can i modify my code to make it return false when comparing the two words.

function mutation(arr) {
  var sorted =[];
  for (var i =0; i<arr.length; i++)  {
    sorted.push(arr[i].toLowerCase());
  }


  for (var j =0; j<sorted.length;j++)  {
    for(var k=0; k<sorted.length; k++)  {
      if(sorted[j]  == sorted[k])  {
        return true;
      } else{
        return false;
      }
    }
  }
}

mutation(["hello", "hey"]);

只需将第二个循环更改为从j + 1开始,因为您实际上是在比较0与0位置。

for(var k=j+1; k<sorted.length; k++)  {

The code sample given the argument provided to 'mutation' has 2 items. My solution also presumes that arr is an Array containing 2 items.

function mutation(arr) {
  if(arr[0] !== arr[1]) {
    return false;
  }
  return true;
}

mutation(["hello", "hey"]);

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