[英]How to display list of numbers based on condition in javascript
I would like to know how to get the list of numbers based on two condition我想知道如何根据两个条件获取数字列表
Expected Output预期产出
6,9,12,15...45 6,9,12,15...45
My attempt我的尝试
function getNumbers() { var result = []; for (var i = 0; i < 50; i++) { if (i % 2 == 0) { return } else { result.push(i); return result.toString() } } } console.log(getNumbers())
This seems to work to specs - your specs says it should start at 6 and not at 1这似乎适用于规格 - 您的规格说它应该从 6 而不是 1 开始
const numbers = [...Array(50).keys()]. filter(num => num !== 0 && num%3 === 0 && !String(num).endsWith("3")) console.log(numbers)
NOTE: You can change [...Array(50).keys()]
to [...Array(50).keys()].slice(1)
if you want to avoid the test for 0注意:如果您想避免测试 0,您可以将
[...Array(50).keys()]
更改为[...Array(50).keys()].slice(1)
You can do that with a check if the modulo of 3 is 0 and the modulo of 10 is not 3. If you want to beautify the code you can combine this answer with mplungjan answer, but i wanted to show a mathematical alternative of the !String(num).endsWith("3")
method provided by mplungjan.您可以通过检查 3 的模数是否为 0 并且 10 的模数不是 3 来做到这一点。如果您想美化代码,您可以将此答案与 mplungjan 答案结合起来,但我想展示
!String(num).endsWith("3")
提供的!String(num).endsWith("3")
方法。
I started your iteration at 1 instead of 0 to avoid 0 being put into the array.我从 1 而不是 0 开始您的迭代,以避免将 0 放入数组中。 I also corrected your return statements.
我还更正了您的退货声明。
function getNumbers() { var result = []; for (var i = 1; i < 50; i++) { if (i % 3 === 0 && i % 10 !== 3) { result.push(i); } } return result; } console.log(getNumbers())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.