I am new to programming, and I am currently doing the FizzBuzz test, it looks simple at first but we got some requirements to perform it:

我是编程新手,我目前正在进行FizzBu​​zz测试,起初看起来很简单,但我们有一些要求来执行它:

  • I can use only one if. No multiple branches, ternary operators or else.
  • 我只能使用一个。没有多个分支,三元运算符或其他。

  • Unit tests.

I made it by using switch statements, but looking on the internet, I found this way which is shorter, but it is not clear how this process of solving the FizzBuzz challenge is.

我是通过使用switch语句来实现的,但是在互联网上看,我发现这种方式更短,但目前还不清楚这个解决FizzBu​​zz挑战的过程是怎样的。

This is the code:

这是代码:

var i, values = [, , 'fizz', , 'buzz', 'fizz', , , 'fizz', 'buzz', , 'fizz', , , 'fizzbuzz'];
for (i = 0; i < 100; console.log(values[i++ % 15] || i));

If anyone understands this way of solving the FizzBuzz challenge I would appreciate if it can be explained.

如果有人理解这种解决FizzBu​​zz挑战的方式,我会很感激,如果可以解释的话。

1 个解决方案

#1


0

It's called a "lookup table". The pattern of responses cycles through all the possibilities every 15 numbers, because that's the least common multiple of 3 and 15. So we calculate the number modulo 15, and use that as the index into an array of all 15 possibilities.

它被称为“查找表”。响应模式每15个数字循环遍历所有可能性,因为这是3和15的最小公倍数。因此我们计算模数15,并将其用作所有15种可能性的数组的索引。

The blank elements in the array are used to print the numbers themselves instead of fizz or buzz. Leaving an array element is roughly equivalent to specifying undefined as the value, so this is just a shorter way of writing

数组中的空白元素用于打印数字本身而不是嘶嘶声或嗡嗡声。保留数组元素大致相当于将undefined指定为值,因此这只是一种较短的写入方式

values = [undefined, undefined, 'fizz', undefined, 'buzz', 'fizz', undefined, undefined, 'fizz', 'buzz', undefined, 'fizz', undefined, undefined, 'fizzbuzz'];

Since undefined is falsey, values[i++ % 15] || i will be i whenever the array element isn't filled in with one of the strings.

由于undefined是假的,因此值为[i ++%15] ||每当数组元素没有填充其中一个字符串时,我将是我。

更多相关文章

  1. iframe操作、调用父页面元素或js函数
  2. 如何使用变量创建数组?
  3. 推json敲出可观察的数组
  4. 从占用转义字符的字符数组创建字符串
  5. Angularjs在ng-repeat中找到最后一个可见元素
  6. 浏览器如何处理HTML元素上的无效/未指定的属性?
  7. 为什么推荐把<script>元素写在body里面
  8. 在bootstrap中为同一元素使用两个数据切换
  9. 如何获取knockoutjs可观察数组的下一个元素?

随机推荐

  1. php 发送http post请求
  2. Apache 2.2.19 + PHP5.2.17配置问题,请高
  3. Pubsub与Node.js和Socket.io为个人用户
  4. 从函数返回2个值[duplicate]
  5. 如何使用用户名作为子域名创建子域?
  6. PHP生成圆心图片-常用作头像圆图等场景
  7. hust校赛d题 PHP is the best language i
  8. 存储用户所需语言的最佳方式
  9. PHP中使用cURL实现Get和Post请求的方法
  10. 一些PHP相关的数据比较