在引入逐位运算符之前,首先将数字转换为字符串,然后使用字符串方法将数字的一部分切成片,然后执行其余部分。在此类型转换必须将数字转换为字符串。但是Bitwise or的引入使任务非常容易。使用Bitwise或时,不需要 类型转换,也不需要使用任何字符串方法,从而减少了代码的工作量和代码长度。
在下面的示例中,一个名为“ string.substring()”的字符串方法用于删除数字的最后一位。
<html> <body> <script> var str = '2345'; document.write((str.substring(0, str.length - 1))); </script> </body> </html>
输出结果
234
但是,随着Bitwise或的出现,类型转换和字符串方法就不在图中了。按位或使代码非常简洁。
<html> <body> <script> document.write(2345 / 10 | 0) document.write("</br>"); document.write(2345 / 100 | 0) document.write("</br>"); document.write(2345 / 1000 | 0) </script> </body> </html>
输出结果
234 23 2