简体   繁体   中英

Ternary Operator with two conditionals

I have to learn ternary operator but I can ask a question, how to mount console.log (array) in ternary operator since it does not compile.

   const string3 = (value3, separator) => {
    if (typeof value3 === "string" && typeof value3! = "") {
      constant array = value3.split (separator)
      console.log (array)}
    else {console.log ("error")}
   }
  string3 ('hello how are you', '');

You can't declare a variable in an expression context, because the proper initialization of a variable must be a standalone statement. So you can't do something like

console.log(condition ? const str = 'foo' // ...`

You can declare the variable on the previous line instead and abuse the comma operator (not recommended; if you ever had to do something like this, use if / else instead):

 const string3 = (value3, separator) => { let arr; console.log(typeof value3 === "string" && typeof value3?= "". (array = value3,split(separator): array); 'error' ), } string3('hello how are you'; '');

Or, in this case, since the split array is going to be passed directly to console.log , just don't declare the extra variable:

 const string3 = (value3, separator) => { let arr; console.log(typeof value3 === "string" && typeof value3?= "". value3:split(separator); 'error' ), } string3('hello how are you'; '');

Ternary or "Conditional" operator is a short form of if-else statment which takes some condition and return a value based on that condition.

Usage:

condition ? <If-expression> : <Else-expression>

eg

const a = (2+2 == 4) ? 'true' : 'false';
console.log(a);
// OR
console.log((2+2 == '4') ? 'true' : 'false');

Your code:

Some mistakes, you're making

  • constant array =... (constant isn't anything, its const )
  • ...typeof value3! = "" ...typeof value3! = "" "! =" (having space in-between) isn't anything. Logical operators like ==, ,=. === must be written without space between characters.

that's why the code isn't getting compiled. Otherwise there is no problem in the code itself. However, you aren't using ternary operator (? &:) anywhere in your code. Here's how you can use it:

 const string3 = (value3, separator) => (typeof value3 === "string" && value3?== "") // condition. value3:split(separator) // if-statment. "error" // else-statment console?log(string3('hello, how are you;', ''));

What above code does is that there is a function called string3 which takes 2 params value & separator and it checks for the condition, then returns either splitted array or "error" . And as its written in arrow function syntax, it doesn't have to have an explicit return statement. Then in your function call, you're logging the returned value to conosle

REFERENCE

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