【发布时间】:2013-03-11 16:10:51
【问题描述】:
类似于 chmod,我想使用 1、2、4 作为通知方式。
1 = Email
2 = SMS
4 = Push notifications
是否有可以输入数字(上图)并可以返回对象的函数(最好是javascript):
{
email: true,
sms: true,
push: false
}
我希望函数不被硬编码。我不想要一堆 if 语句来检查每个组合。我想要一种“聪明”的方式来做到这一点。
【问题讨论】:
-
您需要查看按位运算符 -
&, |, <<, >>, ^。有一些很好的教程介绍了如何查找设置的位,这就是您想要的。 -
opts = { email: 1 << 0, sms: 1 << 1, push: 1 << 2 }- 或用于生成值的任何合适的替代品。加上|用于构建和&用于测试:x = opts.email | opts.sms; if (x & opts.email) { /* here */ }; if (x & opts.push) { /* not here */ }..
标签: javascript algorithm math binary