简体   繁体   中英

How to use conditional(ternary) operator in javascript

Given a string, I need to get the number of occurrence of each character in the string.

Input : "Hello world" 
Expected Output : { H: 1, e: 1, l: 3, o: 2, ' ': 1, w: 1, r: 1, d: 1 }

When I use if else condition the logic works fine , but not with ternary operator.

const string = "Hello world";
const chars = {};

for(let char of string) {
    if(!chars[char]) chars[char] = 1;
    else chars[char]++;
}
console.log(chars); // { H: 1, e: 1, l: 3, o: 2, ' ': 1, w: 1, r: 1, d: 1 } 


But, When I replace the if else condition with ternary operator, the output is unexpected

chars[char] = !chars[char] ? 1: chars[char]++
console.log(chars); // { H: 1, e: 1, l: 1, o: 1, ' ': 1, w: 1, r: 1, d: 1 }

In this case, you'll want to move the ++ before chars[char] :

chars[char] = !chars[char] ? 1 : ++chars[char]

Or just an addition:

chars[char] = !chars[char] ? 1 : chars[char] + 1

Or, even shorter:

 chars[char] = (chars[char] || 0) + 1 

Whether you place the ++ before or after a value changes the value it returns:

  • After ( chars[char]++ ), the operator will return the original value, 1 , as it increments to 2 . The assignment operator, then, will receive the 1 and place it back into chars[char] , undoing the increment.

  • Before ( ++chars[char] ), the operator will return the modified value, 2 , for the assignment to use. Here, the operators aren't in conflict with each other, as they're both setting the same value.

You are setting chars[char] to the result of chars[char]++ which is 0

You want: chars[char] = !chars[char] ? 1: chars[char]+1 chars[char] = !chars[char] ? 1: chars[char]+1

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