简体   繁体   English

如何根据javascript中的条件显示数字列表

[英]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我想知道如何根据两个条件获取数字列表

  • number should be divisible by 3数字应该可以被 3 整除
  • number should not end with 3 How to implement the list within 50 numbers in javascript数字不应以 3 结尾 如何在 javascript 中实现 50 个数字以内的列表

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.

相关问题 如何根据条件显示带有唯一项目符号的无序列表? - How to display a unordered list with unique bullets based on condition? JavaScript如何显示数字 - JavaScript how to display numbers 在javascript中循环一个数组,并根据条件将数字加倍 - looping an array in javascript and doubling the numbers based on condition 角度如何根据数字条件编写字符串 - In angular how to write strings based on condition of numbers 如何根据 JavaScript 中的条件添加数字 - How to add numbers following a condition in JavaScript 根据 javascript 中的条件使用正则表达式突出显示字符串中的数字 - Highlight numbers in a string using regex based on a condition in javascript 如何使用基于 var 的 javascript 在 if 条件中显示链接 - How do I Display a link inside an if-condition using javascript based on var 如何使用 react 和 javascript 根据可重用组件中的条件显示特定文本? - How to display a particular text based on a condition in a reusable component using react and javascript? 如何显示2个随机数字并将其存储到基于Javascript的页面URL的用户缓存中? - How to display 2 random numbers and store it to the users cache based on the page URL with Javascript? 如何在javascript中排列数字列表? - How to arange list of numbers in javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM