javascript - Google 脚本转换数字的方式与 JavaScript 不同

标签 javascript google-apps-script google-sheets

我正在尝试将字符串转换为整数。当字符串是带有前导零的数字时,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/

相关文章:

javascript - 运行 babel-node 时出错

javascript - 如何将函数 A 的返回对象作为参数传递给函数 B?

google-apps-script - 有没有办法在保留文本格式的同时替换 TextBox 形状内的文本?

javascript - Google Sheets 带注释的时间线显示精确值?

google-sheets - 在 Google 表格中如何引用列中的无限行?

google-apps-script - 如何使用 onEdit 函数触发电子邮件

javascript - 获取 window.scrollby 的结尾

javascript - 将赋值变量解构为全局常量

google-apps-script - 对于因触发器是由现已禁用的 Google Workplace 用户创建而被禁用的问题,有什么好的解决方法吗?

google-apps-script - Google Picker - 将文件 ID 返回到我的 Google 脚本