简体   繁体   中英

Javascript ternary operator result always the same

The code below always responds with "hi". Even if i set the campaign1 variable to 0. Can anyone advise if I am writing this out incorrectly?

 campaign1 = 2; campaign_string = (typeof campaign1 > 1 ? "hello" : "hi" );

Kind regards,

You don't need typeof operator. Try repeating without that; and get rid of the unnecessary paranthesis too.

This should do

campaign1 = 2;

campaign_string = campaign1 > 1 ? "hello" : "hi";

You are using typeof but not comparing it to a type. I think you mean to do this.

campaign1 = 2;

campaign_string = (campaign1 > 1 ? "hello" : "hi" );

typeof is used like this.

var variable = 'Test';

typeof variable === 'string' // This is true.

You dont need this 'typeof', so change it to:

campaign1 = 2;

campaign_string = campaign1 > 1 ? "hello" : "hi" );

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