这是一个小的JavaScript。我从函数中得到了意想不到的结果。020*2等于32而不是40。有人知道怎么解决这个问题吗??
function myFunction(a, b) {
return a * b;
}
document.write('04 * 03 = ');
document.write(myFunction(04, 03)); //Result 12, correct
document.write(' << Correct <br/>020 * 02 = ');
document.write(myFunction(020, 02)); //Result 32, wrong - expected result 40
document.write(' << Expected 40 here');
发布于 2015-04-03 22:51:25
16 *2= 32。
示例
将八进制值转换为基数8(八进制)字符串,然后以基数10 (十进制)对其进行解析。
var x = 020; // 16 (octal)
var y = 02; // 2 (octal)
document.body.innerHTML = x + ' x ' + y + ' = ' + x * y; // 32
document.body.innerHTML += '<br />'; // {Separator}
var x2 = parseInt(x.toString(8), 10); // 20 (decimal)
var y2 = parseInt(y.toString(8), 10); // 2 (decimal)
document.body.innerHTML += x2 + ' x ' + y2 + ' = ' + x2 * y2; // 40
发布于 2015-04-03 22:52:59
正如评论中提到的,在数字前加一个零将其类型从十进制(1 - 10)更改为八进制(1 - 8)。要使数字保持十进制,请删除前导零。
以下是包含此建议的代码:
function myFunction(a, b) {
return a * b;
}
document.write('04 * 03 = ');
document.write(myFunction(4, 3)); //Result 12, correct
document.write(' << Correct <br/>20 * 2 = ');
document.write(myFunction(20, 2)); //Result 40, correct
document.write(' << Correct ')myFunction(04, 03)之所以能正确工作,是因为它的八位数中没有数字。另一方面,20 * 02在20的八个点中有一个2,当它乘以八进制的02时,它被解释为2乘以8或16。
https://stackoverflow.com/questions/29434409
复制相似问题