简体   繁体   中英

Google Sheets Javascript indexOf error

I'm have a crazy time trying to get around an error when using indexOf() on a cell without the index criteria.. in this case a comma: indexOf(",") . BTW, I get the same issue when trying to do a .split(",") on a cell with no commas.

问题图片

Is there a way around this so if there are no commas, I can give a variable a value?

Here's the code:

/**
@customfunction
*/
function INDEX_TEST(input){
    var a = 0;
    if (input.indexOf(",") > -1){
      a = 999;
    }
    else {
      a = 0;
    }
    return a;
}

Any help would be appreciated.

Here's a link to a google sheet

Google Sheet with example

You get the error when input is a number not a string. Numbers do not have indexOf or any other string methods. So you have to convert it to string:

if (input.toString().indexOf(",")>-1){a = 999;}

or

if ((input + '').indexOf(",")>-1){a = 999;}

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