Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

javascript - Test whether all array elements are factors of a number - return inside a for loop

I have the following question:

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

I tried the code below:

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are working in a chocolate store, and your boss tells you to check wether all chocolates (there are chili chocolate, caramel chocolate and coffee chocolate) are delicious. He tells you the following:

Go through all chocolates, and for each chocolate, taste it, if it is fine, tell me that everything is fine, otherwise tell me that something is wrong1

You start with the first chocolate, which is chili chocolate, it tastes delucious, you go to your boss and tell him that everything is fine. Your boss yells at you because you haven't tasted the caramel chocolate and the coffee chocolate yet.

You realize that your boss actually wanted you to do:

Go through the chocolates, for each chocolate, taste it, if it doesnt taste well tell, tell me immeadiately, otherwise continue until you tasted them all, then return to me and tell me that everything is fine.2

Or in code:

 // 1
  function checkChocolates(chocolates) {
    for(const chocolate of chocolates) {
       if(isTasty(chocolate)) {
         return true;
       } else {
         return false;
       }
    }
 }

 // 2
 function checkChocolates(chocolates) {
   for(const chocolate of chocolates) {
     if(isTasty(chocolate)) {
       continue; // this could be omitted, as a loop keeps looping nevertheless
     } else {
       return false;
     }
   }
   return true;
 }

As this is a very common task in programming, there is already a shorter way to express this:

 if(chocolates.every(isTasty)) {
   alert("all chocolates are fine");
 } else {
    alert("Oh, that doesnt taste good");
 }

whereas isTasty is a function taking a chocolate and returning either true or false.


If you didn't grasp it yet, just try it out! Buy some chocolate, and taste it! If someone tells you "eating choclate isn't learning", respond with "I'm doing rubber duck debugging" and no one can complain :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...