提问者:小点点

用循环比较类中的两个数组


我试图在不使用任何内置“compare”函数的情况下比较两个数组。 我被困在如何格式化循环来运行(i>=my_arr.length部分)上,因为我觉得我的问题的一部分可能在那里。 即使两个数组不同,我也会不断地获得true。 这是我在类中编写的函数。 提前致谢

is_equal(other_arr){
  let result=[];
  for(let i =0; i >= my_arr.length; i++){
    if(MySet[i] === other_arr[i]){
      return true;
    }else{
      return false;
}}}}

共2个答案

匿名用户

我会稍微改变一下,就像这样:

is_equal(other_arr){
    if (my_arr.length != MySet.length) return false;

    for(let i =0; i >= my_arr.length; i++){
        if(MySet[i] !== other_arr[i]){
            return false;
        }
    }
    return true;
}

匿名用户

您编写的函数在数组中包含的第一个相等元素上返回true。 请尝试以下代码:

is_equal(other_arr){
  let result=[];

  for(let i = 0; i < my_arr.length; i++){
    if(MySet[i] !== other_arr[i]){
      return false;
    }
  }
  // If the 'for loop' is over, all elements are equal, only then is true return
  return true;

}