在提示中指定变量类型

时间:2018-01-12 13:50:58

标签: javascript

此代码正在执行字符串连接,而不是数字添加。 如何在提示字段中指定输入的类型(例如:number,string)。

var jonage = prompt("enter the johns age");
var jonHeight = prompt("enter the johns height");
var jonScore = jonHeight + jonage * 5;
console.log(jonScore);

5 个答案:

答案 0 :(得分:5)

prompt非常基本,除了默认情况下浏览器的操作方式外,无法限制输入(例如,没有换行符)。

相反,之后将字符串转换为数字。有很多方法可以做到这一点:

  • 一元+var jonage = +prompt("enter the johns age");
  • Numbervar jonage = Number(prompt("enter the johns age"));
  • parseIntvar jonage = parseInt(prompt("enter the johns age"));
  • parseFloatvar jonage = parseFloat(prompt("enter the johns age"));

一元+Number

......以同样的方式工作:

  • 如果可能的话,他们会将整个字符串转换为数字,如果整个字符串都无法转换为数字,则会产生NaN。因此+"123abc"NaN
  • 他们将空字符串("")转换为0(令人惊讶)。
  • 他们尊重用于指定数字基数(基数)的JavaScript语法,因此+"0x10"为16,+"0o10"8

parseInt

  • 在第一个无效字符之前,只转换尽可能多的字符串,而不是整个字符串。因此parstInt("123abc")123
  • 将空字符串("")转换为NaN(不是0)。
  • 尊重用于指定数字基数(基数)的JavaScript语法,例如parseInt("0x10")为16。
  • 同样允许您明确指定基数作为第二个参数,以强制它将输入视为该数字基数:parseInt("0x10", 10)0(因为x变为无效,0x不再被视为表示数​​字基数。如果最终用户输入了"010"等字符串,则使用对小数点很重要浏览器已实施"传统"八进制(领先0而不是领先0o),但自{5th edition spec以来已经过去8年了enter image description here 1}}正式允许这样做。
  • 顾名思义,只转换定义整个号码(整数)的字符串部分。

parseInt

parseFloat类似,但是小数字并没有做基数前缀。 parseIntparseFloat("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");
      }
    }
}