分享
三行代码  ›  专栏  ›  技术社区  ›  kevin

数组几何不工作时的函数测试

  •  0
  • kevin  · 技术社区  · 1 年前

    我尝试测试一个数组,如果它是几何的,则返回字符串“geometric”,如果它不是,则返回-1。它只是返回-1。我觉得我的功能很有意义。有什么想法吗?

    var isGeometric = function(arr) {
        let format;
        let interval = arr[1] / arr[0];
        for (let i = 0; i < arr.length; i++) {
            format = (arr[i] * interval === arr[i + 1])? 'Geometric' : - 1;
        }
        return format;
    }
    
    isGeometric([3,9,27]);
    //returns -1, should return 'Geometric';
    
    
    // Geometric array example = [3,9,27] or [5,25,125];
    // each step in the array is multiplied by the same #; 
    
    
    2 回复  |  直到 1 年前
        1
  •  2
  •   trincot    1 年前

    试试这个:

    var isGeometric = function(arr) {
      let format;
      let interval = arr[1] / arr[0];
      for (let i = 0; i < arr.length - 1; i++) {
        format = (arr[i] * interval === arr[i + 1])? 'Geometric' : - 1;
        if (format === -1) break;
      }
      return format;
    }
    

    希望能有所帮助:)

    我解决的问题是:

    1. 你的循环超出了数组大小,我限制了它
    2. 在每次迭代中,您都在重新设置格式,我添加了一个break语句,因为一个示例足以证明它是错误的。
        2
  •  1
  •   yqlim    1 年前

    如果你需要一个更详细的答案,读这个。

    var isGeometric = function(arr) {
    
      const interval = arr[1] / arr[0];
      
      for (let i = 0; i < arr.length; i++) {
        // For the sake of readability
        const a = arr[i];
        const b = arr[i + 1];
    
        // This is to check if `b` is still valid value
        // `b` is undefined when your loop reaches the last array element
        if (!b){
          // If `b` is undefined, and your loop reaches the last loop
          // that means there is nothing else to multiply with.
          // So stop the loop.
          if ((i + 1) === arr.length)
            break;
            
          // If `b` is undefined, and your loop is NOT at the last loop,
          // it means something is wrong with one of your value.
          // That means the array is not a geometric, so return -1;
          // One other possibility for `!b` === true is when `b === 0`.
          // In this case, that means it is not a geometry anyway.
          // So return -1 is also correct.
          else
            return -1;
        }
        
        // Return `-1` as soon as it is not a geometric.
        // If you keep looping, the result might change.
        // Besides, you have no reason to keep the loop if you already know it's not a geometric.
        if ((a * interval) !== b)
          return -1;
      }
    
      // If the above loop successfully finishes running,
      // there is only one reason: the array is a loop.
      // So, return 'Geometric'.
      return 'Geometric';
      
    }
    
    
    console.log(isGeometric([3, 9, 27]));
    console.log(isGeometric([5, 25, 125]));
    console.log(isGeometric([10, 100, 1000]));
    console.log(isGeometric([1, 2, 3]));