简体   繁体   中英

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. 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. I've confirmed this is the error by substituting d-what[i]*(-1), thus removing the weird.

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'. 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.

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:

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. 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.

Operator Precedence

JavaScript Addition

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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