测试是否所有数组元素都是数字因子-在for循环内返回 [英] Test whether all array elements are factors of a number - return inside a for loop

查看:82
本文介绍了测试是否所有数组元素都是数字因子-在for循环内返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题:

编写一个函数,如果数组中的所有整数都是数字因子,则返回true,否则返回false.

Write a function that returns true if all integers in an array are factors of a number, and false otherwise.

我尝试了以下代码:

function checkFactors(factors, num) {

  for (let i=0; i<factors.length; i++){
    let element = factors[i];
      console.log(element)

    if (num % element !== 0){
      return false 
    }
    else {
      return true
    }
  }
}

console.log(checkFactors([1, 2, 3, 8], 12)) //➞ false

我的解决方案返回true,这是错误的.我知道是else语句弄糟了它.但是我想理解为什么else语句不能去那里.

My solution returns true which is wrong. I know it's the else statement that's messing it up. But I want to understand why the else statement can't go there.

推荐答案

只需在循环外返回true,

如果您将return true保留在else part中,只要任何不满足num % element !== 0的值,您的代码就会return true,在这种情况下不应该发生这种情况,因为您正在检查数组中的所有值应该是给定数字的因数

If you keep return true in else part as soon as any of value which does not satisfies num % element !== 0 your code will return true which should not happen in this case as you're checking for all the values in array should be factor of given number

让我们通过第一个例子来理解

Let's understand by 1st example

  • 在数组1中的第一个元素上,它将检查条件num % element !== 0是否变为假,因此它将转到条件和函数中的return true,并且不检查其余值.
  • 因此,您需要在最后保留return true,以便如果循环中的任何值都不满足if条件,那么只有控制权会转到return true
    • On first element in array 1 it will check if condition num % element !== 0 which turns out false, so it will go to else condition and return true from function and will not check for rest of values.
    • So you need to keep return true at the end so if any of the value in loop doesn't satisfy the if condition than only control will go to return true
    • function checkFactors(factors, num) {
      
        for (let i=0; i<factors.length; i++){
          let element = factors[i];
          if (num % element !== 0){
            return false 
          }
        }
        return true
      }
      
      
      
      console.log(checkFactors([1, 2, 3, 8], 12)) //➞ false
      console.log(checkFactors([1, 2], 2))

      简而言之-在这种情况下,如果您希望所有人都必须符合条件作为经验法则,您可以将其视为

      In short - In such case where you want all of them must match a condition as a thumb rule you can consider it like

      1. failing case返回值保留在for循环中
      2. 在函数末尾保留passing case返回值
      1. keep the failing case return value inside for loop
      2. keep the passing case return value at the end of function

      JS具有内置方法 Array.every

      JS have a inbuilt method Array.every for such cases

      function checkFactors(factors, num) {
         return factors.every(element => num % element === 0);
      }
      console.log(checkFactors([1, 2, 3, 8], 12)); 
      console.log(checkFactors([1, 2], 2));

      这篇关于测试是否所有数组元素都是数字因子-在for循环内返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆