为什么我在javascript中添加2 + 4时会得到24 [英] why do I get 24 when adding 2 + 4 in javascript

查看:100
本文介绍了为什么我在javascript中添加2 + 4时会得到24的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试这个:

function add_things() {
  var first = '2';
  var second = '4';
  alert(first + second);
}

但它给了我24而不是6,我做错了什么?

But it gives me 24 instead of 6, what am I doing wrong?

推荐答案

您使用+运算符连接两个字符串。尝试:

You're concatenating two strings with the + operator. Try either:

function add_things() {
  var first = 2;
  var second = 4;
  alert(first + second);
}

function add_things() {
  var first = '2';
  var second = '4';
  alert(parseInt(first, 10) + parseInt(second, 10));
}

function add_things() {
  var first = '2';
  var second = '4';
  alert(Number(first) + Number(second));
}

注意:第二种情况只适用于你从一个属性或用户输入中得到字符串。如果它们是你定义的常量,你想要添加它们然后将它们定义为整数(如第一个例子中所示)。

Note: the second is only really appropriate if you're getting strings from say a property or user input. If they're constants you're defining and you want to add them then define them as integers (as in the first example).

另外,正如所指出的,八进制是邪恶的。 parseInt('010')实际上将以数字8(八进制中的10为8)出现,因此指定10的基数是个好主意。

Also, as pointed out, octal is evil. parseInt('010') will actually come out as the number 8 (10 in octal is 8), hence specifying the radix of 10 is a good idea.

这篇关于为什么我在javascript中添加2 + 4时会得到24的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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