而不是数字添加此代码正在进行字符串连接.如何在提示字段中指定输入的类型(例如:number,string).
var jonage = prompt("enter the johns age");
var jonHeight = prompt("enter the johns height");
var jonScore = jonHeight + jonage * 5;
console.log(jonScore);
Run Code Online (Sandbox Code Playgroud)
prompt 是非常基本的,除了默认情况下浏览器的方式之外,没有办法限制输入(例如,没有换行符).
相反,之后将字符串转换为数字.有很多方法可以做到这一点:
+:var jonage = +prompt("enter the johns age");Number: var jonage = Number(prompt("enter the johns age"));parseInt: var jonage = parseInt(prompt("enter the johns age"));parseFloat: var jonage = parseFloat(prompt("enter the johns age"));+和Number:......以同样的方式工作:
NaN如果整个字符串无法转换为数字,则会产生.所以+"123abc"是NaN."")转换为0(令人惊讶).+"0x10"是16并且+"0o10"是8.parseIntparstInt("123abc")是123."")转换为NaN(不0).parseInt("0x10")为16.parseInt("0x10", 10)是0(因为x变得无效0x.不再为指示基数处理这用来为与小数重要如果最终用户输入的字符串一样"010"实行"遗产"八路(领导和浏览器0,而不是领先0o),但它已经8年了(因为第5版规范)自parseInt正式不容许这样做.parseFloat喜欢parseInt,但是是小数,不做基数前缀.parseFloat("0x16")是0,因为它x是无效的(因为它不做基数前缀).
| 归档时间: |
|
| 查看次数: |
105 次 |
| 最近记录: |