Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

javascript - Google Scripts editor || not working in IF Statement

Can anyone please tell me why the || in if statement is not working. If I take out the || it will produce the desired results of logging the cell number if its not equal.

   function ReformatSheet() {
    
      var GoFlowWHInv = SpreadsheetApp.openById("1pXWj_UOTVy_mFB5gRUPbDfzNJcAK09Z-mDyXPKUJaLE");
      var Data = GoFlowWHInv.getDataRange()
      var Values = GoFlowWHInv.getDataRange().getValues()
    
      Values[i][4]
    
      for (var i = 0; i < Values.length; i++) {
    
        if(Values[i][4] !== "Item Type" || Values[i][4] !== "Standard Product") {
    
          Logger.log(Values[i][4]);
    
        }
      }

Here is the log that I ran both before the for loop and in the for loop.

It should log the first but not the second if it has Item Type or Standard Product therefore I should only see back to back Standard Products in the log.

12:26:12 PM Notice  Execution started
12:26:13 PM Info    Item Type
12:26:13 PM Info    Item Type
12:26:13 PM Info    Kit Product
12:26:13 PM Info    Kit Product
12:26:13 PM Info    Standard Product
12:26:13 PM Info    Standard Product
12:26:13 PM Info    Kit Product
question from:https://stackoverflow.com/questions/65832376/google-scripts-editor-not-working-in-if-statement

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should be using && not ||. In this line

if(Values[i][4] !== "Item Type" && Values[i][4] !== "Standard Product")

it will always call the logger because even if the cell contains Item Type or Standard Product, the other part of the whole expression will be true and it will print to the logger.

For example, if the cell contains Item Type

Values[i][4] !== "Item Type" evaluates to false

but

Values[i][4] !== "Standard Product" evaluates to true

false || true evaluates to true so the whole if statement succeeds.

So you should use this instead:

if(Values[i][4] !== "Item Type" && Values[i][4] !== "Standard Product")

You could also invert the logic and use ||

if(!(Values[i][4] === "Item Type" || Values[i][4] === "Standard Product"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...