Javascript中的字符串转换(十进制到二进制) [英] String Conversion in Javascript (Decimal to Binary)

查看:139
本文介绍了Javascript中的字符串转换(十进制到二进制)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有新手!想知道为什么以下转换失败!

A newbie here! Wondering why the following conversion fails!

var num= prompt("Enter num"); 
alert(num.toString(2));

如果d输入为32 ..我也得到32作为警告消息:/

If d input is 32.. I get 32 as d alert message too :/

推荐答案

尝试

(+num).toString(2)

Number(num).toString(2)

parseInt(num, 10).toString(2)

任何一个都应该更适合你。

Any of those should work better for you.

问题是 toString javascript方法 Number 对象覆盖对象的 toString 方法接受可选基数作为参数的对象,以提供您正在寻找的功能。 String 对象不会覆盖对象 toString 方法,所以传入的任何参数都会被忽略。

The issue is that the toString method of javascript Number objects overrides the toString method of Object objects to accept an optional radix as an argument to provide the functionality you are looking for. The String object does not override Object's toString method, so any arguments passed in are ignored.

有关这些对象的更多详细信息,请参阅Mozilla上的文档:

For more detailed information about these objects, see the docs at Mozilla:

https://developer.mozilla.org/ en-US / docs / JavaScript / Reference / Global_Objects / Number / toString
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String#Methods

或W3学校:

http://www.w3schools.com/jsref/jsref_tostring_number.asp
http://www.w3schools.com/jsr ef / jsref_obj_string.asp

这篇关于Javascript中的字符串转换(十进制到二进制)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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