此代码正在执行字符串连接,而不是数字添加。 如何在提示字段中指定输入的类型(例如:number,string)。
var jonage = prompt("enter the johns age");
var jonHeight = prompt("enter the johns height");
var jonScore = jonHeight + jonage * 5;
console.log(jonScore);
答案 0 :(得分:5)
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
。parseInt
parstInt("123abc")
是123
。""
)转换为NaN
(不是0
)。parseInt("0x10")
为16。parseInt("0x10", 10)
是0
(因为x
变为无效,0x
不再被视为表示数字基数。如果最终用户输入了"010"
等字符串,则使用对小数点很重要浏览器已实施"传统"八进制(领先0
而不是领先0o
),但自{5th edition spec以来已经过去8年了 1}}正式不允许这样做。parseInt
与parseFloat
类似,但是小数字并没有做基数前缀。 parseInt
为parseFloat("0x16")
,因为0
无效(因为它不做基数前缀)。
答案 1 :(得分:1)
你做不到。 prompt
将始终返回一个字符串。
相反,将字符串转换为您想要的任何格式(例如,使用parseFloat
)。
答案 2 :(得分:0)
提示始终将其输入作为String value。
您需要将其解析为任一数字(如果使用小数)或整数(如果使用完整数字):
十进制示例
this.selectedValue = 'identifier'
整数示例
var jonage = Number(prompt("enter the johns age"));
var jonHeight = Number(prompt("enter the johns height"));
var jonScore = jonHeight + jonage * 5;
console.log(jonScore);
答案 3 :(得分:0)
正如其他人所说,你不能改变提示返回的类型。它总是返回一个字符串。相反,在输出结果之前将字符串转换为整数。
此外,您的数学逻辑似乎是错误的?如果您想先添加,请在进行产品之前将其放在括号中。请注意*
和/
在+
和-
之前执行。
var jonage = prompt("enter the johns age");
var jonHeight = prompt("enter the johns height");
var jonScore = (parseInt(jonHeight) + parseInt(jonage)) * 5;
console.log(jonScore);
答案 4 :(得分:-1)
您始终需要转换提示值,因为它始终是字符串。
const functions = require('firebase-functions');
const admin = require('firebase-admin');
exports.sayi = functions.database.ref("/users/{uid}/status").onWrite(event => {
const status = event.data.val();
var user = event.data.ref.parent.key;
if (status =="on") {
console.log(status);
const events = event.data.adminRef.child('users');
const query =events.orderByChild('status').equalTo('on').limitToFirst(2);
query.on("value", sorunsuz,sorunlu);
}
});
function sorunlu(error) {
console.log("Something went wrong.");
console.log(error);
}
function sorunsuz(data) {
console.log("11111");
var fruits = data.val();
console.log(fruits); //it returns null here
var keys = Object.keys(fruits);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if(key==user){
//console.log(fruits[key].sayilar);
console.log("aaa");
}else{
console.log("bbbb");
}
}
}