带提示的两个数字的总和(初学者JavaScript) [英] Sum of two numbers with prompt (Beginner JavaScript)

查看:178
本文介绍了带提示的两个数字的总和(初学者JavaScript)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JavaScript的新手,我正在学习这门语言的基础知识。

I'm new to JavaScript and I'm learning the basics of this language.

过去几天我一直试图解决这个问题:当我通过提示减去,乘以或除2输入数字时,一切正常;但是当我想添加它们时,我只能将两个数字简单地写在一起。

I've been trying to solve this problem for the last couple days: when I subtract, multiply or divide 2 numbers input through a prompt, everything works fine; but when I want to add them, I get the 2 numbers simply written together.

示例:如果我加5和6,我得到56 !!

Example: if I add 5 and 6, I get 56!!

这是我正在使用的代码。

Here's the code I'm working with.

var a = prompt("Enter first number");
var b = prompt("Enter second number");

alert(a + b);

我做错了什么?我是否必须指定值类型?

What am I doing wrong? Do I have to specify the value type?

推荐答案

函数提示返回一个字符串并且 + (不明智地,可能)用于两个字符串连接和数字添加。

The function prompt returns a string and + is (unwisely, perhaps) used for both string concatenation and number addition.

您没有在JavaScript中指定类型,但可以在运行时执行字符串到数字的转换。有很多方法可以做到这一点。最简单的是:

You do not "specify types" in JavaScript but you can do string to number conversion at run time. There are many ways to so this. The simplest is:

var a = +prompt("Enter first number");
var b = +prompt("Enter second number");
alert(a + b);

但你也可以

var a = Number(prompt("Enter first number"));
var b = Number(prompt("Enter second number"));
alert(a + b);

(避免 parseInt 因为它只处理前导字符,不会添加4.5和2.6之类的数字。)

(Avoid parseInt because it only handles the leading characters and will not add numbers like 4.5 and 2.6.)

这篇关于带提示的两个数字的总和(初学者JavaScript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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