我正在尝试将字符串转换为整数。当字符串是带有前导零的数字时,Google 脚本似乎会遇到麻烦。将“07”转换为 7 效果很好,转换“08”则以 NaN 结尾。
function test_parse_int() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
// parses to 7
ss.toast( parseInt("07") );
// parses to NaN ?!?
ss.toast( parseInt("08") );
}
我针对 JavaScript 进行了测试,它工作得很好。
<script>
// parses to 7
document.writeln(parseInt("07"));
// parses to 8
document.writeln(parseInt("08"));
</script>
这种行为对我来说没有任何意义,这是一个错误吗?我错过了什么吗?
最佳答案
来源:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt [感谢 @teemu 评论]
If the input string begins with "0", radix is eight (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet. For this reason always specify a radix when using parseInt.
所以明确提及基数
类似这样的事情:
function test_parse_int() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
// parses to 7
ss.toast( parseInt("07", 10) );
// parses to NaN ?!?
ss.toast( parseInt("08", 10) );
}
关于javascript - Google 脚本转换数字的方式与 JavaScript 不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50673648/