简体   繁体   English

Google脚本正在整数上重载+,就好像它们是字符串一样,我不知道为什么

[英]Google scripts is overloading + on integers as if they were strings and I don't know why

This is a script for a Sheets document where who[] is a char array and what[] is an int array both taken from R1C1 inputs. 这是一张Sheets文档的脚本,其中who []是一个char数组,而what []是一个int数组,两者均取自R1C1输入。 For some reason the d+what[i] concatenates the previous value of d and what[i] (as a string-- unexpected behavior), but the d-what[i] performs integer subtraction as expected. 出于某些原因,d + what [i]将d的先前值和what [i](作为字符串-意外行为)连接起来,但是d-what [i]会按预期执行整数减法。 I've confirmed this is the error by substituting d-what[i]*(-1), thus removing the weird. 我通过替换d-what [i] *(-1)来确认这是错误,从而消除了怪异现象。

function compareExpenses(who, what) {
  var d = 0;
//  var who = ['T','D','T'];
//  var what = [15,10,5];

  for (var i=0; i < what.length; i++) {
    if (who[i] == 'T') {
      d = d+what[i];
    } else {
      d = d-what[i];
    }
  }

  return d/2;
}

In case it is unclear: with the sample inputs in the code the value of d after each iteration is: '015', 5, '55'. 如果不清楚,使用代码中的样本输入,每次迭代后的d值为:“ 015”,5,“ 55”。 No other code exists on this sheet. 此工作表上没有其他代码。 Is something going on behind the scenes I'm not aware of that would cause + to overload this way? 我不知道在幕后发生的事情会导致+以这种方式超载吗?

Depending on how you are using the variable d , either reset the variable d on every iteration. 根据您使用变量d ,在每次迭代中重置变量d

for (var i=0; i < what.length; i++) {
  d = 0; //Reset

  if (who[i] == 'T') {

or convert d to a number at the beginning of every loop: 或在每个循环的开始将d转换为数字:

for (var i=0; i < what.length; i++) {
  d = Number(d); //Convert to number

  if (who[i] == 'T') {

The "plus" operator is used to concatenate text. “加”运算符用于连接文本。 The "minus" operator is not used to concatenate text. “减号”运算符不用于连接文本。 That's the different. 那是不同的。 JavaScript is constantly trying to "coerce" variable types into what it "thinks" the variable type should be. JavaScript一直在努力将变量类型“强制”为它“认为”变量类型应该是什么。 If one value is text and one value is a number, and the plus operator is used, JavaScript will change the number to text and concatenate the text. 如果一个值是文本,一个值是数字,并且使用了加号运算符,则JavaScript会将数字更改为文本并连接文本。

Operator Precedence 运算符优先级

JavaScript Addition JavaScript添加

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM