简体   繁体   English

为什么我的 for 循环只将第一个结果返回到 JavaScript 中的数组?

[英]Why does my for loop only return the first result to an array in JavaScript?

I am attempting to add the results of doubling every other number in an array to a new array.我正在尝试将数组中每隔一个数字加倍的结果添加到一个新数组中。 However the code only seems to be pushing the first index that is doubled.然而,代码似乎只是推动了第一个翻倍的索引。 I assume the problem is with the.push line but I am not sure.我认为问题出在 .push 行上,但我不确定。 Thanks for any help!谢谢你的帮助!

Here is the code I have:这是我的代码:

const addTwoDigits = n => {
  return n % 10 + Math.floor(n / 10);
}

const validateCred = array => {
          let sumNums = []
          let i = array.length - 2
          while (i > 0) {
              let doubleNum = (array[i] * 2)
              if (doubleNum > 9) {
                let addedNum = addTwoDigits(doubleNum)
                sumNums.push(addedNum)
              } else {
                sumNums.push(doubleNum)
              }
              i--; 
              return sumNums;
        }
}

const testArray = [4, 2, 1, 6, 5, 7, 5]
console.log(validateCred(testArray));

I was hoping the sumNums array would contain every other digit doubled (starting with '' in the test array and moving left) but it only returns [ 5 ].我希望 sumNums 数组将包含所有其他加倍的数字(从测试数组中的 '' 开始并向左移动),但它只返回 [5]。

You returned the value in the loop.您在循环中返回了值。 When the compiler comes in loop then first time it returns the value and break the loop.当编译器进入循环时,它第一次返回值并中断循环。

const addTwoDigits = n => {
  return n % 10 + Math.floor(n / 10);
}

const validateCred = array => {
          let sumNums = []
          let i = array.length - 2
          while (i > 0) {
              let doubleNum = (array[i] * 2)
              if (doubleNum > 9) {
                let addedNum = addTwoDigits(doubleNum)
                sumNums.push(addedNum)
              } else {
                sumNums.push(doubleNum)
              }
              i--; 
        }
        return sumNums;
}

const testArray = [4, 2, 1, 6, 5, 7, 5]
console.log(validateCred(testArray));

Your can try this code.你可以试试这个代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM