JS函数写出一个字,二进制计数器风格 [英] JS function for writing out a word, binary counter style

查看:167
本文介绍了JS函数写出一个字,二进制计数器风格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建一个循环来输出给定词是这样的:

...如果这个词是ABCD

  A ---
-b--
ab--
- C-
A-C-
-公元前-
ABC-
--- D
广告
-b-D
AB-D
- 光盘
A-CD
-bcd
A B C D

换言之,字母出现在二进制计数器顺序

  1000
0100
1100
0010
1010

等。

感谢


解决方案

  VAR I = 1;
的console.log(ABCD.replace(/./克​​,功能(C,N){
   返回(ⅰ及(1下;&所述; n))的? C : '-';
}));

只是循环 I 1 (2 ^长度)-1

How can I create a loop to output any given word like this:

...if the word is 'abcd'

a---
-b--
ab--
--c-
a-c-
-bc-
abc-
---d
a--d
-b-d
ab-d
--cd
a-cd
-bcd
abcd

in other words, letters appear in binary counter order

1000
0100
1100
0010
1010

etc.

Thanks

解决方案

var i = 1;
console.log("abcd".replace(/./g, function(c,n) { 
   return (i & (1 << n)) ? c : '-';
}));

Just loop i from 1 to (2 ^ length) -1

这篇关于JS函数写出一个字,二进制计数器风格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆