首页 > 解决方案 > Function testing if array is Geometric not working

问题描述

I am trying to test an array to return a string 'Geometric' if it's Geometric and -1 if it's not. It's only returning - 1. I feel that my function makes sense. Any ideas?

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 #; 

标签: javascriptarrays

解决方案


尝试这个:

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 语句,因为一个示例足以证明它是错误的

推荐阅读