Javascript Google 电子表格脚本 getValues - 强制 int 而不是 string
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11121837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Google Spreadsheet Script getValues - Force int instead of string
提问by user1469541
Is there a way to force .getRange().getValues() to return an int? Although only numbers exist in my range, it is returning them as strings. I would like to avoid using parseInt in every one of my statements or creating a separate array with converted values.
有没有办法强制 .getRange().getValues() 返回一个 int?尽管我的范围内只存在数字,但它将它们作为字符串返回。我想避免在我的每一个语句中使用 parseInt 或使用转换后的值创建一个单独的数组。
Or is that the only solution, to get the array and then parseInt the entire array in a loop?
或者这是获取数组然后在循环中解析整个数组的唯一解决方案?
回答by hoogamaphone
you can do this easily using the unary '+' operator as follows:
您可以使用一元“+”运算符轻松完成此操作,如下所示:
First get your values from your spreadsheet using getValue()
or getValues()
. Suppose you get two such values, and store them in A = 1
and B = 2
. You can force them to be recognized as numbers by using any math binary operator except for +
, which concatenates strings, so A - B = -1
, while A + B
will return '12'.
首先使用getValue()
或从电子表格中获取您的值getValues()
。假设您获得两个这样的值,并将它们存储在A = 1
和 中B = 2
。您可以通过使用任何数学二元运算符强制将它们识别为数字,除了+
连接字符串的 ,因此A - B = -1
,whileA + B
将返回“12”。
You can force the variables to be numbers simply by using the +
unary operator with any variable that might be interpreted as a string. For example, +A + +B
will return the correct value of 3.
您可以简单地通过将+
一元运算符与任何可能被解释为字符串的变量一起使用来强制变量为数字。例如,+A + +B
将返回正确的值 3。
回答by Serge insas
You can use parseInt()
or Number()
您可以使用parseInt()
或Number()
example
例子
var A='12';var B=5
A+B = 125
parseInt(A)+B = 17
Number(A)+B = 17
That said, getValues() is not supposed to return strings unless values have some space or other non-numeric characters in it... are these values entered manually or come as a result of some function ?
也就是说,除非值中有一些空格或其他非数字字符,否则 getValues() 不应该返回字符串……这些值是手动输入的还是某些函数的结果?
回答by Srik
getValues() returns a 2D array of Objects - so these are Strings, Integers or Date objects depending on what these are formatted as in your spreadsheet.
getValues() 返回对象的二维数组 - 因此这些是字符串、整数或日期对象,具体取决于它们在电子表格中的格式。
Go back to your spreadsheet and see what the cells that have integer values are formatted as. Format them as integers and you should get back integers.
返回到您的电子表格并查看具有整数值的单元格的格式。将它们格式化为整数,你应该得到整数。