Javascript eval函数返回八进制值 [英] Javascript eval function returning Octal value

查看:68
本文介绍了Javascript eval函数返回八进制值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试eval函数作为eval(020 * 05 + 05)时,它返回85而不是105.
有人可以解释为什么eval函数的行为如下吗?还建议任何解决这个问题。

when i try "eval" function as eval ("020 * 05 + 05") it is returning 85 instead off 105. Can someone explain me why eval function behave like this? Also suggest any to overcome this problem.

推荐答案

以零开头的数字常量(如020)被解释为八进制。这对于C,C ++,Java,Javascript以及大多数其他语言来说都是如此,甚至与C语言的模糊关系也很模糊。

Numeric constants that start with a zero (like "020") are interpreted as octal. That's true for C, C++, Java, Javascript, and most any other language with even a vague cosmetic relationship to C.

如果由于某种原因你确实需要使用eval(),你有这些奇怪的字符串,数字常量上带有伪造的前导零,你可能会尝试这样的事情:

If for some reason you really, really need to use "eval()", and you've got these weird strings with bogus leading zeros on the numeric constants, you might try something like this:

var answer = eval(weirdString.replace(/\b0(\d+)\b/g, '$1'));

但是我希望你能找到一种方法来使用eval()。 (请注意下面的注释,注意上面显示的hack会出现包含小数部分的数字的问题。)

However I wish you would find a way around using "eval()" at all. (Note the comment below noting that the hack shown above will have problems with numbers containing fractional parts.)

这篇关于Javascript eval函数返回八进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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