【问题标题】:JavaScript remainder (%) operator not working as expected? [closed]JavaScript 余数 (%) 运算符未按预期工作? [关闭]
【发布时间】:2021-06-02 03:11:09
【问题描述】:

我有以下代码:

function divisibleBy(numbers, divisor){
  arr = []
  for(let i = 0 ; i <= numbers.length; i++) {
   if(numbers[i] % divisor === 0) {
      arr.push(i)
   }
  }
  return arr
}

divisibleBy([1,2,3,4,5,6], 2)

我需要的是将数字推入arr 的代码,仅当除法的余数为0 时。预期结果是:[2,4,6] 但是,我得到[1,3,5]。就数学而言,当你除以3 by 2 时,余数应该是1,因此它不应该被添加到数组中。我知道我的代码中可能存在错误,但几个小时后我无法确定所述错误。

由于我是编码新手,请多多包涵。

【问题讨论】:

  • 你在测试numbers[i],但是pushing i; push 与您测试的号码相同,它会起作用。另外,旁注,循环应该限制为i &lt; numbers.length,而不是i &lt;= numbers.length,或者您在可用值之外进行测试(数组索引不包括长度本身,它们会停止它的一小部分)。投票结束是一个错字。
  • 你也可以使用array.filter()来简化你的代码,例如function divisibleBy(numbers, divisor) { return numbers.filter(number =&gt; number % divisor === 0) }

标签: javascript arrays algorithm for-loop


【解决方案1】:

您推送的是索引,而不是元素。将其更改为:

function divisibleBy(numbers, divisor){
  arr = []
  for(let i = 0 ; i <= numbers.length; i++) {
   if(numbers[i] % divisor === 0) {
      arr.push(numbers[i])  // Push the element at index i
   }
  }
  return arr
}

【讨论】:

    【解决方案2】:

    arr.push(i); 推入numbers 数组中数字的索引位置。将其更改为arr.push(numbers[i]);,这样它将是numbers 数组的索引位置处的实际数字。

    function divisibleBy(numbers, divisor){
      arr = []
      for(let i = 0 ; i <= numbers.length; i++) {
       if(numbers[i] % divisor === 0) {
          arr.push(numbers[i]);
       }
      }
      return arr
    }
    
    console.log(divisibleBy([1,2,3,4,5,6], 2))

    【讨论】:

      【解决方案3】:

      这是因为您正在执行 arr.push(i) 而不是 arr.push(numbers[i]) 将索引作为输出而不是值。

      【讨论】:

        猜你喜欢
        • 2018-02-19
        • 2015-05-11
        • 2019-06-20
        • 2021-04-13
        • 1970-01-01
        • 2020-12-29
        • 2021-04-30
        • 2019-12-10
        相关资源
        最近更新 更多