javascript - 变量似乎没有获得新值

标签 javascript arrays loops do-while

  function reachOne(integer) {
      //deal with errors in input
      var array = [];
      //initialize multiply by putting it equal to 1
      var multiply = 1;
      var count = 0;

      if (integer < 0) {
          document.write('Do it again, Input should be a positive Integer')
      } else if (integer < 10 && integer >= 0) {
          document.write(count);
      } else {

          do {
              for (var i = 0; i < integer.length; i++) {
                  multiply = multiply * integer.charAt(i);
                  //if i try to write document.write(multiply), nothing appears
                  console.log("HELLO");
              }
              count++
          }

          while (multiply >= 10)



      }
      //if I write document.write(multiply) here, the result is 1 and not the product of all the numbers
  }
  reachSingle(254)        

    ----------

上面的代码应该采用一个正整数,并返回该整数内的数字必须相乘才能得到一位数字的次数。示例:254 将给出 2:2*5*4=40 和 4*0 = 0。

最佳答案

这应该可以做到:

function reachOne(integer, count) {
	
  if (isNaN(integer) || integer < 1) return 0;
  
	var multiply = 1;
  if (isNaN(count)) count = 1;

  while (integer > 0) {    
    multiply = multiply * (integer % 10);
    integer = Math.floor(integer / 10);
  }
  if (multiply > 9) return reachOne(multiply, ++count);
  return count;
}

console.log(reachOne(254));

关于javascript - 变量似乎没有获得新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42423637/

相关文章:

javascript - 为什么更新的 javascript 文件没有在已部署的网站上执行; azure 网站上的 asp MVC

javascript - 在javascript中动态创建带有字符串索引的二维表

javascript - 游戏节目倒计时音乐

arrays - 使用 Enum 类型保存字典数组,NSCoding

java - 如何对多个元素上的 Vector<Vector<String>> 进行排序,将子项分组在一起?

python - 如何使用 pandas.read_csv 将 CSV 文件中的数据插入到数据框中?

javascript - AWS : How to specify dynamodb arn in javascript SDK

bash - 在循环中打印 sql 查询的单个数据到 stroud

java - 无法退出此循环?

excel - 从给定范围中删除标点符号的 VBA 循环