javascript - 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 #;
解决方案
尝试这个:
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;
}
我希望它有帮助:)
我解决的问题是:
- 你的循环超出了数组大小,我限制了它
- 在每次迭代中,您都在重置格式,我添加了一个 break 语句,因为一个示例足以证明它是错误的
推荐阅读
- python - 如何用 Python pptx 替换 PPP 中的文本?
- arrays - 如何获取输出结果在括号中的数组,如 [1][2][3] 到 [1 2 3]
- javascript - 使用纯 Java 脚本单击旁边的按钮后如何删除每个项目
- android - 是否可以在android中将一个设备共享屏幕到另一台设备?
- android - 如何更改现有的 .apk 应用程序 ID?
- python - ValueError:输入 0 与层 lstm_14 不兼容:预期 ndim=3,发现 ndim=2
- python - Django 2 python“urls”文件中的循环导入
- javascript - 在嵌套循环中反应渲染 html 元素
- php - 如何在PHPexcel中添加空白行以分隔数据
- javascript - 为什么这个 event.target.previousElementSibling 不起作用?