我正在解决 coderbyte.com 的一些挑战,但遇到了一些问题。这是任务:
Using the JavaScript language, have the function
ArithGeo(arr)
take the array of numbers stored inarr
and return the string "Arithmetic" if the sequence follows an arithmetic pattern or return "Geometric" if it follows a geometric pattern. If the sequence doesn't follow either pattern return -1.An arithmetic sequence is one where the difference between each of the numbers is consistent, where as in a geometric sequence, each term after the first is multiplied by some constant or common ratio. Arithmetic example: [2, 4, 6, 8] and Geometric example: [2, 6, 18, 54].
Negative numbers may be entered as parameters, 0 will not be entered, and no array will contain all the same elements.
function ArithGeo(arr) {
var x = 0;
var s = 0;
var allObjects = [];
for(var i=0; i<arr.length;i++) {
while(x<arr.length-1) {
var diff = arr[x+1]-arr[x];
allObjects.push(diff);
x++;
}
while(s<allObjects.length) {
console.log(allObjects.length);
if(allObjects[s]===allObjects[s+1]) {
console.log('entered if');
return "Arithmetic";
s++;
}
else if(allObjects[s+1]%allObjects[s]===0) {
return "Geometric";
s++;
}
else {
return "-1";
s++;
}
}
}
}
// keep this function call here
// to see how to enter arguments in JavaScript scroll down
ArithGeo([1,2,3,100]);
对于allObjects
数组中的每个元素,它只进入第一个if语句一次,并且应该进入3次。你能告诉我这是为什么吗?
最佳答案
问题是 return
中断了函数执行,之后没有执行任何其他操作。
var f = function () {
these();
things = will + be * 3;
executed();
return 4;
while(anything) {
after++;
a = "return statement";
won = 't';
}
};
f();
疯狂猜测:也许continue
将帮助您(跳转到下一个迭代)
关于javascript - 带 if 语句的 while 循环不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24485887/