如何在JavaScript中使用条件(三元)运算符 [英] How to use conditional(ternary) operator in javascript

查看:56
本文介绍了如何在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 }

当我使用if条件时,逻辑工作正常,但不适用于三元运算符.

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 } 


但是,当我用三元运算符替换if else条件时,输出是意外的


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 }

推荐答案

在这种情况下,您需要将 ++ 移到 chars [char] 之前:

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

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

或者只是一个补充:

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

或更短:

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

是否将 ++ 放置在值更改的值之前或之后:

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

  • 在( chars [char] ++ )之后,运算符将返回原始值 1 ,随着其递增到 2 .然后,赋值运算符将接收 1 并将其放回 chars [char] 中,并取消增量.

  • 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.

在( ++ chars [char] )之前,操作员将返回修改后的值 2 ,以供分配使用.在这里,运算符不会互相冲突,因为它们都设置了相同的值.

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.

这篇关于如何在JavaScript中使用条件(三元)运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆