javascript - 带 if 语句的 while 循环不起作用

标签 javascript arrays

我正在解决 coderbyte.com 的一些挑战,但遇到了一些问题。这是任务:

Using the JavaScript language, have the function ArithGeo(arr) take the array of numbers stored in arr 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/

相关文章:

php - 从数据库打印二维数组

javascript - 如何在 JavaScript 中生成随机数并将其分配给我的变量数组?

javascript - 按索引对字符串数组进行排序

javascript - session 文件未在 AJAX 的父页面上更新

javascript - jQuery ajax 禁用解析

javascript - 对存储在变量中的 xml 运行 Xpath(获取 "Uncaught TypeError: undefined is not a function")

c - 从函数返回指针数组

javascript - 使用 Symbol.iterator 获取 ES6 类的第一个属性

javascript - 如何防止嵌套在另一个也使用 onclick 的元素上的链接上的单击事件?

php - 如何在 php 中动态调用对象函数链?