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
459 views
in Technique[技术] by (71.8m points)

javascript - 为什么这两种打印所有被3 AND 5整除的数字在5到50之间的解决方案都起作用?(Why do both these two solutions for printing all numbers divisible by 3 AND 5 between 5 and 50 work?)

This was my solution to the problem:(这是我对问题的解决方案:)

 var count = 5; while (count <= 50) { if ((count % 3 || count % 5) === 0) { console.log(count); } count++; } 

This was my the instructors solution:(这是我的讲师解决方案:)

 var count = 5; while (count <= 50) { if (count % 3 === 0 && count % 5 === 0) { console.log(count); } count++; } 

Both of these solutions gave the proper answer, but I question why ||(这两个解决方案都给出了正确的答案,但我质疑为什么||。)

worked in my problem, rather than &&, I tried both.(解决了我的问题,而不是&&,我都尝试了。) && means both need to be true for it to properly run, right?(&&都需要正确运行才能正确运行,对吗?) So wouldn't that have been the proper use?(那不是正确的用法吗?)   ask by UndeadVandal translate from so

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

1 Reply

0 votes
by (71.8m points)

It is a javascript peculiarity you encounter.(这是您遇到的javascript特性。)

If count % 3 is 0 it is considered "falsy" and the other calculation will be used.(如果count % 3为0,则认为是“虚假”,将使用其他计算。) So if either modulus has a remains, that value is used in the final test against 0.(因此,如果任何一个模数都具有残差,则该值将在最终测试中与0相对。)

So while both works, your teachers code is more readable;(因此,虽然两者都可以工作,但是您的教师代码更具可读性;)

thus better.(因此更好。)

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

...